1 //===- llvm/unittest/Support/CommandLineTest.cpp - CommandLine tests ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Support/CommandLine.h" 10 #include "llvm/ADT/STLExtras.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/StringRef.h" 13 #include "llvm/ADT/Triple.h" 14 #include "llvm/Config/config.h" 15 #include "llvm/Support/Allocator.h" 16 #include "llvm/Support/FileSystem.h" 17 #include "llvm/Support/InitLLVM.h" 18 #include "llvm/Support/MemoryBuffer.h" 19 #include "llvm/Support/Path.h" 20 #include "llvm/Support/Program.h" 21 #include "llvm/Support/StringSaver.h" 22 #include "llvm/Support/VirtualFileSystem.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include "gmock/gmock.h" 25 #include "gtest/gtest.h" 26 #include <fstream> 27 #include <stdlib.h> 28 #include <string> 29 #include <tuple> 30 31 using namespace llvm; 32 33 namespace { 34 35 MATCHER(StringEquality, "Checks if two char* are equal as strings") { 36 return std::string(std::get<0>(arg)) == std::string(std::get<1>(arg)); 37 } 38 39 class TempEnvVar { 40 public: 41 TempEnvVar(const char *name, const char *value) 42 : name(name) { 43 const char *old_value = getenv(name); 44 EXPECT_EQ(nullptr, old_value) << old_value; 45 #if HAVE_SETENV 46 setenv(name, value, true); 47 #else 48 # define SKIP_ENVIRONMENT_TESTS 49 #endif 50 } 51 52 ~TempEnvVar() { 53 #if HAVE_SETENV 54 // Assume setenv and unsetenv come together. 55 unsetenv(name); 56 #else 57 (void)name; // Suppress -Wunused-private-field. 58 #endif 59 } 60 61 private: 62 const char *const name; 63 }; 64 65 template <typename T, typename Base = cl::opt<T>> 66 class StackOption : public Base { 67 public: 68 template <class... Ts> 69 explicit StackOption(Ts &&... Ms) : Base(std::forward<Ts>(Ms)...) {} 70 71 ~StackOption() override { this->removeArgument(); } 72 73 template <class DT> StackOption<T> &operator=(const DT &V) { 74 this->setValue(V); 75 return *this; 76 } 77 }; 78 79 class StackSubCommand : public cl::SubCommand { 80 public: 81 StackSubCommand(StringRef Name, 82 StringRef Description = StringRef()) 83 : SubCommand(Name, Description) {} 84 85 StackSubCommand() : SubCommand() {} 86 87 ~StackSubCommand() { unregisterSubCommand(); } 88 }; 89 90 91 cl::OptionCategory TestCategory("Test Options", "Description"); 92 TEST(CommandLineTest, ModifyExisitingOption) { 93 StackOption<int> TestOption("test-option", cl::desc("old description")); 94 95 static const char Description[] = "New description"; 96 static const char ArgString[] = "new-test-option"; 97 static const char ValueString[] = "Integer"; 98 99 StringMap<cl::Option *> &Map = 100 cl::getRegisteredOptions(*cl::TopLevelSubCommand); 101 102 ASSERT_TRUE(Map.count("test-option") == 1) << 103 "Could not find option in map."; 104 105 cl::Option *Retrieved = Map["test-option"]; 106 ASSERT_EQ(&TestOption, Retrieved) << "Retrieved wrong option."; 107 108 ASSERT_NE(Retrieved->Categories.end(), 109 find_if(Retrieved->Categories, 110 [&](const llvm::cl::OptionCategory *Cat) { 111 return Cat == &cl::GeneralCategory; 112 })) 113 << "Incorrect default option category."; 114 115 Retrieved->addCategory(TestCategory); 116 ASSERT_NE(Retrieved->Categories.end(), 117 find_if(Retrieved->Categories, 118 [&](const llvm::cl::OptionCategory *Cat) { 119 return Cat == &TestCategory; 120 })) 121 << "Failed to modify option's option category."; 122 123 Retrieved->setDescription(Description); 124 ASSERT_STREQ(Retrieved->HelpStr.data(), Description) 125 << "Changing option description failed."; 126 127 Retrieved->setArgStr(ArgString); 128 ASSERT_STREQ(ArgString, Retrieved->ArgStr.data()) 129 << "Failed to modify option's Argument string."; 130 131 Retrieved->setValueStr(ValueString); 132 ASSERT_STREQ(Retrieved->ValueStr.data(), ValueString) 133 << "Failed to modify option's Value string."; 134 135 Retrieved->setHiddenFlag(cl::Hidden); 136 ASSERT_EQ(cl::Hidden, TestOption.getOptionHiddenFlag()) << 137 "Failed to modify option's hidden flag."; 138 } 139 #ifndef SKIP_ENVIRONMENT_TESTS 140 141 const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS"; 142 143 cl::opt<std::string> EnvironmentTestOption("env-test-opt"); 144 TEST(CommandLineTest, ParseEnvironment) { 145 TempEnvVar TEV(test_env_var, "-env-test-opt=hello"); 146 EXPECT_EQ("", EnvironmentTestOption); 147 cl::ParseEnvironmentOptions("CommandLineTest", test_env_var); 148 EXPECT_EQ("hello", EnvironmentTestOption); 149 } 150 151 // This test used to make valgrind complain 152 // ("Conditional jump or move depends on uninitialised value(s)") 153 // 154 // Warning: Do not run any tests after this one that try to gain access to 155 // registered command line options because this will likely result in a 156 // SEGFAULT. This can occur because the cl::opt in the test below is declared 157 // on the stack which will be destroyed after the test completes but the 158 // command line system will still hold a pointer to a deallocated cl::Option. 159 TEST(CommandLineTest, ParseEnvironmentToLocalVar) { 160 // Put cl::opt on stack to check for proper initialization of fields. 161 StackOption<std::string> EnvironmentTestOptionLocal("env-test-opt-local"); 162 TempEnvVar TEV(test_env_var, "-env-test-opt-local=hello-local"); 163 EXPECT_EQ("", EnvironmentTestOptionLocal); 164 cl::ParseEnvironmentOptions("CommandLineTest", test_env_var); 165 EXPECT_EQ("hello-local", EnvironmentTestOptionLocal); 166 } 167 168 #endif // SKIP_ENVIRONMENT_TESTS 169 170 TEST(CommandLineTest, UseOptionCategory) { 171 StackOption<int> TestOption2("test-option", cl::cat(TestCategory)); 172 173 ASSERT_NE(TestOption2.Categories.end(), 174 find_if(TestOption2.Categories, 175 [&](const llvm::cl::OptionCategory *Cat) { 176 return Cat == &TestCategory; 177 })) 178 << "Failed to assign Option Category."; 179 } 180 181 TEST(CommandLineTest, UseMultipleCategories) { 182 StackOption<int> TestOption2("test-option2", cl::cat(TestCategory), 183 cl::cat(cl::GeneralCategory), 184 cl::cat(cl::GeneralCategory)); 185 186 // Make sure cl::GeneralCategory wasn't added twice. 187 ASSERT_EQ(TestOption2.Categories.size(), 2U); 188 189 ASSERT_NE(TestOption2.Categories.end(), 190 find_if(TestOption2.Categories, 191 [&](const llvm::cl::OptionCategory *Cat) { 192 return Cat == &TestCategory; 193 })) 194 << "Failed to assign Option Category."; 195 ASSERT_NE(TestOption2.Categories.end(), 196 find_if(TestOption2.Categories, 197 [&](const llvm::cl::OptionCategory *Cat) { 198 return Cat == &cl::GeneralCategory; 199 })) 200 << "Failed to assign General Category."; 201 202 cl::OptionCategory AnotherCategory("Additional test Options", "Description"); 203 StackOption<int> TestOption("test-option", cl::cat(TestCategory), 204 cl::cat(AnotherCategory)); 205 ASSERT_EQ(TestOption.Categories.end(), 206 find_if(TestOption.Categories, 207 [&](const llvm::cl::OptionCategory *Cat) { 208 return Cat == &cl::GeneralCategory; 209 })) 210 << "Failed to remove General Category."; 211 ASSERT_NE(TestOption.Categories.end(), 212 find_if(TestOption.Categories, 213 [&](const llvm::cl::OptionCategory *Cat) { 214 return Cat == &TestCategory; 215 })) 216 << "Failed to assign Option Category."; 217 ASSERT_NE(TestOption.Categories.end(), 218 find_if(TestOption.Categories, 219 [&](const llvm::cl::OptionCategory *Cat) { 220 return Cat == &AnotherCategory; 221 })) 222 << "Failed to assign Another Category."; 223 } 224 225 typedef void ParserFunction(StringRef Source, StringSaver &Saver, 226 SmallVectorImpl<const char *> &NewArgv, 227 bool MarkEOLs); 228 229 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input, 230 const char *const Output[], size_t OutputSize) { 231 SmallVector<const char *, 0> Actual; 232 BumpPtrAllocator A; 233 StringSaver Saver(A); 234 parse(Input, Saver, Actual, /*MarkEOLs=*/false); 235 EXPECT_EQ(OutputSize, Actual.size()); 236 for (unsigned I = 0, E = Actual.size(); I != E; ++I) { 237 if (I < OutputSize) { 238 EXPECT_STREQ(Output[I], Actual[I]); 239 } 240 } 241 } 242 243 TEST(CommandLineTest, TokenizeGNUCommandLine) { 244 const char Input[] = 245 "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) " 246 "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\""; 247 const char *const Output[] = { 248 "foo bar", "foo bar", "foo bar", "foo\\bar", 249 "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"}; 250 testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output, 251 array_lengthof(Output)); 252 } 253 254 TEST(CommandLineTest, TokenizeWindowsCommandLine1) { 255 const char Input[] = "a\\b c\\\\d e\\\\\"f g\" h\\\"i j\\\\\\\"k \"lmn\" o pqr " 256 "\"st \\\"u\" \\v"; 257 const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k", 258 "lmn", "o", "pqr", "st \"u", "\\v" }; 259 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output, 260 array_lengthof(Output)); 261 } 262 263 TEST(CommandLineTest, TokenizeWindowsCommandLine2) { 264 const char Input[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp"; 265 const char *const Output[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"}; 266 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output, 267 array_lengthof(Output)); 268 } 269 270 TEST(CommandLineTest, TokenizeConfigFile1) { 271 const char *Input = "\\"; 272 const char *const Output[] = { "\\" }; 273 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 274 array_lengthof(Output)); 275 } 276 277 TEST(CommandLineTest, TokenizeConfigFile2) { 278 const char *Input = "\\abc"; 279 const char *const Output[] = { "abc" }; 280 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 281 array_lengthof(Output)); 282 } 283 284 TEST(CommandLineTest, TokenizeConfigFile3) { 285 const char *Input = "abc\\"; 286 const char *const Output[] = { "abc\\" }; 287 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 288 array_lengthof(Output)); 289 } 290 291 TEST(CommandLineTest, TokenizeConfigFile4) { 292 const char *Input = "abc\\\n123"; 293 const char *const Output[] = { "abc123" }; 294 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 295 array_lengthof(Output)); 296 } 297 298 TEST(CommandLineTest, TokenizeConfigFile5) { 299 const char *Input = "abc\\\r\n123"; 300 const char *const Output[] = { "abc123" }; 301 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 302 array_lengthof(Output)); 303 } 304 305 TEST(CommandLineTest, TokenizeConfigFile6) { 306 const char *Input = "abc\\\n"; 307 const char *const Output[] = { "abc" }; 308 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 309 array_lengthof(Output)); 310 } 311 312 TEST(CommandLineTest, TokenizeConfigFile7) { 313 const char *Input = "abc\\\r\n"; 314 const char *const Output[] = { "abc" }; 315 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 316 array_lengthof(Output)); 317 } 318 319 TEST(CommandLineTest, TokenizeConfigFile8) { 320 SmallVector<const char *, 0> Actual; 321 BumpPtrAllocator A; 322 StringSaver Saver(A); 323 cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false); 324 EXPECT_TRUE(Actual.empty()); 325 } 326 327 TEST(CommandLineTest, TokenizeConfigFile9) { 328 SmallVector<const char *, 0> Actual; 329 BumpPtrAllocator A; 330 StringSaver Saver(A); 331 cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false); 332 EXPECT_TRUE(Actual.empty()); 333 } 334 335 TEST(CommandLineTest, TokenizeConfigFile10) { 336 const char *Input = "\\\nabc"; 337 const char *const Output[] = { "abc" }; 338 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 339 array_lengthof(Output)); 340 } 341 342 TEST(CommandLineTest, TokenizeConfigFile11) { 343 const char *Input = "\\\r\nabc"; 344 const char *const Output[] = { "abc" }; 345 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output, 346 array_lengthof(Output)); 347 } 348 349 TEST(CommandLineTest, AliasesWithArguments) { 350 static const size_t ARGC = 3; 351 const char *const Inputs[][ARGC] = { 352 { "-tool", "-actual=x", "-extra" }, 353 { "-tool", "-actual", "x" }, 354 { "-tool", "-alias=x", "-extra" }, 355 { "-tool", "-alias", "x" } 356 }; 357 358 for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) { 359 StackOption<std::string> Actual("actual"); 360 StackOption<bool> Extra("extra"); 361 StackOption<std::string> Input(cl::Positional); 362 363 cl::alias Alias("alias", llvm::cl::aliasopt(Actual)); 364 365 cl::ParseCommandLineOptions(ARGC, Inputs[i]); 366 EXPECT_EQ("x", Actual); 367 EXPECT_EQ(0, Input.getNumOccurrences()); 368 369 Alias.removeArgument(); 370 } 371 } 372 373 void testAliasRequired(int argc, const char *const *argv) { 374 StackOption<std::string> Option("option", cl::Required); 375 cl::alias Alias("o", llvm::cl::aliasopt(Option)); 376 377 cl::ParseCommandLineOptions(argc, argv); 378 EXPECT_EQ("x", Option); 379 EXPECT_EQ(1, Option.getNumOccurrences()); 380 381 Alias.removeArgument(); 382 } 383 384 TEST(CommandLineTest, AliasRequired) { 385 const char *opts1[] = { "-tool", "-option=x" }; 386 const char *opts2[] = { "-tool", "-o", "x" }; 387 testAliasRequired(array_lengthof(opts1), opts1); 388 testAliasRequired(array_lengthof(opts2), opts2); 389 } 390 391 TEST(CommandLineTest, HideUnrelatedOptions) { 392 StackOption<int> TestOption1("hide-option-1"); 393 StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory)); 394 395 cl::HideUnrelatedOptions(TestCategory); 396 397 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag()) 398 << "Failed to hide extra option."; 399 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag()) 400 << "Hid extra option that should be visable."; 401 402 StringMap<cl::Option *> &Map = 403 cl::getRegisteredOptions(*cl::TopLevelSubCommand); 404 ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag()) 405 << "Hid default option that should be visable."; 406 } 407 408 cl::OptionCategory TestCategory2("Test Options set 2", "Description"); 409 410 TEST(CommandLineTest, HideUnrelatedOptionsMulti) { 411 StackOption<int> TestOption1("multi-hide-option-1"); 412 StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory)); 413 StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2)); 414 415 const cl::OptionCategory *VisibleCategories[] = {&TestCategory, 416 &TestCategory2}; 417 418 cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories)); 419 420 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag()) 421 << "Failed to hide extra option."; 422 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag()) 423 << "Hid extra option that should be visable."; 424 ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag()) 425 << "Hid extra option that should be visable."; 426 427 StringMap<cl::Option *> &Map = 428 cl::getRegisteredOptions(*cl::TopLevelSubCommand); 429 ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag()) 430 << "Hid default option that should be visable."; 431 } 432 433 TEST(CommandLineTest, SetValueInSubcategories) { 434 cl::ResetCommandLineParser(); 435 436 StackSubCommand SC1("sc1", "First subcommand"); 437 StackSubCommand SC2("sc2", "Second subcommand"); 438 439 StackOption<bool> TopLevelOpt("top-level", cl::init(false)); 440 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false)); 441 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false)); 442 443 EXPECT_FALSE(TopLevelOpt); 444 EXPECT_FALSE(SC1Opt); 445 EXPECT_FALSE(SC2Opt); 446 const char *args[] = {"prog", "-top-level"}; 447 EXPECT_TRUE( 448 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 449 EXPECT_TRUE(TopLevelOpt); 450 EXPECT_FALSE(SC1Opt); 451 EXPECT_FALSE(SC2Opt); 452 453 TopLevelOpt = false; 454 455 cl::ResetAllOptionOccurrences(); 456 EXPECT_FALSE(TopLevelOpt); 457 EXPECT_FALSE(SC1Opt); 458 EXPECT_FALSE(SC2Opt); 459 const char *args2[] = {"prog", "sc1", "-sc1"}; 460 EXPECT_TRUE( 461 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 462 EXPECT_FALSE(TopLevelOpt); 463 EXPECT_TRUE(SC1Opt); 464 EXPECT_FALSE(SC2Opt); 465 466 SC1Opt = false; 467 468 cl::ResetAllOptionOccurrences(); 469 EXPECT_FALSE(TopLevelOpt); 470 EXPECT_FALSE(SC1Opt); 471 EXPECT_FALSE(SC2Opt); 472 const char *args3[] = {"prog", "sc2", "-sc2"}; 473 EXPECT_TRUE( 474 cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls())); 475 EXPECT_FALSE(TopLevelOpt); 476 EXPECT_FALSE(SC1Opt); 477 EXPECT_TRUE(SC2Opt); 478 } 479 480 TEST(CommandLineTest, LookupFailsInWrongSubCommand) { 481 cl::ResetCommandLineParser(); 482 483 StackSubCommand SC1("sc1", "First subcommand"); 484 StackSubCommand SC2("sc2", "Second subcommand"); 485 486 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false)); 487 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false)); 488 489 std::string Errs; 490 raw_string_ostream OS(Errs); 491 492 const char *args[] = {"prog", "sc1", "-sc2"}; 493 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS)); 494 OS.flush(); 495 EXPECT_FALSE(Errs.empty()); 496 } 497 498 TEST(CommandLineTest, AddToAllSubCommands) { 499 cl::ResetCommandLineParser(); 500 501 StackSubCommand SC1("sc1", "First subcommand"); 502 StackOption<bool> AllOpt("everywhere", cl::sub(*cl::AllSubCommands), 503 cl::init(false)); 504 StackSubCommand SC2("sc2", "Second subcommand"); 505 506 const char *args[] = {"prog", "-everywhere"}; 507 const char *args2[] = {"prog", "sc1", "-everywhere"}; 508 const char *args3[] = {"prog", "sc2", "-everywhere"}; 509 510 std::string Errs; 511 raw_string_ostream OS(Errs); 512 513 EXPECT_FALSE(AllOpt); 514 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); 515 EXPECT_TRUE(AllOpt); 516 517 AllOpt = false; 518 519 cl::ResetAllOptionOccurrences(); 520 EXPECT_FALSE(AllOpt); 521 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); 522 EXPECT_TRUE(AllOpt); 523 524 AllOpt = false; 525 526 cl::ResetAllOptionOccurrences(); 527 EXPECT_FALSE(AllOpt); 528 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); 529 EXPECT_TRUE(AllOpt); 530 531 // Since all parsing succeeded, the error message should be empty. 532 OS.flush(); 533 EXPECT_TRUE(Errs.empty()); 534 } 535 536 TEST(CommandLineTest, ReparseCommandLineOptions) { 537 cl::ResetCommandLineParser(); 538 539 StackOption<bool> TopLevelOpt("top-level", cl::sub(*cl::TopLevelSubCommand), 540 cl::init(false)); 541 542 const char *args[] = {"prog", "-top-level"}; 543 544 EXPECT_FALSE(TopLevelOpt); 545 EXPECT_TRUE( 546 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 547 EXPECT_TRUE(TopLevelOpt); 548 549 TopLevelOpt = false; 550 551 cl::ResetAllOptionOccurrences(); 552 EXPECT_FALSE(TopLevelOpt); 553 EXPECT_TRUE( 554 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 555 EXPECT_TRUE(TopLevelOpt); 556 } 557 558 TEST(CommandLineTest, RemoveFromRegularSubCommand) { 559 cl::ResetCommandLineParser(); 560 561 StackSubCommand SC("sc", "Subcommand"); 562 StackOption<bool> RemoveOption("remove-option", cl::sub(SC), cl::init(false)); 563 StackOption<bool> KeepOption("keep-option", cl::sub(SC), cl::init(false)); 564 565 const char *args[] = {"prog", "sc", "-remove-option"}; 566 567 std::string Errs; 568 raw_string_ostream OS(Errs); 569 570 EXPECT_FALSE(RemoveOption); 571 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS)); 572 EXPECT_TRUE(RemoveOption); 573 OS.flush(); 574 EXPECT_TRUE(Errs.empty()); 575 576 RemoveOption.removeArgument(); 577 578 cl::ResetAllOptionOccurrences(); 579 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS)); 580 OS.flush(); 581 EXPECT_FALSE(Errs.empty()); 582 } 583 584 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) { 585 cl::ResetCommandLineParser(); 586 587 StackOption<bool> TopLevelRemove( 588 "top-level-remove", cl::sub(*cl::TopLevelSubCommand), cl::init(false)); 589 StackOption<bool> TopLevelKeep( 590 "top-level-keep", cl::sub(*cl::TopLevelSubCommand), cl::init(false)); 591 592 const char *args[] = {"prog", "-top-level-remove"}; 593 594 EXPECT_FALSE(TopLevelRemove); 595 EXPECT_TRUE( 596 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 597 EXPECT_TRUE(TopLevelRemove); 598 599 TopLevelRemove.removeArgument(); 600 601 cl::ResetAllOptionOccurrences(); 602 EXPECT_FALSE( 603 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 604 } 605 606 TEST(CommandLineTest, RemoveFromAllSubCommands) { 607 cl::ResetCommandLineParser(); 608 609 StackSubCommand SC1("sc1", "First Subcommand"); 610 StackSubCommand SC2("sc2", "Second Subcommand"); 611 StackOption<bool> RemoveOption("remove-option", cl::sub(*cl::AllSubCommands), 612 cl::init(false)); 613 StackOption<bool> KeepOption("keep-option", cl::sub(*cl::AllSubCommands), 614 cl::init(false)); 615 616 const char *args0[] = {"prog", "-remove-option"}; 617 const char *args1[] = {"prog", "sc1", "-remove-option"}; 618 const char *args2[] = {"prog", "sc2", "-remove-option"}; 619 620 // It should work for all subcommands including the top-level. 621 EXPECT_FALSE(RemoveOption); 622 EXPECT_TRUE( 623 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls())); 624 EXPECT_TRUE(RemoveOption); 625 626 RemoveOption = false; 627 628 cl::ResetAllOptionOccurrences(); 629 EXPECT_FALSE(RemoveOption); 630 EXPECT_TRUE( 631 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls())); 632 EXPECT_TRUE(RemoveOption); 633 634 RemoveOption = false; 635 636 cl::ResetAllOptionOccurrences(); 637 EXPECT_FALSE(RemoveOption); 638 EXPECT_TRUE( 639 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 640 EXPECT_TRUE(RemoveOption); 641 642 RemoveOption.removeArgument(); 643 644 // It should not work for any subcommands including the top-level. 645 cl::ResetAllOptionOccurrences(); 646 EXPECT_FALSE( 647 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls())); 648 cl::ResetAllOptionOccurrences(); 649 EXPECT_FALSE( 650 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls())); 651 cl::ResetAllOptionOccurrences(); 652 EXPECT_FALSE( 653 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 654 } 655 656 TEST(CommandLineTest, GetRegisteredSubcommands) { 657 cl::ResetCommandLineParser(); 658 659 StackSubCommand SC1("sc1", "First Subcommand"); 660 StackOption<bool> Opt1("opt1", cl::sub(SC1), cl::init(false)); 661 StackSubCommand SC2("sc2", "Second subcommand"); 662 StackOption<bool> Opt2("opt2", cl::sub(SC2), cl::init(false)); 663 664 const char *args0[] = {"prog", "sc1"}; 665 const char *args1[] = {"prog", "sc2"}; 666 667 EXPECT_TRUE( 668 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls())); 669 EXPECT_FALSE(Opt1); 670 EXPECT_FALSE(Opt2); 671 for (auto *S : cl::getRegisteredSubcommands()) { 672 if (*S) { 673 EXPECT_EQ("sc1", S->getName()); 674 } 675 } 676 677 cl::ResetAllOptionOccurrences(); 678 EXPECT_TRUE( 679 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls())); 680 EXPECT_FALSE(Opt1); 681 EXPECT_FALSE(Opt2); 682 for (auto *S : cl::getRegisteredSubcommands()) { 683 if (*S) { 684 EXPECT_EQ("sc2", S->getName()); 685 } 686 } 687 } 688 689 TEST(CommandLineTest, DefaultOptions) { 690 cl::ResetCommandLineParser(); 691 692 StackOption<std::string> Bar("bar", cl::sub(*cl::AllSubCommands), 693 cl::DefaultOption); 694 StackOption<std::string, cl::alias> Bar_Alias( 695 "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption); 696 697 StackOption<bool> Foo("foo", cl::init(false), cl::sub(*cl::AllSubCommands), 698 cl::DefaultOption); 699 StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"), 700 cl::aliasopt(Foo), cl::DefaultOption); 701 702 StackSubCommand SC1("sc1", "First Subcommand"); 703 // Override "-b" and change type in sc1 SubCommand. 704 StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false)); 705 StackSubCommand SC2("sc2", "Second subcommand"); 706 // Override "-foo" and change type in sc2 SubCommand. Note that this does not 707 // affect "-f" alias, which continues to work correctly. 708 StackOption<std::string> SC2_Foo("foo", cl::sub(SC2)); 709 710 const char *args0[] = {"prog", "-b", "args0 bar string", "-f"}; 711 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args0) / sizeof(char *), args0, 712 StringRef(), &llvm::nulls())); 713 EXPECT_TRUE(Bar == "args0 bar string"); 714 EXPECT_TRUE(Foo); 715 EXPECT_FALSE(SC1_B); 716 EXPECT_TRUE(SC2_Foo.empty()); 717 718 cl::ResetAllOptionOccurrences(); 719 720 const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"}; 721 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args1) / sizeof(char *), args1, 722 StringRef(), &llvm::nulls())); 723 EXPECT_TRUE(Bar == "args1 bar string"); 724 EXPECT_TRUE(Foo); 725 EXPECT_TRUE(SC1_B); 726 EXPECT_TRUE(SC2_Foo.empty()); 727 for (auto *S : cl::getRegisteredSubcommands()) { 728 if (*S) { 729 EXPECT_EQ("sc1", S->getName()); 730 } 731 } 732 733 cl::ResetAllOptionOccurrences(); 734 735 const char *args2[] = {"prog", "sc2", "-b", "args2 bar string", 736 "-f", "-foo", "foo string"}; 737 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args2) / sizeof(char *), args2, 738 StringRef(), &llvm::nulls())); 739 EXPECT_TRUE(Bar == "args2 bar string"); 740 EXPECT_TRUE(Foo); 741 EXPECT_FALSE(SC1_B); 742 EXPECT_TRUE(SC2_Foo == "foo string"); 743 for (auto *S : cl::getRegisteredSubcommands()) { 744 if (*S) { 745 EXPECT_EQ("sc2", S->getName()); 746 } 747 } 748 cl::ResetCommandLineParser(); 749 } 750 751 TEST(CommandLineTest, ArgumentLimit) { 752 std::string args(32 * 4096, 'a'); 753 EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data())); 754 } 755 756 TEST(CommandLineTest, ResponseFileWindows) { 757 if (!Triple(sys::getProcessTriple()).isOSWindows()) 758 return; 759 760 StackOption<std::string, cl::list<std::string>> InputFilenames( 761 cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore); 762 StackOption<bool> TopLevelOpt("top-level", cl::init(false)); 763 764 // Create response file. 765 int FileDescriptor; 766 SmallString<64> TempPath; 767 std::error_code EC = 768 llvm::sys::fs::createTemporaryFile("resp-", ".txt", FileDescriptor, TempPath); 769 EXPECT_TRUE(!EC); 770 771 std::ofstream RspFile(TempPath.c_str()); 772 EXPECT_TRUE(RspFile.is_open()); 773 RspFile << "-top-level\npath\\dir\\file1\npath/dir/file2"; 774 RspFile.close(); 775 776 llvm::SmallString<128> RspOpt; 777 RspOpt.append(1, '@'); 778 RspOpt.append(TempPath.c_str()); 779 const char *args[] = {"prog", RspOpt.c_str()}; 780 EXPECT_FALSE(TopLevelOpt); 781 EXPECT_TRUE( 782 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 783 EXPECT_TRUE(TopLevelOpt); 784 EXPECT_TRUE(InputFilenames[0] == "path\\dir\\file1"); 785 EXPECT_TRUE(InputFilenames[1] == "path/dir/file2"); 786 787 llvm::sys::fs::remove(TempPath.c_str()); 788 } 789 790 TEST(CommandLineTest, ResponseFiles) { 791 vfs::InMemoryFileSystem FS; 792 #ifdef _WIN32 793 const char *TestRoot = "C:\\"; 794 #else 795 const char *TestRoot = "/"; 796 #endif 797 FS.setCurrentWorkingDirectory(TestRoot); 798 799 // Create included response file of first level. 800 llvm::StringRef IncludedFileName = "resp1"; 801 FS.addFile(IncludedFileName, 0, 802 llvm::MemoryBuffer::getMemBuffer("-option_1 -option_2\n" 803 "@incdir/resp2\n" 804 "-option_3=abcd\n" 805 "@incdir/resp3\n" 806 "-option_4=efjk\n")); 807 808 // Directory for included file. 809 llvm::StringRef IncDir = "incdir"; 810 811 // Create included response file of second level. 812 llvm::SmallString<128> IncludedFileName2; 813 llvm::sys::path::append(IncludedFileName2, IncDir, "resp2"); 814 FS.addFile(IncludedFileName2, 0, 815 MemoryBuffer::getMemBuffer("-option_21 -option_22\n" 816 "-option_23=abcd\n")); 817 818 // Create second included response file of second level. 819 llvm::SmallString<128> IncludedFileName3; 820 llvm::sys::path::append(IncludedFileName3, IncDir, "resp3"); 821 FS.addFile(IncludedFileName3, 0, 822 MemoryBuffer::getMemBuffer("-option_31 -option_32\n" 823 "-option_33=abcd\n")); 824 825 // Prepare 'file' with reference to response file. 826 SmallString<128> IncRef; 827 IncRef.append(1, '@'); 828 IncRef.append(IncludedFileName); 829 llvm::SmallVector<const char *, 4> Argv = {"test/test", "-flag_1", 830 IncRef.c_str(), "-flag_2"}; 831 832 // Expand response files. 833 llvm::BumpPtrAllocator A; 834 llvm::StringSaver Saver(A); 835 ASSERT_TRUE(llvm::cl::ExpandResponseFiles( 836 Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true, FS, 837 /*CurrentDir=*/StringRef(TestRoot))); 838 EXPECT_THAT(Argv, testing::Pointwise( 839 StringEquality(), 840 {"test/test", "-flag_1", "-option_1", "-option_2", 841 "-option_21", "-option_22", "-option_23=abcd", 842 "-option_3=abcd", "-option_31", "-option_32", 843 "-option_33=abcd", "-option_4=efjk", "-flag_2"})); 844 } 845 846 TEST(CommandLineTest, RecursiveResponseFiles) { 847 vfs::InMemoryFileSystem FS; 848 #ifdef _WIN32 849 const char *TestRoot = "C:\\"; 850 #else 851 const char *TestRoot = "/"; 852 #endif 853 FS.setCurrentWorkingDirectory(TestRoot); 854 855 StringRef SelfFilePath = "self.rsp"; 856 std::string SelfFileRef = ("@" + SelfFilePath).str(); 857 858 StringRef NestedFilePath = "nested.rsp"; 859 std::string NestedFileRef = ("@" + NestedFilePath).str(); 860 861 StringRef FlagFilePath = "flag.rsp"; 862 std::string FlagFileRef = ("@" + FlagFilePath).str(); 863 864 std::string SelfFileContents; 865 raw_string_ostream SelfFile(SelfFileContents); 866 SelfFile << "-option_1\n"; 867 SelfFile << FlagFileRef << "\n"; 868 SelfFile << NestedFileRef << "\n"; 869 SelfFile << SelfFileRef << "\n"; 870 FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str())); 871 872 std::string NestedFileContents; 873 raw_string_ostream NestedFile(NestedFileContents); 874 NestedFile << "-option_2\n"; 875 NestedFile << FlagFileRef << "\n"; 876 NestedFile << SelfFileRef << "\n"; 877 NestedFile << NestedFileRef << "\n"; 878 FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str())); 879 880 std::string FlagFileContents; 881 raw_string_ostream FlagFile(FlagFileContents); 882 FlagFile << "-option_x\n"; 883 FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str())); 884 885 // Ensure: 886 // Recursive expansion terminates 887 // Recursive files never expand 888 // Non-recursive repeats are allowed 889 SmallVector<const char *, 4> Argv = {"test/test", SelfFileRef.c_str(), 890 "-option_3"}; 891 BumpPtrAllocator A; 892 StringSaver Saver(A); 893 #ifdef _WIN32 894 cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine; 895 #else 896 cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine; 897 #endif 898 ASSERT_FALSE( 899 cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false, FS, 900 /*CurrentDir=*/llvm::StringRef(TestRoot))); 901 902 EXPECT_THAT(Argv, 903 testing::Pointwise(StringEquality(), 904 {"test/test", "-option_1", "-option_x", 905 "-option_2", "-option_x", SelfFileRef.c_str(), 906 NestedFileRef.c_str(), SelfFileRef.c_str(), 907 "-option_3"})); 908 } 909 910 TEST(CommandLineTest, ResponseFilesAtArguments) { 911 vfs::InMemoryFileSystem FS; 912 #ifdef _WIN32 913 const char *TestRoot = "C:\\"; 914 #else 915 const char *TestRoot = "/"; 916 #endif 917 FS.setCurrentWorkingDirectory(TestRoot); 918 919 StringRef ResponseFilePath = "test.rsp"; 920 921 std::string ResponseFileContents; 922 raw_string_ostream ResponseFile(ResponseFileContents); 923 ResponseFile << "-foo" << "\n"; 924 ResponseFile << "-bar" << "\n"; 925 FS.addFile(ResponseFilePath, 0, 926 MemoryBuffer::getMemBuffer(ResponseFile.str())); 927 928 // Ensure we expand rsp files after lots of non-rsp arguments starting with @. 929 constexpr size_t NON_RSP_AT_ARGS = 64; 930 SmallVector<const char *, 4> Argv = {"test/test"}; 931 Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg"); 932 std::string ResponseFileRef = ("@" + ResponseFilePath).str(); 933 Argv.push_back(ResponseFileRef.c_str()); 934 935 BumpPtrAllocator A; 936 StringSaver Saver(A); 937 ASSERT_FALSE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv, 938 false, false, FS, 939 /*CurrentDir=*/StringRef(TestRoot))); 940 941 // ASSERT instead of EXPECT to prevent potential out-of-bounds access. 942 ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2); 943 size_t i = 0; 944 EXPECT_STREQ(Argv[i++], "test/test"); 945 for (; i < 1 + NON_RSP_AT_ARGS; ++i) 946 EXPECT_STREQ(Argv[i], "@non_rsp_at_arg"); 947 EXPECT_STREQ(Argv[i++], "-foo"); 948 EXPECT_STREQ(Argv[i++], "-bar"); 949 } 950 951 TEST(CommandLineTest, ResponseFileRelativePath) { 952 vfs::InMemoryFileSystem FS; 953 #ifdef _WIN32 954 const char *TestRoot = "C:\\"; 955 #else 956 const char *TestRoot = "//net"; 957 #endif 958 FS.setCurrentWorkingDirectory(TestRoot); 959 960 StringRef OuterFile = "dir/outer.rsp"; 961 StringRef OuterFileContents = "@inner.rsp"; 962 FS.addFile(OuterFile, 0, MemoryBuffer::getMemBuffer(OuterFileContents)); 963 964 StringRef InnerFile = "dir/inner.rsp"; 965 StringRef InnerFileContents = "-flag"; 966 FS.addFile(InnerFile, 0, MemoryBuffer::getMemBuffer(InnerFileContents)); 967 968 SmallVector<const char *, 2> Argv = {"test/test", "@dir/outer.rsp"}; 969 970 BumpPtrAllocator A; 971 StringSaver Saver(A); 972 ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv, 973 false, true, FS, 974 /*CurrentDir=*/StringRef(TestRoot))); 975 EXPECT_THAT(Argv, 976 testing::Pointwise(StringEquality(), {"test/test", "-flag"})); 977 } 978 979 TEST(CommandLineTest, SetDefautValue) { 980 cl::ResetCommandLineParser(); 981 982 StackOption<std::string> Opt1("opt1", cl::init("true")); 983 StackOption<bool> Opt2("opt2", cl::init(true)); 984 cl::alias Alias("alias", llvm::cl::aliasopt(Opt2)); 985 StackOption<int> Opt3("opt3", cl::init(3)); 986 987 const char *args[] = {"prog", "-opt1=false", "-opt2", "-opt3"}; 988 989 EXPECT_TRUE( 990 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 991 992 EXPECT_TRUE(Opt1 == "false"); 993 EXPECT_TRUE(Opt2); 994 EXPECT_TRUE(Opt3 == 3); 995 996 Opt2 = false; 997 Opt3 = 1; 998 999 cl::ResetAllOptionOccurrences(); 1000 1001 for (auto &OM : cl::getRegisteredOptions(*cl::TopLevelSubCommand)) { 1002 cl::Option *O = OM.second; 1003 if (O->ArgStr == "opt2") { 1004 continue; 1005 } 1006 O->setDefault(); 1007 } 1008 1009 EXPECT_TRUE(Opt1 == "true"); 1010 EXPECT_TRUE(Opt2); 1011 EXPECT_TRUE(Opt3 == 3); 1012 Alias.removeArgument(); 1013 } 1014 1015 TEST(CommandLineTest, ReadConfigFile) { 1016 llvm::SmallVector<const char *, 1> Argv; 1017 1018 llvm::SmallString<128> TestDir; 1019 std::error_code EC = 1020 llvm::sys::fs::createUniqueDirectory("unittest", TestDir); 1021 EXPECT_TRUE(!EC); 1022 1023 llvm::SmallString<128> TestCfg; 1024 llvm::sys::path::append(TestCfg, TestDir, "foo"); 1025 std::ofstream ConfigFile(TestCfg.c_str()); 1026 EXPECT_TRUE(ConfigFile.is_open()); 1027 ConfigFile << "# Comment\n" 1028 "-option_1\n" 1029 "@subconfig\n" 1030 "-option_3=abcd\n" 1031 "-option_4=\\\n" 1032 "cdef\n"; 1033 ConfigFile.close(); 1034 1035 llvm::SmallString<128> TestCfg2; 1036 llvm::sys::path::append(TestCfg2, TestDir, "subconfig"); 1037 std::ofstream ConfigFile2(TestCfg2.c_str()); 1038 EXPECT_TRUE(ConfigFile2.is_open()); 1039 ConfigFile2 << "-option_2\n" 1040 "\n" 1041 " # comment\n"; 1042 ConfigFile2.close(); 1043 1044 // Make sure the current directory is not the directory where config files 1045 // resides. In this case the code that expands response files will not find 1046 // 'subconfig' unless it resolves nested inclusions relative to the including 1047 // file. 1048 llvm::SmallString<128> CurrDir; 1049 EC = llvm::sys::fs::current_path(CurrDir); 1050 EXPECT_TRUE(!EC); 1051 EXPECT_TRUE(StringRef(CurrDir) != StringRef(TestDir)); 1052 1053 llvm::BumpPtrAllocator A; 1054 llvm::StringSaver Saver(A); 1055 bool Result = llvm::cl::readConfigFile(TestCfg, Saver, Argv); 1056 1057 EXPECT_TRUE(Result); 1058 EXPECT_EQ(Argv.size(), 4U); 1059 EXPECT_STREQ(Argv[0], "-option_1"); 1060 EXPECT_STREQ(Argv[1], "-option_2"); 1061 EXPECT_STREQ(Argv[2], "-option_3=abcd"); 1062 EXPECT_STREQ(Argv[3], "-option_4=cdef"); 1063 1064 llvm::sys::fs::remove(TestCfg2); 1065 llvm::sys::fs::remove(TestCfg); 1066 llvm::sys::fs::remove(TestDir); 1067 } 1068 1069 TEST(CommandLineTest, PositionalEatArgsError) { 1070 cl::ResetCommandLineParser(); 1071 1072 StackOption<std::string, cl::list<std::string>> PosEatArgs( 1073 "positional-eat-args", cl::Positional, cl::desc("<arguments>..."), 1074 cl::ZeroOrMore, cl::PositionalEatsArgs); 1075 StackOption<std::string, cl::list<std::string>> PosEatArgs2( 1076 "positional-eat-args2", cl::Positional, cl::desc("Some strings"), 1077 cl::ZeroOrMore, cl::PositionalEatsArgs); 1078 1079 const char *args[] = {"prog", "-positional-eat-args=XXXX"}; 1080 const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"}; 1081 const char *args3[] = {"prog", "-positional-eat-args", "-foo"}; 1082 const char *args4[] = {"prog", "-positional-eat-args", 1083 "-foo", "-positional-eat-args2", 1084 "-bar", "foo"}; 1085 1086 std::string Errs; 1087 raw_string_ostream OS(Errs); 1088 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush(); 1089 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1090 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush(); 1091 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1092 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush(); 1093 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1094 1095 cl::ResetAllOptionOccurrences(); 1096 EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4, StringRef(), &OS)); OS.flush(); 1097 EXPECT_TRUE(PosEatArgs.size() == 1); 1098 EXPECT_TRUE(PosEatArgs2.size() == 2); 1099 EXPECT_TRUE(Errs.empty()); 1100 } 1101 1102 #ifdef _WIN32 1103 TEST(CommandLineTest, GetCommandLineArguments) { 1104 int argc = __argc; 1105 char **argv = __argv; 1106 1107 // GetCommandLineArguments is called in InitLLVM. 1108 llvm::InitLLVM X(argc, argv); 1109 1110 EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]), 1111 llvm::sys::path::is_absolute(__argv[0])); 1112 1113 EXPECT_TRUE(llvm::sys::path::filename(argv[0]) 1114 .equals_lower("supporttests.exe")) 1115 << "Filename of test executable is " 1116 << llvm::sys::path::filename(argv[0]); 1117 } 1118 #endif 1119 1120 class OutputRedirector { 1121 public: 1122 OutputRedirector(int RedirectFD) 1123 : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) { 1124 if (OldFD == -1 || 1125 sys::fs::createTemporaryFile("unittest-redirect", "", NewFD, 1126 FilePath) || 1127 dup2(NewFD, RedirectFD) == -1) 1128 Valid = false; 1129 } 1130 1131 ~OutputRedirector() { 1132 dup2(OldFD, RedirectFD); 1133 close(OldFD); 1134 close(NewFD); 1135 } 1136 1137 SmallVector<char, 128> FilePath; 1138 bool Valid = true; 1139 1140 private: 1141 int RedirectFD; 1142 int OldFD; 1143 int NewFD; 1144 }; 1145 1146 struct AutoDeleteFile { 1147 SmallVector<char, 128> FilePath; 1148 ~AutoDeleteFile() { 1149 if (!FilePath.empty()) 1150 sys::fs::remove(std::string(FilePath.data(), FilePath.size())); 1151 } 1152 }; 1153 1154 class PrintOptionInfoTest : public ::testing::Test { 1155 public: 1156 // Return std::string because the output of a failing EXPECT check is 1157 // unreadable for StringRef. It also avoids any lifetime issues. 1158 template <typename... Ts> std::string runTest(Ts... OptionAttributes) { 1159 outs().flush(); // flush any output from previous tests 1160 AutoDeleteFile File; 1161 { 1162 OutputRedirector Stdout(fileno(stdout)); 1163 if (!Stdout.Valid) 1164 return ""; 1165 File.FilePath = Stdout.FilePath; 1166 1167 StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText), 1168 OptionAttributes...); 1169 printOptionInfo(TestOption, 26); 1170 outs().flush(); 1171 } 1172 auto Buffer = MemoryBuffer::getFile(File.FilePath); 1173 if (!Buffer) 1174 return ""; 1175 return Buffer->get()->getBuffer().str(); 1176 } 1177 1178 enum class OptionValue { Val }; 1179 const StringRef Opt = "some-option"; 1180 const StringRef HelpText = "some help"; 1181 1182 private: 1183 // This is a workaround for cl::Option sub-classes having their 1184 // printOptionInfo functions private. 1185 void printOptionInfo(const cl::Option &O, size_t Width) { 1186 O.printOptionInfo(Width); 1187 } 1188 }; 1189 1190 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) { 1191 std::string Output = 1192 runTest(cl::ValueOptional, 1193 cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"))); 1194 1195 // clang-format off 1196 EXPECT_EQ(Output, (" --" + Opt + "=<value> - " + HelpText + "\n" 1197 " =v1 - desc1\n") 1198 .str()); 1199 // clang-format on 1200 } 1201 1202 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) { 1203 std::string Output = runTest( 1204 cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"), 1205 clEnumValN(OptionValue::Val, "", ""))); 1206 1207 // clang-format off 1208 EXPECT_EQ(Output, 1209 (" --" + Opt + " - " + HelpText + "\n" 1210 " --" + Opt + "=<value> - " + HelpText + "\n" 1211 " =v1 - desc1\n") 1212 .str()); 1213 // clang-format on 1214 } 1215 1216 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) { 1217 std::string Output = runTest( 1218 cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"), 1219 clEnumValN(OptionValue::Val, "", "desc2"))); 1220 1221 // clang-format off 1222 EXPECT_EQ(Output, (" --" + Opt + " - " + HelpText + "\n" 1223 " --" + Opt + "=<value> - " + HelpText + "\n" 1224 " =v1 - desc1\n" 1225 " =<empty> - desc2\n") 1226 .str()); 1227 // clang-format on 1228 } 1229 1230 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) { 1231 std::string Output = runTest( 1232 cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"), 1233 clEnumValN(OptionValue::Val, "", ""))); 1234 1235 // clang-format off 1236 EXPECT_EQ(Output, (" --" + Opt + "=<value> - " + HelpText + "\n" 1237 " =v1 - desc1\n" 1238 " =<empty>\n") 1239 .str()); 1240 // clang-format on 1241 } 1242 1243 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) { 1244 std::string Output = runTest( 1245 cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", ""))); 1246 1247 // clang-format off 1248 EXPECT_EQ(Output, 1249 (" --" + Opt + "=<value> - " + HelpText + "\n" 1250 " =v1\n").str()); 1251 // clang-format on 1252 } 1253 1254 class GetOptionWidthTest : public ::testing::Test { 1255 public: 1256 enum class OptionValue { Val }; 1257 1258 template <typename... Ts> 1259 size_t runTest(StringRef ArgName, Ts... OptionAttributes) { 1260 StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"), 1261 OptionAttributes...); 1262 return getOptionWidth(TestOption); 1263 } 1264 1265 private: 1266 // This is a workaround for cl::Option sub-classes having their 1267 // printOptionInfo 1268 // functions private. 1269 size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); } 1270 }; 1271 1272 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) { 1273 StringRef ArgName("a-long-argument-name"); 1274 size_t ExpectedStrSize = (" --" + ArgName + "=<value> - ").str().size(); 1275 EXPECT_EQ( 1276 runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))), 1277 ExpectedStrSize); 1278 } 1279 1280 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) { 1281 StringRef OptName("a-long-option-name"); 1282 size_t ExpectedStrSize = (" =" + OptName + " - ").str().size(); 1283 EXPECT_EQ( 1284 runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"), 1285 clEnumValN(OptionValue::Val, "b", "help"))), 1286 ExpectedStrSize); 1287 } 1288 1289 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) { 1290 StringRef OptName("a-long-option-name"); 1291 size_t ExpectedStrSize = (" =" + OptName + " - ").str().size(); 1292 EXPECT_EQ( 1293 runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"), 1294 clEnumValN(OptionValue::Val, OptName, "help"))), 1295 ExpectedStrSize); 1296 } 1297 1298 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) { 1299 size_t ExpectedStrSize = StringRef(" =<empty> - ").size(); 1300 // The length of a=<value> (including indentation) is actually the same as the 1301 // =<empty> string, so it is impossible to distinguish via testing the case 1302 // where the empty string is picked from where the option name is picked. 1303 EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"), 1304 clEnumValN(OptionValue::Val, "", "help"))), 1305 ExpectedStrSize); 1306 } 1307 1308 TEST_F(GetOptionWidthTest, 1309 GetOptionWidthValueOptionalEmptyOptionWithNoDescription) { 1310 StringRef ArgName("a"); 1311 // The length of a=<value> (including indentation) is actually the same as the 1312 // =<empty> string, so it is impossible to distinguish via testing the case 1313 // where the empty string is ignored from where it is not ignored. 1314 // The dash will not actually be printed, but the space it would take up is 1315 // included to ensure a consistent column width. 1316 size_t ExpectedStrSize = (" -" + ArgName + "=<value> - ").str().size(); 1317 EXPECT_EQ(runTest(ArgName, cl::ValueOptional, 1318 cl::values(clEnumValN(OptionValue::Val, "value", "help"), 1319 clEnumValN(OptionValue::Val, "", ""))), 1320 ExpectedStrSize); 1321 } 1322 1323 TEST_F(GetOptionWidthTest, 1324 GetOptionWidthValueRequiredEmptyOptionWithNoDescription) { 1325 // The length of a=<value> (including indentation) is actually the same as the 1326 // =<empty> string, so it is impossible to distinguish via testing the case 1327 // where the empty string is picked from where the option name is picked 1328 size_t ExpectedStrSize = StringRef(" =<empty> - ").size(); 1329 EXPECT_EQ(runTest("a", cl::ValueRequired, 1330 cl::values(clEnumValN(OptionValue::Val, "value", "help"), 1331 clEnumValN(OptionValue::Val, "", ""))), 1332 ExpectedStrSize); 1333 } 1334 1335 TEST(CommandLineTest, PrefixOptions) { 1336 cl::ResetCommandLineParser(); 1337 1338 StackOption<std::string, cl::list<std::string>> IncludeDirs( 1339 "I", cl::Prefix, cl::desc("Declare an include directory")); 1340 1341 // Test non-prefixed variant works with cl::Prefix options. 1342 EXPECT_TRUE(IncludeDirs.empty()); 1343 const char *args[] = {"prog", "-I=/usr/include"}; 1344 EXPECT_TRUE( 1345 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 1346 EXPECT_TRUE(IncludeDirs.size() == 1); 1347 EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0); 1348 1349 IncludeDirs.erase(IncludeDirs.begin()); 1350 cl::ResetAllOptionOccurrences(); 1351 1352 // Test non-prefixed variant works with cl::Prefix options when value is 1353 // passed in following argument. 1354 EXPECT_TRUE(IncludeDirs.empty()); 1355 const char *args2[] = {"prog", "-I", "/usr/include"}; 1356 EXPECT_TRUE( 1357 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 1358 EXPECT_TRUE(IncludeDirs.size() == 1); 1359 EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0); 1360 1361 IncludeDirs.erase(IncludeDirs.begin()); 1362 cl::ResetAllOptionOccurrences(); 1363 1364 // Test prefixed variant works with cl::Prefix options. 1365 EXPECT_TRUE(IncludeDirs.empty()); 1366 const char *args3[] = {"prog", "-I/usr/include"}; 1367 EXPECT_TRUE( 1368 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls())); 1369 EXPECT_TRUE(IncludeDirs.size() == 1); 1370 EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0); 1371 1372 StackOption<std::string, cl::list<std::string>> MacroDefs( 1373 "D", cl::AlwaysPrefix, cl::desc("Define a macro"), 1374 cl::value_desc("MACRO[=VALUE]")); 1375 1376 cl::ResetAllOptionOccurrences(); 1377 1378 // Test non-prefixed variant does not work with cl::AlwaysPrefix options: 1379 // equal sign is part of the value. 1380 EXPECT_TRUE(MacroDefs.empty()); 1381 const char *args4[] = {"prog", "-D=HAVE_FOO"}; 1382 EXPECT_TRUE( 1383 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls())); 1384 EXPECT_TRUE(MacroDefs.size() == 1); 1385 EXPECT_TRUE(MacroDefs.front().compare("=HAVE_FOO") == 0); 1386 1387 MacroDefs.erase(MacroDefs.begin()); 1388 cl::ResetAllOptionOccurrences(); 1389 1390 // Test non-prefixed variant does not allow value to be passed in following 1391 // argument with cl::AlwaysPrefix options. 1392 EXPECT_TRUE(MacroDefs.empty()); 1393 const char *args5[] = {"prog", "-D", "HAVE_FOO"}; 1394 EXPECT_FALSE( 1395 cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls())); 1396 EXPECT_TRUE(MacroDefs.empty()); 1397 1398 cl::ResetAllOptionOccurrences(); 1399 1400 // Test prefixed variant works with cl::AlwaysPrefix options. 1401 EXPECT_TRUE(MacroDefs.empty()); 1402 const char *args6[] = {"prog", "-DHAVE_FOO"}; 1403 EXPECT_TRUE( 1404 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls())); 1405 EXPECT_TRUE(MacroDefs.size() == 1); 1406 EXPECT_TRUE(MacroDefs.front().compare("HAVE_FOO") == 0); 1407 } 1408 1409 TEST(CommandLineTest, GroupingWithValue) { 1410 cl::ResetCommandLineParser(); 1411 1412 StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag")); 1413 StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag")); 1414 StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed, 1415 cl::desc("ValueDisallowed option")); 1416 StackOption<std::string> OptV("v", cl::Grouping, 1417 cl::desc("ValueRequired option")); 1418 StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional, 1419 cl::desc("ValueOptional option")); 1420 1421 // Should be possible to use an option which requires a value 1422 // at the end of a group. 1423 const char *args1[] = {"prog", "-fv", "val1"}; 1424 EXPECT_TRUE( 1425 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls())); 1426 EXPECT_TRUE(OptF); 1427 EXPECT_STREQ("val1", OptV.c_str()); 1428 OptV.clear(); 1429 cl::ResetAllOptionOccurrences(); 1430 1431 // Should not crash if it is accidentally used elsewhere in the group. 1432 const char *args2[] = {"prog", "-vf", "val2"}; 1433 EXPECT_FALSE( 1434 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 1435 OptV.clear(); 1436 cl::ResetAllOptionOccurrences(); 1437 1438 // Should allow the "opt=value" form at the end of the group 1439 const char *args3[] = {"prog", "-fv=val3"}; 1440 EXPECT_TRUE( 1441 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls())); 1442 EXPECT_TRUE(OptF); 1443 EXPECT_STREQ("val3", OptV.c_str()); 1444 OptV.clear(); 1445 cl::ResetAllOptionOccurrences(); 1446 1447 // Should allow assigning a value for a ValueOptional option 1448 // at the end of the group 1449 const char *args4[] = {"prog", "-fo=val4"}; 1450 EXPECT_TRUE( 1451 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls())); 1452 EXPECT_TRUE(OptF); 1453 EXPECT_STREQ("val4", OptO.c_str()); 1454 OptO.clear(); 1455 cl::ResetAllOptionOccurrences(); 1456 1457 // Should assign an empty value if a ValueOptional option is used elsewhere 1458 // in the group. 1459 const char *args5[] = {"prog", "-fob"}; 1460 EXPECT_TRUE( 1461 cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls())); 1462 EXPECT_TRUE(OptF); 1463 EXPECT_EQ(1, OptO.getNumOccurrences()); 1464 EXPECT_EQ(1, OptB.getNumOccurrences()); 1465 EXPECT_TRUE(OptO.empty()); 1466 cl::ResetAllOptionOccurrences(); 1467 1468 // Should not allow an assignment for a ValueDisallowed option. 1469 const char *args6[] = {"prog", "-fd=false"}; 1470 EXPECT_FALSE( 1471 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls())); 1472 } 1473 1474 TEST(CommandLineTest, GroupingAndPrefix) { 1475 cl::ResetCommandLineParser(); 1476 1477 StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag")); 1478 StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag")); 1479 StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping, 1480 cl::desc("Prefix and Grouping")); 1481 StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping, 1482 cl::desc("AlwaysPrefix and Grouping")); 1483 1484 // Should be possible to use a cl::Prefix option without grouping. 1485 const char *args1[] = {"prog", "-pval1"}; 1486 EXPECT_TRUE( 1487 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls())); 1488 EXPECT_STREQ("val1", OptP.c_str()); 1489 OptP.clear(); 1490 cl::ResetAllOptionOccurrences(); 1491 1492 // Should be possible to pass a value in a separate argument. 1493 const char *args2[] = {"prog", "-p", "val2"}; 1494 EXPECT_TRUE( 1495 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 1496 EXPECT_STREQ("val2", OptP.c_str()); 1497 OptP.clear(); 1498 cl::ResetAllOptionOccurrences(); 1499 1500 // The "-opt=value" form should work, too. 1501 const char *args3[] = {"prog", "-p=val3"}; 1502 EXPECT_TRUE( 1503 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls())); 1504 EXPECT_STREQ("val3", OptP.c_str()); 1505 OptP.clear(); 1506 cl::ResetAllOptionOccurrences(); 1507 1508 // All three previous cases should work the same way if an option with both 1509 // cl::Prefix and cl::Grouping modifiers is used at the end of a group. 1510 const char *args4[] = {"prog", "-fpval4"}; 1511 EXPECT_TRUE( 1512 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls())); 1513 EXPECT_TRUE(OptF); 1514 EXPECT_STREQ("val4", OptP.c_str()); 1515 OptP.clear(); 1516 cl::ResetAllOptionOccurrences(); 1517 1518 const char *args5[] = {"prog", "-fp", "val5"}; 1519 EXPECT_TRUE( 1520 cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls())); 1521 EXPECT_TRUE(OptF); 1522 EXPECT_STREQ("val5", OptP.c_str()); 1523 OptP.clear(); 1524 cl::ResetAllOptionOccurrences(); 1525 1526 const char *args6[] = {"prog", "-fp=val6"}; 1527 EXPECT_TRUE( 1528 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls())); 1529 EXPECT_TRUE(OptF); 1530 EXPECT_STREQ("val6", OptP.c_str()); 1531 OptP.clear(); 1532 cl::ResetAllOptionOccurrences(); 1533 1534 // Should assign a value even if the part after a cl::Prefix option is equal 1535 // to the name of another option. 1536 const char *args7[] = {"prog", "-fpb"}; 1537 EXPECT_TRUE( 1538 cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls())); 1539 EXPECT_TRUE(OptF); 1540 EXPECT_STREQ("b", OptP.c_str()); 1541 EXPECT_FALSE(OptB); 1542 OptP.clear(); 1543 cl::ResetAllOptionOccurrences(); 1544 1545 // Should be possible to use a cl::AlwaysPrefix option without grouping. 1546 const char *args8[] = {"prog", "-aval8"}; 1547 EXPECT_TRUE( 1548 cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls())); 1549 EXPECT_STREQ("val8", OptA.c_str()); 1550 OptA.clear(); 1551 cl::ResetAllOptionOccurrences(); 1552 1553 // Should not be possible to pass a value in a separate argument. 1554 const char *args9[] = {"prog", "-a", "val9"}; 1555 EXPECT_FALSE( 1556 cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls())); 1557 cl::ResetAllOptionOccurrences(); 1558 1559 // With the "-opt=value" form, the "=" symbol should be preserved. 1560 const char *args10[] = {"prog", "-a=val10"}; 1561 EXPECT_TRUE( 1562 cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls())); 1563 EXPECT_STREQ("=val10", OptA.c_str()); 1564 OptA.clear(); 1565 cl::ResetAllOptionOccurrences(); 1566 1567 // All three previous cases should work the same way if an option with both 1568 // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group. 1569 const char *args11[] = {"prog", "-faval11"}; 1570 EXPECT_TRUE( 1571 cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls())); 1572 EXPECT_TRUE(OptF); 1573 EXPECT_STREQ("val11", OptA.c_str()); 1574 OptA.clear(); 1575 cl::ResetAllOptionOccurrences(); 1576 1577 const char *args12[] = {"prog", "-fa", "val12"}; 1578 EXPECT_FALSE( 1579 cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls())); 1580 cl::ResetAllOptionOccurrences(); 1581 1582 const char *args13[] = {"prog", "-fa=val13"}; 1583 EXPECT_TRUE( 1584 cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls())); 1585 EXPECT_TRUE(OptF); 1586 EXPECT_STREQ("=val13", OptA.c_str()); 1587 OptA.clear(); 1588 cl::ResetAllOptionOccurrences(); 1589 1590 // Should assign a value even if the part after a cl::AlwaysPrefix option 1591 // is equal to the name of another option. 1592 const char *args14[] = {"prog", "-fab"}; 1593 EXPECT_TRUE( 1594 cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls())); 1595 EXPECT_TRUE(OptF); 1596 EXPECT_STREQ("b", OptA.c_str()); 1597 EXPECT_FALSE(OptB); 1598 OptA.clear(); 1599 cl::ResetAllOptionOccurrences(); 1600 } 1601 1602 TEST(CommandLineTest, LongOptions) { 1603 cl::ResetCommandLineParser(); 1604 1605 StackOption<bool> OptA("a", cl::desc("Some flag")); 1606 StackOption<bool> OptBLong("long-flag", cl::desc("Some long flag")); 1607 StackOption<bool, cl::alias> OptB("b", cl::desc("Alias to --long-flag"), 1608 cl::aliasopt(OptBLong)); 1609 StackOption<std::string> OptAB("ab", cl::desc("Another long option")); 1610 1611 std::string Errs; 1612 raw_string_ostream OS(Errs); 1613 1614 const char *args1[] = {"prog", "-a", "-ab", "val1"}; 1615 const char *args2[] = {"prog", "-a", "--ab", "val1"}; 1616 const char *args3[] = {"prog", "-ab", "--ab", "val1"}; 1617 1618 // 1619 // The following tests treat `-` and `--` the same, and always match the 1620 // longest string. 1621 // 1622 1623 EXPECT_TRUE( 1624 cl::ParseCommandLineOptions(4, args1, StringRef(), &OS)); OS.flush(); 1625 EXPECT_TRUE(OptA); 1626 EXPECT_FALSE(OptBLong); 1627 EXPECT_STREQ("val1", OptAB.c_str()); 1628 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1629 cl::ResetAllOptionOccurrences(); 1630 1631 EXPECT_TRUE( 1632 cl::ParseCommandLineOptions(4, args2, StringRef(), &OS)); OS.flush(); 1633 EXPECT_TRUE(OptA); 1634 EXPECT_FALSE(OptBLong); 1635 EXPECT_STREQ("val1", OptAB.c_str()); 1636 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1637 cl::ResetAllOptionOccurrences(); 1638 1639 // Fails because `-ab` and `--ab` are treated the same and appear more than 1640 // once. Also, `val1` is unexpected. 1641 EXPECT_FALSE( 1642 cl::ParseCommandLineOptions(4, args3, StringRef(), &OS)); OS.flush(); 1643 outs()<< Errs << "\n"; 1644 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1645 cl::ResetAllOptionOccurrences(); 1646 1647 // 1648 // The following tests treat `-` and `--` differently, with `-` for short, and 1649 // `--` for long options. 1650 // 1651 1652 // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and 1653 // `val1` is unexpected. 1654 EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(), 1655 &OS, nullptr, true)); OS.flush(); 1656 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1657 cl::ResetAllOptionOccurrences(); 1658 1659 // Works because `-a` is treated differently than `--ab`. 1660 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(), 1661 &OS, nullptr, true)); OS.flush(); 1662 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1663 cl::ResetAllOptionOccurrences(); 1664 1665 // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option. 1666 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(), 1667 &OS, nullptr, true)); 1668 EXPECT_TRUE(OptA); 1669 EXPECT_TRUE(OptBLong); 1670 EXPECT_STREQ("val1", OptAB.c_str()); 1671 OS.flush(); 1672 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1673 cl::ResetAllOptionOccurrences(); 1674 } 1675 1676 TEST(CommandLineTest, OptionErrorMessage) { 1677 // When there is an error, we expect some error message like: 1678 // prog: for the -a option: [...] 1679 // 1680 // Test whether the "for the -a option"-part is correctly formatted. 1681 cl::ResetCommandLineParser(); 1682 1683 StackOption<bool> OptA("a", cl::desc("Some option")); 1684 StackOption<bool> OptLong("long", cl::desc("Some long option")); 1685 1686 std::string Errs; 1687 raw_string_ostream OS(Errs); 1688 1689 OptA.error("custom error", OS); 1690 OS.flush(); 1691 EXPECT_FALSE(Errs.find("for the -a option:") == std::string::npos); 1692 Errs.clear(); 1693 1694 OptLong.error("custom error", OS); 1695 OS.flush(); 1696 EXPECT_FALSE(Errs.find("for the --long option:") == std::string::npos); 1697 Errs.clear(); 1698 1699 cl::ResetAllOptionOccurrences(); 1700 } 1701 1702 TEST(CommandLineTest, OptionErrorMessageSuggest) { 1703 // When there is an error, and the edit-distance is not very large, 1704 // we expect some error message like: 1705 // prog: did you mean '--option'? 1706 // 1707 // Test whether this message is well-formatted. 1708 cl::ResetCommandLineParser(); 1709 1710 StackOption<bool> OptLong("aluminium", cl::desc("Some long option")); 1711 1712 const char *args[] = {"prog", "--aluminum"}; 1713 1714 std::string Errs; 1715 raw_string_ostream OS(Errs); 1716 1717 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); 1718 OS.flush(); 1719 EXPECT_FALSE(Errs.find("prog: Did you mean '--aluminium'?\n") == 1720 std::string::npos); 1721 Errs.clear(); 1722 1723 cl::ResetAllOptionOccurrences(); 1724 } 1725 } // anonymous namespace 1726