argument_parser.hpp 19.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
Paul's avatar
Paul committed
24
25
26
#ifndef MIGRAPHX_GUARD_RTGLIB_ARGUMENT_PARSER_HPP
#define MIGRAPHX_GUARD_RTGLIB_ARGUMENT_PARSER_HPP

Paul's avatar
Paul committed
27
28
29
#include <algorithm>
#include <functional>
#include <iostream>
Paul's avatar
Paul committed
30
#include <list>
Paul's avatar
Paul committed
31
#include <set>
Paul's avatar
Paul committed
32
#include <string>
Paul's avatar
Paul committed
33
#include <sstream>
Paul's avatar
Paul committed
34
35
#include <type_traits>
#include <unordered_map>
Paul's avatar
Paul committed
36
#include <utility>
Paul's avatar
Paul committed
37
38
#include <vector>

Paul's avatar
Paul committed
39
#include <migraphx/config.hpp>
Paul's avatar
Paul committed
40
41
#include <migraphx/requires.hpp>
#include <migraphx/type_name.hpp>
Paul's avatar
Paul committed
42
#include <migraphx/functional.hpp>
Paul's avatar
Paul committed
43
#include <migraphx/filesystem.hpp>
Paul's avatar
Paul committed
44
#include <migraphx/stringutils.hpp>
Paul's avatar
Paul committed
45
#include <migraphx/algorithm.hpp>
Paul's avatar
Paul committed
46
#include <migraphx/ranges.hpp>
kahmed10's avatar
kahmed10 committed
47
#include <migraphx/rank.hpp>
Paul's avatar
Paul committed
48

Paul's avatar
Paul committed
49
50
51
52
#ifndef _WIN32
#include <unistd.h>
#endif

Paul's avatar
Paul committed
53
54
55
namespace migraphx {
namespace driver {
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
56

Paul's avatar
Paul committed
57
58
59
60
61
62
#ifdef MIGRAPHX_USE_CLANG_TIDY
#define MIGRAPHX_DRIVER_STATIC
#else
#define MIGRAPHX_DRIVER_STATIC static
#endif

Paul's avatar
Paul committed
63
template <class T>
Paul's avatar
Paul committed
64
65
66
67
68
using bare = std::remove_cv_t<std::remove_reference_t<T>>;

namespace detail {

template <class T>
Paul's avatar
Paul committed
69
auto is_container(int, T&& x) -> decltype(x.insert(x.end(), *x.begin()), std::true_type{});
Paul's avatar
Paul committed
70
71
72
73
74
75
76
77
78
79
80
81
82

template <class T>
std::false_type is_container(float, T&&);

} // namespace detail

template <class T>
struct is_container : decltype(detail::is_container(int(0), std::declval<T>()))
{
};

template <class T>
using is_multi_value =
Paul's avatar
Paul committed
83
    std::integral_constant<bool, (is_container<T>{} and not std::is_convertible<T, std::string>{})>;
Paul's avatar
Paul committed
84

Paul's avatar
Paul committed
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
enum class color
{
    reset      = 0,
    bold       = 1,
    underlined = 4,
    fg_red     = 31,
    fg_green   = 32,
    fg_yellow  = 33,
    fg_blue    = 34,
    fg_default = 39,
    bg_red     = 41,
    bg_green   = 42,
    bg_yellow  = 43,
    bg_blue    = 44,
    bg_default = 49
};
inline std::ostream& operator<<(std::ostream& os, const color& c)
{
#ifndef _WIN32
    static const bool use_color = isatty(STDOUT_FILENO) != 0;
    if(use_color)
        return os << "\033[" << static_cast<std::size_t>(c) << "m";
#endif
    return os;
}

Paul's avatar
Paul committed
111
112
113
114
115
116
117
inline std::string colorize(color c, const std::string& s)
{
    std::stringstream ss;
    ss << c << s << color::reset;
    return ss.str();
}

Paul's avatar
Paul committed
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
template <class T>
struct type_name
{
    static const std::string& apply() { return migraphx::get_type_name<T>(); }
};

template <>
struct type_name<std::string>
{
    static const std::string& apply()
    {
        static const std::string name = "std::string";
        return name;
    }
};

template <class T>
struct type_name<std::vector<T>>
{
    static const std::string& apply()
    {
        static const std::string name = "std::vector<" + type_name<T>::apply() + ">";
        return name;
    }
};

Paul's avatar
Paul committed
144
145
146
template <class T>
struct value_parser
{
Paul's avatar
Paul committed
147
    template <MIGRAPHX_REQUIRES(not std::is_enum<T>{} and not is_multi_value<T>{})>
Paul's avatar
Paul committed
148
149
150
151
152
153
154
    static T apply(const std::string& x)
    {
        T result;
        std::stringstream ss;
        ss.str(x);
        ss >> result;
        if(ss.fail())
Paul's avatar
Paul committed
155
            throw std::runtime_error("Failed to parse '" + x + "' as " + type_name<T>::apply());
Paul's avatar
Paul committed
156
157
158
        return result;
    }

Paul's avatar
Paul committed
159
    template <MIGRAPHX_REQUIRES(std::is_enum<T>{} and not is_multi_value<T>{})>
Paul's avatar
Paul committed
160
161
162
163
164
165
166
    static T apply(const std::string& x)
    {
        std::ptrdiff_t i;
        std::stringstream ss;
        ss.str(x);
        ss >> i;
        if(ss.fail())
Paul's avatar
Paul committed
167
            throw std::runtime_error("Failed to parse '" + x + "' as " + type_name<T>::apply());
Paul's avatar
Paul committed
168
169
        return static_cast<T>(i);
    }
Paul's avatar
Paul committed
170
171
172
173
174
175
176
177
178

