argument_parser.hpp 23.4 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>
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>
36
#include <unordered_set>
Paul's avatar
Paul committed
37
#include <utility>
Paul's avatar
Paul committed
38
39
#include <vector>

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

50
51
52
53
#ifndef _WIN32
#include <unistd.h>
#endif

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

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

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

namespace detail {

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

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
84
    std::integral_constant<bool, (is_container<T>{} and not std::is_convertible<T, std::string>{})>;
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
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";
108
109
#else
    (void)c;
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
#endif
    return os;
}

inline std::string colorize(color c, const std::string& s)
{
    std::stringstream ss;
    ss << c << s << color::reset;
    return ss.str();
}

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
147
148
149
template <class T>
struct value_parser
{
Paul's avatar
Paul committed
150
    template <MIGRAPHX_REQUIRES(not std::is_enum<T>{} and not is_multi_value<T>{})>
Paul's avatar
Paul committed
151
152
    static T apply(const std::string& x)
    {
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
        // handle whitespace in string
        if constexpr(std::is_same<T, std::string>{})
        {
            return x;
        }
        else
        {
            T result;
            std::stringstream ss;
            ss.str(x);
            ss >> result;
            if(ss.fail())
                throw std::runtime_error("Failed to parse '" + x + "' as " + type_name<T>::apply());
            return result;
        }
Paul's avatar
Paul committed
168
169
    }

Paul's avatar
Paul committed
170
    template <MIGRAPHX_REQUIRES(std::is_enum<T>{} and not is_multi_value<T>{})>
Paul's avatar
Paul committed
171
172
173
174
175
176
177
    static T apply(const std::string& x)
    {
        std::ptrdiff_t i;
        std::stringstream ss;
        ss.str(x);
        ss >> i;
        if(ss.fail())
178
            throw std::runtime_error("Failed to parse '" + x + "' as " + type_name<T>::apply());
Paul's avatar
Paul committed
179
180
        return static_cast<T>(i);
    }
Paul's avatar
Paul committed
181
182
183
184
185
186
187
188
189

    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
190
191
};

192
193
194
195
196
197
198
// version for std::optional object
template <class T>
struct value_parser<std::optional<T>>
{
    static T apply(const std::string& x) { return value_parser<T>::apply(x); }
};

Paul's avatar
Paul committed
199
200
201
202
struct argument_parser
{
    struct argument
    {
203
204
205
206
        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
207
        std::vector<std::string> flags;
208
        action_function action{};
Paul's avatar
Paul committed
209
210
211
        std::string type          = "";
        std::string help          = "";
        std::string metavar       = "";
Paul's avatar
Paul committed
212
        std::string default_value = "";
213
        std::string group         = "";
Paul's avatar
Paul committed
214
        unsigned nargs            = 1;
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        bool required             = false;
        std::vector<validate_function> validations{};

