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