    template <MIGRAPHX_REQUIRES(is_multi_value<T>{} and not std::is_enum<T>{})>
    static T apply(const std::string& x)
    {
        T result;
        using value_type = typename T::value_type;
        result.insert(result.end(), value_parser<value_type>::apply(x));
        return result;
    }
Paul's avatar
Paul committed
179
180
181
182
183
184
};

struct argument_parser
{
    struct argument
    {
Paul's avatar
Paul committed
185
186
        using action_function = std::function<bool(argument_parser&, const std::vector<std::string>&)>;
        using validate_function = std::function<void(const argument_parser&, const std::vector<std::string>&)>;
Paul's avatar
Paul committed
187
        std::vector<std::string> flags;
Paul's avatar
Paul committed
188
        action_function action{};
Paul's avatar
Paul committed
189
190
191
        std::string type          = "";
        std::string help          = "";
        std::string metavar       = "";
Paul's avatar
Paul committed
192
        std::string default_value = "";
Paul's avatar
Paul committed
193
        unsigned nargs            = 1;
Paul's avatar
Paul committed
194
195
        bool required = true;
        std::vector<validate_function> validations{};
Paul's avatar
Paul committed
196
197
    };

Paul's avatar
Paul committed
198
    template <class T, MIGRAPHX_REQUIRES(is_multi_value<T>{})>
Paul's avatar
Paul committed
199
200
201
202
203
    std::string as_string_value(const T& x)
    {
        return to_string_range(x);
    }

kahmed10's avatar
kahmed10 committed
204
205
206
207
208
209
210
211
212
213
214
215
    template <class T>
    auto as_string_value(rank<1>, const T& x) -> decltype(to_string(x))
    {
        return to_string(x);
    }

