command.hpp 1.66 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef MIGRAPHX_GUARD_RTGLIB_COMMAND_HPP
#define MIGRAPHX_GUARD_RTGLIB_COMMAND_HPP

#include "argument_parser.hpp"

#include <migraphx/config.hpp>
#include <migraphx/type_name.hpp>

#include <unordered_map>
#include <vector>

namespace migraphx {
namespace driver {
inline namespace MIGRAPHX_INLINE_NS {

inline auto& get_commands()
{
    static std::unordered_map<std::string, std::function<void(std::vector<std::string> args)>> m;
    return m;
}

Paul's avatar
Paul committed
22
template <class T>
Paul's avatar
Paul committed
23
24
25
26
27
28
std::string command_name()
{
    static const std::string& name = get_type_name<T>();
    return name.substr(name.rfind("::") + 2);
}

Paul's avatar
Paul committed
29
30
31
32
33
34
35
36
37
38
39
40
41
template<class T>
void run_command(std::vector<std::string> args, bool add_help=false)
{
    T x;
    argument_parser ap;
    if (add_help)
        ap.add(nullptr, {"-h", "--help"}, ap.help("Show help"), ap.show_help());
    x.parse(ap);
    if (ap.parse(args))
        return;
    x.run();
}

Paul's avatar
Paul committed
42
43
44
template <class T>
int auto_register_command()
{
Paul's avatar
Paul committed
45
    auto& m              = get_commands();
Paul's avatar
Paul committed
46
    m[command_name<T>()] = [](std::vector<std::string> args) {
Paul's avatar
Paul committed
47
        run_command<T>(args, true);
Paul's avatar
Paul committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    };
    return 0;
}

template <class T>
struct command
{
    static int static_register;
    // This typedef ensures that the static member will be instantiated if
    // the class itself is instantiated
    using static_register_type =
        std::integral_constant<decltype(&static_register), &static_register>;
};

Paul's avatar
Paul committed
62
63
64
65
66
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif

Paul's avatar
Paul committed
67
68
69
70
71
72
73
74
template <class T>
int command<T>::static_register = auto_register_command<T>(); // NOLINT

} // namespace MIGRAPHX_INLINE_NS
} // namespace driver
} // namespace migraphx

#endif