        std::string usage(const std::string& flag) const
        {
            std::stringstream ss;
            if(flag.empty())
            {
                ss << metavar;
            }
            else
            {
                ss << flag;
                if(not type.empty())
                    ss << " [" << type << "]";
            }
            return ss.str();
        }
        std::string usage() const
        {
            if(flags.empty())
                return usage("");
            return usage(flags.front());
        }
Paul's avatar
Paul committed
239
240
    };

Paul's avatar
Paul committed
241
    template <class T, MIGRAPHX_REQUIRES(is_multi_value<T>{})>
Paul's avatar
Paul committed
242
243
244
245
246
    std::string as_string_value(const T& x)
    {
        return to_string_range(x);
    }

kahmed10's avatar
kahmed10 committed
247
248
249
250
251
252
253
254
255
256
257
258
    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
259
    template <class T, MIGRAPHX_REQUIRES(not is_multi_value<T>{})>
Paul's avatar
Paul committed
260
261
    std::string as_string_value(const T& x)
    {
kahmed10's avatar
kahmed10 committed
262
        return as_string_value(rank<1>{}, x);
Paul's avatar
Paul committed
263
264
    }

Paul's avatar
Paul committed
265
    template <class T, class... Fs>
Paul's avatar
Paul committed
266
    void operator()(T& x, const std::vector<std::string>& flags, Fs... fs)
Paul's avatar
Paul committed
267
    {
Paul's avatar
Paul committed
268
        arguments.push_back({flags, [&](auto&&, const std::vector<std::string>& params) {
Paul's avatar
Paul committed
269
270
                                 if(params.empty())
                                     throw std::runtime_error("Flag with no value.");
271
272
                                 if(not is_multi_value<T>{} and params.size() > 1)
                                     throw std::runtime_error("Too many arguments passed.");
Paul's avatar
Paul committed
273
274
275
                                 x = value_parser<T>::apply(params.back());
                                 return false;
                             }});
Paul's avatar
Paul committed
276

kahmed10's avatar
kahmed10 committed
277
        argument& arg = arguments.back();
278
        arg.type      = type_name<T>::apply();
Paul's avatar
Paul committed
279
        migraphx::each_args([&](auto f) { f(x, arg); }, fs...);
kahmed10's avatar
kahmed10 committed
280
281
        if(not arg.default_value.empty() and arg.nargs > 0)
            arg.default_value = as_string_value(x);
Paul's avatar
Paul committed
282
283
    }

Paul's avatar
Paul committed
284
    template <class... Fs>
Paul's avatar
Paul committed
285
    void operator()(std::nullptr_t x, std::vector<std::string> flags, Fs... fs)
Paul's avatar
Paul committed
286
    {
Paul's avatar
Paul committed
287
        arguments.push_back({std::move(flags)});
Paul's avatar
Paul committed
288
289
290

        argument& arg = arguments.back();
        arg.type      = "";
Paul's avatar
Paul committed
291
        arg.nargs     = 0;
Paul's avatar
Paul committed
292
293
294
        migraphx::each_args([&](auto f) { f(x, arg); }, fs...);
    }

Paul's avatar
Paul committed
295
    MIGRAPHX_DRIVER_STATIC auto nargs(unsigned n = 1)
Paul's avatar
Paul committed
296
    {
Paul's avatar
Paul committed
297
        return [=](auto&&, auto& arg) { arg.nargs = n; };
Paul's avatar
Paul committed
298
299
    }

300
301
302
303
304
    MIGRAPHX_DRIVER_STATIC auto required()
    {
        return [=](auto&&, auto& arg) { arg.required = true; };
    }

Paul's avatar
Paul committed
305
    template <class F>
Paul's avatar
Paul committed
306
    MIGRAPHX_DRIVER_STATIC auto write_action(F f)
Paul's avatar
Paul committed
307
308
    {
        return [=](auto& x, auto& arg) {
Paul's avatar
Paul committed
309
            arg.action = [&, f](auto& self, const std::vector<std::string>& params) {
Paul's avatar
Paul committed
310
311
312
313
314
315
                f(self, x, params);
                return false;
            };
        };
    }

Paul's avatar
Paul committed
316
    template <class F>
Paul's avatar
Paul committed
317
    MIGRAPHX_DRIVER_STATIC auto do_action(F f)
Paul's avatar
Paul committed
318
319
    {
        return [=](auto&, auto& arg) {
Paul's avatar
Paul committed
320
            arg.nargs  = 0;
Paul's avatar
Paul committed
321
            arg.action = [&, f](auto& self, const std::vector<std::string>&) {
Paul's avatar
Paul committed
322
323
324
325
326
327
                f(self);
                return true;
            };
        };
    }

Paul's avatar
Paul committed
328
    MIGRAPHX_DRIVER_STATIC auto append()
Paul's avatar
Paul committed
329
    {
Paul's avatar
Paul committed
330
        return write_action([](auto&, auto& x, auto& params) {
Paul's avatar
Paul committed
331
            using type = typename bare<decltype(params)>::value_type;
Paul's avatar
Paul committed
332
            std::transform(params.begin(),
Paul's avatar
Paul committed
333
334
                           params.end(),
                           std::inserter(x, x.end()),
Paul's avatar
Paul committed
335
336
                           [](std::string y) { return value_parser<type>::apply(y); });
        });
Paul's avatar
Paul committed
337
338
    }

339
340
341
342
343
344
345
346
347
348
349
    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()
    {
350
        return validate([](auto&, auto&, const auto& params) {
351
352
353
            if(params.empty())
                throw std::runtime_error("No argument passed.");
            if(not fs::exists(params.back()))
354
355
356
357
358
359
                throw std::runtime_error("Path does not exist: " + params.back());
        });
    }

