Debian Codegraph @

tools/flags/CommandLineFlags.h

raw
1 /*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SK_COMMAND_LINE_FLAGS_H
9 #define SK_COMMAND_LINE_FLAGS_H
10
11 #include "include/core/SkString.h"
12 #include "include/private/base/SkMacros.h"
13 #include "include/private/base/SkTArray.h"
14 #include "include/private/base/SkTDArray.h"
15 #include "src/core/SkTHash.h"
16
17 /**
18 * Including this file (and compiling CommandLineFlags.cpp) provides command line
19 * parsing. In order to use it, use the following macros in global
20 * namespace:
21 *
22 * DEFINE_bool(name, defaultValue, helpString);
23 * DEFINE_string(name, defaultValue, helpString);
24 * DEFINE_int(name, defaultValue, helpString);
25 * DEFINE_double(name, defaultValue, helpString);
26 *
27 * Then, in main, call CommandLineFlags::SetUsage() to describe usage and call
28 * CommandLineFlags::Parse() to parse the flags. Henceforth, each flag can
29 * be referenced using
30 *
31 * FLAGS_name
32 *
33 * For example, the line
34 *
35 * DEFINE_bool(boolean, false, "The variable boolean does such and such");
36 *
37 * will create the following variable:
38 *
39 * bool FLAGS_boolean;
40 *
41 * which will initially be set to false, and can be set to true by using the
42 * flag "--boolean" on the commandline. "--noboolean" will set FLAGS_boolean
43 * to false. FLAGS_boolean can also be set using "--boolean=true" or
44 * "--boolean true" (where "true" can be replaced by "false", "TRUE", "FALSE",
45 * "1" or "0").
46 *
47 * The helpString will be printed if the help flag (-h or -help) is used.
48 *
49 * Similarly, the line
50 *
51 * DEFINE_int(integer, .., ..);
52 *
53 * will create
54 *
55 * int FLAGS_integer;
56 *
57 * and
58 *
59 * DEFINE_double(real, .., ..);
60 *
61 * will create
62 *
63 * double FLAGS_real;
64 *
65 * These flags can be set by specifying, for example, "--integer 7" and
66 * "--real 3.14" on the command line. Unsigned integers are parsed from the
67 * command line using strtoul() so will detect the base (0 for octal, and
68 * 0x or 0X for hex, otherwise assumes decimal).
69 *
70 * Unlike the others, the line
71 *
72 * DEFINE_string(args, .., ..);
73 *
74 * creates an array:
75 *
76 * CommandLineFlags::StringArray FLAGS_args;
77 *
78 * If the default value is the empty string, FLAGS_args will default to a size
79 * of zero. Otherwise it will default to a size of 1 with the default string
80 * as its value. All strings that follow the flag on the command line (until
81 * a string that begins with '-') will be entries in the array.
82 *
83 * DEFINE_extended_string(args, .., .., extendedHelpString);
84 *
85 * creates a similar string array flag as DEFINE_string. The flag will have extended help text
86 * (extendedHelpString) that can the user can see with '--help <args>' flag.
87 *
88 * Any flag can be referenced from another file after using the following:
89 *
90 * DECLARE_x(name);
91 *
92 * (where 'x' is the type specified in the DEFINE).
93 *
94 * Inspired by gflags (https://code.google.com/p/gflags/). Is not quite as
95 * robust as gflags, but suits our purposes. For example, allows creating
96 * a flag -h or -help which will never be used, since CommandLineFlags handles it.
97 * CommandLineFlags will also allow creating --flag and --noflag. Uses the same input
98 * format as gflags and creates similarly named variables (i.e. FLAGS_name).
99 * Strings are handled differently (resulting variable will be an array of
100 * strings) so that a flag can be followed by multiple parameters.
101 */
102
103 class SkFlagInfo;
104
105 class CommandLineFlags {
106 public:
107 /**
108 * Call to set the help message to be displayed. Should be called before
109 * Parse.
110 */
111 static void SetUsage(const char* usage);
112
113 /**
114 * Call this to display the help message. Should be called after SetUsage.
115 */
116 static void PrintUsage();
117
118 /**
119 * Call at the beginning of main to parse flags created by DEFINE_x, above.
120 * Must only be called once.
121 */
122 static void Parse(int argc, const char* const* argv);
123
124 /**
125 * Custom class for holding the arguments for a string flag.
126 * Publicly only has accessors so the strings cannot be modified.
127 */
128 class StringArray {
129 public:
130 StringArray() {}
131 explicit StringArray(const skia_private::TArray<SkString>& strings) : fStrings(strings) {}
132 const char* operator[](int i) const {
133 SkASSERT(i >= 0 && i < fStrings.size());
134 return fStrings[i].c_str();
135 }
136
137 int size() const { return fStrings.size(); }
138
139 bool isEmpty() const { return this->size() == 0; }
140
141 /**
142 * Returns true iff string is equal to one of the strings in this array.
143 */
144 bool contains(const char* string) const {
145 for (int i = 0; i < fStrings.size(); i++) {
146 if (fStrings[i].equals(string)) {
147 return true;
148 }
149 }
150 return false;
151 }
152
153 void set(int i, const char* str) {
154 if (i >= fStrings.size()) {
155 this->append(str);
156 return;
157 }
158 fStrings[i].set(str);
159 }
160
161 const SkString* begin() const { return fStrings.begin(); }
162 const SkString* end() const { return fStrings.end(); }
163
164 /**
165 * Parses and validates a string flag that requires exactly one value out of a set of
166 * possible values. Returns a non-empty message in the case of errors.
167 */
168 template <class E>
169 SkString parseAndValidate(const char* name,
170 const skia_private::THashMap<SkString, E>& possibleValues,
171 E* out) const {
172 if (size() == 0) {
173 return SkStringPrintf("Flag %s is required.", name);
174 }
175 if (size() != 1) {
176 return SkStringPrintf("Flag %s takes 1 value, got %d.", name, size());
177 }
178 E* found = possibleValues.find(SkString(operator[](0)));
179 if (found != nullptr) {
180 *out = *found;
181 return SkString();
182 }
183 return SkStringPrintf("Unknown value for flag %s: %s.", name, operator[](0));
184 }
185
186 private:
187 void reset() { fStrings.clear(); }
188
189 void append(const char* string) { fStrings.push_back().set(string); }
190
191 void append(const char* string, size_t length) { fStrings.push_back().set(string, length); }
192
193 skia_private::TArray<SkString> fStrings;
194
195 friend class SkFlagInfo;
196 };
197
198 /* Takes a list of the form [~][^]match[$]
199 ~ causes a matching test to always be skipped
200 ^ requires the start of the test to match
201 $ requires the end of the test to match
202 ^ and $ requires an exact match
203 If a test does not match any list entry, it is skipped unless some list entry starts with ~
204 */
205 static bool ShouldSkip(const SkTDArray<const char*>& strings, const char* name);
206 static bool ShouldSkip(const StringArray& strings, const char* name);
207
208 private:
209 static SkFlagInfo* gHead;
210 static SkString gUsage;
211
212 // For access to gHead.
213 friend class SkFlagInfo;
214 };
215
216 #define DEFINE_bool(name, defaultValue, helpString) \
217 bool FLAGS_##name; \
218 [[maybe_unused]] static bool unused_##name = SkFlagInfo::CreateBoolFlag( \
219 SK_MACRO_STRINGIFY(name), nullptr, &FLAGS_##name, defaultValue, helpString)
220
221 // bool 2 allows specifying a short name. No check is done to ensure that shortName
222 // is actually shorter than name.
223 #define DEFINE_bool2(name, shortName, defaultValue, helpString) \
224 bool FLAGS_##name; \
225 [[maybe_unused]] static bool unused_##name = \
226 SkFlagInfo::CreateBoolFlag(SK_MACRO_STRINGIFY(name), \
227 SK_MACRO_STRINGIFY(shortName), \
228 &FLAGS_##name, \
229 defaultValue, \
230 helpString)
231
232 #define DECLARE_bool(name) extern bool FLAGS_##name;
233
234 #define DEFINE_string(name, defaultValue, helpString) \
235 CommandLineFlags::StringArray FLAGS_##name; \
236 [[maybe_unused]] static bool unused_##name = SkFlagInfo::CreateStringFlag( \
237 SK_MACRO_STRINGIFY(name), nullptr, &FLAGS_##name, defaultValue, helpString, nullptr)
238 #define DEFINE_extended_string(name, defaultValue, helpString, extendedHelpString) \
239 CommandLineFlags::StringArray FLAGS_##name; \
240 [[maybe_unused]] static bool unused_##name = \
241 SkFlagInfo::CreateStringFlag(SK_MACRO_STRINGIFY(name), \
242 nullptr, \
243 &FLAGS_##name, \
244 defaultValue, \
245 helpString, \
246 extendedHelpString)
247
248 // string2 allows specifying a short name. There is an assert that shortName
249 // is only 1 character.
250 #define DEFINE_string2(name, shortName, defaultValue, helpString) \
251 CommandLineFlags::StringArray FLAGS_##name; \
252 [[maybe_unused]] static bool unused_##name = \
253 SkFlagInfo::CreateStringFlag(SK_MACRO_STRINGIFY(name), \
254 SK_MACRO_STRINGIFY(shortName), \
255 &FLAGS_##name, \
256 defaultValue, \
257 helpString, \
258 nullptr)
259
260 #define DECLARE_string(name) extern CommandLineFlags::StringArray FLAGS_##name;
261
262 #define DEFINE_int(name, defaultValue, helpString) \
263 int FLAGS_##name; \
264 [[maybe_unused]] static bool unused_##name = SkFlagInfo::CreateIntFlag( \
265 SK_MACRO_STRINGIFY(name), &FLAGS_##name, defaultValue, helpString)
266
267 #define DEFINE_int_2(name, shortName, defaultValue, helpString) \
268 int FLAGS_##name; \
269 [[maybe_unused]] static bool unused_##name = \
270 SkFlagInfo::CreateIntFlag(SK_MACRO_STRINGIFY(name), \
271 SK_MACRO_STRINGIFY(shortName), \
272 &FLAGS_##name, \
273 defaultValue, \
274 helpString)
275
276 #define DECLARE_int(name) extern int FLAGS_##name;
277
278 #define DEFINE_double(name, defaultValue, helpString) \
279 double FLAGS_##name; \
280 [[maybe_unused]] static bool unused_##name = SkFlagInfo::CreateDoubleFlag( \
281 SK_MACRO_STRINGIFY(name), &FLAGS_##name, defaultValue, helpString)
282
283 #define DECLARE_double(name) extern double FLAGS_##name;
284
285 class SkFlagInfo {
286 public:
287 enum FlagTypes {
288 kBool_FlagType,
289 kString_FlagType,
290 kInt_FlagType,
291 kDouble_FlagType,
292 };
293
294 /**
295 * Each Create<Type>Flag function creates an SkFlagInfo of the specified type. The SkFlagInfo
296 * object is appended to a list, which is deleted when CommandLineFlags::Parse is called.
297 * Therefore, each call should be made before the call to ::Parse. They are not intended
298 * to be called directly. Instead, use the macros described above.
299 * @param name Long version (at least 2 characters) of the name of the flag. This name can
300 * be referenced on the command line as "--name" to set the value of this flag.
301 * @param shortName Short version (one character) of the name of the flag. This name can
302 * be referenced on the command line as "-shortName" to set the value of this flag.
303 * @param p<Type> Pointer to a global variable which holds the value set by CommandLineFlags.
304 * @param defaultValue The default value of this flag. The variable pointed to by p<Type> will
305 * be set to this value initially. This is also displayed as part of the help output.
306 * @param helpString Explanation of what this flag changes in the program.
307 */
308 static bool CreateBoolFlag(const char* name,
309 const char* shortName,
310 bool* pBool,
311 bool defaultValue,
312 const char* helpString) {
313 SkFlagInfo* info = new SkFlagInfo(name, shortName, kBool_FlagType, helpString, nullptr);
314 info->fBoolValue = pBool;
315 *info->fBoolValue = info->fDefaultBool = defaultValue;
316 return true;
317 }
318
319 /**
320 * See comments for CreateBoolFlag.
321 * @param pStrings Unlike the others, this is a pointer to an array of values.
322 * @param defaultValue Thise default will be parsed so that strings separated by spaces
323 * will be added to pStrings.
324 */
325 static bool CreateStringFlag(const char* name,
326 const char* shortName,
327 CommandLineFlags::StringArray* pStrings,
328 const char* defaultValue,
329 const char* helpString,
330 const char* extendedHelpString);
331
332 /**
333 * See comments for CreateBoolFlag.
334 */
335 static bool CreateIntFlag(const char* name,
336 int* pInt,
337 int defaultValue,
338 const char* helpString) {
339 SkFlagInfo* info = new SkFlagInfo(name, nullptr, kInt_FlagType, helpString, nullptr);
340 info->fIntValue = pInt;
341 *info->fIntValue = info->fDefaultInt = defaultValue;
342 return true;
343 }
344
345 static bool CreateIntFlag(const char* name,
346 const char* shortName,
347 int* pInt,
348 int defaultValue,
349 const char* helpString) {
350 SkFlagInfo* info = new SkFlagInfo(name, shortName, kInt_FlagType, helpString, nullptr);
351 info->fIntValue = pInt;
352 *info->fIntValue = info->fDefaultInt = defaultValue;
353 return true;
354 }
355
356 /**
357 * See comments for CreateBoolFlag.
358 */
359 static bool CreateDoubleFlag(const char* name,
360 double* pDouble,
361 double defaultValue,
362 const char* helpString) {
363 SkFlagInfo* info = new SkFlagInfo(name, nullptr, kDouble_FlagType, helpString, nullptr);
364 info->fDoubleValue = pDouble;
365 *info->fDoubleValue = info->fDefaultDouble = defaultValue;
366 return true;
367 }
368
369 /**
370 * Returns true if the string matches this flag.
371 * For a boolean flag, also sets the value, since a boolean flag can be set in a number of ways
372 * without looking at the following string:
373 * --name
374 * --noname
375 * --name=true
376 * --name=false
377 * --name=1
378 * --name=0
379 * --name=TRUE
380 * --name=FALSE
381 */
382 bool match(const char* string);
383
384 FlagTypes getFlagType() const { return fFlagType; }
385
386 void resetStrings() {
387 if (kString_FlagType == fFlagType) {
388 fStrings->reset();
389 } else {
390 SkDEBUGFAIL("Can only call resetStrings on kString_FlagType");
391 }
392 }
393
394 void append(const char* string) {
395 if (kString_FlagType == fFlagType) {
396 fStrings->append(string);
397 } else {
398 SkDEBUGFAIL("Can only append to kString_FlagType");
399 }
400 }
401
402 void setInt(int value) {
403 if (kInt_FlagType == fFlagType) {
404 *fIntValue = value;
405 } else {
406 SkDEBUGFAIL("Can only call setInt on kInt_FlagType");
407 }
408 }
409
410 void setDouble(double value) {
411 if (kDouble_FlagType == fFlagType) {
412 *fDoubleValue = value;
413 } else {
414 SkDEBUGFAIL("Can only call setDouble on kDouble_FlagType");
415 }
416 }
417
418 void setBool(bool value) {
419 if (kBool_FlagType == fFlagType) {
420 *fBoolValue = value;
421 } else {
422 SkDEBUGFAIL("Can only call setBool on kBool_FlagType");
423 }
424 }
425
426 SkFlagInfo* next() { return fNext; }
427
428 const SkString& name() const { return fName; }
429
430 const SkString& shortName() const { return fShortName; }
431
432 const SkString& help() const { return fHelpString; }
433 const SkString& extendedHelp() const { return fExtendedHelpString; }
434
435 SkString defaultValue() const {
436 SkString result;
437 switch (fFlagType) {
438 case SkFlagInfo::kBool_FlagType:
439 result.printf("%s", fDefaultBool ? "true" : "false");
440 break;
441 case SkFlagInfo::kString_FlagType: return fDefaultString;
442 case SkFlagInfo::kInt_FlagType: result.printf("%i", fDefaultInt); break;
443 case SkFlagInfo::kDouble_FlagType: result.printf("%2.2f", fDefaultDouble); break;
444 default: SkDEBUGFAIL("Invalid flag type");
445 }
446 return result;
447 }
448
449 SkString typeAsString() const {
450 switch (fFlagType) {
451 case SkFlagInfo::kBool_FlagType: return SkString("bool");
452 case SkFlagInfo::kString_FlagType: return SkString("string");
453 case SkFlagInfo::kInt_FlagType: return SkString("int");
454 case SkFlagInfo::kDouble_FlagType: return SkString("double");
455 default: SkDEBUGFAIL("Invalid flag type"); return SkString();
456 }
457 }
458
459 private:
460 SkFlagInfo(const char* name,
461 const char* shortName,
462 FlagTypes type,
463 const char* helpString,
464 const char* extendedHelpString)
465 : fName(name)
466 , fShortName(shortName)
467 , fFlagType(type)
468 , fHelpString(helpString)
469 , fExtendedHelpString(extendedHelpString)
470 , fBoolValue(nullptr)
471 , fDefaultBool(false)
472 , fIntValue(nullptr)
473 , fDefaultInt(0)
474 , fDoubleValue(nullptr)
475 , fDefaultDouble(0)
476 , fStrings(nullptr) {
477 fNext = CommandLineFlags::gHead;
478 CommandLineFlags::gHead = this;
479 SkASSERT(name && strlen(name) > 1);
480 SkASSERT(nullptr == shortName || 1 == strlen(shortName));
481 }
482
483 /**
484 * Set a StringArray to hold the values stored in defaultStrings.
485 * @param array The StringArray to modify.
486 * @param defaultStrings Space separated list of strings that should be inserted into array
487 * individually.
488 */
489 static void SetDefaultStrings(CommandLineFlags::StringArray* array, const char* defaultStrings);
490
491 // Name of the flag, without initial dashes
492 SkString fName;
493 SkString fShortName;
494 FlagTypes fFlagType;
495 SkString fHelpString;
496 SkString fExtendedHelpString;
497 bool* fBoolValue;
498 bool fDefaultBool;
499 int* fIntValue;
500 int fDefaultInt;
501 double* fDoubleValue;
502 double fDefaultDouble;
503 CommandLineFlags::StringArray* fStrings;
504 // Both for the help string and in case fStrings is empty.
505 SkString fDefaultString;
506
507 // In order to keep a linked list.
508 SkFlagInfo* fNext;
509 };
510 #endif // SK_COMMAND_LINE_FLAGS_H