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