    MIGRAPHX_DRIVER_STATIC auto matches(const std::unordered_set<std::string>& names)
    {
360
361
362
363
364
365
        return validate([=](auto&, auto&, const auto& params) {
            auto invalid_param = std::find_if(
                params.begin(), params.end(), [&](const auto& p) { return names.count(p) == 0; });
            if(invalid_param != params.end())
                throw std::runtime_error("Invalid argument: " + *invalid_param +
                                         ". Valid arguments are {" + to_string_range(names) + "}");
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
        });
    }

    template <class F>
    argument* find_argument(F f)
    {
        auto it = std::find_if(arguments.begin(), arguments.end(), f);
        if(it == arguments.end())
            return nullptr;
        return std::addressof(*it);
    }
    template <class F>
    bool has_argument(F f)
    {
        return find_argument(f) != nullptr;
    }

    template <class F>
    std::vector<argument*> find_arguments(F f)
    {
        std::vector<argument*> result;
        for(auto& arg : arguments)
        {
            if(not f(arg))
                continue;
            result.push_back(&arg);
        }
        return result;
    }

    std::vector<argument*> get_group_arguments(const std::string& group)
    {
        return find_arguments([&](const auto& arg) { return arg.group == group; });
    }

    std::vector<argument*> get_required_arguments()
    {
        return find_arguments([&](const auto& arg) { return arg.required; });
    }

    template <class SequenceContainer>
    std::vector<std::string> get_argument_usages(SequenceContainer args)
    {
        std::vector<std::string> usage_flags;
        std::unordered_set<std::string> found_groups;
        // Remove arguments that belong to a group
        auto it = std::remove_if(args.begin(), args.end(), [&](const argument* arg) {
            if(arg->group.empty())
                return false;
            found_groups.insert(arg->group);
            return true;
        });
        args.erase(it, args.end());
        transform(found_groups, std::back_inserter(usage_flags), [&](auto&& group) {
            std::vector<std::string> either_flags;
            transform(get_group_arguments(group), std::back_inserter(either_flags), [](auto* arg) {
                return arg->usage();
            });
            return "(" + join_strings(either_flags, "|") + ")";
        });
        transform(args, std::back_inserter(usage_flags), [&](auto* arg) { return arg->usage(); });
        return usage_flags;
    }

    auto show_help(const std::string& msg = "")
Paul's avatar
Paul committed
431
    {
Paul's avatar
Paul committed
432
        return do_action([=](auto& self) {
433
434
435
436
437
438
439
440
441
            argument* input_argument =
                self.find_argument([](const auto& arg) { return arg.flags.empty(); });
            auto required_usages = get_argument_usages(get_required_arguments());
            if(required_usages.empty() && input_argument)
                required_usages.push_back(input_argument->metavar);
            required_usages.insert(required_usages.begin(), "<options>");
            print_usage(required_usages);
            std::cout << std::endl;
            if(self.find_argument([](const auto& arg) { return arg.nargs == 0; }))
Paul's avatar
Paul committed
442
            {
443
                std::cout << color::fg_yellow << "FLAGS:" << color::reset << std::endl;
Paul's avatar
Paul committed
444
                std::cout << std::endl;
445
                for(auto&& arg : self.arguments)
Paul's avatar
Paul committed
446
                {
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
                    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
472
                }
473
474
475
476
477
478
                std::cout << std::endl;
            }
            if(self.find_argument([](const auto& arg) { return arg.nargs != 0; }))
            {
                std::cout << color::fg_yellow << "OPTIONS:" << color::reset << std::endl;
                for(auto&& arg : self.arguments)
Paul's avatar
Paul committed
479
                {
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
                    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
505
                }
Paul's avatar
Paul committed
506
507
                std::cout << std::endl;
            }
Paul's avatar
Paul committed
508
            if(not msg.empty())
Paul's avatar
Paul committed
509
                std::cout << msg << std::endl;
Paul's avatar
Paul committed
510
511
512
        });
    }

Paul's avatar
Paul committed
513
    MIGRAPHX_DRIVER_STATIC auto help(const std::string& help)
Paul's avatar
Paul committed
514
    {
Paul's avatar
Paul committed
515
        return [=](auto&, auto& arg) { arg.help = help; };
Paul's avatar
Paul committed
516
517
    }

Paul's avatar
Paul committed
518
    MIGRAPHX_DRIVER_STATIC auto metavar(const std::string& metavar)
Paul's avatar
Paul committed
519
520
521
522
    {
        return [=](auto&, auto& arg) { arg.metavar = metavar; };
    }

523
524
525
526
527
    MIGRAPHX_DRIVER_STATIC auto type(const std::string& type)
    {
        return [=](auto&, auto& arg) { arg.type = type; };
    }

528
529
530
531
532
    MIGRAPHX_DRIVER_STATIC auto group(const std::string& group)
    {
        return [=](auto&, auto& arg) { arg.group = group; };
    }

Paul's avatar
Paul committed
533
    template <class T>
Paul's avatar
Paul committed
534
    MIGRAPHX_DRIVER_STATIC auto set_value(T value)
Paul's avatar
Paul committed
535
536
    {
        return [=](auto& x, auto& arg) {
Paul's avatar
Paul committed
537
            arg.nargs  = 0;
Paul's avatar
Paul committed
538
            arg.type   = "";
Paul's avatar
Paul committed
539
            arg.action = [&, value](auto&, const std::vector<std::string>&) {
Paul's avatar
Paul committed
540
541
542
543
544
545
                x = value;
                return false;
            };
        };
    }

546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    template <class T>
    void set_exe_name_to(T& x)
    {
        actions.push_back([&](const auto& self) { x = self.exe_name; });
    }

