1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef ART_CMDLINE_DETAIL_CMDLINE_PARSE_ARGUMENT_DETAIL_H_ 18 #define ART_CMDLINE_DETAIL_CMDLINE_PARSE_ARGUMENT_DETAIL_H_ 19 20 #include <assert.h> 21 #include <algorithm> 22 #include <functional> 23 #include <memory> 24 #include <numeric> 25 #include <string_view> 26 #include <type_traits> 27 #include <vector> 28 29 #include "android-base/strings.h" 30 31 #include "base/indenter.h" 32 #include "cmdline_parse_result.h" 33 #include "cmdline_types.h" 34 #include "token_range.h" 35 #include "unit.h" 36 37 namespace art { 38 // Implementation details for the parser. Do not look inside if you hate templates. 39 namespace detail { 40 41 // A non-templated base class for argument parsers. Used by the general parser 42 // to parse arguments, without needing to know the argument type at compile time. 43 // 44 // This is an application of the type erasure idiom. 45 struct CmdlineParseArgumentAny { ~CmdlineParseArgumentAnyCmdlineParseArgumentAny46 virtual ~CmdlineParseArgumentAny() {} 47 48 // Attempt to parse this argument starting at arguments[position]. 49 // If the parsing succeeds, the parsed value will be saved as a side-effect. 50 // 51 // In most situations, the parsing will not match by returning kUnknown. In this case, 52 // no tokens were consumed and the position variable will not be updated. 53 // 54 // At other times, parsing may fail due to validation but the initial token was still matched 55 // (for example an out of range value, or passing in a string where an int was expected). 56 // In this case the tokens are still consumed, and the position variable will get incremented 57 // by all the consumed tokens. 58 // 59 // The # of tokens consumed by the parse attempt will be set as an out-parameter into 60 // consumed_tokens. The parser should skip this many tokens before parsing the next 61 // argument. 62 virtual CmdlineResult ParseArgument(const TokenRange& arguments, size_t* consumed_tokens) = 0; 63 // How many tokens should be taken off argv for parsing this argument. 64 // For example "--help" is just 1, "-compiler-option _" would be 2 (since there's a space). 65 // 66 // A [min,max] range is returned to represent argument definitions with multiple 67 // value tokens. (e.g. {"-h", "-h " } would return [1,2]). 68 virtual std::pair<size_t, size_t> GetNumTokens() const = 0; 69 // Get the run-time typename of the argument type. 70 virtual const char* GetTypeName() const = 0; 71 // Try to do a close match, returning how many tokens were matched against this argument 72 // definition. More tokens is better. 73 // 74 // Do a quick match token-by-token, and see if they match. 75 // Any tokens with a wildcard in them are only matched up until the wildcard. 76 // If this is true, then the wildcard matching later on can still fail, so this is not 77 // a guarantee that the argument is correct, it's more of a strong hint that the 78 // user-provided input *probably* was trying to match this argument. 79 // 80 // Returns how many tokens were either matched (or ignored because there was a 81 // wildcard present). 0 means no match. If the Size() tokens are returned. 82 virtual size_t MaybeMatches(const TokenRange& tokens) = 0; 83 84 virtual void DumpHelp(VariableIndentationOutputStream& os) = 0; 85 86 virtual const std::optional<const char*>& GetCategory() = 0; 87 }; 88 89 template <typename T> 90 using EnableIfNumeric = std::enable_if<std::is_arithmetic<T>::value>; 91 92 template <typename T> 93 using DisableIfNumeric = std::enable_if<!std::is_arithmetic<T>::value>; 94 95 // Argument definition information, created by an ArgumentBuilder and an UntypedArgumentBuilder. 96 template <typename TArg> 97 struct CmdlineParserArgumentInfo { 98 // This version will only be used if TArg is arithmetic and thus has the <= operators. 99 template <typename T = TArg> // Necessary to get SFINAE to kick in. 100 bool CheckRange(const TArg& value, typename EnableIfNumeric<T>::type* = nullptr) { 101 if (has_range_) { 102 return min_ <= value && value <= max_; 103 } 104 return true; 105 } 106 107 // This version will be used at other times when TArg is not arithmetic. 108 template <typename T = TArg> 109 bool CheckRange(const TArg&, typename DisableIfNumeric<T>::type* = nullptr) { 110 assert(!has_range_); 111 return true; 112 } 113 114 // Do a quick match token-by-token, and see if they match. 115 // Any tokens with a wildcard in them only match the prefix up until the wildcard. 116 // 117 // If this is true, then the wildcard matching later on can still fail, so this is not 118 // a guarantee that the argument is correct, it's more of a strong hint that the 119 // user-provided input *probably* was trying to match this argument. MaybeMatchesCmdlineParserArgumentInfo120 size_t MaybeMatches(const TokenRange& token_list) const { 121 auto best_match = FindClosestMatch(token_list); 122 123 return best_match.second; 124 } 125 126 // Attempt to find the closest match (see MaybeMatches). 127 // 128 // Returns the token range that was the closest match and the # of tokens that 129 // this range was matched up until. FindClosestMatchCmdlineParserArgumentInfo130 std::pair<const TokenRange*, size_t> FindClosestMatch(const TokenRange& token_list) const { 131 const TokenRange* best_match_ptr = nullptr; 132 133 size_t best_match = 0; 134 for (auto&& token_range : tokenized_names_) { 135 size_t this_match = token_range.MaybeMatches(token_list, std::string("_")); 136 137 if (this_match > best_match) { 138 best_match_ptr = &token_range; 139 best_match = this_match; 140 } 141 } 142 143 return std::make_pair(best_match_ptr, best_match); 144 } 145 146 template <typename T = TArg> // Necessary to get SFINAE to kick in. DumpHelpCmdlineParserArgumentInfo147 void DumpHelp(VariableIndentationOutputStream& vios) { 148 for (auto cname : names_) { 149 std::string_view name = cname; 150 auto& os = vios.Stream(); 151 std::function<void()> print_once; 152 if (using_blanks_) { 153 std::string_view nblank = name.substr(0, name.find("_")); 154 print_once = [&]() { 155 os << nblank; 156 if (has_value_map_) { 157 bool first = true; 158 for (auto [val, unused] : value_map_) { 159 os << (first ? "{" : "|") << val; 160 first = false; 161 } 162 os << "}"; 163 } else if (metavar_) { 164 os << metavar_.value(); 165 } else { 166 os << "{" << CmdlineType<T>::DescribeType() << "}"; 167 } 168 }; 169 } else { 170 print_once = [&]() { 171 os << name; 172 }; 173 } 174 print_once(); 175 if (appending_values_) { 176 os << " ["; 177 print_once(); 178 os << "...]"; 179 } 180 os << std::endl; 181 } 182 if (help_) { 183 ScopedIndentation si(&vios); 184 vios.Stream() << help_.value() << std::endl; 185 } 186 } 187 188 189 // Mark the argument definition as completed, do not mutate the object anymore after this 190 // call is done. 191 // 192 // Performs several checks of the validity and token calculations. CompleteArgumentCmdlineParserArgumentInfo193 void CompleteArgument() { 194 assert(names_.size() >= 1); 195 assert(!is_completed_); 196 197 is_completed_ = true; 198 199 size_t blank_count = 0; 200 size_t token_count = 0; 201 202 size_t global_blank_count = 0; 203 size_t global_token_count = 0; 204 for (auto&& name : names_) { 205 std::string s(name); 206 207 size_t local_blank_count = std::count(s.begin(), s.end(), '_'); 208 size_t local_token_count = std::count(s.begin(), s.end(), ' '); 209 210 if (global_blank_count != 0) { 211 assert(local_blank_count == global_blank_count 212 && "Every argument descriptor string must have same amount of blanks (_)"); 213 } 214 215 if (local_blank_count != 0) { 216 global_blank_count = local_blank_count; 217 blank_count++; 218 219 assert(local_blank_count == 1 && "More than one blank is not supported"); 220 assert(s.back() == '_' && "The blank character must only be at the end of the string"); 221 } 222 223 if (global_token_count != 0) { 224 assert(local_token_count == global_token_count 225 && "Every argument descriptor string must have same amount of tokens (spaces)"); 226 } 227 228 if (local_token_count != 0) { 229 global_token_count = local_token_count; 230 token_count++; 231 } 232 233 // Tokenize every name, turning it from a string to a token list. 234 tokenized_names_.clear(); 235 for (auto&& name1 : names_) { 236 // Split along ' ' only, removing any duplicated spaces. 237 tokenized_names_.push_back( 238 TokenRange::Split(name1, {' '}).RemoveToken(" ")); 239 } 240 241 // remove the _ character from each of the token ranges 242 // we will often end up with an empty token (i.e. ["-XX", "_"] -> ["-XX", ""] 243 // and this is OK because we still need an empty token to simplify 244 // range comparisons 245 simple_names_.clear(); 246 247 for (auto&& tokenized_name : tokenized_names_) { 248 simple_names_.push_back(tokenized_name.RemoveCharacter('_')); 249 } 250 } 251 252 if (token_count != 0) { 253 assert(("Every argument descriptor string must have equal amount of tokens (spaces)" && 254 token_count == names_.size())); 255 } 256 257 if (blank_count != 0) { 258 assert(("Every argument descriptor string must have an equal amount of blanks (_)" && 259 blank_count == names_.size())); 260 } 261 262 using_blanks_ = blank_count > 0; 263 { 264 size_t smallest_name_token_range_size = 265 std::accumulate(tokenized_names_.begin(), tokenized_names_.end(), ~(0u), 266 [](size_t min, const TokenRange& cur) { 267 return std::min(min, cur.Size()); 268 }); 269 size_t largest_name_token_range_size = 270 std::accumulate(tokenized_names_.begin(), tokenized_names_.end(), 0u, 271 [](size_t max, const TokenRange& cur) { 272 return std::max(max, cur.Size()); 273 }); 274 275 token_range_size_ = std::make_pair(smallest_name_token_range_size, 276 largest_name_token_range_size); 277 } 278 279 if (has_value_list_) { 280 assert(names_.size() == value_list_.size() 281 && "Number of arg descriptors must match number of values"); 282 assert(!has_value_map_); 283 } 284 if (has_value_map_) { 285 if (!using_blanks_) { 286 assert(names_.size() == value_map_.size() && 287 "Since no blanks were specified, each arg is mapped directly into a mapped " 288 "value without parsing; sizes must match"); 289 } 290 291 assert(!has_value_list_); 292 } 293 294 if (!using_blanks_ && !CmdlineType<TArg>::kCanParseBlankless) { 295 assert((has_value_map_ || has_value_list_) && 296 "Arguments without a blank (_) must provide either a value map or a value list"); 297 } 298 299 TypedCheck(); 300 } 301 302 // List of aliases for a single argument definition, e.g. {"-Xdex2oat", "-Xnodex2oat"}. 303 std::vector<const char*> names_; 304 // Is there at least 1 wildcard '_' in the argument definition? 305 bool using_blanks_ = false; 306 // [min, max] token counts in each arg def 307 std::pair<size_t, size_t> token_range_size_; 308 309 // contains all the names in a tokenized form, i.e. as a space-delimited list 310 std::vector<TokenRange> tokenized_names_; 311 312 // contains the tokenized names, but with the _ character stripped 313 std::vector<TokenRange> simple_names_; 314 315 // For argument definitions created with '.AppendValues()' 316 // Meaning that parsing should mutate the existing value in-place if possible. 317 bool appending_values_ = false; 318 319 // For argument definitions created with '.WithRange(min, max)' 320 bool has_range_ = false; 321 TArg min_; 322 TArg max_; 323 324 // For argument definitions created with '.WithValueMap' 325 bool has_value_map_ = false; 326 std::vector<std::pair<const char*, TArg>> value_map_; 327 328 // For argument definitions created with '.WithValues' 329 bool has_value_list_ = false; 330 std::vector<TArg> value_list_; 331 332 std::optional<const char*> help_; 333 std::optional<const char*> category_; 334 std::optional<const char*> metavar_; 335 336 // Make sure there's a default constructor. 337 CmdlineParserArgumentInfo() = default; 338 339 // Ensure there's a default move constructor. 340 CmdlineParserArgumentInfo(CmdlineParserArgumentInfo&&) = default; 341 342 private: 343 // Perform type-specific checks at runtime. 344 template <typename T = TArg> 345 void TypedCheck(typename std::enable_if<std::is_same<Unit, T>::value>::type* = 0) { 346 assert(!using_blanks_ && 347 "Blanks are not supported in Unit arguments; since a Unit has no parse-able value"); 348 } 349 TypedCheckCmdlineParserArgumentInfo350 void TypedCheck() {} 351 352 bool is_completed_ = false; 353 }; 354 355 // A virtual-implementation of the necessary argument information in order to 356 // be able to parse arguments. 357 template <typename TArg> 358 struct CmdlineParseArgument : CmdlineParseArgumentAny { CmdlineParseArgumentCmdlineParseArgument359 CmdlineParseArgument(CmdlineParserArgumentInfo<TArg>&& argument_info, 360 std::function<void(TArg&)>&& save_argument, 361 std::function<TArg&(void)>&& load_argument) 362 : argument_info_(std::forward<decltype(argument_info)>(argument_info)), 363 save_argument_(std::forward<decltype(save_argument)>(save_argument)), 364 load_argument_(std::forward<decltype(load_argument)>(load_argument)) { 365 } 366 367 using UserTypeInfo = CmdlineType<TArg>; 368 ParseArgumentCmdlineParseArgument369 virtual CmdlineResult ParseArgument(const TokenRange& arguments, size_t* consumed_tokens) { 370 assert(arguments.Size() > 0); 371 assert(consumed_tokens != nullptr); 372 373 auto closest_match_res = argument_info_.FindClosestMatch(arguments); 374 size_t best_match_size = closest_match_res.second; 375 const TokenRange* best_match_arg_def = closest_match_res.first; 376 377 if (best_match_size > arguments.Size()) { 378 // The best match has more tokens than were provided. 379 // Shouldn't happen in practice since the outer parser does this check. 380 return CmdlineResult(CmdlineResult::kUnknown, "Size mismatch"); 381 } 382 383 assert(best_match_arg_def != nullptr); 384 *consumed_tokens = best_match_arg_def->Size(); 385 386 if (!argument_info_.using_blanks_) { 387 return ParseArgumentSingle(arguments.Join(' ')); 388 } 389 390 // Extract out the blank value from arguments 391 // e.g. for a def of "foo:_" and input "foo:bar", blank_value == "bar" 392 std::string blank_value = ""; 393 size_t idx = 0; 394 for (auto&& def_token : *best_match_arg_def) { 395 auto&& arg_token = arguments[idx]; 396 397 // Does this definition-token have a wildcard in it? 398 if (def_token.find('_') == std::string::npos) { 399 // No, regular token. Match 1:1 against the argument token. 400 bool token_match = def_token == arg_token; 401 402 if (!token_match) { 403 return CmdlineResult(CmdlineResult::kFailure, 404 std::string("Failed to parse ") + best_match_arg_def->GetToken(0) 405 + " at token " + std::to_string(idx)); 406 } 407 } else { 408 // This is a wild-carded token. 409 TokenRange def_split_wildcards = TokenRange::Split(def_token, {'_'}); 410 411 // Extract the wildcard contents out of the user-provided arg_token. 412 std::unique_ptr<TokenRange> arg_matches = 413 def_split_wildcards.MatchSubstrings(arg_token, "_"); 414 if (arg_matches == nullptr) { 415 return CmdlineResult(CmdlineResult::kFailure, 416 std::string("Failed to parse ") + best_match_arg_def->GetToken(0) 417 + ", with a wildcard pattern " + def_token 418 + " at token " + std::to_string(idx)); 419 } 420 421 // Get the corresponding wildcard tokens from arg_matches, 422 // and concatenate it to blank_value. 423 for (size_t sub_idx = 0; 424 sub_idx < def_split_wildcards.Size() && sub_idx < arg_matches->Size(); ++sub_idx) { 425 if (def_split_wildcards[sub_idx] == "_") { 426 blank_value += arg_matches->GetToken(sub_idx); 427 } 428 } 429 } 430 431 ++idx; 432 } 433 434 return ParseArgumentSingle(blank_value); 435 } 436 DumpHelpCmdlineParseArgument437 virtual void DumpHelp(VariableIndentationOutputStream& os) { 438 argument_info_.DumpHelp(os); 439 } 440 GetCategoryCmdlineParseArgument441 virtual const std::optional<const char*>& GetCategory() { 442 return argument_info_.category_; 443 } 444 445 private: ParseArgumentSingleCmdlineParseArgument446 virtual CmdlineResult ParseArgumentSingle(const std::string& argument) { 447 // TODO: refactor to use LookupValue for the value lists/maps 448 449 // Handle the 'WithValueMap(...)' argument definition 450 if (argument_info_.has_value_map_) { 451 for (auto&& value_pair : argument_info_.value_map_) { 452 const char* name = value_pair.first; 453 454 if (argument == name) { 455 return SaveArgument(value_pair.second); 456 } 457 } 458 459 // Error case: Fail, telling the user what the allowed values were. 460 std::vector<std::string> allowed_values; 461 for (auto&& value_pair : argument_info_.value_map_) { 462 const char* name = value_pair.first; 463 allowed_values.push_back(name); 464 } 465 466 std::string allowed_values_flat = android::base::Join(allowed_values, ','); 467 return CmdlineResult(CmdlineResult::kFailure, 468 "Argument value '" + argument + "' does not match any of known valid " 469 "values: {" + allowed_values_flat + "}"); 470 } 471 472 // Handle the 'WithValues(...)' argument definition 473 if (argument_info_.has_value_list_) { 474 size_t arg_def_idx = 0; 475 for (auto&& value : argument_info_.value_list_) { 476 auto&& arg_def_token = argument_info_.names_[arg_def_idx]; 477 478 if (arg_def_token == argument) { 479 return SaveArgument(value); 480 } 481 ++arg_def_idx; 482 } 483 484 assert(arg_def_idx + 1 == argument_info_.value_list_.size() && 485 "Number of named argument definitions must match number of values defined"); 486 487 // Error case: Fail, telling the user what the allowed values were. 488 std::vector<std::string> allowed_values; 489 for (auto&& arg_name : argument_info_.names_) { 490 allowed_values.push_back(arg_name); 491 } 492 493 std::string allowed_values_flat = android::base::Join(allowed_values, ','); 494 return CmdlineResult(CmdlineResult::kFailure, 495 "Argument value '" + argument + "' does not match any of known valid" 496 "values: {" + allowed_values_flat + "}"); 497 } 498 499 // Handle the regular case where we parsed an unknown value from a blank. 500 UserTypeInfo type_parser; 501 502 if (argument_info_.appending_values_) { 503 TArg& existing = load_argument_(); 504 CmdlineParseResult<TArg> result = type_parser.ParseAndAppend(argument, existing); 505 506 assert(!argument_info_.has_range_); 507 508 return std::move(result); 509 } 510 511 CmdlineParseResult<TArg> result = type_parser.Parse(argument); 512 513 if (result.IsSuccess()) { 514 TArg& value = result.GetValue(); 515 516 // Do a range check for 'WithRange(min,max)' argument definition. 517 if (!argument_info_.CheckRange(value)) { 518 return CmdlineParseResult<TArg>::OutOfRange( 519 value, argument_info_.min_, argument_info_.max_); 520 } 521 522 return SaveArgument(value); 523 } 524 525 // Some kind of type-specific parse error. Pass the result as-is. 526 CmdlineResult raw_result = std::move(result); 527 return raw_result; 528 } 529 530 public: GetTypeNameCmdlineParseArgument531 virtual const char* GetTypeName() const { 532 // TODO: Obviate the need for each type specialization to hardcode the type name 533 return UserTypeInfo::Name(); 534 } 535 536 // How many tokens should be taken off argv for parsing this argument. 537 // For example "--help" is just 1, "-compiler-option _" would be 2 (since there's a space). 538 // 539 // A [min,max] range is returned to represent argument definitions with multiple 540 // value tokens. (e.g. {"-h", "-h " } would return [1,2]). GetNumTokensCmdlineParseArgument541 virtual std::pair<size_t, size_t> GetNumTokens() const { 542 return argument_info_.token_range_size_; 543 } 544 545 // See if this token range might begin the same as the argument definition. MaybeMatchesCmdlineParseArgument546 virtual size_t MaybeMatches(const TokenRange& tokens) { 547 return argument_info_.MaybeMatches(tokens); 548 } 549 550 private: SaveArgumentCmdlineParseArgument551 CmdlineResult SaveArgument(const TArg& value) { 552 assert(!argument_info_.appending_values_ 553 && "If the values are being appended, then the updated parse value is " 554 "updated by-ref as a side effect and shouldn't be stored directly"); 555 TArg val = value; 556 save_argument_(val); 557 return CmdlineResult(CmdlineResult::kSuccess); 558 } 559 560 CmdlineParserArgumentInfo<TArg> argument_info_; 561 std::function<void(TArg&)> save_argument_; 562 std::function<TArg&(void)> load_argument_; 563 }; 564 } // namespace detail // NOLINT [readability/namespace] [5] 565 } // namespace art 566 567 #endif // ART_CMDLINE_DETAIL_CMDLINE_PARSE_ARGUMENT_DETAIL_H_ 568