aboutsummaryrefslogtreecommitdiff
path: root/src/server/game/Chat/ChatCommands/ChatCommandArgs.h
blob: 630e7ea6237f4bfd6b83fef8264274c962f05639 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef TRINITY_CHATCOMMANDARGS_H
#define TRINITY_CHATCOMMANDARGS_H

#include "ChatCommandHelpers.h"
#include "ChatCommandTags.h"
#include "EnumFlag.h"
#include "SmartEnum.h"
#include "StringConvert.h"
#include "StringFormat.h"
#include "Util.h"
#include <charconv>
#include <map>
#include <string>
#include <string_view>

struct GameTele;

namespace Trinity::Impl::ChatCommands
{

    /************************** ARGUMENT HANDLERS *******************************************\
    |* Define how to extract contents of a certain requested type from a string             *|
    |* Must implement the following:                                                        *|
    |* - TryConsume: T&, ChatHandler const*, std::string_view -> ChatCommandResult          *|
    |*   - on match, returns tail of the provided argument string (as std::string_view)     *|
    |*   - on specific error, returns error message (as std::string&& or char const*)       *|
    |*   - on generic error, returns std::nullopt (this will print command usage)           *|
    |*                                                                                      *|
    |*   - if a match is returned, T& should be initialized to the matched value            *|
    |*   - otherwise, the state of T& is indeterminate and caller will not use it           *|
    |*                                                                                      *|
    \****************************************************************************************/
    template <typename T, typename = void>
    struct ArgInfo { static_assert(Trinity::dependant_false_v<T>, "Invalid command parameter type - see ChatCommandArgs.h for possible types"); };

    // catch-all for number types
    template <typename T>
    struct ArgInfo<T, std::enable_if_t<std::is_integral_v<T> || std::is_floating_point_v<T>>>
    {
        static ChatCommandResult TryConsume(T& val, ChatHandler const* handler, std::string_view args)
        {
            auto [token, tail] = tokenize(args);
            if (token.empty())
                return std::nullopt;

            if (Optional<T> v = StringTo<T>(token, 0))
                val = *v;
            else
                return FormatTrinityString(handler, LANG_CMDPARSER_STRING_VALUE_INVALID, STRING_VIEW_FMT_ARG(token), Trinity::GetTypeName<T>().c_str());

            if constexpr (std::is_floating_point_v<T>)
            {
                if (!std::isfinite(val))
                    return FormatTrinityString(handler, LANG_CMDPARSER_STRING_VALUE_INVALID, STRING_VIEW_FMT_ARG(token), Trinity::GetTypeName<T>().c_str());
            }

            return tail;
        }
    };

    // string_view
    template <>
    struct ArgInfo<std::string_view, void>
    {
        static ChatCommandResult TryConsume(std::string_view& val, ChatHandler const*, std::string_view args)
        {
            auto [token, next] = tokenize(args);
            if (token.empty())
                return std::nullopt;
            val = token;
            return next;
        }
    };

    // string
    template <>
    struct ArgInfo<std::string, void>
    {
        static ChatCommandResult TryConsume(std::string& val, ChatHandler const* handler, std::string_view args)
        {
            std::string_view view;
            ChatCommandResult next = ArgInfo<std::string_view>::TryConsume(view, handler, args);
            if (next)
                val.assign(view);
            return next;
        }
    };

    // wstring
    template <>
    struct ArgInfo<std::wstring, void>
    {
        static ChatCommandResult TryConsume(std::wstring& val, ChatHandler const* handler, std::string_view args)
        {
            std::string_view utf8view;
            ChatCommandResult next = ArgInfo<std::string_view>::TryConsume(utf8view, handler, args);

            if (next)
            {
                if (Utf8toWStr(utf8view, val))
                    return next;
                else
                    return GetTrinityString(handler, LANG_CMDPARSER_INVALID_UTF8);
            }
            else
                return std::nullopt;
        }
    };

    // enum
    template <typename T>
    struct ArgInfo<T, std::enable_if_t<std::is_enum_v<T>>>
    {
        using SearchMap = std::map<std::string_view, Optional<T>, StringCompareLessI_T>;
        static SearchMap MakeSearchMap()
        {
            SearchMap map;
            for (T val : EnumUtils::Iterate<T>())
            {
                EnumText text = EnumUtils::ToString(val);

                std::string_view title(text.Title);
                std::string_view constant(text.Constant);

                auto [constantIt, constantNew] = map.try_emplace(constant, val);
                if (!constantNew)
                    constantIt->second = std::nullopt;

                if (title != constant)
                {
                    auto [titleIt, titleNew] = map.try_emplace(title, val);
                    if (!titleNew)
                        titleIt->second = std::nullopt;
                }
            }
            return map;
        }

        static inline SearchMap const _map = MakeSearchMap();

        static T const* Match(std::string_view s)
        {
            auto it = _map.lower_bound(s);
            if (it == _map.end() || !StringStartsWithI(it->first, s)) // not a match
                return nullptr;

            if (!StringEqualI(it->first, s)) // we don't have an exact match - check if it is unique
            {
                auto it2 = it;
                ++it2;
                if ((it2 != _map.end()) && StringStartsWithI(it2->first, s)) // not unique
                    return nullptr;
            }

            if (it->second)
                return &*it->second;
            else
                return nullptr;
        }

