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