    void print_try_help()
    {
        if(has_argument([](const auto& a) { return contains(a.flags, "--help"); }))
        {
            std::cout << std::endl;
            std::cout << "For more information try '" << color::fg_green << "--help" << color::reset
                      << "'" << std::endl;
        }
    }

    void print_usage(const std::vector<std::string>& flags) const
    {
        std::cout << color::fg_yellow << "USAGE:" << color::reset << std::endl;
        std::cout << "    " << exe_name << " ";
        std::cout << join_strings(flags, " ") << std::endl;
    }

    auto spellcheck(const std::vector<std::string>& inputs)
    {
        struct result_t
        {
            const argument* arg     = nullptr;
            std::string correct     = "";
            std::string incorrect   = "";
            std::ptrdiff_t distance = std::numeric_limits<std::ptrdiff_t>::max();
        };
        result_t result;
        for(const auto& input : inputs)
        {
            if(input.empty())
                continue;
            if(input[0] != '-')
                continue;
            for(const auto& arg : arguments)
            {
                for(const auto& flag : arg.flags)
                {
                    if(flag.empty())
                        continue;
                    if(flag[0] != '-')
                        continue;
593
                    std::ptrdiff_t d = levenshtein_distance(flag, input);
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
                    if(d < result.distance)
                        result = result_t{&arg, flag, input, d};
                }
            }
        }
        return result;
    }