        static ChatCommandResult TryConsume(T& val, ChatHandler const* handler, std::string_view args)
        {
            std::string_view strVal;
            ChatCommandResult next1 = ArgInfo<std::string_view>::TryConsume(strVal, handler, args);
            if (next1)
            {
                if (T const* match = Match(strVal))
                {
                    val = *match;
                    return next1;
                }
            }

            // Value not found. Try to parse arg as underlying type and cast it to enum type
            do
            {
                using U = std::underlying_type_t<T>;
                U uVal = 0;
                if (ChatCommandResult next2 = ArgInfo<U>::TryConsume(uVal, handler, args))
                {
                    // validate numeric value only if its not a flag to allow combined flags
                    if constexpr (!EnumTraits::IsFlag<T>::value)
                        if (!EnumUtils::IsValid<T>(uVal))
                            break;

                    val = static_cast<T>(uVal);
                    return next2;
                }
            } while (false);

            if (next1)
                return FormatTrinityString(handler, LANG_CMDPARSER_STRING_VALUE_INVALID, STRING_VIEW_FMT_ARG(strVal), Trinity::GetTypeName<T>().c_str());
            else
                return next1;
        }
    };

    // a container tag
    template <typename T>
    struct ArgInfo<T, std::enable_if_t<std::is_base_of_v<ContainerTag, T>>>
    {
        static ChatCommandResult TryConsume(T& tag, ChatHandler const* handler, std::string_view args)
        {
            return tag.TryConsume(handler, args);
        }
    };

    // non-empty vector
    template <typename T>
    struct ArgInfo<std::vector<T>, void>
    {
        static ChatCommandResult TryConsume(std::vector<T>& val, ChatHandler const* handler, std::string_view args)
        {
            val.clear();
            ChatCommandResult next = ArgInfo<T>::TryConsume(val.emplace_back(), handler, args);

            if (!next)
                return next;

            while (ChatCommandResult next2 = ArgInfo<T>::TryConsume(val.emplace_back(), handler, *next))
                next = std::move(next2);

            val.pop_back();
            return next;
        }
    };

    // fixed-size array
    template <typename T, size_t N>
    struct ArgInfo<std::array<T, N>, void>
    {
        static ChatCommandResult TryConsume(std::array<T, N>& val, ChatHandler const* handler, std::string_view args)
        {
            ChatCommandResult next = args;
            for (T& t : val)
                if (!(next = ArgInfo<T>::TryConsume(t, handler, *next)))
                    break;
            return next;
        }
    };

    // variant
    template <typename... Ts>
    struct ArgInfo<Trinity::ChatCommands::Variant<Ts...>>
    {
        using V = std::variant<Ts...>;
        static constexpr size_t N = std::variant_size_v<V>;

        template <size_t I>
        static ChatCommandResult TryAtIndex([[maybe_unused]] Trinity::ChatCommands::Variant<Ts...>& val, [[maybe_unused]] ChatHandler const* handler, [[maybe_unused]] std::string_view args)
        {
            if constexpr (I < N)
            {
                ChatCommandResult thisResult = ArgInfo<std::variant_alternative_t<I, V>>::TryConsume(val.template emplace<I>(), handler, args);
                if (thisResult)
                    return thisResult;
                else
                {
                    ChatCommandResult nestedResult = TryAtIndex<I + 1>(val, handler, args);
                    if (nestedResult || !thisResult.HasErrorMessage())
                        return nestedResult;
                    if (!nestedResult.HasErrorMessage())
                        return thisResult;
                    if (StringStartsWith(nestedResult.GetErrorMessage(), "\""))
                        return Trinity::StringFormat("\"{}\"\n{} {}", thisResult.GetErrorMessage(), GetTrinityString(handler, LANG_CMDPARSER_OR), nestedResult.GetErrorMessage());
                    else
                        return Trinity::StringFormat("\"{}\"\n{} \"{}\"", thisResult.GetErrorMessage(), GetTrinityString(handler, LANG_CMDPARSER_OR), nestedResult.GetErrorMessage());
                }
            }
            else
                return std::nullopt;
        }

        static ChatCommandResult TryConsume(Trinity::ChatCommands::Variant<Ts...>& val, ChatHandler const* handler, std::string_view args)
        {
            ChatCommandResult result = TryAtIndex<0>(val, handler, args);
            if (result.HasErrorMessage() && (result.GetErrorMessage().find('\n') != std::string::npos))
                return Trinity::StringFormat("{} {}", GetTrinityString(handler, LANG_CMDPARSER_EITHER), result.GetErrorMessage());
            return result;
        }
    };

    // AchievementEntry* from numeric id or link
    template <>
    struct TC_GAME_API ArgInfo<AchievementEntry const*>
    {
        static ChatCommandResult TryConsume(AchievementEntry const*&, ChatHandler const*, std::string_view);
    };

    // CurrencyTypesEntry* from numeric id or link
    template <>
    struct TC_GAME_API ArgInfo<CurrencyTypesEntry const*>
    {
        static ChatCommandResult TryConsume(CurrencyTypesEntry const*&, ChatHandler const*, std::string_view);
    };

    // GameTele* from string name or link
    template <>
    struct TC_GAME_API ArgInfo<GameTele const*>
    {
        static ChatCommandResult TryConsume(GameTele const*&, ChatHandler const*, std::string_view);
    };

    // ItemTemplate* from numeric id or link
    template <>
    struct TC_GAME_API ArgInfo<ItemTemplate const*>
    {
        static ChatCommandResult TryConsume(ItemTemplate const*&, ChatHandler const*, std::string_view);
    };

    // Quest* from numeric id or link
    template <>
    struct TC_GAME_API ArgInfo<Quest const*>
    {
        static ChatCommandResult TryConsume(Quest const*&, ChatHandler const*, std::string_view);
    };

    // SpellInfo const* from spell id or link
    template <>
    struct TC_GAME_API ArgInfo<SpellInfo const*>
    {
        static ChatCommandResult TryConsume(SpellInfo const*&, ChatHandler const*, std::string_view);
    };

}

#endif