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