1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15
16 /// Command line argument parsing.
17 ///
18 /// The objects defined below can be used to parse command line arguments of
19 /// different types. These objects are "just enough" defined for current use
20 /// cases, but the design is intended to be extensible as new types and traits
21 /// are needed.
22 ///
23 /// Example:
24 ///
25 /// Given a boolean flag "verbose", a numerical flag "runs", and a positional
26 /// "port" argument to be parsed, we can create a vector of parsers. In this
27 /// example, we modify the parsers during creation to set default values:
28 ///
29 /// @code
30 /// Vector<ArgParserVariant, 3> parsers = {
31 /// BoolParser("-v", "--verbose").set_default(false),
32 /// UnsignedParser<size_t>("-r", "--runs").set_default(1000),
33 /// UnsignedParser<uint16_t>("port").set_default(11111),
34 /// };
35 /// @endcode
36 ///
37 /// With this vector, we can then parse command line arguments and extract
38 /// the values of arguments that were set, e.g.:
39 ///
40 /// @code
41 /// if (!ParseArgs(parsers, argc, argv).ok()) {
42 /// PrintUsage(parsers, argv[0]);
43 /// return 1;
44 /// }
45 /// bool verbose;
46 /// size_t runs;
47 /// uint16_t port;
48 /// if (!GetArg(parsers, "--verbose", &verbose).ok() ||
49 /// !GetArg(parsers, "--runs", &runs).ok() ||
50 /// !GetArg(parsers, "port", &port).ok()) {
51 /// // Shouldn't happen unless names do not match.
52 /// return 1;
53 /// }
54 ///
55 /// // Do stuff with `verbose`, `runs`, and `port`...
56 /// @endcode
57
58 #include <cstddef>
59 #include <cstdint>
60 #include <optional>
61 #include <string_view>
62 #include <variant>
63
64 #include "pw_containers/vector.h"
65 #include "pw_status/status.h"
66
67 namespace pw::rpc::fuzz {
68
69 /// Enumerates the results of trying to parse a specific command line argument
70 /// with a particular parsers.
71 enum ParseStatus {
72 /// The argument matched the parser and was successfully parsed without a
73 /// value.
74 kParsedOne,
75
76 /// The argument matched the parser and was successfully parsed with a value.
77 kParsedTwo,
78
79 /// The argument did not match the parser. This is not necessarily an error;
80 /// the argument may match a different parser.
81 kParseMismatch,
82
83 /// The argument matched a parser, but could not be parsed. This may be due to
84 /// a missing value for a flag, a value of the wrong type, a provided value
85 /// being out of range, etc. Parsers should log additional details before
86 /// returning this value.
87 kParseFailure,
88 };
89
90 /// Holds parsed argument values of different types.
91 using ArgVariant = std::variant<std::monostate, bool, uint64_t>;
92
93 /// Base class for argument parsers.
94 class ArgParserBase {
95 public:
96 virtual ~ArgParserBase() = default;
97
short_name()98 std::string_view short_name() const { return short_name_; }
long_name()99 std::string_view long_name() const { return long_name_; }
positional()100 bool positional() const { return positional_; }
101
102 /// Clears the value. Typically, command line arguments are only parsed once,
103 /// but this method is useful for testing.
Reset()104 void Reset() { value_ = std::monostate(); }
105
106 protected:
107 /// Defines an argument parser with a single name. This may be a positional
108 /// argument or a flag.
109 ArgParserBase(std::string_view name);
110
111 /// Defines an argument parser for a flag with short and long names.
112 ArgParserBase(std::string_view shortopt, std::string_view longopt);
113
set_initial(ArgVariant initial)114 void set_initial(ArgVariant initial) { initial_ = initial; }
set_value(ArgVariant value)115 void set_value(ArgVariant value) { value_ = value; }
116
117 /// Examines if the given `arg` matches this parser. A parser for a flag can
118 /// match the short name (e.g. '-f') if set, or the long name (e.g. '--foo').
119 /// A parser for a positional argument will match anything until it has a
120 /// value set.
121 bool Match(std::string_view arg);
122
123 /// Returns the parsed value.
124 template <typename T>
Get()125 T Get() const {
126 return std::get<T>(GetValue());
127 }
128
129 private:
130 const ArgVariant& GetValue() const;
131
132 std::string_view short_name_;
133 std::string_view long_name_;
134 bool positional_;
135
136 ArgVariant initial_;
137 ArgVariant value_;
138 };
139
140 // Argument parsers for boolean arguments. These arguments are always flags, and
141 // can be specified as, e.g. "-f" (true), "--foo" (true) or "--no-foo" (false).
142 class BoolParser : public ArgParserBase {
143 public:
144 BoolParser(std::string_view optname);
145 BoolParser(std::string_view shortopt, std::string_view longopt);
146
value()147 bool value() const { return Get<bool>(); }
148 BoolParser& set_default(bool value);
149
150 ParseStatus Parse(std::string_view arg0,
151 std::string_view arg1 = std::string_view());
152 };
153
154 // Type-erasing argument parser for unsigned integer arguments. This object
155 // always parses values as `uint64_t`s and should not be used directly.
156 // Instead, use `UnsignedParser<T>` with a type to explicitly narrow to.
157 class UnsignedParserBase : public ArgParserBase {
158 protected:
159 UnsignedParserBase(std::string_view name);
160 UnsignedParserBase(std::string_view shortopt, std::string_view longopt);
161
162 ParseStatus Parse(std::string_view arg0, std::string_view arg1, uint64_t max);
163 };
164
165 // Argument parser for unsigned integer arguments. These arguments may be flags
166 // or positional arguments.
167 template <typename T, typename std::enable_if_t<std::is_unsigned_v<T>, int> = 0>
168 class UnsignedParser : public UnsignedParserBase {
169 public:
UnsignedParser(std::string_view name)170 UnsignedParser(std::string_view name) : UnsignedParserBase(name) {}
UnsignedParser(std::string_view shortopt,std::string_view longopt)171 UnsignedParser(std::string_view shortopt, std::string_view longopt)
172 : UnsignedParserBase(shortopt, longopt) {}
173
value()174 T value() const { return static_cast<T>(Get<uint64_t>()); }
175
set_default(T value)176 UnsignedParser& set_default(T value) {
177 set_initial(static_cast<uint64_t>(value));
178 return *this;
179 }
180
181 ParseStatus Parse(std::string_view arg0,
182 std::string_view arg1 = std::string_view()) {
183 return UnsignedParserBase::Parse(arg0, arg1, std::numeric_limits<T>::max());
184 }
185 };
186
187 // Holds argument parsers of different types.
188 using ArgParserVariant =
189 std::variant<BoolParser, UnsignedParser<uint16_t>, UnsignedParser<size_t>>;
190
191 // Parses the command line arguments and sets the values of the given `parsers`.
192 Status ParseArgs(Vector<ArgParserVariant>& parsers, int argc, char** argv);
193
194 // Logs a usage message based on the given `parsers` and the program name given
195 // by `argv0`.
196 void PrintUsage(const Vector<ArgParserVariant>& parsers,
197 std::string_view argv0);
198
199 // Attempts to find the parser in `parsers` with the given `name`, and returns
200 // its value if found.
201 std::optional<ArgVariant> GetArg(const Vector<ArgParserVariant>& parsers,
202 std::string_view name);
203
GetArgValue(const ArgVariant & arg,bool * out)204 inline void GetArgValue(const ArgVariant& arg, bool* out) {
205 *out = std::get<bool>(arg);
206 }
207
208 template <typename T, typename std::enable_if_t<std::is_unsigned_v<T>, int> = 0>
GetArgValue(const ArgVariant & arg,T * out)209 void GetArgValue(const ArgVariant& arg, T* out) {
210 *out = static_cast<T>(std::get<uint64_t>(arg));
211 }
212
213 // Like `GetArgVariant` above, but extracts the typed value from the variant
214 // into `out`. Returns an error if no parser exists in `parsers` with the given
215 // `name`.
216 template <typename T>
GetArg(const Vector<ArgParserVariant> & parsers,std::string_view name,T * out)217 Status GetArg(const Vector<ArgParserVariant>& parsers,
218 std::string_view name,
219 T* out) {
220 const auto& arg = GetArg(parsers, name);
221 if (!arg.has_value()) {
222 return Status::InvalidArgument();
223 }
224 GetArgValue(*arg, out);
225 return OkStatus();
226 }
227
228 // Resets the parser with the given name. Returns an error if not found.
229 Status ResetArg(Vector<ArgParserVariant>& parsers, std::string_view name);
230
231 } // namespace pw::rpc::fuzz
232