    template <class T>
    std::string as_string_value(rank<0>, const T&)
    {
        throw std::runtime_error("Can't convert to string");
    }

Paul's avatar
Paul committed
216
    template <class T, MIGRAPHX_REQUIRES(not is_multi_value<T>{})>
Paul's avatar
Paul committed
217
218
    std::string as_string_value(const T& x)
    {
kahmed10's avatar
kahmed10 committed
219
        return as_string_value(rank<1>{}, x);
Paul's avatar
Paul committed
220
221
    }

Paul's avatar
Paul committed
222
    template <class T, class... Fs>
Paul's avatar
Paul committed
223
    void operator()(T& x, const std::vector<std::string>& flags, Fs... fs)
Paul's avatar
Paul committed
224
    {
Paul's avatar
Paul committed
225
        arguments.push_back({flags, [&](auto&&, const std::vector<std::string>& params) {
Paul's avatar
Paul committed
226
227
                                 if(params.empty())
                                     throw std::runtime_error("Flag with no value.");
Paul's avatar
Paul committed
228
229
                                 if (not is_multi_value<T>{} and params.size() > 1)
                                     throw std::runtime_error("Too many arguments passed.");
Paul's avatar
Paul committed
230
231
232
                                 x = value_parser<T>::apply(params.back());
                                 return false;
                             }});
Paul's avatar
Paul committed
233

kahmed10's avatar
kahmed10 committed
234
        argument& arg = arguments.back();
235
        arg.type      = type_name<T>::apply();
Paul's avatar
Paul committed
236
        migraphx::each_args([&](auto f) { f(x, arg); }, fs...);
kahmed10's avatar
kahmed10 committed
237
238
        if(not arg.default_value.empty() and arg.nargs > 0)
            arg.default_value = as_string_value(x);
Paul's avatar
Paul committed
239
240
    }

Paul's avatar
Paul committed
241
    template <class... Fs>
Paul's avatar
Paul committed
242
    void operator()(std::nullptr_t x, std::vector<std::string> flags, Fs... fs)
Paul's avatar
Paul committed
243
    {
Paul's avatar
Paul committed
244
        arguments.push_back({std::move(flags)});
Paul's avatar
Paul committed
245
246
247

        argument& arg = arguments.back();
        arg.type      = "";
Paul's avatar
Paul committed
248
        arg.nargs     = 0;
Paul's avatar
Paul committed
249
250
251
        migraphx::each_args([&](auto f) { f(x, arg); }, fs...);
    }

Paul's avatar
Paul committed
252
    MIGRAPHX_DRIVER_STATIC auto nargs(unsigned n = 1)
Paul's avatar
Paul committed
253
    {
Paul's avatar
Paul committed
254
        return [=](auto&&, auto& arg) { arg.nargs = n; };
Paul's avatar
Paul committed
255
256
    }

Paul's avatar
Paul committed
257
258
259
260
261
    MIGRAPHX_DRIVER_STATIC auto required()
    {
        return [=](auto&&, auto& arg) { arg.required = true; };
    }

Paul's avatar
Paul committed
262
    template <class F>
Paul's avatar
Paul committed
263
    MIGRAPHX_DRIVER_STATIC auto write_action(F f)
Paul's avatar
Paul committed
264
265
    {
        return [=](auto& x, auto& arg) {
Paul's avatar
Paul committed
266
            arg.action = [&, f](auto& self, const std::vector<std::string>& params) {
Paul's avatar
Paul committed
267
268
269
270
271
272
                f(self, x, params);
                return false;
            };
        };
    }

Paul's avatar
Paul committed
273
    template <class F>
Paul's avatar
Paul committed
274
    MIGRAPHX_DRIVER_STATIC auto do_action(F f)
Paul's avatar
Paul committed
275
276
    {
        return [=](auto&, auto& arg) {
Paul's avatar
Paul committed
277
            arg.nargs  = 0;
Paul's avatar
Paul committed
278
            arg.action = [&, f](auto& self, const std::vector<std::string>&) {
Paul's avatar
Paul committed
279
280
281
282
283
284
                f(self);
                return true;
            };
        };
    }

Paul's avatar
Paul committed
285
    MIGRAPHX_DRIVER_STATIC auto append()
Paul's avatar
Paul committed
286
    {
Paul's avatar
Paul committed
287
        return write_action([](auto&, auto& x, auto& params) {
Paul's avatar
Paul committed
288
            using type = typename bare<decltype(params)>::value_type;
Paul's avatar
Paul committed
289
            std::transform(params.begin(),
Paul's avatar
Paul committed
290
291
                           params.end(),
                           std::inserter(x, x.end()),
Paul's avatar
Paul committed
292
293
                           [](std::string y) { return value_parser<type>::apply(y); });
        });
Paul's avatar
Paul committed
294
295
    }

Paul's avatar
Paul committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    template <class F>
    MIGRAPHX_DRIVER_STATIC auto validate(F f)
    {
        return [=](const auto& x, auto& arg) {
            arg.validations.push_back([&, f](auto& self, const std::vector<std::string>& params) {
                f(self, x, params);
            });
        };
    }