    bool
    run_action(const argument& arg, const std::string& flag, const std::vector<std::string>& inputs)
    {
        std::string msg = "";
        try
        {
            for(const auto& v : arg.validations)
                v(*this, inputs);
            return arg.action(*this, inputs);
        }
        catch(const std::exception& e)
        {
            msg = e.what();
        }
        catch(...)
        {
            msg = "unknown exception";
        }
        std::cout << color::fg_red << color::bold << "error: " << color::reset;
        auto sc = spellcheck(inputs);
        if(sc.distance < 5)
        {
            std::cout << "Found argument '" << color::fg_yellow << sc.incorrect << color::reset
                      << "'"
                      << " which wasn't expected, or isn't valid in this context" << std::endl;
            std::cout << "       "
                      << "Did you mean " << color::fg_green << sc.correct << color::reset << "?"
                      << std::endl;
            std::cout << std::endl;
            print_usage({sc.arg->usage(sc.correct)});
        }
        else
        {
            const auto& flag_name = flag.empty() ? arg.metavar : flag;
            std::cout << "Invalid input to '" << color::fg_yellow;
            std::cout << arg.usage(flag_name);
            std::cout << color::reset << "'" << std::endl;
            std::cout << "       " << msg << std::endl;
            std::cout << std::endl;
            print_usage({arg.usage()});
        }
        std::cout << std::endl;
        print_try_help();
        return true;
    }

Paul's avatar
Paul committed
648
    bool parse(std::vector<std::string> args)
Paul's avatar
Paul committed
649
    {
Paul's avatar
Paul committed
650
        std::unordered_map<std::string, unsigned> keywords;
Paul's avatar
Paul committed
651
        for(auto&& arg : arguments)
Paul's avatar
Paul committed
652
        {
Paul's avatar
Paul committed
653
            for(auto&& flag : arg.flags)
Paul's avatar
Paul committed
654
                keywords[flag] = arg.nargs + 1;
Paul's avatar
Paul committed
655
        }
Paul's avatar
Paul committed
656
657
        auto arg_map =
            generic_parse(std::move(args), [&](const std::string& x) { return keywords[x]; });
658
659
        std::list<const argument*> missing_arguments;
        std::unordered_set<std::string> groups_used;
Paul's avatar
Paul committed
660
        for(auto&& arg : arguments)
Paul's avatar
Paul committed
661
        {
662
            bool used  = false;
Paul's avatar
Paul committed
663
            auto flags = arg.flags;
Paul's avatar
Paul committed
664
            if(flags.empty())
Paul's avatar
Paul committed
665
                flags = {""};
Paul's avatar
Paul committed
666
            for(auto&& flag : flags)
Paul's avatar
Paul committed
667
            {
Paul's avatar
Paul committed
668
                if(arg_map.count(flag) > 0)
Paul's avatar
Paul committed
669
                {
670
                    if(run_action(arg, flag, arg_map[flag]))
Paul's avatar
Paul committed
671
                        return true;
672
                    used = true;
Paul's avatar
Paul committed
673
674
                }
            }
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
            if(used and not arg.group.empty())
                groups_used.insert(arg.group);
            if(arg.required and not used)
                missing_arguments.push_back(&arg);
        }
        // Remove arguments from a group that is being used
        missing_arguments.remove_if(
            [&](const argument* arg) { return groups_used.count(arg->group); });
        if(not missing_arguments.empty())
        {
            std::cout << color::fg_red << color::bold << "error: " << color::reset;
            std::cout << "The following required arguments were not provided:" << std::endl;
            std::cout << "       " << color::fg_red
                      << join_strings(get_argument_usages(std::move(missing_arguments)), " ")
                      << color::reset << std::endl;
            std::cout << std::endl;
            auto required_usages = get_argument_usages(get_required_arguments());
            print_usage(required_usages);
            print_try_help();
            return true;
Paul's avatar
Paul committed
695
        }
696
697
        for(auto&& action : actions)
            action(*this);
Paul's avatar
Paul committed
698
        return false;
Paul's avatar
Paul committed
699
700
    }

701
702
703
704
    void set_exe_name(const std::string& s) { exe_name = s; }

    const std::string& get_exe_name() const { return exe_name; }

Paul's avatar
Paul committed
705
706
707
708
709
710
711
    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
712
        bool clear = false;
Paul's avatar
Paul committed
713
714
        for(auto&& x : as)
        {
Paul's avatar
Paul committed
715
716
            auto k = is_keyword(x);
            if(k > 0)
Paul's avatar
Paul committed
717
718
719
            {
                flag = x;
                result[flag]; // Ensure the flag exists
Paul's avatar
Paul committed
720
                if(k == 1)
Paul's avatar
Paul committed
721
                    flag = "";
Paul's avatar
Paul committed
722
                else if(k == 2)
Paul's avatar
Paul committed
723
724
725
                    clear = true;
                else
                    clear = false;
Paul's avatar
Paul committed
726
727
728
729
            }
            else
            {
                result[flag].push_back(x);
Paul's avatar
Paul committed
730
                if(clear)
Paul's avatar
Paul committed
731
732
                    flag = "";
                clear = false;
Paul's avatar
Paul committed
733
734
735
736
            }
        }
        return result;
    }
Paul's avatar
Paul committed
737

Paul's avatar
Paul committed
738
    private:
739
740
741
    std::list<argument> arguments;
    std::string exe_name = "";
    std::vector<std::function<void(argument_parser&)>> actions;
Paul's avatar
Paul committed
742
743
};

Paul's avatar
Paul committed
744
745
746
747
} // namespace MIGRAPHX_INLINE_NS
} // namespace driver
} // namespace migraphx

Paul's avatar
Paul committed
748
#endif