• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2017-2020 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #ifndef ARM_COMPUTE_UTILS_COMMANDLINEPARSER
25 #define ARM_COMPUTE_UTILS_COMMANDLINEPARSER
26 
27 #include "Option.h"
28 #include "arm_compute/core/utils/misc/Utility.h"
29 #include "support/MemorySupport.h"
30 
31 #include <iostream>
32 #include <map>
33 #include <memory>
34 #include <regex>
35 #include <string>
36 #include <utility>
37 #include <vector>
38 
39 namespace arm_compute
40 {
41 namespace utils
42 {
43 /** Class to parse command line arguments. */
44 class CommandLineParser final
45 {
46 public:
47     /** Default constructor. */
48     CommandLineParser() = default;
49 
50     /** Function to add a new option to the parser.
51      *
52      * @param[in] name Name of the option. Will be available under --name=VALUE.
53      * @param[in] args Option specific configuration arguments.
54      *
55      * @return Pointer to the option. The option is owned by the parser.
56      */
57     template <typename T, typename... As>
58     T *add_option(const std::string &name, As &&... args);
59 
60     /** Function to add a new positional argument to the parser.
61      *
62      * @param[in] args Option specific configuration arguments.
63      *
64      * @return Pointer to the option. The option is owned by the parser.
65      */
66     template <typename T, typename... As>
67     T *add_positional_option(As &&... args);
68 
69     /** Parses the command line arguments and updates the options accordingly.
70      *
71      * @param[in] argc Number of arguments.
72      * @param[in] argv Arguments.
73      */
74     void parse(int argc, char **argv);
75 
76     /** Validates the previously parsed command line arguments.
77      *
78      * Validation fails if not all required options are provided. Additionally
79      * warnings are generated for options that have illegal values or unknown
80      * options.
81      *
82      * @return True if all required options have been provided.
83      */
84     bool validate() const;
85 
86     /** Prints a help message for all configured options.
87      *
88      * @param[in] program_name Name of the program to be used in the help message.
89      */
90     void print_help(const std::string &program_name) const;
91 
92 private:
93     using OptionsMap              = std::map<std::string, std::unique_ptr<Option>>;
94     using PositionalOptionsVector = std::vector<std::unique_ptr<Option>>;
95 
96     OptionsMap               _options{};
97     PositionalOptionsVector  _positional_options{};
98     std::vector<std::string> _unknown_options{};
99     std::vector<std::string> _invalid_options{};
100 };
101 
102 template <typename T, typename... As>
add_option(const std::string & name,As &&...args)103 inline T *CommandLineParser::add_option(const std::string &name, As &&... args)
104 {
105     auto result = _options.emplace(name, support::cpp14::make_unique<T>(name, std::forward<As>(args)...));
106     return static_cast<T *>(result.first->second.get());
107 }
108 
109 template <typename T, typename... As>
add_positional_option(As &&...args)110 inline T *CommandLineParser::add_positional_option(As &&... args)
111 {
112     _positional_options.emplace_back(support::cpp14::make_unique<T>(std::forward<As>(args)...));
113     return static_cast<T *>(_positional_options.back().get());
114 }
115 
parse(int argc,char ** argv)116 inline void CommandLineParser::parse(int argc, char **argv)
117 {
118     const std::regex option_regex{ "--((?:no-)?)([^=]+)(?:=(.*))?" };
119 
120     const auto set_option = [&](const std::string & option, const std::string & name, const std::string & value)
121     {
122         if(_options.find(name) == _options.end())
123         {
124             _unknown_options.push_back(option);
125             return;
126         }
127 
128         const bool success = _options[name]->parse(value);
129 
130         if(!success)
131         {
132             _invalid_options.push_back(option);
133         }
134     };
135 
136     unsigned int positional_index = 0;
137 
138     for(int i = 1; i < argc; ++i)
139     {
140         std::string mixed_case_opt{ argv[i] };
141         int         equal_sign = mixed_case_opt.find('=');
142         int         pos        = (equal_sign == -1) ? strlen(argv[i]) : equal_sign;
143 
144         const std::string option = arm_compute::utility::tolower(mixed_case_opt.substr(0, pos)) + mixed_case_opt.substr(pos);
145         std::smatch       option_matches;
146 
147         if(std::regex_match(option, option_matches, option_regex))
148         {
149             // Boolean option
150             if(option_matches.str(3).empty())
151             {
152                 set_option(option, option_matches.str(2), option_matches.str(1).empty() ? "true" : "false");
153             }
154             else
155             {
156                 // Can't have "no-" and a value
157                 if(!option_matches.str(1).empty())
158                 {
159                     _invalid_options.emplace_back(option);
160                 }
161                 else
162                 {
163                     set_option(option, option_matches.str(2), option_matches.str(3));
164                 }
165             }
166         }
167         else
168         {
169             if(positional_index >= _positional_options.size())
170             {
171                 _invalid_options.push_back(mixed_case_opt);
172             }
173             else
174             {
175                 _positional_options[positional_index]->parse(mixed_case_opt);
176                 ++positional_index;
177             }
178         }
179     }
180 }
181 
validate()182 inline bool CommandLineParser::validate() const
183 {
184     bool is_valid = true;
185 
186     for(const auto &option : _options)
187     {
188         if(option.second->is_required() && !option.second->is_set())
189         {
190             is_valid = false;
191             std::cerr << "ERROR: Option '" << option.second->name() << "' is required but not given!\n";
192         }
193     }
194 
195     for(const auto &option : _positional_options)
196     {
197         if(option->is_required() && !option->is_set())
198         {
199             is_valid = false;
200             std::cerr << "ERROR: Option '" << option->name() << "' is required but not given!\n";
201         }
202     }
203 
204     for(const auto &option : _unknown_options)
205     {
206         std::cerr << "WARNING: Skipping unknown option '" << option << "'!\n";
207     }
208 
209     for(const auto &option : _invalid_options)
210     {
211         std::cerr << "WARNING: Skipping invalid option '" << option << "'!\n";
212     }
213 
214     return is_valid;
215 }
216 
print_help(const std::string & program_name)217 inline void CommandLineParser::print_help(const std::string &program_name) const
218 {
219     std::cout << "usage: " << program_name << " \n";
220 
221     for(const auto &option : _options)
222     {
223         std::cout << option.second->help() << "\n";
224     }
225 
226     for(const auto &option : _positional_options)
227     {
228         std::string help_to_print;
229 
230         // Extract help sub-string
231         const std::string help_str = option->help();
232         const size_t      help_pos = help_str.find(" - ");
233         if(help_pos != std::string::npos)
234         {
235             help_to_print = help_str.substr(help_pos);
236         }
237 
238         std::cout << option->name() << help_to_print << "\n";
239     }
240 }
241 } // namespace utils
242 } // namespace arm_compute
243 #endif /* ARM_COMPUTE_UTILS_COMMANDLINEPARSER */
244