    MIGRAPHX_DRIVER_STATIC auto file_exist()
    {
        return validate([](auto&, auto&, auto& params) {
            if (params.empty())
                throw std::runtime_error("No argument passed.");
            if (not fs::exists(params.back()))
                throw std::runtime_error("Path does not exists: " + params.back());
        });
    }

Paul's avatar
Format  
Paul committed
316
    template <class F>
Paul's avatar
Paul committed
317
318
319
    argument* find_argument(F f)
    {
        auto it = std::find_if(arguments.begin(), arguments.end(), f);
Paul's avatar
Format  
Paul committed
320
        if(it == arguments.end())
Paul's avatar
Paul committed
321
322
323
            return nullptr;
        return std::addressof(*it);
    }
Paul's avatar
Paul committed
324
325
326
327
328
    template <class F>
    bool has_argument(F f)
    {
        return find_argument(f) != nullptr;
    }
Paul's avatar
Paul committed
329

Paul's avatar
Paul committed
330
    MIGRAPHX_DRIVER_STATIC auto show_help(const std::string& msg = "")
Paul's avatar
Paul committed
331
    {
Paul's avatar
Paul committed
332
        return do_action([=](auto& self) {
Paul's avatar
Format  
Paul committed
333
334
            argument* input_argument =
                self.find_argument([](const auto& arg) { return arg.flags.empty(); });
Paul's avatar
Paul committed
335
336
            std::cout << color::fg_yellow << "USAGE:" << color::reset << std::endl;
            std::cout << "    " << self.exe_name << " <options> ";
Paul's avatar
Format  
Paul committed
337
            if(input_argument)
Paul's avatar
Paul committed
338
                std::cout << input_argument->metavar;
Paul's avatar
Paul committed
339
340
            std::cout << std::endl;
            std::cout << std::endl;
Paul's avatar
Format  
Paul committed
341
            if(self.find_argument([](const auto& arg) { return arg.nargs == 0; }))
Paul's avatar
Paul committed
342
            {
Paul's avatar
Paul committed
343
                std::cout << color::fg_yellow << "FLAGS:" << color::reset << std::endl;
Paul's avatar
Paul committed
344
                std::cout << std::endl;
Paul's avatar
Paul committed
345
                for(auto&& arg : self.arguments)
Paul's avatar
Paul committed
346
                {
Paul's avatar
Paul committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
                    if(arg.nargs != 0)
                        continue;
                    const int col_align = 35;
                    std::string prefix  = "    ";
                    int len             = 0;
                    std::cout << color::fg_green;
                    for(const std::string& a : arg.flags)
                    {
                        len += prefix.length() + a.length();
                        std::cout << prefix;
                        std::cout << a;
                        prefix = ", ";
                    }
                    std::cout << color::reset;
                    int spaces = col_align - len;
                    if(spaces < 0)
                    {
                        std::cout << std::endl;
                    }
                    else
                    {
                        for(int i = 0; i < spaces; i++)
                            std::cout << " ";
                    }
                    std::cout << arg.help << std::endl;
Paul's avatar
Paul committed
372
                }
Paul's avatar
Paul committed
373
374
                std::cout << std::endl;
            }
Paul's avatar
Format  
Paul committed
375
            if(self.find_argument([](const auto& arg) { return arg.nargs != 0; }))
Paul's avatar
Paul committed
376
377
378
            {
                std::cout << color::fg_yellow << "OPTIONS:" << color::reset << std::endl;
                for(auto&& arg : self.arguments)
Paul's avatar
Paul committed
379
                {
Paul's avatar
Paul committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
                    if(arg.nargs == 0)
                        continue;
                    std::cout << std::endl;
                    std::string prefix = "    ";
                    std::cout << color::fg_green;
                    if(arg.flags.empty())
                    {
                        std::cout << prefix;
                        std::cout << arg.metavar;
                    }
                    for(const std::string& a : arg.flags)
                    {
                        std::cout << prefix;
                        std::cout << a;
                        prefix = ", ";
                    }
                    std::cout << color::reset;
                    if(not arg.type.empty())
                    {
                        std::cout << " [" << color::fg_blue << arg.type << color::reset << "]";
                        if(not arg.default_value.empty())
                            std::cout << " (Default: " << arg.default_value << ")";
                    }
                    std::cout << std::endl;
                    std::cout << "        " << arg.help << std::endl;
Paul's avatar
Paul committed
405
                }
Paul's avatar
Paul committed
406
407
                std::cout << std::endl;
            }
Paul's avatar
Paul committed
408
            if(not msg.empty())
Paul's avatar
Paul committed
409
                std::cout << msg << std::endl;
Paul's avatar
Paul committed
410
411
412
        });
    }

Paul's avatar
Paul committed
413
    MIGRAPHX_DRIVER_STATIC auto help(const std::string& help)
Paul's avatar
Paul committed
414
    {
Paul's avatar
Paul committed
415
        return [=](auto&, auto& arg) { arg.help = help; };
Paul's avatar
Paul committed
416
417
    }

Paul's avatar
Paul committed
418
    MIGRAPHX_DRIVER_STATIC auto metavar(const std::string& metavar)
Paul's avatar
Paul committed
419
420
421
422
    {
        return [=](auto&, auto& arg) { arg.metavar = metavar; };
    }

423
424
425
426
427
    MIGRAPHX_DRIVER_STATIC auto type(const std::string& type)
    {
        return [=](auto&, auto& arg) { arg.type = type; };
    }

Paul's avatar
Paul committed
428
    template <class T>
Paul's avatar
Paul committed
429
    MIGRAPHX_DRIVER_STATIC auto set_value(T value)
Paul's avatar
Paul committed
430
431
    {
        return [=](auto& x, auto& arg) {
Paul's avatar
Paul committed
432
            arg.nargs  = 0;
Paul's avatar
Paul committed
433
            arg.type   = "";
Paul's avatar
Paul committed
434
            arg.action = [&, value](auto&, const std::vector<std::string>&) {
Paul's avatar
Paul committed
435
436
437
438
439
440
                x = value;
                return false;
            };
        };
    }

Paul's avatar
Format  
Paul committed
441
    template <class T>
442
443
    void set_exe_name_to(T& x)
    {
Paul's avatar
Paul committed
444
        actions.push_back([&](const auto& self) { x = self.exe_name; });
445
446
    }

Paul's avatar
Paul committed
447
448
449
450
    void print_usage_for(const argument& arg, const std::string& flag) const
    {
        std::cout << color::fg_yellow << "USAGE:" << color::reset << std::endl;
        std::cout << "    " << exe_name << " ";
Paul's avatar
Paul committed
451
452
453
454
455
456
457
458
459
460
        if (flag.empty())
        {
            std::cout << arg.metavar;
        }
        else
        {
            std::cout << flag;
            if(not arg.type.empty())
                std::cout << " [" << arg.type << "]";
        }
Paul's avatar
Paul committed
461
462
463
464
465
466
467
        std::cout << std::endl;
    }

