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/Config/config.h" 14 #include "llvm/Support/Allocator.h" 15 #include "llvm/Support/FileSystem.h" 16 #include "llvm/Support/InitLLVM.h" 17 #include "llvm/Support/MemoryBuffer.h" 18 #include "llvm/Support/Path.h" 19 #include "llvm/Support/Program.h" 20 #include "llvm/Support/StringSaver.h" 21 #include "llvm/Support/VirtualFileSystem.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include "llvm/TargetParser/Host.h" 24 #include "llvm/TargetParser/Triple.h" 25 #include "llvm/Testing/Support/SupportHelpers.h" 26 #include "gmock/gmock.h" 27 #include "gtest/gtest.h" 28 #include <fstream> 29 #include <stdlib.h> 30 #include <string> 31 32 using namespace llvm; 33 using llvm::unittest::TempDir; 34 using llvm::unittest::TempFile; 35 36 namespace { 37 38 MATCHER(StringEquality, "Checks if two char* are equal as strings") { 39 return std::string(std::get<0>(arg)) == std::string(std::get<1>(arg)); 40 } 41 42 class TempEnvVar { 43 public: 44 TempEnvVar(const char *name, const char *value) 45 : name(name) { 46 const char *old_value = getenv(name); 47 EXPECT_EQ(nullptr, old_value) << old_value; 48 #if HAVE_SETENV 49 setenv(name, value, true); 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::SubCommand::getTopLevel()); 102 103 ASSERT_EQ(Map.count("test-option"), 1u) << "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::getGeneralCategory(); 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 140 TEST(CommandLineTest, UseOptionCategory) { 141 StackOption<int> TestOption2("test-option", cl::cat(TestCategory)); 142 143 ASSERT_NE(TestOption2.Categories.end(), 144 find_if(TestOption2.Categories, 145 [&](const llvm::cl::OptionCategory *Cat) { 146 return Cat == &TestCategory; 147 })) 148 << "Failed to assign Option Category."; 149 } 150 151 TEST(CommandLineTest, UseMultipleCategories) { 152 StackOption<int> TestOption2("test-option2", cl::cat(TestCategory), 153 cl::cat(cl::getGeneralCategory()), 154 cl::cat(cl::getGeneralCategory())); 155 156 // Make sure cl::getGeneralCategory() wasn't added twice. 157 ASSERT_EQ(TestOption2.Categories.size(), 2U); 158 159 ASSERT_NE(TestOption2.Categories.end(), 160 find_if(TestOption2.Categories, 161 [&](const llvm::cl::OptionCategory *Cat) { 162 return Cat == &TestCategory; 163 })) 164 << "Failed to assign Option Category."; 165 ASSERT_NE(TestOption2.Categories.end(), 166 find_if(TestOption2.Categories, 167 [&](const llvm::cl::OptionCategory *Cat) { 168 return Cat == &cl::getGeneralCategory(); 169 })) 170 << "Failed to assign General Category."; 171 172 cl::OptionCategory AnotherCategory("Additional test Options", "Description"); 173 StackOption<int> TestOption("test-option", cl::cat(TestCategory), 174 cl::cat(AnotherCategory)); 175 ASSERT_EQ(TestOption.Categories.end(), 176 find_if(TestOption.Categories, 177 [&](const llvm::cl::OptionCategory *Cat) { 178 return Cat == &cl::getGeneralCategory(); 179 })) 180 << "Failed to remove General Category."; 181 ASSERT_NE(TestOption.Categories.end(), 182 find_if(TestOption.Categories, 183 [&](const llvm::cl::OptionCategory *Cat) { 184 return Cat == &TestCategory; 185 })) 186 << "Failed to assign Option Category."; 187 ASSERT_NE(TestOption.Categories.end(), 188 find_if(TestOption.Categories, 189 [&](const llvm::cl::OptionCategory *Cat) { 190 return Cat == &AnotherCategory; 191 })) 192 << "Failed to assign Another Category."; 193 } 194 195 typedef void ParserFunction(StringRef Source, StringSaver &Saver, 196 SmallVectorImpl<const char *> &NewArgv, 197 bool MarkEOLs); 198 199 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input, 200 ArrayRef<const char *> Output, 201 bool MarkEOLs = false) { 202 SmallVector<const char *, 0> Actual; 203 BumpPtrAllocator A; 204 StringSaver Saver(A); 205 parse(Input, Saver, Actual, MarkEOLs); 206 EXPECT_EQ(Output.size(), Actual.size()); 207 for (unsigned I = 0, E = Actual.size(); I != E; ++I) { 208 if (I < Output.size()) { 209 EXPECT_STREQ(Output[I], Actual[I]); 210 } 211 } 212 } 213 214 TEST(CommandLineTest, TokenizeGNUCommandLine) { 215 const char Input[] = 216 "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) " 217 "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\""; 218 const char *const Output[] = { 219 "foo bar", "foo bar", "foo bar", "foo\\bar", 220 "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"}; 221 testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output); 222 } 223 224 TEST(CommandLineTest, TokenizeWindowsCommandLine1) { 225 const char Input[] = 226 R"(a\b c\\d e\\"f g" h\"i j\\\"k "lmn" o pqr "st \"u" \v)"; 227 const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k", 228 "lmn", "o", "pqr", "st \"u", "\\v" }; 229 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output); 230 } 231 232 TEST(CommandLineTest, TokenizeWindowsCommandLine2) { 233 const char Input[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp"; 234 const char *const Output[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"}; 235 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output); 236 } 237 238 TEST(CommandLineTest, TokenizeWindowsCommandLineQuotedLastArgument) { 239 // Whitespace at the end of the command line doesn't cause an empty last word 240 const char Input0[] = R"(a b c d )"; 241 const char *const Output0[] = {"a", "b", "c", "d"}; 242 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input0, Output0); 243 244 // But an explicit "" does 245 const char Input1[] = R"(a b c d "")"; 246 const char *const Output1[] = {"a", "b", "c", "d", ""}; 247 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input1, Output1); 248 249 // An unterminated quoted string is also emitted as an argument word, empty 250 // or not 251 const char Input2[] = R"(a b c d ")"; 252 const char *const Output2[] = {"a", "b", "c", "d", ""}; 253 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input2, Output2); 254 const char Input3[] = R"(a b c d "text)"; 255 const char *const Output3[] = {"a", "b", "c", "d", "text"}; 256 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input3, Output3); 257 } 258 259 TEST(CommandLineTest, TokenizeWindowsCommandLineExeName) { 260 const char Input1[] = 261 R"("C:\Program Files\Whatever\"clang.exe z.c -DY=\"x\")"; 262 const char *const Output1[] = {"C:\\Program Files\\Whatever\\clang.exe", 263 "z.c", "-DY=\"x\""}; 264 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input1, Output1); 265 266 const char Input2[] = "\"a\\\"b c\\\"d\n\"e\\\"f g\\\"h\n"; 267 const char *const Output2[] = {"a\\b", "c\"d", nullptr, 268 "e\\f", "g\"h", nullptr}; 269 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input2, Output2, 270 /*MarkEOLs=*/true); 271 272 const char Input3[] = R"(\\server\share\subdir\clang.exe)"; 273 const char *const Output3[] = {"\\\\server\\share\\subdir\\clang.exe"}; 274 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input3, Output3); 275 } 276 277 TEST(CommandLineTest, TokenizeAndMarkEOLs) { 278 // Clang uses EOL marking in response files to support options that consume 279 // the rest of the arguments on the current line, but do not consume arguments 280 // from subsequent lines. For example, given these rsp files contents: 281 // /c /Zi /O2 282 // /Oy- /link /debug /opt:ref 283 // /Zc:ThreadsafeStatics- 284 // 285 // clang-cl needs to treat "/debug /opt:ref" as linker flags, and everything 286 // else as compiler flags. The tokenizer inserts nullptr sentinels into the 287 // output so that clang-cl can find the end of the current line. 288 const char Input[] = "clang -Xclang foo\n\nfoo\"bar\"baz\n x.cpp\n"; 289 const char *const Output[] = {"clang", "-Xclang", "foo", 290 nullptr, nullptr, "foobarbaz", 291 nullptr, "x.cpp", nullptr}; 292 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output, 293 /*MarkEOLs=*/true); 294 testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output, 295 /*MarkEOLs=*/true); 296 } 297 298 TEST(CommandLineTest, TokenizeConfigFile1) { 299 const char *Input = "\\"; 300 const char *const Output[] = { "\\" }; 301 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 302 } 303 304 TEST(CommandLineTest, TokenizeConfigFile2) { 305 const char *Input = "\\abc"; 306 const char *const Output[] = { "abc" }; 307 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 308 } 309 310 TEST(CommandLineTest, TokenizeConfigFile3) { 311 const char *Input = "abc\\"; 312 const char *const Output[] = { "abc\\" }; 313 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 314 } 315 316 TEST(CommandLineTest, TokenizeConfigFile4) { 317 const char *Input = "abc\\\n123"; 318 const char *const Output[] = { "abc123" }; 319 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 320 } 321 322 TEST(CommandLineTest, TokenizeConfigFile5) { 323 const char *Input = "abc\\\r\n123"; 324 const char *const Output[] = { "abc123" }; 325 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 326 } 327 328 TEST(CommandLineTest, TokenizeConfigFile6) { 329 const char *Input = "abc\\\n"; 330 const char *const Output[] = { "abc" }; 331 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 332 } 333 334 TEST(CommandLineTest, TokenizeConfigFile7) { 335 const char *Input = "abc\\\r\n"; 336 const char *const Output[] = { "abc" }; 337 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 338 } 339 340 TEST(CommandLineTest, TokenizeConfigFile8) { 341 SmallVector<const char *, 0> Actual; 342 BumpPtrAllocator A; 343 StringSaver Saver(A); 344 cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false); 345 EXPECT_TRUE(Actual.empty()); 346 } 347 348 TEST(CommandLineTest, TokenizeConfigFile9) { 349 SmallVector<const char *, 0> Actual; 350 BumpPtrAllocator A; 351 StringSaver Saver(A); 352 cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false); 353 EXPECT_TRUE(Actual.empty()); 354 } 355 356 TEST(CommandLineTest, TokenizeConfigFile10) { 357 const char *Input = "\\\nabc"; 358 const char *const Output[] = { "abc" }; 359 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 360 } 361 362 TEST(CommandLineTest, TokenizeConfigFile11) { 363 const char *Input = "\\\r\nabc"; 364 const char *const Output[] = { "abc" }; 365 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output); 366 } 367 368 TEST(CommandLineTest, AliasesWithArguments) { 369 static const size_t ARGC = 3; 370 const char *const Inputs[][ARGC] = { 371 { "-tool", "-actual=x", "-extra" }, 372 { "-tool", "-actual", "x" }, 373 { "-tool", "-alias=x", "-extra" }, 374 { "-tool", "-alias", "x" } 375 }; 376 377 for (size_t i = 0, e = std::size(Inputs); i < e; ++i) { 378 StackOption<std::string> Actual("actual"); 379 StackOption<bool> Extra("extra"); 380 StackOption<std::string> Input(cl::Positional); 381 382 cl::alias Alias("alias", llvm::cl::aliasopt(Actual)); 383 384 cl::ParseCommandLineOptions(ARGC, Inputs[i]); 385 EXPECT_EQ("x", Actual); 386 EXPECT_EQ(0, Input.getNumOccurrences()); 387 388 Alias.removeArgument(); 389 } 390 } 391 392 void testAliasRequired(int argc, const char *const *argv) { 393 StackOption<std::string> Option("option", cl::Required); 394 cl::alias Alias("o", llvm::cl::aliasopt(Option)); 395 396 cl::ParseCommandLineOptions(argc, argv); 397 EXPECT_EQ("x", Option); 398 EXPECT_EQ(1, Option.getNumOccurrences()); 399 400 Alias.removeArgument(); 401 } 402 403 TEST(CommandLineTest, AliasRequired) { 404 const char *opts1[] = { "-tool", "-option=x" }; 405 const char *opts2[] = { "-tool", "-o", "x" }; 406 testAliasRequired(std::size(opts1), opts1); 407 testAliasRequired(std::size(opts2), opts2); 408 } 409 410 TEST(CommandLineTest, HideUnrelatedOptions) { 411 StackOption<int> TestOption1("hide-option-1"); 412 StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory)); 413 414 cl::HideUnrelatedOptions(TestCategory); 415 416 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag()) 417 << "Failed to hide extra option."; 418 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag()) 419 << "Hid extra option that should be visable."; 420 421 StringMap<cl::Option *> &Map = 422 cl::getRegisteredOptions(cl::SubCommand::getTopLevel()); 423 ASSERT_TRUE(Map.count("help") == (size_t)0 || 424 cl::NotHidden == Map["help"]->getOptionHiddenFlag()) 425 << "Hid default option that should be visable."; 426 } 427 428 cl::OptionCategory TestCategory2("Test Options set 2", "Description"); 429 430 TEST(CommandLineTest, HideUnrelatedOptionsMulti) { 431 StackOption<int> TestOption1("multi-hide-option-1"); 432 StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory)); 433 StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2)); 434 435 const cl::OptionCategory *VisibleCategories[] = {&TestCategory, 436 &TestCategory2}; 437 438 cl::HideUnrelatedOptions(ArrayRef(VisibleCategories)); 439 440 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag()) 441 << "Failed to hide extra option."; 442 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag()) 443 << "Hid extra option that should be visable."; 444 ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag()) 445 << "Hid extra option that should be visable."; 446 447 StringMap<cl::Option *> &Map = 448 cl::getRegisteredOptions(cl::SubCommand::getTopLevel()); 449 ASSERT_TRUE(Map.count("help") == (size_t)0 || 450 cl::NotHidden == Map["help"]->getOptionHiddenFlag()) 451 << "Hid default option that should be visable."; 452 } 453 454 TEST(CommandLineTest, SetMultiValues) { 455 StackOption<int> Option("option"); 456 const char *args[] = {"prog", "-option=1", "-option=2"}; 457 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(), 458 &llvm::nulls())); 459 EXPECT_EQ(Option, 2); 460 } 461 462 TEST(CommandLineTest, SetValueInSubcategories) { 463 cl::ResetCommandLineParser(); 464 465 StackSubCommand SC1("sc1", "First subcommand"); 466 StackSubCommand SC2("sc2", "Second subcommand"); 467 468 StackOption<bool> TopLevelOpt("top-level", cl::init(false)); 469 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false)); 470 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false)); 471 472 EXPECT_FALSE(TopLevelOpt); 473 EXPECT_FALSE(SC1Opt); 474 EXPECT_FALSE(SC2Opt); 475 const char *args[] = {"prog", "-top-level"}; 476 EXPECT_TRUE( 477 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 478 EXPECT_TRUE(TopLevelOpt); 479 EXPECT_FALSE(SC1Opt); 480 EXPECT_FALSE(SC2Opt); 481 482 TopLevelOpt = false; 483 484 cl::ResetAllOptionOccurrences(); 485 EXPECT_FALSE(TopLevelOpt); 486 EXPECT_FALSE(SC1Opt); 487 EXPECT_FALSE(SC2Opt); 488 const char *args2[] = {"prog", "sc1", "-sc1"}; 489 EXPECT_TRUE( 490 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 491 EXPECT_FALSE(TopLevelOpt); 492 EXPECT_TRUE(SC1Opt); 493 EXPECT_FALSE(SC2Opt); 494 495 SC1Opt = false; 496 497 cl::ResetAllOptionOccurrences(); 498 EXPECT_FALSE(TopLevelOpt); 499 EXPECT_FALSE(SC1Opt); 500 EXPECT_FALSE(SC2Opt); 501 const char *args3[] = {"prog", "sc2", "-sc2"}; 502 EXPECT_TRUE( 503 cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls())); 504 EXPECT_FALSE(TopLevelOpt); 505 EXPECT_FALSE(SC1Opt); 506 EXPECT_TRUE(SC2Opt); 507 } 508 509 TEST(CommandLineTest, LookupFailsInWrongSubCommand) { 510 cl::ResetCommandLineParser(); 511 512 StackSubCommand SC1("sc1", "First subcommand"); 513 StackSubCommand SC2("sc2", "Second subcommand"); 514 515 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false)); 516 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false)); 517 518 std::string Errs; 519 raw_string_ostream OS(Errs); 520 521 const char *args[] = {"prog", "sc1", "-sc2"}; 522 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS)); 523 EXPECT_FALSE(Errs.empty()); 524 } 525 526 TEST(CommandLineTest, TopLevelOptInSubcommand) { 527 enum LiteralOptionEnum { 528 foo, 529 bar, 530 baz, 531 }; 532 533 cl::ResetCommandLineParser(); 534 535 // This is a top-level option and not associated with a subcommand. 536 // A command line using subcommand should parse both subcommand options and 537 // top-level options. A valid use case is that users of llvm command line 538 // tools should be able to specify top-level options defined in any library. 539 StackOption<std::string> TopLevelOpt("str", cl::init("txt"), 540 cl::desc("A top-level option.")); 541 542 StackSubCommand SC("sc", "Subcommand"); 543 StackOption<std::string> PositionalOpt( 544 cl::Positional, cl::desc("positional argument test coverage"), 545 cl::sub(SC)); 546 StackOption<LiteralOptionEnum> LiteralOpt( 547 cl::desc("literal argument test coverage"), cl::sub(SC), cl::init(bar), 548 cl::values(clEnumVal(foo, "foo"), clEnumVal(bar, "bar"), 549 clEnumVal(baz, "baz"))); 550 StackOption<bool> EnableOpt("enable", cl::sub(SC), cl::init(false)); 551 StackOption<int> ThresholdOpt("threshold", cl::sub(SC), cl::init(1)); 552 553 const char *PositionalOptVal = "input-file"; 554 const char *args[] = {"prog", "sc", PositionalOptVal, 555 "-enable", "--str=csv", "--threshold=2"}; 556 557 // cl::ParseCommandLineOptions returns true on success. Otherwise, it will 558 // print the error message to stderr and exit in this setting (`Errs` ostream 559 // is not set). 560 ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]), args, 561 StringRef())); 562 EXPECT_STREQ(PositionalOpt.getValue().c_str(), PositionalOptVal); 563 EXPECT_TRUE(EnableOpt); 564 // Tests that the value of `str` option is `csv` as specified. 565 EXPECT_STREQ(TopLevelOpt.getValue().c_str(), "csv"); 566 EXPECT_EQ(ThresholdOpt, 2); 567 568 for (auto &[LiteralOptVal, WantLiteralOpt] : 569 {std::pair{"--bar", bar}, {"--foo", foo}, {"--baz", baz}}) { 570 const char *args[] = {"prog", "sc", LiteralOptVal}; 571 ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]), 572 args, StringRef())); 573 574 // Tests that literal options are parsed correctly. 575 EXPECT_EQ(LiteralOpt, WantLiteralOpt); 576 } 577 } 578 579 TEST(CommandLineTest, AddToAllSubCommands) { 580 cl::ResetCommandLineParser(); 581 582 StackSubCommand SC1("sc1", "First subcommand"); 583 StackOption<bool> AllOpt("everywhere", cl::sub(cl::SubCommand::getAll()), 584 cl::init(false)); 585 StackSubCommand SC2("sc2", "Second subcommand"); 586 587 EXPECT_TRUE(cl::SubCommand::getTopLevel().OptionsMap.contains("everywhere")); 588 EXPECT_TRUE(cl::SubCommand::getAll().OptionsMap.contains("everywhere")); 589 EXPECT_TRUE(SC1.OptionsMap.contains("everywhere")); 590 EXPECT_TRUE(SC2.OptionsMap.contains("everywhere")); 591 592 const char *args[] = {"prog", "-everywhere"}; 593 const char *args2[] = {"prog", "sc1", "-everywhere"}; 594 const char *args3[] = {"prog", "sc2", "-everywhere"}; 595 596 std::string Errs; 597 raw_string_ostream OS(Errs); 598 599 EXPECT_FALSE(AllOpt); 600 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); 601 EXPECT_TRUE(AllOpt); 602 603 AllOpt = false; 604 605 cl::ResetAllOptionOccurrences(); 606 EXPECT_FALSE(AllOpt); 607 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); 608 EXPECT_TRUE(AllOpt); 609 610 AllOpt = false; 611 612 cl::ResetAllOptionOccurrences(); 613 EXPECT_FALSE(AllOpt); 614 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); 615 EXPECT_TRUE(AllOpt); 616 617 // Since all parsing succeeded, the error message should be empty. 618 EXPECT_TRUE(Errs.empty()); 619 } 620 621 TEST(CommandLineTest, ReparseCommandLineOptions) { 622 cl::ResetCommandLineParser(); 623 624 StackOption<bool> TopLevelOpt( 625 "top-level", cl::sub(cl::SubCommand::getTopLevel()), cl::init(false)); 626 627 const char *args[] = {"prog", "-top-level"}; 628 629 EXPECT_FALSE(TopLevelOpt); 630 EXPECT_TRUE( 631 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 632 EXPECT_TRUE(TopLevelOpt); 633 634 TopLevelOpt = false; 635 636 cl::ResetAllOptionOccurrences(); 637 EXPECT_FALSE(TopLevelOpt); 638 EXPECT_TRUE( 639 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 640 EXPECT_TRUE(TopLevelOpt); 641 } 642 643 TEST(CommandLineTest, RemoveFromRegularSubCommand) { 644 cl::ResetCommandLineParser(); 645 646 StackSubCommand SC("sc", "Subcommand"); 647 StackOption<bool> RemoveOption("remove-option", cl::sub(SC), cl::init(false)); 648 StackOption<bool> KeepOption("keep-option", cl::sub(SC), cl::init(false)); 649 650 const char *args[] = {"prog", "sc", "-remove-option"}; 651 652 std::string Errs; 653 raw_string_ostream OS(Errs); 654 655 EXPECT_FALSE(RemoveOption); 656 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS)); 657 EXPECT_TRUE(RemoveOption); 658 EXPECT_TRUE(Errs.empty()); 659 660 RemoveOption.removeArgument(); 661 662 cl::ResetAllOptionOccurrences(); 663 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS)); 664 EXPECT_FALSE(Errs.empty()); 665 } 666 667 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) { 668 cl::ResetCommandLineParser(); 669 670 StackOption<bool> TopLevelRemove("top-level-remove", 671 cl::sub(cl::SubCommand::getTopLevel()), 672 cl::init(false)); 673 StackOption<bool> TopLevelKeep("top-level-keep", 674 cl::sub(cl::SubCommand::getTopLevel()), 675 cl::init(false)); 676 677 const char *args[] = {"prog", "-top-level-remove"}; 678 679 EXPECT_FALSE(TopLevelRemove); 680 EXPECT_TRUE( 681 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 682 EXPECT_TRUE(TopLevelRemove); 683 684 TopLevelRemove.removeArgument(); 685 686 cl::ResetAllOptionOccurrences(); 687 EXPECT_FALSE( 688 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 689 } 690 691 TEST(CommandLineTest, RemoveFromAllSubCommands) { 692 cl::ResetCommandLineParser(); 693 694 StackSubCommand SC1("sc1", "First Subcommand"); 695 StackSubCommand SC2("sc2", "Second Subcommand"); 696 StackOption<bool> RemoveOption( 697 "remove-option", cl::sub(cl::SubCommand::getAll()), cl::init(false)); 698 StackOption<bool> KeepOption("keep-option", cl::sub(cl::SubCommand::getAll()), 699 cl::init(false)); 700 701 const char *args0[] = {"prog", "-remove-option"}; 702 const char *args1[] = {"prog", "sc1", "-remove-option"}; 703 const char *args2[] = {"prog", "sc2", "-remove-option"}; 704 705 // It should work for all subcommands including the top-level. 706 EXPECT_FALSE(RemoveOption); 707 EXPECT_TRUE( 708 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls())); 709 EXPECT_TRUE(RemoveOption); 710 711 RemoveOption = false; 712 713 cl::ResetAllOptionOccurrences(); 714 EXPECT_FALSE(RemoveOption); 715 EXPECT_TRUE( 716 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls())); 717 EXPECT_TRUE(RemoveOption); 718 719 RemoveOption = false; 720 721 cl::ResetAllOptionOccurrences(); 722 EXPECT_FALSE(RemoveOption); 723 EXPECT_TRUE( 724 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 725 EXPECT_TRUE(RemoveOption); 726 727 RemoveOption.removeArgument(); 728 729 // It should not work for any subcommands including the top-level. 730 cl::ResetAllOptionOccurrences(); 731 EXPECT_FALSE( 732 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls())); 733 cl::ResetAllOptionOccurrences(); 734 EXPECT_FALSE( 735 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls())); 736 cl::ResetAllOptionOccurrences(); 737 EXPECT_FALSE( 738 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 739 } 740 741 TEST(CommandLineTest, GetRegisteredSubcommands) { 742 cl::ResetCommandLineParser(); 743 744 StackSubCommand SC1("sc1", "First Subcommand"); 745 StackOption<bool> Opt1("opt1", cl::sub(SC1), cl::init(false)); 746 StackSubCommand SC2("sc2", "Second subcommand"); 747 StackOption<bool> Opt2("opt2", cl::sub(SC2), cl::init(false)); 748 749 const char *args0[] = {"prog", "sc1"}; 750 const char *args1[] = {"prog", "sc2"}; 751 752 EXPECT_TRUE( 753 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls())); 754 EXPECT_FALSE(Opt1); 755 EXPECT_FALSE(Opt2); 756 for (auto *S : cl::getRegisteredSubcommands()) { 757 if (*S) { 758 EXPECT_EQ("sc1", S->getName()); 759 } 760 } 761 762 cl::ResetAllOptionOccurrences(); 763 EXPECT_TRUE( 764 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls())); 765 EXPECT_FALSE(Opt1); 766 EXPECT_FALSE(Opt2); 767 for (auto *S : cl::getRegisteredSubcommands()) { 768 if (*S) { 769 EXPECT_EQ("sc2", S->getName()); 770 } 771 } 772 } 773 774 TEST(CommandLineTest, DefaultOptions) { 775 cl::ResetCommandLineParser(); 776 777 StackOption<std::string> Bar("bar", cl::sub(cl::SubCommand::getAll()), 778 cl::DefaultOption); 779 StackOption<std::string, cl::alias> Bar_Alias( 780 "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption); 781 782 StackOption<bool> Foo("foo", cl::init(false), 783 cl::sub(cl::SubCommand::getAll()), cl::DefaultOption); 784 StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"), 785 cl::aliasopt(Foo), cl::DefaultOption); 786 787 StackSubCommand SC1("sc1", "First Subcommand"); 788 // Override "-b" and change type in sc1 SubCommand. 789 StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false)); 790 StackSubCommand SC2("sc2", "Second subcommand"); 791 // Override "-foo" and change type in sc2 SubCommand. Note that this does not 792 // affect "-f" alias, which continues to work correctly. 793 StackOption<std::string> SC2_Foo("foo", cl::sub(SC2)); 794 795 const char *args0[] = {"prog", "-b", "args0 bar string", "-f"}; 796 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args0), args0, 797 StringRef(), &llvm::nulls())); 798 EXPECT_EQ(Bar, "args0 bar string"); 799 EXPECT_TRUE(Foo); 800 EXPECT_FALSE(SC1_B); 801 EXPECT_TRUE(SC2_Foo.empty()); 802 803 cl::ResetAllOptionOccurrences(); 804 805 const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"}; 806 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args1), args1, 807 StringRef(), &llvm::nulls())); 808 EXPECT_EQ(Bar, "args1 bar string"); 809 EXPECT_TRUE(Foo); 810 EXPECT_TRUE(SC1_B); 811 EXPECT_TRUE(SC2_Foo.empty()); 812 for (auto *S : cl::getRegisteredSubcommands()) { 813 if (*S) { 814 EXPECT_EQ("sc1", S->getName()); 815 } 816 } 817 818 cl::ResetAllOptionOccurrences(); 819 820 const char *args2[] = {"prog", "sc2", "-b", "args2 bar string", 821 "-f", "-foo", "foo string"}; 822 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args2), args2, 823 StringRef(), &llvm::nulls())); 824 EXPECT_EQ(Bar, "args2 bar string"); 825 EXPECT_TRUE(Foo); 826 EXPECT_FALSE(SC1_B); 827 EXPECT_EQ(SC2_Foo, "foo string"); 828 for (auto *S : cl::getRegisteredSubcommands()) { 829 if (*S) { 830 EXPECT_EQ("sc2", S->getName()); 831 } 832 } 833 cl::ResetCommandLineParser(); 834 } 835 836 TEST(CommandLineTest, ArgumentLimit) { 837 std::string args(32 * 4096, 'a'); 838 EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data())); 839 std::string args2(256, 'a'); 840 EXPECT_TRUE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args2.data())); 841 } 842 843 TEST(CommandLineTest, ArgumentLimitWindows) { 844 if (!Triple(sys::getProcessTriple()).isOSWindows()) 845 GTEST_SKIP(); 846 // We use 32000 as a limit for command line length. Program name ('cl'), 847 // separating spaces and termination null character occupy 5 symbols. 848 std::string long_arg(32000 - 5, 'b'); 849 EXPECT_TRUE( 850 llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data())); 851 long_arg += 'b'; 852 EXPECT_FALSE( 853 llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data())); 854 } 855 856 TEST(CommandLineTest, ResponseFileWindows) { 857 if (!Triple(sys::getProcessTriple()).isOSWindows()) 858 GTEST_SKIP(); 859 860 StackOption<std::string, cl::list<std::string>> InputFilenames( 861 cl::Positional, cl::desc("<input files>")); 862 StackOption<bool> TopLevelOpt("top-level", cl::init(false)); 863 864 // Create response file. 865 TempFile ResponseFile("resp-", ".txt", 866 "-top-level\npath\\dir\\file1\npath/dir/file2", 867 /*Unique*/ true); 868 869 llvm::SmallString<128> RspOpt; 870 RspOpt.append(1, '@'); 871 RspOpt.append(ResponseFile.path()); 872 const char *args[] = {"prog", RspOpt.c_str()}; 873 EXPECT_FALSE(TopLevelOpt); 874 EXPECT_TRUE( 875 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 876 EXPECT_TRUE(TopLevelOpt); 877 EXPECT_EQ(InputFilenames[0], "path\\dir\\file1"); 878 EXPECT_EQ(InputFilenames[1], "path/dir/file2"); 879 } 880 881 TEST(CommandLineTest, ResponseFiles) { 882 vfs::InMemoryFileSystem FS; 883 #ifdef _WIN32 884 const char *TestRoot = "C:\\"; 885 #else 886 const char *TestRoot = "/"; 887 #endif 888 FS.setCurrentWorkingDirectory(TestRoot); 889 890 // Create included response file of first level. 891 llvm::StringRef IncludedFileName = "resp1"; 892 FS.addFile(IncludedFileName, 0, 893 llvm::MemoryBuffer::getMemBuffer("-option_1 -option_2\n" 894 "@incdir/resp2\n" 895 "-option_3=abcd\n" 896 "@incdir/resp3\n" 897 "-option_4=efjk\n")); 898 899 // Directory for included file. 900 llvm::StringRef IncDir = "incdir"; 901 902 // Create included response file of second level. 903 llvm::SmallString<128> IncludedFileName2; 904 llvm::sys::path::append(IncludedFileName2, IncDir, "resp2"); 905 FS.addFile(IncludedFileName2, 0, 906 MemoryBuffer::getMemBuffer("-option_21 -option_22\n" 907 "-option_23=abcd\n")); 908 909 // Create second included response file of second level. 910 llvm::SmallString<128> IncludedFileName3; 911 llvm::sys::path::append(IncludedFileName3, IncDir, "resp3"); 912 FS.addFile(IncludedFileName3, 0, 913 MemoryBuffer::getMemBuffer("-option_31 -option_32\n" 914 "-option_33=abcd\n")); 915 916 // Prepare 'file' with reference to response file. 917 SmallString<128> IncRef; 918 IncRef.append(1, '@'); 919 IncRef.append(IncludedFileName); 920 llvm::SmallVector<const char *, 4> Argv = {"test/test", "-flag_1", 921 IncRef.c_str(), "-flag_2"}; 922 923 // Expand response files. 924 llvm::BumpPtrAllocator A; 925 llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine); 926 ECtx.setVFS(&FS).setCurrentDir(TestRoot).setRelativeNames(true); 927 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv)); 928 EXPECT_THAT(Argv, testing::Pointwise( 929 StringEquality(), 930 {"test/test", "-flag_1", "-option_1", "-option_2", 931 "-option_21", "-option_22", "-option_23=abcd", 932 "-option_3=abcd", "-option_31", "-option_32", 933 "-option_33=abcd", "-option_4=efjk", "-flag_2"})); 934 } 935 936 TEST(CommandLineTest, RecursiveResponseFiles) { 937 vfs::InMemoryFileSystem FS; 938 #ifdef _WIN32 939 const char *TestRoot = "C:\\"; 940 #else 941 const char *TestRoot = "/"; 942 #endif 943 FS.setCurrentWorkingDirectory(TestRoot); 944 945 StringRef SelfFilePath = "self.rsp"; 946 std::string SelfFileRef = ("@" + SelfFilePath).str(); 947 948 StringRef NestedFilePath = "nested.rsp"; 949 std::string NestedFileRef = ("@" + NestedFilePath).str(); 950 951 StringRef FlagFilePath = "flag.rsp"; 952 std::string FlagFileRef = ("@" + FlagFilePath).str(); 953 954 std::string SelfFileContents; 955 raw_string_ostream SelfFile(SelfFileContents); 956 SelfFile << "-option_1\n"; 957 SelfFile << FlagFileRef << "\n"; 958 SelfFile << NestedFileRef << "\n"; 959 SelfFile << SelfFileRef << "\n"; 960 FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str())); 961 962 std::string NestedFileContents; 963 raw_string_ostream NestedFile(NestedFileContents); 964 NestedFile << "-option_2\n"; 965 NestedFile << FlagFileRef << "\n"; 966 NestedFile << SelfFileRef << "\n"; 967 NestedFile << NestedFileRef << "\n"; 968 FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str())); 969 970 std::string FlagFileContents; 971 raw_string_ostream FlagFile(FlagFileContents); 972 FlagFile << "-option_x\n"; 973 FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str())); 974 975 // Ensure: 976 // Recursive expansion terminates 977 // Recursive files never expand 978 // Non-recursive repeats are allowed 979 SmallVector<const char *, 4> Argv = {"test/test", SelfFileRef.c_str(), 980 "-option_3"}; 981 BumpPtrAllocator A; 982 #ifdef _WIN32 983 cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine; 984 #else 985 cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine; 986 #endif 987 llvm::cl::ExpansionContext ECtx(A, Tokenizer); 988 ECtx.setVFS(&FS).setCurrentDir(TestRoot); 989 llvm::Error Err = ECtx.expandResponseFiles(Argv); 990 ASSERT_TRUE((bool)Err); 991 SmallString<128> FilePath = SelfFilePath; 992 std::error_code EC = FS.makeAbsolute(FilePath); 993 ASSERT_FALSE((bool)EC); 994 std::string ExpectedMessage = 995 std::string("recursive expansion of: '") + std::string(FilePath) + "'"; 996 ASSERT_TRUE(toString(std::move(Err)) == ExpectedMessage); 997 998 EXPECT_THAT(Argv, 999 testing::Pointwise(StringEquality(), 1000 {"test/test", "-option_1", "-option_x", 1001 "-option_2", "-option_x", SelfFileRef.c_str(), 1002 NestedFileRef.c_str(), SelfFileRef.c_str(), 1003 "-option_3"})); 1004 } 1005 1006 TEST(CommandLineTest, ResponseFilesAtArguments) { 1007 vfs::InMemoryFileSystem FS; 1008 #ifdef _WIN32 1009 const char *TestRoot = "C:\\"; 1010 #else 1011 const char *TestRoot = "/"; 1012 #endif 1013 FS.setCurrentWorkingDirectory(TestRoot); 1014 1015 StringRef ResponseFilePath = "test.rsp"; 1016 1017 std::string ResponseFileContents; 1018 raw_string_ostream ResponseFile(ResponseFileContents); 1019 ResponseFile << "-foo" << "\n"; 1020 ResponseFile << "-bar" << "\n"; 1021 FS.addFile(ResponseFilePath, 0, 1022 MemoryBuffer::getMemBuffer(ResponseFile.str())); 1023 1024 // Ensure we expand rsp files after lots of non-rsp arguments starting with @. 1025 constexpr size_t NON_RSP_AT_ARGS = 64; 1026 SmallVector<const char *, 4> Argv = {"test/test"}; 1027 Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg"); 1028 std::string ResponseFileRef = ("@" + ResponseFilePath).str(); 1029 Argv.push_back(ResponseFileRef.c_str()); 1030 1031 BumpPtrAllocator A; 1032 llvm::cl::ExpansionContext ECtx(A, cl::TokenizeGNUCommandLine); 1033 ECtx.setVFS(&FS).setCurrentDir(TestRoot); 1034 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv)); 1035 1036 // ASSERT instead of EXPECT to prevent potential out-of-bounds access. 1037 ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2); 1038 size_t i = 0; 1039 EXPECT_STREQ(Argv[i++], "test/test"); 1040 for (; i < 1 + NON_RSP_AT_ARGS; ++i) 1041 EXPECT_STREQ(Argv[i], "@non_rsp_at_arg"); 1042 EXPECT_STREQ(Argv[i++], "-foo"); 1043 EXPECT_STREQ(Argv[i++], "-bar"); 1044 } 1045 1046 TEST(CommandLineTest, ResponseFileRelativePath) { 1047 vfs::InMemoryFileSystem FS; 1048 #ifdef _WIN32 1049 const char *TestRoot = "C:\\"; 1050 #else 1051 const char *TestRoot = "//net"; 1052 #endif 1053 FS.setCurrentWorkingDirectory(TestRoot); 1054 1055 StringRef OuterFile = "dir/outer.rsp"; 1056 StringRef OuterFileContents = "@inner.rsp"; 1057 FS.addFile(OuterFile, 0, MemoryBuffer::getMemBuffer(OuterFileContents)); 1058 1059 StringRef InnerFile = "dir/inner.rsp"; 1060 StringRef InnerFileContents = "-flag"; 1061 FS.addFile(InnerFile, 0, MemoryBuffer::getMemBuffer(InnerFileContents)); 1062 1063 SmallVector<const char *, 2> Argv = {"test/test", "@dir/outer.rsp"}; 1064 1065 BumpPtrAllocator A; 1066 llvm::cl::ExpansionContext ECtx(A, cl::TokenizeGNUCommandLine); 1067 ECtx.setVFS(&FS).setCurrentDir(TestRoot).setRelativeNames(true); 1068 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv)); 1069 EXPECT_THAT(Argv, 1070 testing::Pointwise(StringEquality(), {"test/test", "-flag"})); 1071 } 1072 1073 TEST(CommandLineTest, ResponseFileEOLs) { 1074 vfs::InMemoryFileSystem FS; 1075 #ifdef _WIN32 1076 const char *TestRoot = "C:\\"; 1077 #else 1078 const char *TestRoot = "//net"; 1079 #endif 1080 FS.setCurrentWorkingDirectory(TestRoot); 1081 FS.addFile("eols.rsp", 0, 1082 MemoryBuffer::getMemBuffer("-Xclang -Wno-whatever\n input.cpp")); 1083 SmallVector<const char *, 2> Argv = {"clang", "@eols.rsp"}; 1084 BumpPtrAllocator A; 1085 llvm::cl::ExpansionContext ECtx(A, cl::TokenizeWindowsCommandLine); 1086 ECtx.setVFS(&FS).setCurrentDir(TestRoot).setMarkEOLs(true).setRelativeNames( 1087 true); 1088 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv)); 1089 const char *Expected[] = {"clang", "-Xclang", "-Wno-whatever", nullptr, 1090 "input.cpp"}; 1091 ASSERT_EQ(std::size(Expected), Argv.size()); 1092 for (size_t I = 0, E = std::size(Expected); I < E; ++I) { 1093 if (Expected[I] == nullptr) { 1094 ASSERT_EQ(Argv[I], nullptr); 1095 } else { 1096 ASSERT_STREQ(Expected[I], Argv[I]); 1097 } 1098 } 1099 } 1100 1101 TEST(CommandLineTest, BadResponseFile) { 1102 BumpPtrAllocator A; 1103 StringSaver Saver(A); 1104 TempDir ADir("dir", /*Unique*/ true); 1105 SmallString<128> AFilePath = ADir.path(); 1106 llvm::sys::path::append(AFilePath, "file.rsp"); 1107 std::string AFileExp = std::string("@") + std::string(AFilePath.str()); 1108 SmallVector<const char *, 2> Argv = {"clang", AFileExp.c_str()}; 1109 1110 bool Res = cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv); 1111 ASSERT_TRUE(Res); 1112 ASSERT_EQ(2U, Argv.size()); 1113 ASSERT_STREQ(Argv[0], "clang"); 1114 ASSERT_STREQ(Argv[1], AFileExp.c_str()); 1115 1116 std::string ADirExp = std::string("@") + std::string(ADir.path()); 1117 Argv = {"clang", ADirExp.c_str()}; 1118 Res = cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv); 1119 ASSERT_FALSE(Res); 1120 ASSERT_EQ(2U, Argv.size()); 1121 ASSERT_STREQ(Argv[0], "clang"); 1122 ASSERT_STREQ(Argv[1], ADirExp.c_str()); 1123 } 1124 1125 TEST(CommandLineTest, SetDefaultValue) { 1126 cl::ResetCommandLineParser(); 1127 1128 StackOption<std::string> Opt1("opt1", cl::init("true")); 1129 StackOption<bool> Opt2("opt2", cl::init(true)); 1130 cl::alias Alias("alias", llvm::cl::aliasopt(Opt2)); 1131 StackOption<int> Opt3("opt3", cl::init(3)); 1132 1133 llvm::SmallVector<int, 3> IntVals = {1, 2, 3}; 1134 llvm::SmallVector<std::string, 3> StrVals = {"foo", "bar", "baz"}; 1135 1136 StackOption<int, cl::list<int>> List1( 1137 "list1", cl::list_init<int>(llvm::ArrayRef<int>(IntVals)), 1138 cl::CommaSeparated); 1139 StackOption<std::string, cl::list<std::string>> List2( 1140 "list2", cl::list_init<std::string>(llvm::ArrayRef<std::string>(StrVals)), 1141 cl::CommaSeparated); 1142 cl::alias ListAlias("list-alias", llvm::cl::aliasopt(List2)); 1143 1144 const char *args[] = {"prog", "-opt1=false", "-list1", "4", 1145 "-list1", "5,6", "-opt2", "-opt3"}; 1146 1147 EXPECT_TRUE( 1148 cl::ParseCommandLineOptions(7, args, StringRef(), &llvm::nulls())); 1149 1150 EXPECT_EQ(Opt1, "false"); 1151 EXPECT_TRUE(Opt2); 1152 EXPECT_EQ(Opt3, 3); 1153 1154 for (size_t I = 0, E = IntVals.size(); I < E; ++I) { 1155 EXPECT_EQ(IntVals[I] + 3, List1[I]); 1156 EXPECT_EQ(StrVals[I], List2[I]); 1157 } 1158 1159 Opt2 = false; 1160 Opt3 = 1; 1161 1162 cl::ResetAllOptionOccurrences(); 1163 1164 for (auto &OM : cl::getRegisteredOptions(cl::SubCommand::getTopLevel())) { 1165 cl::Option *O = OM.second; 1166 if (O->ArgStr == "opt2") { 1167 continue; 1168 } 1169 O->setDefault(); 1170 } 1171 1172 EXPECT_EQ(Opt1, "true"); 1173 EXPECT_TRUE(Opt2); 1174 EXPECT_EQ(Opt3, 3); 1175 for (size_t I = 0, E = IntVals.size(); I < E; ++I) { 1176 EXPECT_EQ(IntVals[I], List1[I]); 1177 EXPECT_EQ(StrVals[I], List2[I]); 1178 } 1179 1180 Alias.removeArgument(); 1181 ListAlias.removeArgument(); 1182 } 1183 1184 TEST(CommandLineTest, ReadConfigFile) { 1185 llvm::SmallVector<const char *, 1> Argv; 1186 1187 TempDir TestDir("unittest", /*Unique*/ true); 1188 TempDir TestSubDir(TestDir.path("subdir"), /*Unique*/ false); 1189 1190 llvm::SmallString<128> TestCfg = TestDir.path("foo"); 1191 TempFile ConfigFile(TestCfg, "", 1192 "# Comment\n" 1193 "-option_1\n" 1194 "-option_2=<CFGDIR>/dir1\n" 1195 "-option_3=<CFGDIR>\n" 1196 "-option_4 <CFGDIR>\n" 1197 "-option_5=<CFG\\\n" 1198 "DIR>\n" 1199 "-option_6=<CFGDIR>/dir1,<CFGDIR>/dir2\n" 1200 "@subconfig\n" 1201 "-option_11=abcd\n" 1202 "-option_12=\\\n" 1203 "cdef\n"); 1204 1205 llvm::SmallString<128> TestCfg2 = TestDir.path("subconfig"); 1206 TempFile ConfigFile2(TestCfg2, "", 1207 "-option_7\n" 1208 "-option_8=<CFGDIR>/dir2\n" 1209 "@subdir/subfoo\n" 1210 "\n" 1211 " # comment\n"); 1212 1213 llvm::SmallString<128> TestCfg3 = TestSubDir.path("subfoo"); 1214 TempFile ConfigFile3(TestCfg3, "", 1215 "-option_9=<CFGDIR>/dir3\n" 1216 "@<CFGDIR>/subfoo2\n"); 1217 1218 llvm::SmallString<128> TestCfg4 = TestSubDir.path("subfoo2"); 1219 TempFile ConfigFile4(TestCfg4, "", "-option_10\n"); 1220 1221 // Make sure the current directory is not the directory where config files 1222 // resides. In this case the code that expands response files will not find 1223 // 'subconfig' unless it resolves nested inclusions relative to the including 1224 // file. 1225 llvm::SmallString<128> CurrDir; 1226 std::error_code EC = llvm::sys::fs::current_path(CurrDir); 1227 EXPECT_TRUE(!EC); 1228 EXPECT_NE(CurrDir.str(), TestDir.path()); 1229 1230 llvm::BumpPtrAllocator A; 1231 llvm::cl::ExpansionContext ECtx(A, cl::tokenizeConfigFile); 1232 llvm::Error Result = ECtx.readConfigFile(ConfigFile.path(), Argv); 1233 1234 EXPECT_FALSE((bool)Result); 1235 EXPECT_EQ(Argv.size(), 13U); 1236 EXPECT_STREQ(Argv[0], "-option_1"); 1237 EXPECT_STREQ(Argv[1], 1238 ("-option_2=" + TestDir.path() + "/dir1").str().c_str()); 1239 EXPECT_STREQ(Argv[2], ("-option_3=" + TestDir.path()).str().c_str()); 1240 EXPECT_STREQ(Argv[3], "-option_4"); 1241 EXPECT_STREQ(Argv[4], TestDir.path().str().c_str()); 1242 EXPECT_STREQ(Argv[5], ("-option_5=" + TestDir.path()).str().c_str()); 1243 EXPECT_STREQ(Argv[6], ("-option_6=" + TestDir.path() + "/dir1," + 1244 TestDir.path() + "/dir2") 1245 .str() 1246 .c_str()); 1247 EXPECT_STREQ(Argv[7], "-option_7"); 1248 EXPECT_STREQ(Argv[8], 1249 ("-option_8=" + TestDir.path() + "/dir2").str().c_str()); 1250 EXPECT_STREQ(Argv[9], 1251 ("-option_9=" + TestSubDir.path() + "/dir3").str().c_str()); 1252 EXPECT_STREQ(Argv[10], "-option_10"); 1253 EXPECT_STREQ(Argv[11], "-option_11=abcd"); 1254 EXPECT_STREQ(Argv[12], "-option_12=cdef"); 1255 } 1256 1257 TEST(CommandLineTest, PositionalEatArgsError) { 1258 cl::ResetCommandLineParser(); 1259 1260 StackOption<std::string, cl::list<std::string>> PosEatArgs( 1261 "positional-eat-args", cl::Positional, cl::desc("<arguments>..."), 1262 cl::PositionalEatsArgs); 1263 StackOption<std::string, cl::list<std::string>> PosEatArgs2( 1264 "positional-eat-args2", cl::Positional, cl::desc("Some strings"), 1265 cl::PositionalEatsArgs); 1266 1267 const char *args[] = {"prog", "-positional-eat-args=XXXX"}; 1268 const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"}; 1269 const char *args3[] = {"prog", "-positional-eat-args", "-foo"}; 1270 const char *args4[] = {"prog", "-positional-eat-args", 1271 "-foo", "-positional-eat-args2", 1272 "-bar", "foo"}; 1273 1274 std::string Errs; 1275 raw_string_ostream OS(Errs); 1276 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); 1277 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1278 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); 1279 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1280 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); 1281 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1282 1283 cl::ResetAllOptionOccurrences(); 1284 EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4, StringRef(), &OS)); 1285 EXPECT_EQ(PosEatArgs.size(), 1u); 1286 EXPECT_EQ(PosEatArgs2.size(), 2u); 1287 EXPECT_TRUE(Errs.empty()); 1288 } 1289 1290 #ifdef _WIN32 1291 void checkSeparators(StringRef Path) { 1292 char UndesiredSeparator = sys::path::get_separator()[0] == '/' ? '\\' : '/'; 1293 ASSERT_EQ(Path.find(UndesiredSeparator), StringRef::npos); 1294 } 1295 1296 TEST(CommandLineTest, GetCommandLineArguments) { 1297 int argc = __argc; 1298 char **argv = __argv; 1299 1300 // GetCommandLineArguments is called in InitLLVM. 1301 llvm::InitLLVM X(argc, argv); 1302 1303 EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]), 1304 llvm::sys::path::is_absolute(__argv[0])); 1305 checkSeparators(argv[0]); 1306 1307 EXPECT_TRUE( 1308 llvm::sys::path::filename(argv[0]).equals_insensitive("supporttests.exe")) 1309 << "Filename of test executable is " 1310 << llvm::sys::path::filename(argv[0]); 1311 } 1312 #endif 1313 1314 class OutputRedirector { 1315 public: 1316 OutputRedirector(int RedirectFD) 1317 : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) { 1318 if (OldFD == -1 || 1319 sys::fs::createTemporaryFile("unittest-redirect", "", NewFD, 1320 FilePath) || 1321 dup2(NewFD, RedirectFD) == -1) 1322 Valid = false; 1323 } 1324 1325 ~OutputRedirector() { 1326 dup2(OldFD, RedirectFD); 1327 close(OldFD); 1328 close(NewFD); 1329 } 1330 1331 SmallVector<char, 128> FilePath; 1332 bool Valid = true; 1333 1334 private: 1335 int RedirectFD; 1336 int OldFD; 1337 int NewFD; 1338 }; 1339 1340 struct AutoDeleteFile { 1341 SmallVector<char, 128> FilePath; 1342 ~AutoDeleteFile() { 1343 if (!FilePath.empty()) 1344 sys::fs::remove(std::string(FilePath.data(), FilePath.size())); 1345 } 1346 }; 1347 1348 static std::string interceptStdout(std::function<void()> F) { 1349 outs().flush(); // flush any output from previous tests 1350 AutoDeleteFile File; 1351 { 1352 OutputRedirector Stdout(fileno(stdout)); 1353 if (!Stdout.Valid) 1354 return ""; 1355 File.FilePath = Stdout.FilePath; 1356 F(); 1357 outs().flush(); 1358 } 1359 auto Buffer = MemoryBuffer::getFile(File.FilePath); 1360 if (!Buffer) 1361 return ""; 1362 return Buffer->get()->getBuffer().str(); 1363 } 1364 1365 template <void (*Func)(const cl::Option &)> 1366 class PrintOptionTestBase : public ::testing::Test { 1367 public: 1368 // Return std::string because the output of a failing EXPECT check is 1369 // unreadable for StringRef. It also avoids any lifetime issues. 1370 template <typename... Ts> std::string runTest(Ts... OptionAttributes) { 1371 StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText), 1372 OptionAttributes...); 1373 return interceptStdout([&]() { Func(TestOption); }); 1374 } 1375 1376 enum class OptionValue { Val }; 1377 const StringRef Opt = "some-option"; 1378 const StringRef HelpText = "some help"; 1379 }; 1380 1381 // This is a workaround for cl::Option sub-classes having their 1382 // printOptionInfo functions private. 1383 void printOptionInfo(const cl::Option &O) { 1384 O.printOptionInfo(/*GlobalWidth=*/26); 1385 } 1386 1387 using PrintOptionInfoTest = PrintOptionTestBase<printOptionInfo>; 1388 1389 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) { 1390 std::string Output = 1391 runTest(cl::ValueOptional, 1392 cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"))); 1393 1394 // clang-format off 1395 EXPECT_EQ(Output, (" --" + Opt + "=<value> - " + HelpText + "\n" 1396 " =v1 - desc1\n") 1397 .str()); 1398 // clang-format on 1399 } 1400 1401 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) { 1402 std::string Output = runTest( 1403 cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"), 1404 clEnumValN(OptionValue::Val, "", ""))); 1405 1406 // clang-format off 1407 EXPECT_EQ(Output, 1408 (" --" + Opt + " - " + HelpText + "\n" 1409 " --" + Opt + "=<value> - " + HelpText + "\n" 1410 " =v1 - desc1\n") 1411 .str()); 1412 // clang-format on 1413 } 1414 1415 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) { 1416 std::string Output = runTest( 1417 cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"), 1418 clEnumValN(OptionValue::Val, "", "desc2"))); 1419 1420 // clang-format off 1421 EXPECT_EQ(Output, (" --" + Opt + " - " + HelpText + "\n" 1422 " --" + Opt + "=<value> - " + HelpText + "\n" 1423 " =v1 - desc1\n" 1424 " =<empty> - desc2\n") 1425 .str()); 1426 // clang-format on 1427 } 1428 1429 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) { 1430 std::string Output = runTest( 1431 cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"), 1432 clEnumValN(OptionValue::Val, "", ""))); 1433 1434 // clang-format off 1435 EXPECT_EQ(Output, (" --" + Opt + "=<value> - " + HelpText + "\n" 1436 " =v1 - desc1\n" 1437 " =<empty>\n") 1438 .str()); 1439 // clang-format on 1440 } 1441 1442 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) { 1443 std::string Output = runTest( 1444 cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", ""))); 1445 1446 // clang-format off 1447 EXPECT_EQ(Output, 1448 (" --" + Opt + "=<value> - " + HelpText + "\n" 1449 " =v1\n").str()); 1450 // clang-format on 1451 } 1452 1453 TEST_F(PrintOptionInfoTest, PrintOptionInfoMultilineValueDescription) { 1454 std::string Output = 1455 runTest(cl::ValueRequired, 1456 cl::values(clEnumValN(OptionValue::Val, "v1", 1457 "This is the first enum value\n" 1458 "which has a really long description\n" 1459 "thus it is multi-line."), 1460 clEnumValN(OptionValue::Val, "", 1461 "This is an unnamed enum value\n" 1462 "Should be indented as well"))); 1463 1464 // clang-format off 1465 EXPECT_EQ(Output, 1466 (" --" + Opt + "=<value> - " + HelpText + "\n" 1467 " =v1 - This is the first enum value\n" 1468 " which has a really long description\n" 1469 " thus it is multi-line.\n" 1470 " =<empty> - This is an unnamed enum value\n" 1471 " Should be indented as well\n").str()); 1472 // clang-format on 1473 } 1474 1475 void printOptionValue(const cl::Option &O) { 1476 O.printOptionValue(/*GlobalWidth=*/12, /*Force=*/true); 1477 } 1478 1479 using PrintOptionValueTest = PrintOptionTestBase<printOptionValue>; 1480 1481 TEST_F(PrintOptionValueTest, PrintOptionDefaultValue) { 1482 std::string Output = 1483 runTest(cl::init(OptionValue::Val), 1484 cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"))); 1485 1486 EXPECT_EQ(Output, (" --" + Opt + " = v1 (default: v1)\n").str()); 1487 } 1488 1489 TEST_F(PrintOptionValueTest, PrintOptionNoDefaultValue) { 1490 std::string Output = 1491 runTest(cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"))); 1492 1493 // Note: the option still has a (zero-initialized) value, but the default 1494 // is invalid and doesn't match any value. 1495 EXPECT_EQ(Output, (" --" + Opt + " = v1 (default: )\n").str()); 1496 } 1497 1498 TEST_F(PrintOptionValueTest, PrintOptionUnknownValue) { 1499 std::string Output = runTest(cl::init(OptionValue::Val)); 1500 1501 EXPECT_EQ(Output, (" --" + Opt + " = *unknown option value*\n").str()); 1502 } 1503 1504 class GetOptionWidthTest : public ::testing::Test { 1505 public: 1506 enum class OptionValue { Val }; 1507 1508 template <typename... Ts> 1509 size_t runTest(StringRef ArgName, Ts... OptionAttributes) { 1510 StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"), 1511 OptionAttributes...); 1512 return getOptionWidth(TestOption); 1513 } 1514 1515 private: 1516 // This is a workaround for cl::Option sub-classes having their 1517 // printOptionInfo 1518 // functions private. 1519 size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); } 1520 }; 1521 1522 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) { 1523 StringRef ArgName("a-long-argument-name"); 1524 size_t ExpectedStrSize = (" --" + ArgName + "=<value> - ").str().size(); 1525 EXPECT_EQ( 1526 runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))), 1527 ExpectedStrSize); 1528 } 1529 1530 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) { 1531 StringRef OptName("a-long-option-name"); 1532 size_t ExpectedStrSize = (" =" + OptName + " - ").str().size(); 1533 EXPECT_EQ( 1534 runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"), 1535 clEnumValN(OptionValue::Val, "b", "help"))), 1536 ExpectedStrSize); 1537 } 1538 1539 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) { 1540 StringRef OptName("a-long-option-name"); 1541 size_t ExpectedStrSize = (" =" + OptName + " - ").str().size(); 1542 EXPECT_EQ( 1543 runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"), 1544 clEnumValN(OptionValue::Val, OptName, "help"))), 1545 ExpectedStrSize); 1546 } 1547 1548 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) { 1549 size_t ExpectedStrSize = StringRef(" =<empty> - ").size(); 1550 // The length of a=<value> (including indentation) is actually the same as the 1551 // =<empty> string, so it is impossible to distinguish via testing the case 1552 // where the empty string is picked from where the option name is picked. 1553 EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"), 1554 clEnumValN(OptionValue::Val, "", "help"))), 1555 ExpectedStrSize); 1556 } 1557 1558 TEST_F(GetOptionWidthTest, 1559 GetOptionWidthValueOptionalEmptyOptionWithNoDescription) { 1560 StringRef ArgName("a"); 1561 // The length of a=<value> (including indentation) is actually the same as the 1562 // =<empty> string, so it is impossible to distinguish via testing the case 1563 // where the empty string is ignored from where it is not ignored. 1564 // The dash will not actually be printed, but the space it would take up is 1565 // included to ensure a consistent column width. 1566 size_t ExpectedStrSize = (" -" + ArgName + "=<value> - ").str().size(); 1567 EXPECT_EQ(runTest(ArgName, cl::ValueOptional, 1568 cl::values(clEnumValN(OptionValue::Val, "value", "help"), 1569 clEnumValN(OptionValue::Val, "", ""))), 1570 ExpectedStrSize); 1571 } 1572 1573 TEST_F(GetOptionWidthTest, 1574 GetOptionWidthValueRequiredEmptyOptionWithNoDescription) { 1575 // The length of a=<value> (including indentation) is actually the same as the 1576 // =<empty> string, so it is impossible to distinguish via testing the case 1577 // where the empty string is picked from where the option name is picked 1578 size_t ExpectedStrSize = StringRef(" =<empty> - ").size(); 1579 EXPECT_EQ(runTest("a", cl::ValueRequired, 1580 cl::values(clEnumValN(OptionValue::Val, "value", "help"), 1581 clEnumValN(OptionValue::Val, "", ""))), 1582 ExpectedStrSize); 1583 } 1584 1585 TEST(CommandLineTest, PrefixOptions) { 1586 cl::ResetCommandLineParser(); 1587 1588 StackOption<std::string, cl::list<std::string>> IncludeDirs( 1589 "I", cl::Prefix, cl::desc("Declare an include directory")); 1590 1591 // Test non-prefixed variant works with cl::Prefix options. 1592 EXPECT_TRUE(IncludeDirs.empty()); 1593 const char *args[] = {"prog", "-I=/usr/include"}; 1594 EXPECT_TRUE( 1595 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls())); 1596 EXPECT_EQ(IncludeDirs.size(), 1u); 1597 EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0); 1598 1599 IncludeDirs.erase(IncludeDirs.begin()); 1600 cl::ResetAllOptionOccurrences(); 1601 1602 // Test non-prefixed variant works with cl::Prefix options when value is 1603 // passed in following argument. 1604 EXPECT_TRUE(IncludeDirs.empty()); 1605 const char *args2[] = {"prog", "-I", "/usr/include"}; 1606 EXPECT_TRUE( 1607 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 1608 EXPECT_EQ(IncludeDirs.size(), 1u); 1609 EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0); 1610 1611 IncludeDirs.erase(IncludeDirs.begin()); 1612 cl::ResetAllOptionOccurrences(); 1613 1614 // Test prefixed variant works with cl::Prefix options. 1615 EXPECT_TRUE(IncludeDirs.empty()); 1616 const char *args3[] = {"prog", "-I/usr/include"}; 1617 EXPECT_TRUE( 1618 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls())); 1619 EXPECT_EQ(IncludeDirs.size(), 1u); 1620 EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0); 1621 1622 StackOption<std::string, cl::list<std::string>> MacroDefs( 1623 "D", cl::AlwaysPrefix, cl::desc("Define a macro"), 1624 cl::value_desc("MACRO[=VALUE]")); 1625 1626 cl::ResetAllOptionOccurrences(); 1627 1628 // Test non-prefixed variant does not work with cl::AlwaysPrefix options: 1629 // equal sign is part of the value. 1630 EXPECT_TRUE(MacroDefs.empty()); 1631 const char *args4[] = {"prog", "-D=HAVE_FOO"}; 1632 EXPECT_TRUE( 1633 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls())); 1634 EXPECT_EQ(MacroDefs.size(), 1u); 1635 EXPECT_EQ(MacroDefs.front().compare("=HAVE_FOO"), 0); 1636 1637 MacroDefs.erase(MacroDefs.begin()); 1638 cl::ResetAllOptionOccurrences(); 1639 1640 // Test non-prefixed variant does not allow value to be passed in following 1641 // argument with cl::AlwaysPrefix options. 1642 EXPECT_TRUE(MacroDefs.empty()); 1643 const char *args5[] = {"prog", "-D", "HAVE_FOO"}; 1644 EXPECT_FALSE( 1645 cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls())); 1646 EXPECT_TRUE(MacroDefs.empty()); 1647 1648 cl::ResetAllOptionOccurrences(); 1649 1650 // Test prefixed variant works with cl::AlwaysPrefix options. 1651 EXPECT_TRUE(MacroDefs.empty()); 1652 const char *args6[] = {"prog", "-DHAVE_FOO"}; 1653 EXPECT_TRUE( 1654 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls())); 1655 EXPECT_EQ(MacroDefs.size(), 1u); 1656 EXPECT_EQ(MacroDefs.front().compare("HAVE_FOO"), 0); 1657 } 1658 1659 TEST(CommandLineTest, GroupingWithValue) { 1660 cl::ResetCommandLineParser(); 1661 1662 StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag")); 1663 StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag")); 1664 StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed, 1665 cl::desc("ValueDisallowed option")); 1666 StackOption<std::string> OptV("v", cl::Grouping, 1667 cl::desc("ValueRequired option")); 1668 StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional, 1669 cl::desc("ValueOptional option")); 1670 1671 // Should be possible to use an option which requires a value 1672 // at the end of a group. 1673 const char *args1[] = {"prog", "-fv", "val1"}; 1674 EXPECT_TRUE( 1675 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls())); 1676 EXPECT_TRUE(OptF); 1677 EXPECT_STREQ("val1", OptV.c_str()); 1678 OptV.clear(); 1679 cl::ResetAllOptionOccurrences(); 1680 1681 // Should not crash if it is accidentally used elsewhere in the group. 1682 const char *args2[] = {"prog", "-vf", "val2"}; 1683 EXPECT_FALSE( 1684 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 1685 OptV.clear(); 1686 cl::ResetAllOptionOccurrences(); 1687 1688 // Should allow the "opt=value" form at the end of the group 1689 const char *args3[] = {"prog", "-fv=val3"}; 1690 EXPECT_TRUE( 1691 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls())); 1692 EXPECT_TRUE(OptF); 1693 EXPECT_STREQ("val3", OptV.c_str()); 1694 OptV.clear(); 1695 cl::ResetAllOptionOccurrences(); 1696 1697 // Should allow assigning a value for a ValueOptional option 1698 // at the end of the group 1699 const char *args4[] = {"prog", "-fo=val4"}; 1700 EXPECT_TRUE( 1701 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls())); 1702 EXPECT_TRUE(OptF); 1703 EXPECT_STREQ("val4", OptO.c_str()); 1704 OptO.clear(); 1705 cl::ResetAllOptionOccurrences(); 1706 1707 // Should assign an empty value if a ValueOptional option is used elsewhere 1708 // in the group. 1709 const char *args5[] = {"prog", "-fob"}; 1710 EXPECT_TRUE( 1711 cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls())); 1712 EXPECT_TRUE(OptF); 1713 EXPECT_EQ(1, OptO.getNumOccurrences()); 1714 EXPECT_EQ(1, OptB.getNumOccurrences()); 1715 EXPECT_TRUE(OptO.empty()); 1716 cl::ResetAllOptionOccurrences(); 1717 1718 // Should not allow an assignment for a ValueDisallowed option. 1719 const char *args6[] = {"prog", "-fd=false"}; 1720 EXPECT_FALSE( 1721 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls())); 1722 } 1723 1724 TEST(CommandLineTest, GroupingAndPrefix) { 1725 cl::ResetCommandLineParser(); 1726 1727 StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag")); 1728 StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag")); 1729 StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping, 1730 cl::desc("Prefix and Grouping")); 1731 StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping, 1732 cl::desc("AlwaysPrefix and Grouping")); 1733 1734 // Should be possible to use a cl::Prefix option without grouping. 1735 const char *args1[] = {"prog", "-pval1"}; 1736 EXPECT_TRUE( 1737 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls())); 1738 EXPECT_STREQ("val1", OptP.c_str()); 1739 OptP.clear(); 1740 cl::ResetAllOptionOccurrences(); 1741 1742 // Should be possible to pass a value in a separate argument. 1743 const char *args2[] = {"prog", "-p", "val2"}; 1744 EXPECT_TRUE( 1745 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls())); 1746 EXPECT_STREQ("val2", OptP.c_str()); 1747 OptP.clear(); 1748 cl::ResetAllOptionOccurrences(); 1749 1750 // The "-opt=value" form should work, too. 1751 const char *args3[] = {"prog", "-p=val3"}; 1752 EXPECT_TRUE( 1753 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls())); 1754 EXPECT_STREQ("val3", OptP.c_str()); 1755 OptP.clear(); 1756 cl::ResetAllOptionOccurrences(); 1757 1758 // All three previous cases should work the same way if an option with both 1759 // cl::Prefix and cl::Grouping modifiers is used at the end of a group. 1760 const char *args4[] = {"prog", "-fpval4"}; 1761 EXPECT_TRUE( 1762 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls())); 1763 EXPECT_TRUE(OptF); 1764 EXPECT_STREQ("val4", OptP.c_str()); 1765 OptP.clear(); 1766 cl::ResetAllOptionOccurrences(); 1767 1768 const char *args5[] = {"prog", "-fp", "val5"}; 1769 EXPECT_TRUE( 1770 cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls())); 1771 EXPECT_TRUE(OptF); 1772 EXPECT_STREQ("val5", OptP.c_str()); 1773 OptP.clear(); 1774 cl::ResetAllOptionOccurrences(); 1775 1776 const char *args6[] = {"prog", "-fp=val6"}; 1777 EXPECT_TRUE( 1778 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls())); 1779 EXPECT_TRUE(OptF); 1780 EXPECT_STREQ("val6", OptP.c_str()); 1781 OptP.clear(); 1782 cl::ResetAllOptionOccurrences(); 1783 1784 // Should assign a value even if the part after a cl::Prefix option is equal 1785 // to the name of another option. 1786 const char *args7[] = {"prog", "-fpb"}; 1787 EXPECT_TRUE( 1788 cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls())); 1789 EXPECT_TRUE(OptF); 1790 EXPECT_STREQ("b", OptP.c_str()); 1791 EXPECT_FALSE(OptB); 1792 OptP.clear(); 1793 cl::ResetAllOptionOccurrences(); 1794 1795 // Should be possible to use a cl::AlwaysPrefix option without grouping. 1796 const char *args8[] = {"prog", "-aval8"}; 1797 EXPECT_TRUE( 1798 cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls())); 1799 EXPECT_STREQ("val8", OptA.c_str()); 1800 OptA.clear(); 1801 cl::ResetAllOptionOccurrences(); 1802 1803 // Should not be possible to pass a value in a separate argument. 1804 const char *args9[] = {"prog", "-a", "val9"}; 1805 EXPECT_FALSE( 1806 cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls())); 1807 cl::ResetAllOptionOccurrences(); 1808 1809 // With the "-opt=value" form, the "=" symbol should be preserved. 1810 const char *args10[] = {"prog", "-a=val10"}; 1811 EXPECT_TRUE( 1812 cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls())); 1813 EXPECT_STREQ("=val10", OptA.c_str()); 1814 OptA.clear(); 1815 cl::ResetAllOptionOccurrences(); 1816 1817 // All three previous cases should work the same way if an option with both 1818 // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group. 1819 const char *args11[] = {"prog", "-faval11"}; 1820 EXPECT_TRUE( 1821 cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls())); 1822 EXPECT_TRUE(OptF); 1823 EXPECT_STREQ("val11", OptA.c_str()); 1824 OptA.clear(); 1825 cl::ResetAllOptionOccurrences(); 1826 1827 const char *args12[] = {"prog", "-fa", "val12"}; 1828 EXPECT_FALSE( 1829 cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls())); 1830 cl::ResetAllOptionOccurrences(); 1831 1832 const char *args13[] = {"prog", "-fa=val13"}; 1833 EXPECT_TRUE( 1834 cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls())); 1835 EXPECT_TRUE(OptF); 1836 EXPECT_STREQ("=val13", OptA.c_str()); 1837 OptA.clear(); 1838 cl::ResetAllOptionOccurrences(); 1839 1840 // Should assign a value even if the part after a cl::AlwaysPrefix option 1841 // is equal to the name of another option. 1842 const char *args14[] = {"prog", "-fab"}; 1843 EXPECT_TRUE( 1844 cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls())); 1845 EXPECT_TRUE(OptF); 1846 EXPECT_STREQ("b", OptA.c_str()); 1847 EXPECT_FALSE(OptB); 1848 OptA.clear(); 1849 cl::ResetAllOptionOccurrences(); 1850 } 1851 1852 TEST(CommandLineTest, LongOptions) { 1853 cl::ResetCommandLineParser(); 1854 1855 StackOption<bool> OptA("a", cl::desc("Some flag")); 1856 StackOption<bool> OptBLong("long-flag", cl::desc("Some long flag")); 1857 StackOption<bool, cl::alias> OptB("b", cl::desc("Alias to --long-flag"), 1858 cl::aliasopt(OptBLong)); 1859 StackOption<std::string> OptAB("ab", cl::desc("Another long option")); 1860 1861 std::string Errs; 1862 raw_string_ostream OS(Errs); 1863 1864 const char *args1[] = {"prog", "-a", "-ab", "val1"}; 1865 const char *args2[] = {"prog", "-a", "--ab", "val1"}; 1866 const char *args3[] = {"prog", "-ab", "--ab", "val1"}; 1867 1868 // 1869 // The following tests treat `-` and `--` the same, and always match the 1870 // longest string. 1871 // 1872 1873 EXPECT_TRUE( 1874 cl::ParseCommandLineOptions(4, args1, StringRef(), &OS)); 1875 EXPECT_TRUE(OptA); 1876 EXPECT_FALSE(OptBLong); 1877 EXPECT_STREQ("val1", OptAB.c_str()); 1878 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1879 cl::ResetAllOptionOccurrences(); 1880 1881 EXPECT_TRUE( 1882 cl::ParseCommandLineOptions(4, args2, StringRef(), &OS)); 1883 EXPECT_TRUE(OptA); 1884 EXPECT_FALSE(OptBLong); 1885 EXPECT_STREQ("val1", OptAB.c_str()); 1886 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1887 cl::ResetAllOptionOccurrences(); 1888 1889 // Fails because `-ab` and `--ab` are treated the same and appear more than 1890 // once. Also, `val1` is unexpected. 1891 EXPECT_FALSE( 1892 cl::ParseCommandLineOptions(4, args3, StringRef(), &OS)); 1893 outs()<< Errs << "\n"; 1894 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1895 cl::ResetAllOptionOccurrences(); 1896 1897 // 1898 // The following tests treat `-` and `--` differently, with `-` for short, and 1899 // `--` for long options. 1900 // 1901 1902 // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and 1903 // `val1` is unexpected. 1904 EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(), 1905 &OS, nullptr, true)); 1906 EXPECT_FALSE(Errs.empty()); Errs.clear(); 1907 cl::ResetAllOptionOccurrences(); 1908 1909 // Works because `-a` is treated differently than `--ab`. 1910 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(), 1911 &OS, nullptr, true)); 1912 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1913 cl::ResetAllOptionOccurrences(); 1914 1915 // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option. 1916 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(), 1917 &OS, nullptr, true)); 1918 EXPECT_TRUE(OptA); 1919 EXPECT_TRUE(OptBLong); 1920 EXPECT_STREQ("val1", OptAB.c_str()); 1921 EXPECT_TRUE(Errs.empty()); Errs.clear(); 1922 cl::ResetAllOptionOccurrences(); 1923 } 1924 1925 TEST(CommandLineTest, OptionErrorMessage) { 1926 // When there is an error, we expect some error message like: 1927 // prog: for the -a option: [...] 1928 // 1929 // Test whether the "for the -a option"-part is correctly formatted. 1930 cl::ResetCommandLineParser(); 1931 1932 StackOption<bool> OptA("a", cl::desc("Some option")); 1933 StackOption<bool> OptLong("long", cl::desc("Some long option")); 1934 1935 std::string Errs; 1936 raw_string_ostream OS(Errs); 1937 1938 OptA.error("custom error", OS); 1939 EXPECT_NE(Errs.find("for the -a option:"), std::string::npos); 1940 Errs.clear(); 1941 1942 OptLong.error("custom error", OS); 1943 EXPECT_NE(Errs.find("for the --long option:"), std::string::npos); 1944 Errs.clear(); 1945 1946 cl::ResetAllOptionOccurrences(); 1947 } 1948 1949 TEST(CommandLineTest, OptionErrorMessageSuggest) { 1950 // When there is an error, and the edit-distance is not very large, 1951 // we expect some error message like: 1952 // prog: did you mean '--option'? 1953 // 1954 // Test whether this message is well-formatted. 1955 cl::ResetCommandLineParser(); 1956 1957 StackOption<bool> OptLong("aluminium", cl::desc("Some long option")); 1958 1959 const char *args[] = {"prog", "--aluminum"}; 1960 1961 std::string Errs; 1962 raw_string_ostream OS(Errs); 1963 1964 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); 1965 EXPECT_NE(Errs.find("prog: Did you mean '--aluminium'?\n"), 1966 std::string::npos); 1967 Errs.clear(); 1968 1969 cl::ResetAllOptionOccurrences(); 1970 } 1971 1972 TEST(CommandLineTest, OptionErrorMessageSuggestNoHidden) { 1973 // We expect that 'really hidden' option do not show up in option 1974 // suggestions. 1975 cl::ResetCommandLineParser(); 1976 1977 StackOption<bool> OptLong("aluminium", cl::desc("Some long option")); 1978 StackOption<bool> OptLong2("aluminum", cl::desc("Bad option"), 1979 cl::ReallyHidden); 1980 1981 const char *args[] = {"prog", "--alumnum"}; 1982 1983 std::string Errs; 1984 raw_string_ostream OS(Errs); 1985 1986 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); 1987 EXPECT_NE(Errs.find("prog: Did you mean '--aluminium'?\n"), 1988 std::string::npos); 1989 Errs.clear(); 1990 1991 cl::ResetAllOptionOccurrences(); 1992 } 1993 1994 TEST(CommandLineTest, Callback) { 1995 cl::ResetCommandLineParser(); 1996 1997 StackOption<bool> OptA("a", cl::desc("option a")); 1998 StackOption<bool> OptB( 1999 "b", cl::desc("option b -- This option turns on option a"), 2000 cl::callback([&](const bool &) { OptA = true; })); 2001 StackOption<bool> OptC( 2002 "c", cl::desc("option c -- This option turns on options a and b"), 2003 cl::callback([&](const bool &) { OptB = true; })); 2004 StackOption<std::string, cl::list<std::string>> List( 2005 "list", 2006 cl::desc("option list -- This option turns on options a, b, and c when " 2007 "'foo' is included in list"), 2008 cl::CommaSeparated, 2009 cl::callback([&](const std::string &Str) { 2010 if (Str == "foo") 2011 OptC = true; 2012 })); 2013 2014 const char *args1[] = {"prog", "-a"}; 2015 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args1)); 2016 EXPECT_TRUE(OptA); 2017 EXPECT_FALSE(OptB); 2018 EXPECT_FALSE(OptC); 2019 EXPECT_EQ(List.size(), 0u); 2020 cl::ResetAllOptionOccurrences(); 2021 2022 const char *args2[] = {"prog", "-b"}; 2023 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args2)); 2024 EXPECT_TRUE(OptA); 2025 EXPECT_TRUE(OptB); 2026 EXPECT_FALSE(OptC); 2027 EXPECT_EQ(List.size(), 0u); 2028 cl::ResetAllOptionOccurrences(); 2029 2030 const char *args3[] = {"prog", "-c"}; 2031 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args3)); 2032 EXPECT_TRUE(OptA); 2033 EXPECT_TRUE(OptB); 2034 EXPECT_TRUE(OptC); 2035 EXPECT_EQ(List.size(), 0u); 2036 cl::ResetAllOptionOccurrences(); 2037 2038 const char *args4[] = {"prog", "--list=foo,bar"}; 2039 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args4)); 2040 EXPECT_TRUE(OptA); 2041 EXPECT_TRUE(OptB); 2042 EXPECT_TRUE(OptC); 2043 EXPECT_EQ(List.size(), 2u); 2044 cl::ResetAllOptionOccurrences(); 2045 2046 const char *args5[] = {"prog", "--list=bar"}; 2047 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args5)); 2048 EXPECT_FALSE(OptA); 2049 EXPECT_FALSE(OptB); 2050 EXPECT_FALSE(OptC); 2051 EXPECT_EQ(List.size(), 1u); 2052 2053 cl::ResetAllOptionOccurrences(); 2054 } 2055 2056 enum Enum { Val1, Val2 }; 2057 static cl::bits<Enum> ExampleBits( 2058 cl::desc("An example cl::bits to ensure it compiles"), 2059 cl::values( 2060 clEnumValN(Val1, "bits-val1", "The Val1 value"), 2061 clEnumValN(Val1, "bits-val2", "The Val2 value"))); 2062 2063 TEST(CommandLineTest, ConsumeAfterOnePositional) { 2064 cl::ResetCommandLineParser(); 2065 2066 // input [args] 2067 StackOption<std::string, cl::opt<std::string>> Input(cl::Positional, 2068 cl::Required); 2069 StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter); 2070 2071 const char *Args[] = {"prog", "input", "arg1", "arg2"}; 2072 2073 std::string Errs; 2074 raw_string_ostream OS(Errs); 2075 EXPECT_TRUE(cl::ParseCommandLineOptions(4, Args, StringRef(), &OS)); 2076 EXPECT_EQ("input", Input); 2077 EXPECT_EQ(ExtraArgs.size(), 2u); 2078 EXPECT_EQ(ExtraArgs[0], "arg1"); 2079 EXPECT_EQ(ExtraArgs[1], "arg2"); 2080 EXPECT_TRUE(Errs.empty()); 2081 } 2082 2083 TEST(CommandLineTest, ConsumeAfterTwoPositionals) { 2084 cl::ResetCommandLineParser(); 2085 2086 // input1 input2 [args] 2087 StackOption<std::string, cl::opt<std::string>> Input1(cl::Positional, 2088 cl::Required); 2089 StackOption<std::string, cl::opt<std::string>> Input2(cl::Positional, 2090 cl::Required); 2091 StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter); 2092 2093 const char *Args[] = {"prog", "input1", "input2", "arg1", "arg2"}; 2094 2095 std::string Errs; 2096 raw_string_ostream OS(Errs); 2097 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args, StringRef(), &OS)); 2098 EXPECT_EQ("input1", Input1); 2099 EXPECT_EQ("input2", Input2); 2100 EXPECT_EQ(ExtraArgs.size(), 2u); 2101 EXPECT_EQ(ExtraArgs[0], "arg1"); 2102 EXPECT_EQ(ExtraArgs[1], "arg2"); 2103 EXPECT_TRUE(Errs.empty()); 2104 } 2105 2106 TEST(CommandLineTest, ResetAllOptionOccurrences) { 2107 cl::ResetCommandLineParser(); 2108 2109 // -option -str -enableA -enableC [sink] input [args] 2110 StackOption<bool> Option("option"); 2111 StackOption<std::string> Str("str"); 2112 enum Vals { ValA, ValB, ValC }; 2113 StackOption<Vals, cl::bits<Vals>> Bits( 2114 cl::values(clEnumValN(ValA, "enableA", "Enable A"), 2115 clEnumValN(ValB, "enableB", "Enable B"), 2116 clEnumValN(ValC, "enableC", "Enable C"))); 2117 StackOption<std::string, cl::list<std::string>> Sink(cl::Sink); 2118 StackOption<std::string> Input(cl::Positional); 2119 StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter); 2120 2121 const char *Args[] = {"prog", "-option", "-str=STR", "-enableA", 2122 "-enableC", "-unknown", "input", "-arg"}; 2123 2124 std::string Errs; 2125 raw_string_ostream OS(Errs); 2126 EXPECT_TRUE(cl::ParseCommandLineOptions(8, Args, StringRef(), &OS)); 2127 EXPECT_TRUE(OS.str().empty()); 2128 2129 EXPECT_TRUE(Option); 2130 EXPECT_EQ("STR", Str); 2131 EXPECT_EQ((1u << ValA) | (1u << ValC), Bits.getBits()); 2132 EXPECT_EQ(1u, Sink.size()); 2133 EXPECT_EQ("-unknown", Sink[0]); 2134 EXPECT_EQ("input", Input); 2135 EXPECT_EQ(1u, ExtraArgs.size()); 2136 EXPECT_EQ("-arg", ExtraArgs[0]); 2137 2138 cl::ResetAllOptionOccurrences(); 2139 EXPECT_FALSE(Option); 2140 EXPECT_EQ("", Str); 2141 EXPECT_EQ(0u, Bits.getBits()); 2142 EXPECT_EQ(0u, Sink.size()); 2143 EXPECT_EQ(0, Input.getNumOccurrences()); 2144 EXPECT_EQ(0u, ExtraArgs.size()); 2145 } 2146 2147 TEST(CommandLineTest, DefaultValue) { 2148 cl::ResetCommandLineParser(); 2149 2150 StackOption<bool> BoolOption("bool-option"); 2151 StackOption<std::string> StrOption("str-option"); 2152 StackOption<bool> BoolInitOption("bool-init-option", cl::init(true)); 2153 StackOption<std::string> StrInitOption("str-init-option", 2154 cl::init("str-default-value")); 2155 2156 const char *Args[] = {"prog"}; // no options 2157 2158 std::string Errs; 2159 raw_string_ostream OS(Errs); 2160 EXPECT_TRUE(cl::ParseCommandLineOptions(1, Args, StringRef(), &OS)); 2161 EXPECT_TRUE(OS.str().empty()); 2162 2163 EXPECT_TRUE(!BoolOption); 2164 EXPECT_FALSE(BoolOption.Default.hasValue()); 2165 EXPECT_EQ(0, BoolOption.getNumOccurrences()); 2166 2167 EXPECT_EQ("", StrOption); 2168 EXPECT_FALSE(StrOption.Default.hasValue()); 2169 EXPECT_EQ(0, StrOption.getNumOccurrences()); 2170 2171 EXPECT_TRUE(BoolInitOption); 2172 EXPECT_TRUE(BoolInitOption.Default.hasValue()); 2173 EXPECT_EQ(0, BoolInitOption.getNumOccurrences()); 2174 2175 EXPECT_EQ("str-default-value", StrInitOption); 2176 EXPECT_TRUE(StrInitOption.Default.hasValue()); 2177 EXPECT_EQ(0, StrInitOption.getNumOccurrences()); 2178 2179 const char *Args2[] = {"prog", "-bool-option", "-str-option=str-value", 2180 "-bool-init-option=0", 2181 "-str-init-option=str-init-value"}; 2182 2183 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args2, StringRef(), &OS)); 2184 EXPECT_TRUE(OS.str().empty()); 2185 2186 EXPECT_TRUE(BoolOption); 2187 EXPECT_FALSE(BoolOption.Default.hasValue()); 2188 EXPECT_EQ(1, BoolOption.getNumOccurrences()); 2189 2190 EXPECT_EQ("str-value", StrOption); 2191 EXPECT_FALSE(StrOption.Default.hasValue()); 2192 EXPECT_EQ(1, StrOption.getNumOccurrences()); 2193 2194 EXPECT_FALSE(BoolInitOption); 2195 EXPECT_TRUE(BoolInitOption.Default.hasValue()); 2196 EXPECT_EQ(1, BoolInitOption.getNumOccurrences()); 2197 2198 EXPECT_EQ("str-init-value", StrInitOption); 2199 EXPECT_TRUE(StrInitOption.Default.hasValue()); 2200 EXPECT_EQ(1, StrInitOption.getNumOccurrences()); 2201 } 2202 2203 TEST(CommandLineTest, HelpWithoutSubcommands) { 2204 // Check that the help message does not contain the "[subcommand]" placeholder 2205 // and the "SUBCOMMANDS" section if there are no subcommands. 2206 cl::ResetCommandLineParser(); 2207 StackOption<bool> Opt("opt", cl::init(false)); 2208 const char *args[] = {"prog"}; 2209 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(), 2210 &llvm::nulls())); 2211 auto Output = interceptStdout([]() { cl::PrintHelpMessage(); }); 2212 EXPECT_NE(std::string::npos, Output.find("USAGE: prog [options]")) << Output; 2213 EXPECT_EQ(std::string::npos, Output.find("SUBCOMMANDS:")) << Output; 2214 cl::ResetCommandLineParser(); 2215 } 2216 2217 TEST(CommandLineTest, HelpWithSubcommands) { 2218 // Check that the help message contains the "[subcommand]" placeholder in the 2219 // "USAGE" line and describes subcommands. 2220 cl::ResetCommandLineParser(); 2221 StackSubCommand SC1("sc1", "First Subcommand"); 2222 StackSubCommand SC2("sc2", "Second Subcommand"); 2223 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false)); 2224 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false)); 2225 const char *args[] = {"prog"}; 2226 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(), 2227 &llvm::nulls())); 2228 auto Output = interceptStdout([]() { cl::PrintHelpMessage(); }); 2229 EXPECT_NE(std::string::npos, 2230 Output.find("USAGE: prog [subcommand] [options]")) 2231 << Output; 2232 EXPECT_NE(std::string::npos, Output.find("SUBCOMMANDS:")) << Output; 2233 EXPECT_NE(std::string::npos, Output.find("sc1 - First Subcommand")) << Output; 2234 EXPECT_NE(std::string::npos, Output.find("sc2 - Second Subcommand")) 2235 << Output; 2236 cl::ResetCommandLineParser(); 2237 } 2238 2239 TEST(CommandLineTest, UnknownCommands) { 2240 cl::ResetCommandLineParser(); 2241 2242 StackSubCommand SC1("foo", "Foo subcommand"); 2243 StackSubCommand SC2("bar", "Bar subcommand"); 2244 StackOption<bool> SC1Opt("put", cl::sub(SC1)); 2245 StackOption<bool> SC2Opt("get", cl::sub(SC2)); 2246 StackOption<bool> TopOpt1("peek"); 2247 StackOption<bool> TopOpt2("set"); 2248 2249 std::string Errs; 2250 raw_string_ostream OS(Errs); 2251 2252 const char *Args1[] = {"prog", "baz", "--get"}; 2253 EXPECT_FALSE( 2254 cl::ParseCommandLineOptions(std::size(Args1), Args1, StringRef(), &OS)); 2255 EXPECT_EQ(Errs, 2256 "prog: Unknown subcommand 'baz'. Try: 'prog --help'\n" 2257 "prog: Did you mean 'bar'?\n" 2258 "prog: Unknown command line argument '--get'. Try: 'prog --help'\n" 2259 "prog: Did you mean '--set'?\n"); 2260 2261 // Do not show a suggestion if the subcommand is not similar to any known. 2262 Errs.clear(); 2263 const char *Args2[] = {"prog", "faz"}; 2264 EXPECT_FALSE( 2265 cl::ParseCommandLineOptions(std::size(Args2), Args2, StringRef(), &OS)); 2266 EXPECT_EQ(Errs, "prog: Unknown subcommand 'faz'. Try: 'prog --help'\n"); 2267 } 2268 2269 TEST(CommandLineTest, SubCommandGroups) { 2270 // Check that options in subcommand groups are associated with expected 2271 // subcommands. 2272 2273 cl::ResetCommandLineParser(); 2274 2275 StackSubCommand SC1("sc1", "SC1 subcommand"); 2276 StackSubCommand SC2("sc2", "SC2 subcommand"); 2277 StackSubCommand SC3("sc3", "SC3 subcommand"); 2278 cl::SubCommandGroup Group12 = {&SC1, &SC2}; 2279 2280 StackOption<bool> Opt12("opt12", cl::sub(Group12), cl::init(false)); 2281 StackOption<bool> Opt3("opt3", cl::sub(SC3), cl::init(false)); 2282 2283 // The "--opt12" option is expected to be added to both subcommands in the 2284 // group, but not to the top-level "no subcommand" pseudo-subcommand or the 2285 // "sc3" subcommand. 2286 EXPECT_EQ(1U, SC1.OptionsMap.size()); 2287 EXPECT_TRUE(SC1.OptionsMap.contains("opt12")); 2288 2289 EXPECT_EQ(1U, SC2.OptionsMap.size()); 2290 EXPECT_TRUE(SC2.OptionsMap.contains("opt12")); 2291 2292 EXPECT_FALSE(cl::SubCommand::getTopLevel().OptionsMap.contains("opt12")); 2293 EXPECT_FALSE(SC3.OptionsMap.contains("opt12")); 2294 } 2295 2296 TEST(CommandLineTest, HelpWithEmptyCategory) { 2297 cl::ResetCommandLineParser(); 2298 2299 cl::OptionCategory Category1("First Category"); 2300 cl::OptionCategory Category2("Second Category"); 2301 StackOption<int> Opt1("opt1", cl::cat(Category1)); 2302 StackOption<int> Opt2("opt2", cl::cat(Category2)); 2303 cl::HideUnrelatedOptions(Category2); 2304 2305 const char *args[] = {"prog"}; 2306 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(), 2307 &llvm::nulls())); 2308 auto Output = interceptStdout( 2309 []() { cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); }); 2310 EXPECT_EQ(std::string::npos, Output.find("First Category")) 2311 << "An empty category should not be printed"; 2312 2313 Output = interceptStdout( 2314 []() { cl::PrintHelpMessage(/*Hidden=*/true, /*Categorized=*/true); }); 2315 EXPECT_EQ(std::string::npos, Output.find("First Category")) 2316 << "An empty category should not be printed"; 2317 2318 cl::ResetCommandLineParser(); 2319 } 2320 2321 } // anonymous namespace 2322