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