    auto spellcheck(const std::vector<std::string>& inputs)
    {
        struct result_t
        {
Paul's avatar
Format  
Paul committed
468
469
470
            const argument* arg     = nullptr;
            std::string correct     = "";
            std::string incorrect   = "";
Paul's avatar
Paul committed
471
472
473
            std::ptrdiff_t distance = std::numeric_limits<std::ptrdiff_t>::max();
        };
        result_t result;
Paul's avatar
Format  
Paul committed
474
        for(const auto& input : inputs)
Paul's avatar
Paul committed
475
        {
Paul's avatar
Format  
Paul committed
476
            if(input.empty())
Paul's avatar
Paul committed
477
                continue;
Paul's avatar
Format  
Paul committed
478
            if(input[0] != '-')
Paul's avatar
Paul committed
479
                continue;
Paul's avatar
Format  
Paul committed
480
            for(const auto& arg : arguments)
Paul's avatar
Paul committed
481
            {
Paul's avatar
Format  
Paul committed
482
                for(const auto& flag : arg.flags)
Paul's avatar
Paul committed
483
                {
Paul's avatar
Format  
Paul committed
484
                    if(flag.empty())
Paul's avatar
Paul committed
485
                        continue;
Paul's avatar
Format  
Paul committed
486
                    if(flag[0] != '-')
Paul's avatar
Paul committed
487
                        continue;
Paul's avatar
Format  
Paul committed
488
489
490
                    auto d =
                        levenshtein_distance(flag.begin(), flag.end(), input.begin(), input.end());
                    if(d < result.distance)
Paul's avatar
Paul committed
491
492
493
494
495
496
497
                        result = result_t{&arg, flag, input, d};
                }
            }
        }
        return result;
    }

Paul's avatar
Format  
Paul committed
498
499
    bool
    run_action(const argument& arg, const std::string& flag, const std::vector<std::string>& inputs)
Paul's avatar
Paul committed
500
501
502
503
    {
        std::string msg = "";
        try
        {
Paul's avatar
Paul committed
504
505
            for(const auto& v:arg.validations)
                v(*this, inputs);
Paul's avatar
Paul committed
506
507
508
509
510
511
512
513
514
515
            return arg.action(*this, inputs);
        }
        catch(const std::exception& e)
        {
            msg = e.what();
        }
        catch(...)
        {
            msg = "unknown exception";
        }
Paul's avatar
Paul committed
516
517
        std::cout << color::fg_red << color::bold << "error: " << color::reset;
        auto sc = spellcheck(inputs);
Paul's avatar
Format  
Paul committed
518
        if(sc.distance < 5)
Paul's avatar
Paul committed
519
        {
Paul's avatar
Paul committed
520
521
            std::cout << "Found argument '" << color::fg_yellow << sc.incorrect << color::reset
                      << "'"
Paul's avatar
Format  
Paul committed
522
                      << " which wasn't expected, or isn't valid in this context" << std::endl;
Paul's avatar
Paul committed
523
            std::cout << "       "
Paul's avatar
Format  
Paul committed
524
                      << "Did you mean " << color::fg_green << sc.correct << color::reset << "?"
Paul's avatar
Format  
Paul committed
525
                      << std::endl;
Paul's avatar
Paul committed
526
527
528
529
530
            std::cout << std::endl;
            print_usage_for(*sc.arg, sc.correct);
        }
        else
        {
Paul's avatar
Paul committed
531
            const auto& flag_name = flag.empty() ? arg.metavar : flag;
Paul's avatar
Paul committed
532
            std::cout << "Invalid input to '" << color::fg_yellow;
Paul's avatar
Paul committed
533
            std::cout << flag_name;
Paul's avatar
Paul committed
534
535
            if(not arg.type.empty())
                std::cout << " [" << arg.type << "]";
Paul's avatar
Paul committed
536
537
538
539
540
            std::cout << color::reset << "'" << std::endl;
            std::cout << "       " << msg << std::endl;
            std::cout << std::endl;
            print_usage_for(arg, flag);
        }
Paul's avatar
Paul committed
541
        std::cout << std::endl;
Paul's avatar
Paul committed
542
        if(has_argument([](const auto& a) { return contains(a.flags, "--help"); }))
Paul's avatar
Paul committed
543
544
        {
            std::cout << std::endl;
Paul's avatar
Format  
Paul committed
545
546
            std::cout << "For more information try '" << color::fg_green << "--help" << color::reset
                      << "'" << std::endl;
Paul's avatar
Paul committed
547
548
549
550
        }
        return true;
    }

Paul's avatar
Paul committed
551
    bool parse(std::vector<std::string> args)
Paul's avatar
Paul committed
552
    {
Paul's avatar
Paul committed
553
        std::unordered_map<std::string, unsigned> keywords;
Paul's avatar
Paul committed
554
        for(auto&& arg : arguments)
Paul's avatar
Paul committed
555
        {
Paul's avatar
Paul committed
556
            for(auto&& flag : arg.flags)
Paul's avatar
Paul committed
557
                keywords[flag] = arg.nargs + 1;
Paul's avatar
Paul committed
558
        }
Paul's avatar
Paul committed
559
560
        auto arg_map =
            generic_parse(std::move(args), [&](const std::string& x) { return keywords[x]; });
Paul's avatar
Paul committed
561
        for(auto&& arg : arguments)
Paul's avatar
Paul committed
562
        {
Paul's avatar
Paul committed
563
            bool used = false;
Paul's avatar
Paul committed
564
            auto flags = arg.flags;
Paul's avatar
Paul committed
565
            if(flags.empty())
Paul's avatar
Paul committed
566
                flags = {""};
Paul's avatar
Paul committed
567
            for(auto&& flag : flags)
Paul's avatar
Paul committed
568
            {
Paul's avatar
Paul committed
569
                if(arg_map.count(flag) > 0)
Paul's avatar
Paul committed
570
                {
Paul's avatar
Paul committed
571
                    if(run_action(arg, flag, arg_map[flag]))
Paul's avatar
Paul committed
572
                        return true;
Paul's avatar
Paul committed
573
                    used = true;
Paul's avatar
Paul committed
574
575
576
                }
            }
        }
Paul's avatar
Format  
Paul committed
577
        for(auto&& action : actions)
578
            action(*this);
Paul's avatar
Paul committed
579
        return false;
Paul's avatar
Paul committed
580
581
    }

Paul's avatar
Format  
Paul committed
582
    void set_exe_name(const std::string& s) { exe_name = s; }
Paul's avatar
Paul committed
583

Paul's avatar
Format  
Paul committed
584
    const std::string& get_exe_name() const { return exe_name; }
Paul's avatar
Paul committed
585

Paul's avatar
Paul committed
586
587
588
589
590
591
592
    using string_map = std::unordered_map<std::string, std::vector<std::string>>;
    template <class IsKeyword>
    static string_map generic_parse(std::vector<std::string> as, IsKeyword is_keyword)
    {
        string_map result;

        std::string flag;
Paul's avatar
Paul committed
593
        bool clear = false;
Paul's avatar
Paul committed
594
595
        for(auto&& x : as)
        {
Paul's avatar
Paul committed
596
597
            auto k = is_keyword(x);
            if(k > 0)
Paul's avatar
Paul committed
598
599
600
            {
                flag = x;
                result[flag]; // Ensure the flag exists
Paul's avatar
Paul committed
601
                if(k == 1)
Paul's avatar
Paul committed
602
                    flag = "";
Paul's avatar
Paul committed
603
                else if(k == 2)
Paul's avatar
Paul committed
604
605
606
                    clear = true;
                else
                    clear = false;
Paul's avatar
Paul committed
607
608
609
610
            }
            else
            {
                result[flag].push_back(x);
Paul's avatar
Paul committed
611
                if(clear)
Paul's avatar
Paul committed
612
613
                    flag = "";
                clear = false;
Paul's avatar
Paul committed
614
615
616
617
            }
        }
        return result;
    }
Paul's avatar
Paul committed
618

Paul's avatar
Paul committed
619
    private:
Paul's avatar
Paul committed
620
621
    std::list<argument> arguments;
    std::string exe_name = "";
622
    std::vector<std::function<void(argument_parser&)>> actions;
Paul's avatar
Paul committed
623
624
};

Paul's avatar
Paul committed
625
626
627
628
} // namespace MIGRAPHX_INLINE_NS
} // namespace driver
} // namespace migraphx

Paul's avatar
Paul committed
629
#endif