[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / unittests / Support / CommandLineTest.cpp
blob32dc440135cb332f9e59fcdc918d455c97f4a19f
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 //===----------------------------------------------------------------------===//
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>
33 using namespace llvm;
34 using llvm::unittest::TempDir;
35 using llvm::unittest::TempFile;
37 namespace {
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));
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
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
63 private:
64 const char *const name;
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)...) {}
73 ~StackOption() override { this->removeArgument(); }
75 template <class DT> StackOption<T> &operator=(const DT &V) {
76 Base::operator=(V);
77 return *this;
81 class StackSubCommand : public cl::SubCommand {
82 public:
83 StackSubCommand(StringRef Name,
84 StringRef Description = StringRef())
85 : SubCommand(Name, Description) {}
87 StackSubCommand() : SubCommand() {}
89 ~StackSubCommand() { unregisterSubCommand(); }
93 cl::OptionCategory TestCategory("Test Options", "Description");
94 TEST(CommandLineTest, ModifyExisitingOption) {
95 StackOption<int> TestOption("test-option", cl::desc("old description"));
97 static const char Description[] = "New description";
98 static const char ArgString[] = "new-test-option";
99 static const char ValueString[] = "Integer";
101 StringMap<cl::Option *> &Map =
102 cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
104 ASSERT_EQ(Map.count("test-option"), 1u) << "Could not find option in map.";
106 cl::Option *Retrieved = Map["test-option"];
107 ASSERT_EQ(&TestOption, Retrieved) << "Retrieved wrong option.";
109 ASSERT_NE(Retrieved->Categories.end(),
110 find_if(Retrieved->Categories,
111 [&](const llvm::cl::OptionCategory *Cat) {
112 return Cat == &cl::getGeneralCategory();
114 << "Incorrect default option category.";
116 Retrieved->addCategory(TestCategory);
117 ASSERT_NE(Retrieved->Categories.end(),
118 find_if(Retrieved->Categories,
119 [&](const llvm::cl::OptionCategory *Cat) {
120 return Cat == &TestCategory;
122 << "Failed to modify option's option category.";
124 Retrieved->setDescription(Description);
125 ASSERT_STREQ(Retrieved->HelpStr.data(), Description)
126 << "Changing option description failed.";
128 Retrieved->setArgStr(ArgString);
129 ASSERT_STREQ(ArgString, Retrieved->ArgStr.data())
130 << "Failed to modify option's Argument string.";
132 Retrieved->setValueStr(ValueString);
133 ASSERT_STREQ(Retrieved->ValueStr.data(), ValueString)
134 << "Failed to modify option's Value string.";
136 Retrieved->setHiddenFlag(cl::Hidden);
137 ASSERT_EQ(cl::Hidden, TestOption.getOptionHiddenFlag()) <<
138 "Failed to modify option's hidden flag.";
141 TEST(CommandLineTest, UseOptionCategory) {
142 StackOption<int> TestOption2("test-option", cl::cat(TestCategory));
144 ASSERT_NE(TestOption2.Categories.end(),
145 find_if(TestOption2.Categories,
146 [&](const llvm::cl::OptionCategory *Cat) {
147 return Cat == &TestCategory;
149 << "Failed to assign Option Category.";
152 TEST(CommandLineTest, UseMultipleCategories) {
153 StackOption<int> TestOption2("test-option2", cl::cat(TestCategory),
154 cl::cat(cl::getGeneralCategory()),
155 cl::cat(cl::getGeneralCategory()));
157 // Make sure cl::getGeneralCategory() wasn't added twice.
158 ASSERT_EQ(TestOption2.Categories.size(), 2U);
160 ASSERT_NE(TestOption2.Categories.end(),
161 find_if(TestOption2.Categories,
162 [&](const llvm::cl::OptionCategory *Cat) {
163 return Cat == &TestCategory;
165 << "Failed to assign Option Category.";
166 ASSERT_NE(TestOption2.Categories.end(),
167 find_if(TestOption2.Categories,
168 [&](const llvm::cl::OptionCategory *Cat) {
169 return Cat == &cl::getGeneralCategory();
171 << "Failed to assign General Category.";
173 cl::OptionCategory AnotherCategory("Additional test Options", "Description");
174 StackOption<int> TestOption("test-option", cl::cat(TestCategory),
175 cl::cat(AnotherCategory));
176 ASSERT_EQ(TestOption.Categories.end(),
177 find_if(TestOption.Categories,
178 [&](const llvm::cl::OptionCategory *Cat) {
179 return Cat == &cl::getGeneralCategory();
181 << "Failed to remove General Category.";
182 ASSERT_NE(TestOption.Categories.end(),
183 find_if(TestOption.Categories,
184 [&](const llvm::cl::OptionCategory *Cat) {
185 return Cat == &TestCategory;
187 << "Failed to assign Option Category.";
188 ASSERT_NE(TestOption.Categories.end(),
189 find_if(TestOption.Categories,
190 [&](const llvm::cl::OptionCategory *Cat) {
191 return Cat == &AnotherCategory;
193 << "Failed to assign Another Category.";
196 typedef void ParserFunction(StringRef Source, StringSaver &Saver,
197 SmallVectorImpl<const char *> &NewArgv,
198 bool MarkEOLs);
200 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input,
201 ArrayRef<const char *> Output,
202 bool MarkEOLs = false) {
203 SmallVector<const char *, 0> Actual;
204 BumpPtrAllocator A;
205 StringSaver Saver(A);
206 parse(Input, Saver, Actual, MarkEOLs);
207 EXPECT_EQ(Output.size(), Actual.size());
208 for (unsigned I = 0, E = Actual.size(); I != E; ++I) {
209 if (I < Output.size()) {
210 EXPECT_STREQ(Output[I], Actual[I]);
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);
225 TEST(CommandLineTest, TokenizeWindowsCommandLine1) {
226 const char Input[] =
227 R"(a\b c\\d e\\"f g" h\"i j\\\"k "lmn" o pqr "st \"u" \v)";
228 const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
229 "lmn", "o", "pqr", "st \"u", "\\v" };
230 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output);
233 TEST(CommandLineTest, TokenizeWindowsCommandLine2) {
234 const char Input[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp";
235 const char *const Output[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"};
236 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output);
239 TEST(CommandLineTest, TokenizeWindowsCommandLineQuotedLastArgument) {
240 // Whitespace at the end of the command line doesn't cause an empty last word
241 const char Input0[] = R"(a b c d )";
242 const char *const Output0[] = {"a", "b", "c", "d"};
243 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input0, Output0);
245 // But an explicit "" does
246 const char Input1[] = R"(a b c d "")";
247 const char *const Output1[] = {"a", "b", "c", "d", ""};
248 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input1, Output1);
250 // An unterminated quoted string is also emitted as an argument word, empty
251 // or not
252 const char Input2[] = R"(a b c d ")";
253 const char *const Output2[] = {"a", "b", "c", "d", ""};
254 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input2, Output2);
255 const char Input3[] = R"(a b c d "text)";
256 const char *const Output3[] = {"a", "b", "c", "d", "text"};
257 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input3, Output3);
260 TEST(CommandLineTest, TokenizeWindowsCommandLineExeName) {
261 const char Input1[] =
262 R"("C:\Program Files\Whatever\"clang.exe z.c -DY=\"x\")";
263 const char *const Output1[] = {"C:\\Program Files\\Whatever\\clang.exe",
264 "z.c", "-DY=\"x\""};
265 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input1, Output1);
267 const char Input2[] = "\"a\\\"b c\\\"d\n\"e\\\"f g\\\"h\n";
268 const char *const Output2[] = {"a\\b", "c\"d", nullptr,
269 "e\\f", "g\"h", nullptr};
270 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input2, Output2,
271 /*MarkEOLs=*/true);
273 const char Input3[] = R"(\\server\share\subdir\clang.exe)";
274 const char *const Output3[] = {"\\\\server\\share\\subdir\\clang.exe"};
275 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input3, Output3);
278 TEST(CommandLineTest, TokenizeAndMarkEOLs) {
279 // Clang uses EOL marking in response files to support options that consume
280 // the rest of the arguments on the current line, but do not consume arguments
281 // from subsequent lines. For example, given these rsp files contents:
282 // /c /Zi /O2
283 // /Oy- /link /debug /opt:ref
284 // /Zc:ThreadsafeStatics-
286 // clang-cl needs to treat "/debug /opt:ref" as linker flags, and everything
287 // else as compiler flags. The tokenizer inserts nullptr sentinels into the
288 // output so that clang-cl can find the end of the current line.
289 const char Input[] = "clang -Xclang foo\n\nfoo\"bar\"baz\n x.cpp\n";
290 const char *const Output[] = {"clang", "-Xclang", "foo",
291 nullptr, nullptr, "foobarbaz",
292 nullptr, "x.cpp", nullptr};
293 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
294 /*MarkEOLs=*/true);
295 testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
296 /*MarkEOLs=*/true);
299 TEST(CommandLineTest, TokenizeConfigFile1) {
300 const char *Input = "\\";
301 const char *const Output[] = { "\\" };
302 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
305 TEST(CommandLineTest, TokenizeConfigFile2) {
306 const char *Input = "\\abc";
307 const char *const Output[] = { "abc" };
308 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
311 TEST(CommandLineTest, TokenizeConfigFile3) {
312 const char *Input = "abc\\";
313 const char *const Output[] = { "abc\\" };
314 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
317 TEST(CommandLineTest, TokenizeConfigFile4) {
318 const char *Input = "abc\\\n123";
319 const char *const Output[] = { "abc123" };
320 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
323 TEST(CommandLineTest, TokenizeConfigFile5) {
324 const char *Input = "abc\\\r\n123";
325 const char *const Output[] = { "abc123" };
326 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
329 TEST(CommandLineTest, TokenizeConfigFile6) {
330 const char *Input = "abc\\\n";
331 const char *const Output[] = { "abc" };
332 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
335 TEST(CommandLineTest, TokenizeConfigFile7) {
336 const char *Input = "abc\\\r\n";
337 const char *const Output[] = { "abc" };
338 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
341 TEST(CommandLineTest, TokenizeConfigFile8) {
342 SmallVector<const char *, 0> Actual;
343 BumpPtrAllocator A;
344 StringSaver Saver(A);
345 cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false);
346 EXPECT_TRUE(Actual.empty());
349 TEST(CommandLineTest, TokenizeConfigFile9) {
350 SmallVector<const char *, 0> Actual;
351 BumpPtrAllocator A;
352 StringSaver Saver(A);
353 cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false);
354 EXPECT_TRUE(Actual.empty());
357 TEST(CommandLineTest, TokenizeConfigFile10) {
358 const char *Input = "\\\nabc";
359 const char *const Output[] = { "abc" };
360 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
363 TEST(CommandLineTest, TokenizeConfigFile11) {
364 const char *Input = "\\\r\nabc";
365 const char *const Output[] = { "abc" };
366 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
369 TEST(CommandLineTest, AliasesWithArguments) {
370 static const size_t ARGC = 3;
371 const char *const Inputs[][ARGC] = {
372 { "-tool", "-actual=x", "-extra" },
373 { "-tool", "-actual", "x" },
374 { "-tool", "-alias=x", "-extra" },
375 { "-tool", "-alias", "x" }
378 for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) {
379 StackOption<std::string> Actual("actual");
380 StackOption<bool> Extra("extra");
381 StackOption<std::string> Input(cl::Positional);
383 cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
385 cl::ParseCommandLineOptions(ARGC, Inputs[i]);
386 EXPECT_EQ("x", Actual);
387 EXPECT_EQ(0, Input.getNumOccurrences());
389 Alias.removeArgument();
393 void testAliasRequired(int argc, const char *const *argv) {
394 StackOption<std::string> Option("option", cl::Required);
395 cl::alias Alias("o", llvm::cl::aliasopt(Option));
397 cl::ParseCommandLineOptions(argc, argv);
398 EXPECT_EQ("x", Option);
399 EXPECT_EQ(1, Option.getNumOccurrences());
401 Alias.removeArgument();
404 TEST(CommandLineTest, AliasRequired) {
405 const char *opts1[] = { "-tool", "-option=x" };
406 const char *opts2[] = { "-tool", "-o", "x" };
407 testAliasRequired(array_lengthof(opts1), opts1);
408 testAliasRequired(array_lengthof(opts2), opts2);
411 TEST(CommandLineTest, HideUnrelatedOptions) {
412 StackOption<int> TestOption1("hide-option-1");
413 StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory));
415 cl::HideUnrelatedOptions(TestCategory);
417 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
418 << "Failed to hide extra option.";
419 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
420 << "Hid extra option that should be visable.";
422 StringMap<cl::Option *> &Map =
423 cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
424 ASSERT_TRUE(Map.count("help") == (size_t)0 ||
425 cl::NotHidden == Map["help"]->getOptionHiddenFlag())
426 << "Hid default option that should be visable.";
429 cl::OptionCategory TestCategory2("Test Options set 2", "Description");
431 TEST(CommandLineTest, HideUnrelatedOptionsMulti) {
432 StackOption<int> TestOption1("multi-hide-option-1");
433 StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory));
434 StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2));
436 const cl::OptionCategory *VisibleCategories[] = {&TestCategory,
437 &TestCategory2};
439 cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
441 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
442 << "Failed to hide extra option.";
443 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
444 << "Hid extra option that should be visable.";
445 ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag())
446 << "Hid extra option that should be visable.";
448 StringMap<cl::Option *> &Map =
449 cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
450 ASSERT_TRUE(Map.count("help") == (size_t)0 ||
451 cl::NotHidden == Map["help"]->getOptionHiddenFlag())
452 << "Hid default option that should be visable.";
455 TEST(CommandLineTest, SetMultiValues) {
456 StackOption<int> Option("option");
457 const char *args[] = {"prog", "-option=1", "-option=2"};
458 EXPECT_TRUE(cl::ParseCommandLineOptions(array_lengthof(args), args,
459 StringRef(), &llvm::nulls()));
460 EXPECT_EQ(Option, 2);
463 TEST(CommandLineTest, SetValueInSubcategories) {
464 cl::ResetCommandLineParser();
466 StackSubCommand SC1("sc1", "First subcommand");
467 StackSubCommand SC2("sc2", "Second subcommand");
469 StackOption<bool> TopLevelOpt("top-level", cl::init(false));
470 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
471 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
473 EXPECT_FALSE(TopLevelOpt);
474 EXPECT_FALSE(SC1Opt);
475 EXPECT_FALSE(SC2Opt);
476 const char *args[] = {"prog", "-top-level"};
477 EXPECT_TRUE(
478 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
479 EXPECT_TRUE(TopLevelOpt);
480 EXPECT_FALSE(SC1Opt);
481 EXPECT_FALSE(SC2Opt);
483 TopLevelOpt = false;
485 cl::ResetAllOptionOccurrences();
486 EXPECT_FALSE(TopLevelOpt);
487 EXPECT_FALSE(SC1Opt);
488 EXPECT_FALSE(SC2Opt);
489 const char *args2[] = {"prog", "sc1", "-sc1"};
490 EXPECT_TRUE(
491 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
492 EXPECT_FALSE(TopLevelOpt);
493 EXPECT_TRUE(SC1Opt);
494 EXPECT_FALSE(SC2Opt);
496 SC1Opt = false;
498 cl::ResetAllOptionOccurrences();
499 EXPECT_FALSE(TopLevelOpt);
500 EXPECT_FALSE(SC1Opt);
501 EXPECT_FALSE(SC2Opt);
502 const char *args3[] = {"prog", "sc2", "-sc2"};
503 EXPECT_TRUE(
504 cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls()));
505 EXPECT_FALSE(TopLevelOpt);
506 EXPECT_FALSE(SC1Opt);
507 EXPECT_TRUE(SC2Opt);
510 TEST(CommandLineTest, LookupFailsInWrongSubCommand) {
511 cl::ResetCommandLineParser();
513 StackSubCommand SC1("sc1", "First subcommand");
514 StackSubCommand SC2("sc2", "Second subcommand");
516 StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
517 StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
519 std::string Errs;
520 raw_string_ostream OS(Errs);
522 const char *args[] = {"prog", "sc1", "-sc2"};
523 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
524 OS.flush();
525 EXPECT_FALSE(Errs.empty());
528 TEST(CommandLineTest, AddToAllSubCommands) {
529 cl::ResetCommandLineParser();
531 StackSubCommand SC1("sc1", "First subcommand");
532 StackOption<bool> AllOpt("everywhere", cl::sub(cl::SubCommand::getAll()),
533 cl::init(false));
534 StackSubCommand SC2("sc2", "Second subcommand");
536 const char *args[] = {"prog", "-everywhere"};
537 const char *args2[] = {"prog", "sc1", "-everywhere"};
538 const char *args3[] = {"prog", "sc2", "-everywhere"};
540 std::string Errs;
541 raw_string_ostream OS(Errs);
543 EXPECT_FALSE(AllOpt);
544 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
545 EXPECT_TRUE(AllOpt);
547 AllOpt = false;
549 cl::ResetAllOptionOccurrences();
550 EXPECT_FALSE(AllOpt);
551 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS));
552 EXPECT_TRUE(AllOpt);
554 AllOpt = false;
556 cl::ResetAllOptionOccurrences();
557 EXPECT_FALSE(AllOpt);
558 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS));
559 EXPECT_TRUE(AllOpt);
561 // Since all parsing succeeded, the error message should be empty.
562 OS.flush();
563 EXPECT_TRUE(Errs.empty());
566 TEST(CommandLineTest, ReparseCommandLineOptions) {
567 cl::ResetCommandLineParser();
569 StackOption<bool> TopLevelOpt(
570 "top-level", cl::sub(cl::SubCommand::getTopLevel()), cl::init(false));
572 const char *args[] = {"prog", "-top-level"};
574 EXPECT_FALSE(TopLevelOpt);
575 EXPECT_TRUE(
576 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
577 EXPECT_TRUE(TopLevelOpt);
579 TopLevelOpt = false;
581 cl::ResetAllOptionOccurrences();
582 EXPECT_FALSE(TopLevelOpt);
583 EXPECT_TRUE(
584 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
585 EXPECT_TRUE(TopLevelOpt);
588 TEST(CommandLineTest, RemoveFromRegularSubCommand) {
589 cl::ResetCommandLineParser();
591 StackSubCommand SC("sc", "Subcommand");
592 StackOption<bool> RemoveOption("remove-option", cl::sub(SC), cl::init(false));
593 StackOption<bool> KeepOption("keep-option", cl::sub(SC), cl::init(false));
595 const char *args[] = {"prog", "sc", "-remove-option"};
597 std::string Errs;
598 raw_string_ostream OS(Errs);
600 EXPECT_FALSE(RemoveOption);
601 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
602 EXPECT_TRUE(RemoveOption);
603 OS.flush();
604 EXPECT_TRUE(Errs.empty());
606 RemoveOption.removeArgument();
608 cl::ResetAllOptionOccurrences();
609 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
610 OS.flush();
611 EXPECT_FALSE(Errs.empty());
614 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
615 cl::ResetCommandLineParser();
617 StackOption<bool> TopLevelRemove("top-level-remove",
618 cl::sub(cl::SubCommand::getTopLevel()),
619 cl::init(false));
620 StackOption<bool> TopLevelKeep("top-level-keep",
621 cl::sub(cl::SubCommand::getTopLevel()),
622 cl::init(false));
624 const char *args[] = {"prog", "-top-level-remove"};
626 EXPECT_FALSE(TopLevelRemove);
627 EXPECT_TRUE(
628 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
629 EXPECT_TRUE(TopLevelRemove);
631 TopLevelRemove.removeArgument();
633 cl::ResetAllOptionOccurrences();
634 EXPECT_FALSE(
635 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
638 TEST(CommandLineTest, RemoveFromAllSubCommands) {
639 cl::ResetCommandLineParser();
641 StackSubCommand SC1("sc1", "First Subcommand");
642 StackSubCommand SC2("sc2", "Second Subcommand");
643 StackOption<bool> RemoveOption(
644 "remove-option", cl::sub(cl::SubCommand::getAll()), cl::init(false));
645 StackOption<bool> KeepOption("keep-option", cl::sub(cl::SubCommand::getAll()),
646 cl::init(false));
648 const char *args0[] = {"prog", "-remove-option"};
649 const char *args1[] = {"prog", "sc1", "-remove-option"};
650 const char *args2[] = {"prog", "sc2", "-remove-option"};
652 // It should work for all subcommands including the top-level.
653 EXPECT_FALSE(RemoveOption);
654 EXPECT_TRUE(
655 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
656 EXPECT_TRUE(RemoveOption);
658 RemoveOption = false;
660 cl::ResetAllOptionOccurrences();
661 EXPECT_FALSE(RemoveOption);
662 EXPECT_TRUE(
663 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
664 EXPECT_TRUE(RemoveOption);
666 RemoveOption = false;
668 cl::ResetAllOptionOccurrences();
669 EXPECT_FALSE(RemoveOption);
670 EXPECT_TRUE(
671 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
672 EXPECT_TRUE(RemoveOption);
674 RemoveOption.removeArgument();
676 // It should not work for any subcommands including the top-level.
677 cl::ResetAllOptionOccurrences();
678 EXPECT_FALSE(
679 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
680 cl::ResetAllOptionOccurrences();
681 EXPECT_FALSE(
682 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
683 cl::ResetAllOptionOccurrences();
684 EXPECT_FALSE(
685 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
688 TEST(CommandLineTest, GetRegisteredSubcommands) {
689 cl::ResetCommandLineParser();
691 StackSubCommand SC1("sc1", "First Subcommand");
692 StackOption<bool> Opt1("opt1", cl::sub(SC1), cl::init(false));
693 StackSubCommand SC2("sc2", "Second subcommand");
694 StackOption<bool> Opt2("opt2", cl::sub(SC2), cl::init(false));
696 const char *args0[] = {"prog", "sc1"};
697 const char *args1[] = {"prog", "sc2"};
699 EXPECT_TRUE(
700 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
701 EXPECT_FALSE(Opt1);
702 EXPECT_FALSE(Opt2);
703 for (auto *S : cl::getRegisteredSubcommands()) {
704 if (*S) {
705 EXPECT_EQ("sc1", S->getName());
709 cl::ResetAllOptionOccurrences();
710 EXPECT_TRUE(
711 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
712 EXPECT_FALSE(Opt1);
713 EXPECT_FALSE(Opt2);
714 for (auto *S : cl::getRegisteredSubcommands()) {
715 if (*S) {
716 EXPECT_EQ("sc2", S->getName());
721 TEST(CommandLineTest, DefaultOptions) {
722 cl::ResetCommandLineParser();
724 StackOption<std::string> Bar("bar", cl::sub(cl::SubCommand::getAll()),
725 cl::DefaultOption);
726 StackOption<std::string, cl::alias> Bar_Alias(
727 "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption);
729 StackOption<bool> Foo("foo", cl::init(false),
730 cl::sub(cl::SubCommand::getAll()), cl::DefaultOption);
731 StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"),
732 cl::aliasopt(Foo), cl::DefaultOption);
734 StackSubCommand SC1("sc1", "First Subcommand");
735 // Override "-b" and change type in sc1 SubCommand.
736 StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false));
737 StackSubCommand SC2("sc2", "Second subcommand");
738 // Override "-foo" and change type in sc2 SubCommand. Note that this does not
739 // affect "-f" alias, which continues to work correctly.
740 StackOption<std::string> SC2_Foo("foo", cl::sub(SC2));
742 const char *args0[] = {"prog", "-b", "args0 bar string", "-f"};
743 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args0) / sizeof(char *), args0,
744 StringRef(), &llvm::nulls()));
745 EXPECT_EQ(Bar, "args0 bar string");
746 EXPECT_TRUE(Foo);
747 EXPECT_FALSE(SC1_B);
748 EXPECT_TRUE(SC2_Foo.empty());
750 cl::ResetAllOptionOccurrences();
752 const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"};
753 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args1) / sizeof(char *), args1,
754 StringRef(), &llvm::nulls()));
755 EXPECT_EQ(Bar, "args1 bar string");
756 EXPECT_TRUE(Foo);
757 EXPECT_TRUE(SC1_B);
758 EXPECT_TRUE(SC2_Foo.empty());
759 for (auto *S : cl::getRegisteredSubcommands()) {
760 if (*S) {
761 EXPECT_EQ("sc1", S->getName());
765 cl::ResetAllOptionOccurrences();
767 const char *args2[] = {"prog", "sc2", "-b", "args2 bar string",
768 "-f", "-foo", "foo string"};
769 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args2) / sizeof(char *), args2,
770 StringRef(), &llvm::nulls()));
771 EXPECT_EQ(Bar, "args2 bar string");
772 EXPECT_TRUE(Foo);
773 EXPECT_FALSE(SC1_B);
774 EXPECT_EQ(SC2_Foo, "foo string");
775 for (auto *S : cl::getRegisteredSubcommands()) {
776 if (*S) {
777 EXPECT_EQ("sc2", S->getName());
780 cl::ResetCommandLineParser();
783 TEST(CommandLineTest, ArgumentLimit) {
784 std::string args(32 * 4096, 'a');
785 EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data()));
786 std::string args2(256, 'a');
787 EXPECT_TRUE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args2.data()));
790 TEST(CommandLineTest, ArgumentLimitWindows) {
791 if (!Triple(sys::getProcessTriple()).isOSWindows())
792 GTEST_SKIP();
793 // We use 32000 as a limit for command line length. Program name ('cl'),
794 // separating spaces and termination null character occupy 5 symbols.
795 std::string long_arg(32000 - 5, 'b');
796 EXPECT_TRUE(
797 llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data()));
798 long_arg += 'b';
799 EXPECT_FALSE(
800 llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data()));
803 TEST(CommandLineTest, ResponseFileWindows) {
804 if (!Triple(sys::getProcessTriple()).isOSWindows())
805 GTEST_SKIP();
807 StackOption<std::string, cl::list<std::string>> InputFilenames(
808 cl::Positional, cl::desc("<input files>"));
809 StackOption<bool> TopLevelOpt("top-level", cl::init(false));
811 // Create response file.
812 TempFile ResponseFile("resp-", ".txt",
813 "-top-level\npath\\dir\\file1\npath/dir/file2",
814 /*Unique*/ true);
816 llvm::SmallString<128> RspOpt;
817 RspOpt.append(1, '@');
818 RspOpt.append(ResponseFile.path());
819 const char *args[] = {"prog", RspOpt.c_str()};
820 EXPECT_FALSE(TopLevelOpt);
821 EXPECT_TRUE(
822 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
823 EXPECT_TRUE(TopLevelOpt);
824 EXPECT_EQ(InputFilenames[0], "path\\dir\\file1");
825 EXPECT_EQ(InputFilenames[1], "path/dir/file2");
828 TEST(CommandLineTest, ResponseFiles) {
829 vfs::InMemoryFileSystem FS;
830 #ifdef _WIN32
831 const char *TestRoot = "C:\\";
832 #else
833 const char *TestRoot = "/";
834 #endif
835 FS.setCurrentWorkingDirectory(TestRoot);
837 // Create included response file of first level.
838 llvm::StringRef IncludedFileName = "resp1";
839 FS.addFile(IncludedFileName, 0,
840 llvm::MemoryBuffer::getMemBuffer("-option_1 -option_2\n"
841 "@incdir/resp2\n"
842 "-option_3=abcd\n"
843 "@incdir/resp3\n"
844 "-option_4=efjk\n"));
846 // Directory for included file.
847 llvm::StringRef IncDir = "incdir";
849 // Create included response file of second level.
850 llvm::SmallString<128> IncludedFileName2;
851 llvm::sys::path::append(IncludedFileName2, IncDir, "resp2");
852 FS.addFile(IncludedFileName2, 0,
853 MemoryBuffer::getMemBuffer("-option_21 -option_22\n"
854 "-option_23=abcd\n"));
856 // Create second included response file of second level.
857 llvm::SmallString<128> IncludedFileName3;
858 llvm::sys::path::append(IncludedFileName3, IncDir, "resp3");
859 FS.addFile(IncludedFileName3, 0,
860 MemoryBuffer::getMemBuffer("-option_31 -option_32\n"
861 "-option_33=abcd\n"));
863 // Prepare 'file' with reference to response file.
864 SmallString<128> IncRef;
865 IncRef.append(1, '@');
866 IncRef.append(IncludedFileName);
867 llvm::SmallVector<const char *, 4> Argv = {"test/test", "-flag_1",
868 IncRef.c_str(), "-flag_2"};
870 // Expand response files.
871 llvm::BumpPtrAllocator A;
872 llvm::StringSaver Saver(A);
873 ASSERT_TRUE(llvm::cl::ExpandResponseFiles(
874 Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true, false,
875 /*CurrentDir=*/StringRef(TestRoot), FS));
876 EXPECT_THAT(Argv, testing::Pointwise(
877 StringEquality(),
878 {"test/test", "-flag_1", "-option_1", "-option_2",
879 "-option_21", "-option_22", "-option_23=abcd",
880 "-option_3=abcd", "-option_31", "-option_32",
881 "-option_33=abcd", "-option_4=efjk", "-flag_2"}));
884 TEST(CommandLineTest, RecursiveResponseFiles) {
885 vfs::InMemoryFileSystem FS;
886 #ifdef _WIN32
887 const char *TestRoot = "C:\\";
888 #else
889 const char *TestRoot = "/";
890 #endif
891 FS.setCurrentWorkingDirectory(TestRoot);
893 StringRef SelfFilePath = "self.rsp";
894 std::string SelfFileRef = ("@" + SelfFilePath).str();
896 StringRef NestedFilePath = "nested.rsp";
897 std::string NestedFileRef = ("@" + NestedFilePath).str();
899 StringRef FlagFilePath = "flag.rsp";
900 std::string FlagFileRef = ("@" + FlagFilePath).str();
902 std::string SelfFileContents;
903 raw_string_ostream SelfFile(SelfFileContents);
904 SelfFile << "-option_1\n";
905 SelfFile << FlagFileRef << "\n";
906 SelfFile << NestedFileRef << "\n";
907 SelfFile << SelfFileRef << "\n";
908 FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str()));
910 std::string NestedFileContents;
911 raw_string_ostream NestedFile(NestedFileContents);
912 NestedFile << "-option_2\n";
913 NestedFile << FlagFileRef << "\n";
914 NestedFile << SelfFileRef << "\n";
915 NestedFile << NestedFileRef << "\n";
916 FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str()));
918 std::string FlagFileContents;
919 raw_string_ostream FlagFile(FlagFileContents);
920 FlagFile << "-option_x\n";
921 FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str()));
923 // Ensure:
924 // Recursive expansion terminates
925 // Recursive files never expand
926 // Non-recursive repeats are allowed
927 SmallVector<const char *, 4> Argv = {"test/test", SelfFileRef.c_str(),
928 "-option_3"};
929 BumpPtrAllocator A;
930 StringSaver Saver(A);
931 #ifdef _WIN32
932 cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine;
933 #else
934 cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
935 #endif
936 ASSERT_FALSE(
937 cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false, false,
938 /*CurrentDir=*/llvm::StringRef(TestRoot), FS));
940 EXPECT_THAT(Argv,
941 testing::Pointwise(StringEquality(),
942 {"test/test", "-option_1", "-option_x",
943 "-option_2", "-option_x", SelfFileRef.c_str(),
944 NestedFileRef.c_str(), SelfFileRef.c_str(),
945 "-option_3"}));
948 TEST(CommandLineTest, ResponseFilesAtArguments) {
949 vfs::InMemoryFileSystem FS;
950 #ifdef _WIN32
951 const char *TestRoot = "C:\\";
952 #else
953 const char *TestRoot = "/";
954 #endif
955 FS.setCurrentWorkingDirectory(TestRoot);
957 StringRef ResponseFilePath = "test.rsp";
959 std::string ResponseFileContents;
960 raw_string_ostream ResponseFile(ResponseFileContents);
961 ResponseFile << "-foo" << "\n";
962 ResponseFile << "-bar" << "\n";
963 FS.addFile(ResponseFilePath, 0,
964 MemoryBuffer::getMemBuffer(ResponseFile.str()));
966 // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
967 constexpr size_t NON_RSP_AT_ARGS = 64;
968 SmallVector<const char *, 4> Argv = {"test/test"};
969 Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg");
970 std::string ResponseFileRef = ("@" + ResponseFilePath).str();
971 Argv.push_back(ResponseFileRef.c_str());
973 BumpPtrAllocator A;
974 StringSaver Saver(A);
975 ASSERT_FALSE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
976 false, false, false,
977 /*CurrentDir=*/StringRef(TestRoot), FS));
979 // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
980 ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2);
981 size_t i = 0;
982 EXPECT_STREQ(Argv[i++], "test/test");
983 for (; i < 1 + NON_RSP_AT_ARGS; ++i)
984 EXPECT_STREQ(Argv[i], "@non_rsp_at_arg");
985 EXPECT_STREQ(Argv[i++], "-foo");
986 EXPECT_STREQ(Argv[i++], "-bar");
989 TEST(CommandLineTest, ResponseFileRelativePath) {
990 vfs::InMemoryFileSystem FS;
991 #ifdef _WIN32
992 const char *TestRoot = "C:\\";
993 #else
994 const char *TestRoot = "//net";
995 #endif
996 FS.setCurrentWorkingDirectory(TestRoot);
998 StringRef OuterFile = "dir/outer.rsp";
999 StringRef OuterFileContents = "@inner.rsp";
1000 FS.addFile(OuterFile, 0, MemoryBuffer::getMemBuffer(OuterFileContents));
1002 StringRef InnerFile = "dir/inner.rsp";
1003 StringRef InnerFileContents = "-flag";
1004 FS.addFile(InnerFile, 0, MemoryBuffer::getMemBuffer(InnerFileContents));
1006 SmallVector<const char *, 2> Argv = {"test/test", "@dir/outer.rsp"};
1008 BumpPtrAllocator A;
1009 StringSaver Saver(A);
1010 ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
1011 false, true, false,
1012 /*CurrentDir=*/StringRef(TestRoot), FS));
1013 EXPECT_THAT(Argv,
1014 testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
1017 TEST(CommandLineTest, ResponseFileEOLs) {
1018 vfs::InMemoryFileSystem FS;
1019 #ifdef _WIN32
1020 const char *TestRoot = "C:\\";
1021 #else
1022 const char *TestRoot = "//net";
1023 #endif
1024 FS.setCurrentWorkingDirectory(TestRoot);
1025 FS.addFile("eols.rsp", 0,
1026 MemoryBuffer::getMemBuffer("-Xclang -Wno-whatever\n input.cpp"));
1027 SmallVector<const char *, 2> Argv = {"clang", "@eols.rsp"};
1028 BumpPtrAllocator A;
1029 StringSaver Saver(A);
1030 ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeWindowsCommandLine,
1031 Argv, true, true, false,
1032 /*CurrentDir=*/StringRef(TestRoot), FS));
1033 const char *Expected[] = {"clang", "-Xclang", "-Wno-whatever", nullptr,
1034 "input.cpp"};
1035 ASSERT_EQ(array_lengthof(Expected), Argv.size());
1036 for (size_t I = 0, E = array_lengthof(Expected); I < E; ++I) {
1037 if (Expected[I] == nullptr) {
1038 ASSERT_EQ(Argv[I], nullptr);
1039 } else {
1040 ASSERT_STREQ(Expected[I], Argv[I]);
1045 TEST(CommandLineTest, SetDefautValue) {
1046 cl::ResetCommandLineParser();
1048 StackOption<std::string> Opt1("opt1", cl::init("true"));
1049 StackOption<bool> Opt2("opt2", cl::init(true));
1050 cl::alias Alias("alias", llvm::cl::aliasopt(Opt2));
1051 StackOption<int> Opt3("opt3", cl::init(3));
1053 const char *args[] = {"prog", "-opt1=false", "-opt2", "-opt3"};
1055 EXPECT_TRUE(
1056 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1058 EXPECT_EQ(Opt1, "false");
1059 EXPECT_TRUE(Opt2);
1060 EXPECT_EQ(Opt3, 3);
1062 Opt2 = false;
1063 Opt3 = 1;
1065 cl::ResetAllOptionOccurrences();
1067 for (auto &OM : cl::getRegisteredOptions(cl::SubCommand::getTopLevel())) {
1068 cl::Option *O = OM.second;
1069 if (O->ArgStr == "opt2") {
1070 continue;
1072 O->setDefault();
1075 EXPECT_EQ(Opt1, "true");
1076 EXPECT_TRUE(Opt2);
1077 EXPECT_EQ(Opt3, 3);
1078 Alias.removeArgument();
1081 TEST(CommandLineTest, ReadConfigFile) {
1082 llvm::SmallVector<const char *, 1> Argv;
1084 TempDir TestDir("unittest", /*Unique*/ true);
1085 TempDir TestSubDir(TestDir.path("subdir"), /*Unique*/ false);
1087 llvm::SmallString<128> TestCfg = TestDir.path("foo");
1088 TempFile ConfigFile(TestCfg, "",
1089 "# Comment\n"
1090 "-option_1\n"
1091 "-option_2=<CFGDIR>/dir1\n"
1092 "-option_3=<CFGDIR>\n"
1093 "-option_4 <CFGDIR>\n"
1094 "-option_5=<CFG\\\n"
1095 "DIR>\n"
1096 "-option_6=<CFGDIR>/dir1,<CFGDIR>/dir2\n"
1097 "@subconfig\n"
1098 "-option_11=abcd\n"
1099 "-option_12=\\\n"
1100 "cdef\n");
1102 llvm::SmallString<128> TestCfg2 = TestDir.path("subconfig");
1103 TempFile ConfigFile2(TestCfg2, "",
1104 "-option_7\n"
1105 "-option_8=<CFGDIR>/dir2\n"
1106 "@subdir/subfoo\n"
1107 "\n"
1108 " # comment\n");
1110 llvm::SmallString<128> TestCfg3 = TestSubDir.path("subfoo");
1111 TempFile ConfigFile3(TestCfg3, "",
1112 "-option_9=<CFGDIR>/dir3\n"
1113 "@<CFGDIR>/subfoo2\n");
1115 llvm::SmallString<128> TestCfg4 = TestSubDir.path("subfoo2");
1116 TempFile ConfigFile4(TestCfg4, "", "-option_10\n");
1118 // Make sure the current directory is not the directory where config files
1119 // resides. In this case the code that expands response files will not find
1120 // 'subconfig' unless it resolves nested inclusions relative to the including
1121 // file.
1122 llvm::SmallString<128> CurrDir;
1123 std::error_code EC = llvm::sys::fs::current_path(CurrDir);
1124 EXPECT_TRUE(!EC);
1125 EXPECT_NE(CurrDir.str(), TestDir.path());
1127 llvm::BumpPtrAllocator A;
1128 llvm::StringSaver Saver(A);
1129 bool Result = llvm::cl::readConfigFile(ConfigFile.path(), Saver, Argv);
1131 EXPECT_TRUE(Result);
1132 EXPECT_EQ(Argv.size(), 13U);
1133 EXPECT_STREQ(Argv[0], "-option_1");
1134 EXPECT_STREQ(Argv[1],
1135 ("-option_2=" + TestDir.path() + "/dir1").str().c_str());
1136 EXPECT_STREQ(Argv[2], ("-option_3=" + TestDir.path()).str().c_str());
1137 EXPECT_STREQ(Argv[3], "-option_4");
1138 EXPECT_STREQ(Argv[4], TestDir.path().str().c_str());
1139 EXPECT_STREQ(Argv[5], ("-option_5=" + TestDir.path()).str().c_str());
1140 EXPECT_STREQ(Argv[6], ("-option_6=" + TestDir.path() + "/dir1," +
1141 TestDir.path() + "/dir2")
1142 .str()
1143 .c_str());
1144 EXPECT_STREQ(Argv[7], "-option_7");
1145 EXPECT_STREQ(Argv[8],
1146 ("-option_8=" + TestDir.path() + "/dir2").str().c_str());
1147 EXPECT_STREQ(Argv[9],
1148 ("-option_9=" + TestSubDir.path() + "/dir3").str().c_str());
1149 EXPECT_STREQ(Argv[10], "-option_10");
1150 EXPECT_STREQ(Argv[11], "-option_11=abcd");
1151 EXPECT_STREQ(Argv[12], "-option_12=cdef");
1154 TEST(CommandLineTest, PositionalEatArgsError) {
1155 cl::ResetCommandLineParser();
1157 StackOption<std::string, cl::list<std::string>> PosEatArgs(
1158 "positional-eat-args", cl::Positional, cl::desc("<arguments>..."),
1159 cl::PositionalEatsArgs);
1160 StackOption<std::string, cl::list<std::string>> PosEatArgs2(
1161 "positional-eat-args2", cl::Positional, cl::desc("Some strings"),
1162 cl::PositionalEatsArgs);
1164 const char *args[] = {"prog", "-positional-eat-args=XXXX"};
1165 const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1166 const char *args3[] = {"prog", "-positional-eat-args", "-foo"};
1167 const char *args4[] = {"prog", "-positional-eat-args",
1168 "-foo", "-positional-eat-args2",
1169 "-bar", "foo"};
1171 std::string Errs;
1172 raw_string_ostream OS(Errs);
1173 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush();
1174 EXPECT_FALSE(Errs.empty()); Errs.clear();
1175 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush();
1176 EXPECT_FALSE(Errs.empty()); Errs.clear();
1177 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush();
1178 EXPECT_TRUE(Errs.empty()); Errs.clear();
1180 cl::ResetAllOptionOccurrences();
1181 EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4, StringRef(), &OS)); OS.flush();
1182 EXPECT_EQ(PosEatArgs.size(), 1u);
1183 EXPECT_EQ(PosEatArgs2.size(), 2u);
1184 EXPECT_TRUE(Errs.empty());
1187 #ifdef _WIN32
1188 void checkSeparators(StringRef Path) {
1189 char UndesiredSeparator = sys::path::get_separator()[0] == '/' ? '\\' : '/';
1190 ASSERT_EQ(Path.find(UndesiredSeparator), StringRef::npos);
1193 TEST(CommandLineTest, GetCommandLineArguments) {
1194 int argc = __argc;
1195 char **argv = __argv;
1197 // GetCommandLineArguments is called in InitLLVM.
1198 llvm::InitLLVM X(argc, argv);
1200 EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]),
1201 llvm::sys::path::is_absolute(__argv[0]));
1202 checkSeparators(argv[0]);
1204 EXPECT_TRUE(
1205 llvm::sys::path::filename(argv[0]).equals_insensitive("supporttests.exe"))
1206 << "Filename of test executable is "
1207 << llvm::sys::path::filename(argv[0]);
1209 #endif
1211 class OutputRedirector {
1212 public:
1213 OutputRedirector(int RedirectFD)
1214 : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) {
1215 if (OldFD == -1 ||
1216 sys::fs::createTemporaryFile("unittest-redirect", "", NewFD,
1217 FilePath) ||
1218 dup2(NewFD, RedirectFD) == -1)
1219 Valid = false;
1222 ~OutputRedirector() {
1223 dup2(OldFD, RedirectFD);
1224 close(OldFD);
1225 close(NewFD);
1228 SmallVector<char, 128> FilePath;
1229 bool Valid = true;
1231 private:
1232 int RedirectFD;
1233 int OldFD;
1234 int NewFD;
1237 struct AutoDeleteFile {
1238 SmallVector<char, 128> FilePath;
1239 ~AutoDeleteFile() {
1240 if (!FilePath.empty())
1241 sys::fs::remove(std::string(FilePath.data(), FilePath.size()));
1245 class PrintOptionInfoTest : public ::testing::Test {
1246 public:
1247 // Return std::string because the output of a failing EXPECT check is
1248 // unreadable for StringRef. It also avoids any lifetime issues.
1249 template <typename... Ts> std::string runTest(Ts... OptionAttributes) {
1250 outs().flush(); // flush any output from previous tests
1251 AutoDeleteFile File;
1253 OutputRedirector Stdout(fileno(stdout));
1254 if (!Stdout.Valid)
1255 return "";
1256 File.FilePath = Stdout.FilePath;
1258 StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText),
1259 OptionAttributes...);
1260 printOptionInfo(TestOption, 26);
1261 outs().flush();
1263 auto Buffer = MemoryBuffer::getFile(File.FilePath);
1264 if (!Buffer)
1265 return "";
1266 return Buffer->get()->getBuffer().str();
1269 enum class OptionValue { Val };
1270 const StringRef Opt = "some-option";
1271 const StringRef HelpText = "some help";
1273 private:
1274 // This is a workaround for cl::Option sub-classes having their
1275 // printOptionInfo functions private.
1276 void printOptionInfo(const cl::Option &O, size_t Width) {
1277 O.printOptionInfo(Width);
1281 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) {
1282 std::string Output =
1283 runTest(cl::ValueOptional,
1284 cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
1286 // clang-format off
1287 EXPECT_EQ(Output, (" --" + Opt + "=<value> - " + HelpText + "\n"
1288 " =v1 - desc1\n")
1289 .str());
1290 // clang-format on
1293 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) {
1294 std::string Output = runTest(
1295 cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1296 clEnumValN(OptionValue::Val, "", "")));
1298 // clang-format off
1299 EXPECT_EQ(Output,
1300 (" --" + Opt + " - " + HelpText + "\n"
1301 " --" + Opt + "=<value> - " + HelpText + "\n"
1302 " =v1 - desc1\n")
1303 .str());
1304 // clang-format on
1307 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) {
1308 std::string Output = runTest(
1309 cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1310 clEnumValN(OptionValue::Val, "", "desc2")));
1312 // clang-format off
1313 EXPECT_EQ(Output, (" --" + Opt + " - " + HelpText + "\n"
1314 " --" + Opt + "=<value> - " + HelpText + "\n"
1315 " =v1 - desc1\n"
1316 " =<empty> - desc2\n")
1317 .str());
1318 // clang-format on
1321 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) {
1322 std::string Output = runTest(
1323 cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1324 clEnumValN(OptionValue::Val, "", "")));
1326 // clang-format off
1327 EXPECT_EQ(Output, (" --" + Opt + "=<value> - " + HelpText + "\n"
1328 " =v1 - desc1\n"
1329 " =<empty>\n")
1330 .str());
1331 // clang-format on
1334 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) {
1335 std::string Output = runTest(
1336 cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "")));
1338 // clang-format off
1339 EXPECT_EQ(Output,
1340 (" --" + Opt + "=<value> - " + HelpText + "\n"
1341 " =v1\n").str());
1342 // clang-format on
1345 TEST_F(PrintOptionInfoTest, PrintOptionInfoMultilineValueDescription) {
1346 std::string Output =
1347 runTest(cl::ValueRequired,
1348 cl::values(clEnumValN(OptionValue::Val, "v1",
1349 "This is the first enum value\n"
1350 "which has a really long description\n"
1351 "thus it is multi-line."),
1352 clEnumValN(OptionValue::Val, "",
1353 "This is an unnamed enum value option\n"
1354 "Should be indented as well")));
1356 // clang-format off
1357 EXPECT_EQ(Output,
1358 (" --" + Opt + "=<value> - " + HelpText + "\n"
1359 " =v1 - This is the first enum value\n"
1360 " which has a really long description\n"
1361 " thus it is multi-line.\n"
1362 " =<empty> - This is an unnamed enum value option\n"
1363 " Should be indented as well\n").str());
1364 // clang-format on
1367 class GetOptionWidthTest : public ::testing::Test {
1368 public:
1369 enum class OptionValue { Val };
1371 template <typename... Ts>
1372 size_t runTest(StringRef ArgName, Ts... OptionAttributes) {
1373 StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"),
1374 OptionAttributes...);
1375 return getOptionWidth(TestOption);
1378 private:
1379 // This is a workaround for cl::Option sub-classes having their
1380 // printOptionInfo
1381 // functions private.
1382 size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); }
1385 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) {
1386 StringRef ArgName("a-long-argument-name");
1387 size_t ExpectedStrSize = (" --" + ArgName + "=<value> - ").str().size();
1388 EXPECT_EQ(
1389 runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))),
1390 ExpectedStrSize);
1393 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) {
1394 StringRef OptName("a-long-option-name");
1395 size_t ExpectedStrSize = (" =" + OptName + " - ").str().size();
1396 EXPECT_EQ(
1397 runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"),
1398 clEnumValN(OptionValue::Val, "b", "help"))),
1399 ExpectedStrSize);
1402 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) {
1403 StringRef OptName("a-long-option-name");
1404 size_t ExpectedStrSize = (" =" + OptName + " - ").str().size();
1405 EXPECT_EQ(
1406 runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1407 clEnumValN(OptionValue::Val, OptName, "help"))),
1408 ExpectedStrSize);
1411 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) {
1412 size_t ExpectedStrSize = StringRef(" =<empty> - ").size();
1413 // The length of a=<value> (including indentation) is actually the same as the
1414 // =<empty> string, so it is impossible to distinguish via testing the case
1415 // where the empty string is picked from where the option name is picked.
1416 EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1417 clEnumValN(OptionValue::Val, "", "help"))),
1418 ExpectedStrSize);
1421 TEST_F(GetOptionWidthTest,
1422 GetOptionWidthValueOptionalEmptyOptionWithNoDescription) {
1423 StringRef ArgName("a");
1424 // The length of a=<value> (including indentation) is actually the same as the
1425 // =<empty> string, so it is impossible to distinguish via testing the case
1426 // where the empty string is ignored from where it is not ignored.
1427 // The dash will not actually be printed, but the space it would take up is
1428 // included to ensure a consistent column width.
1429 size_t ExpectedStrSize = (" -" + ArgName + "=<value> - ").str().size();
1430 EXPECT_EQ(runTest(ArgName, cl::ValueOptional,
1431 cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1432 clEnumValN(OptionValue::Val, "", ""))),
1433 ExpectedStrSize);
1436 TEST_F(GetOptionWidthTest,
1437 GetOptionWidthValueRequiredEmptyOptionWithNoDescription) {
1438 // The length of a=<value> (including indentation) is actually the same as the
1439 // =<empty> string, so it is impossible to distinguish via testing the case
1440 // where the empty string is picked from where the option name is picked
1441 size_t ExpectedStrSize = StringRef(" =<empty> - ").size();
1442 EXPECT_EQ(runTest("a", cl::ValueRequired,
1443 cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1444 clEnumValN(OptionValue::Val, "", ""))),
1445 ExpectedStrSize);
1448 TEST(CommandLineTest, PrefixOptions) {
1449 cl::ResetCommandLineParser();
1451 StackOption<std::string, cl::list<std::string>> IncludeDirs(
1452 "I", cl::Prefix, cl::desc("Declare an include directory"));
1454 // Test non-prefixed variant works with cl::Prefix options.
1455 EXPECT_TRUE(IncludeDirs.empty());
1456 const char *args[] = {"prog", "-I=/usr/include"};
1457 EXPECT_TRUE(
1458 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1459 EXPECT_EQ(IncludeDirs.size(), 1u);
1460 EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0);
1462 IncludeDirs.erase(IncludeDirs.begin());
1463 cl::ResetAllOptionOccurrences();
1465 // Test non-prefixed variant works with cl::Prefix options when value is
1466 // passed in following argument.
1467 EXPECT_TRUE(IncludeDirs.empty());
1468 const char *args2[] = {"prog", "-I", "/usr/include"};
1469 EXPECT_TRUE(
1470 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1471 EXPECT_EQ(IncludeDirs.size(), 1u);
1472 EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0);
1474 IncludeDirs.erase(IncludeDirs.begin());
1475 cl::ResetAllOptionOccurrences();
1477 // Test prefixed variant works with cl::Prefix options.
1478 EXPECT_TRUE(IncludeDirs.empty());
1479 const char *args3[] = {"prog", "-I/usr/include"};
1480 EXPECT_TRUE(
1481 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1482 EXPECT_EQ(IncludeDirs.size(), 1u);
1483 EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0);
1485 StackOption<std::string, cl::list<std::string>> MacroDefs(
1486 "D", cl::AlwaysPrefix, cl::desc("Define a macro"),
1487 cl::value_desc("MACRO[=VALUE]"));
1489 cl::ResetAllOptionOccurrences();
1491 // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1492 // equal sign is part of the value.
1493 EXPECT_TRUE(MacroDefs.empty());
1494 const char *args4[] = {"prog", "-D=HAVE_FOO"};
1495 EXPECT_TRUE(
1496 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1497 EXPECT_EQ(MacroDefs.size(), 1u);
1498 EXPECT_EQ(MacroDefs.front().compare("=HAVE_FOO"), 0);
1500 MacroDefs.erase(MacroDefs.begin());
1501 cl::ResetAllOptionOccurrences();
1503 // Test non-prefixed variant does not allow value to be passed in following
1504 // argument with cl::AlwaysPrefix options.
1505 EXPECT_TRUE(MacroDefs.empty());
1506 const char *args5[] = {"prog", "-D", "HAVE_FOO"};
1507 EXPECT_FALSE(
1508 cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1509 EXPECT_TRUE(MacroDefs.empty());
1511 cl::ResetAllOptionOccurrences();
1513 // Test prefixed variant works with cl::AlwaysPrefix options.
1514 EXPECT_TRUE(MacroDefs.empty());
1515 const char *args6[] = {"prog", "-DHAVE_FOO"};
1516 EXPECT_TRUE(
1517 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1518 EXPECT_EQ(MacroDefs.size(), 1u);
1519 EXPECT_EQ(MacroDefs.front().compare("HAVE_FOO"), 0);
1522 TEST(CommandLineTest, GroupingWithValue) {
1523 cl::ResetCommandLineParser();
1525 StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1526 StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1527 StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed,
1528 cl::desc("ValueDisallowed option"));
1529 StackOption<std::string> OptV("v", cl::Grouping,
1530 cl::desc("ValueRequired option"));
1531 StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional,
1532 cl::desc("ValueOptional option"));
1534 // Should be possible to use an option which requires a value
1535 // at the end of a group.
1536 const char *args1[] = {"prog", "-fv", "val1"};
1537 EXPECT_TRUE(
1538 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
1539 EXPECT_TRUE(OptF);
1540 EXPECT_STREQ("val1", OptV.c_str());
1541 OptV.clear();
1542 cl::ResetAllOptionOccurrences();
1544 // Should not crash if it is accidentally used elsewhere in the group.
1545 const char *args2[] = {"prog", "-vf", "val2"};
1546 EXPECT_FALSE(
1547 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1548 OptV.clear();
1549 cl::ResetAllOptionOccurrences();
1551 // Should allow the "opt=value" form at the end of the group
1552 const char *args3[] = {"prog", "-fv=val3"};
1553 EXPECT_TRUE(
1554 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1555 EXPECT_TRUE(OptF);
1556 EXPECT_STREQ("val3", OptV.c_str());
1557 OptV.clear();
1558 cl::ResetAllOptionOccurrences();
1560 // Should allow assigning a value for a ValueOptional option
1561 // at the end of the group
1562 const char *args4[] = {"prog", "-fo=val4"};
1563 EXPECT_TRUE(
1564 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1565 EXPECT_TRUE(OptF);
1566 EXPECT_STREQ("val4", OptO.c_str());
1567 OptO.clear();
1568 cl::ResetAllOptionOccurrences();
1570 // Should assign an empty value if a ValueOptional option is used elsewhere
1571 // in the group.
1572 const char *args5[] = {"prog", "-fob"};
1573 EXPECT_TRUE(
1574 cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls()));
1575 EXPECT_TRUE(OptF);
1576 EXPECT_EQ(1, OptO.getNumOccurrences());
1577 EXPECT_EQ(1, OptB.getNumOccurrences());
1578 EXPECT_TRUE(OptO.empty());
1579 cl::ResetAllOptionOccurrences();
1581 // Should not allow an assignment for a ValueDisallowed option.
1582 const char *args6[] = {"prog", "-fd=false"};
1583 EXPECT_FALSE(
1584 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1587 TEST(CommandLineTest, GroupingAndPrefix) {
1588 cl::ResetCommandLineParser();
1590 StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1591 StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1592 StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping,
1593 cl::desc("Prefix and Grouping"));
1594 StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping,
1595 cl::desc("AlwaysPrefix and Grouping"));
1597 // Should be possible to use a cl::Prefix option without grouping.
1598 const char *args1[] = {"prog", "-pval1"};
1599 EXPECT_TRUE(
1600 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
1601 EXPECT_STREQ("val1", OptP.c_str());
1602 OptP.clear();
1603 cl::ResetAllOptionOccurrences();
1605 // Should be possible to pass a value in a separate argument.
1606 const char *args2[] = {"prog", "-p", "val2"};
1607 EXPECT_TRUE(
1608 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1609 EXPECT_STREQ("val2", OptP.c_str());
1610 OptP.clear();
1611 cl::ResetAllOptionOccurrences();
1613 // The "-opt=value" form should work, too.
1614 const char *args3[] = {"prog", "-p=val3"};
1615 EXPECT_TRUE(
1616 cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1617 EXPECT_STREQ("val3", OptP.c_str());
1618 OptP.clear();
1619 cl::ResetAllOptionOccurrences();
1621 // All three previous cases should work the same way if an option with both
1622 // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1623 const char *args4[] = {"prog", "-fpval4"};
1624 EXPECT_TRUE(
1625 cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1626 EXPECT_TRUE(OptF);
1627 EXPECT_STREQ("val4", OptP.c_str());
1628 OptP.clear();
1629 cl::ResetAllOptionOccurrences();
1631 const char *args5[] = {"prog", "-fp", "val5"};
1632 EXPECT_TRUE(
1633 cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1634 EXPECT_TRUE(OptF);
1635 EXPECT_STREQ("val5", OptP.c_str());
1636 OptP.clear();
1637 cl::ResetAllOptionOccurrences();
1639 const char *args6[] = {"prog", "-fp=val6"};
1640 EXPECT_TRUE(
1641 cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1642 EXPECT_TRUE(OptF);
1643 EXPECT_STREQ("val6", OptP.c_str());
1644 OptP.clear();
1645 cl::ResetAllOptionOccurrences();
1647 // Should assign a value even if the part after a cl::Prefix option is equal
1648 // to the name of another option.
1649 const char *args7[] = {"prog", "-fpb"};
1650 EXPECT_TRUE(
1651 cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls()));
1652 EXPECT_TRUE(OptF);
1653 EXPECT_STREQ("b", OptP.c_str());
1654 EXPECT_FALSE(OptB);
1655 OptP.clear();
1656 cl::ResetAllOptionOccurrences();
1658 // Should be possible to use a cl::AlwaysPrefix option without grouping.
1659 const char *args8[] = {"prog", "-aval8"};
1660 EXPECT_TRUE(
1661 cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls()));
1662 EXPECT_STREQ("val8", OptA.c_str());
1663 OptA.clear();
1664 cl::ResetAllOptionOccurrences();
1666 // Should not be possible to pass a value in a separate argument.
1667 const char *args9[] = {"prog", "-a", "val9"};
1668 EXPECT_FALSE(
1669 cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls()));
1670 cl::ResetAllOptionOccurrences();
1672 // With the "-opt=value" form, the "=" symbol should be preserved.
1673 const char *args10[] = {"prog", "-a=val10"};
1674 EXPECT_TRUE(
1675 cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls()));
1676 EXPECT_STREQ("=val10", OptA.c_str());
1677 OptA.clear();
1678 cl::ResetAllOptionOccurrences();
1680 // All three previous cases should work the same way if an option with both
1681 // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1682 const char *args11[] = {"prog", "-faval11"};
1683 EXPECT_TRUE(
1684 cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls()));
1685 EXPECT_TRUE(OptF);
1686 EXPECT_STREQ("val11", OptA.c_str());
1687 OptA.clear();
1688 cl::ResetAllOptionOccurrences();
1690 const char *args12[] = {"prog", "-fa", "val12"};
1691 EXPECT_FALSE(
1692 cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls()));
1693 cl::ResetAllOptionOccurrences();
1695 const char *args13[] = {"prog", "-fa=val13"};
1696 EXPECT_TRUE(
1697 cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls()));
1698 EXPECT_TRUE(OptF);
1699 EXPECT_STREQ("=val13", OptA.c_str());
1700 OptA.clear();
1701 cl::ResetAllOptionOccurrences();
1703 // Should assign a value even if the part after a cl::AlwaysPrefix option
1704 // is equal to the name of another option.
1705 const char *args14[] = {"prog", "-fab"};
1706 EXPECT_TRUE(
1707 cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls()));
1708 EXPECT_TRUE(OptF);
1709 EXPECT_STREQ("b", OptA.c_str());
1710 EXPECT_FALSE(OptB);
1711 OptA.clear();
1712 cl::ResetAllOptionOccurrences();
1715 TEST(CommandLineTest, LongOptions) {
1716 cl::ResetCommandLineParser();
1718 StackOption<bool> OptA("a", cl::desc("Some flag"));
1719 StackOption<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1720 StackOption<bool, cl::alias> OptB("b", cl::desc("Alias to --long-flag"),
1721 cl::aliasopt(OptBLong));
1722 StackOption<std::string> OptAB("ab", cl::desc("Another long option"));
1724 std::string Errs;
1725 raw_string_ostream OS(Errs);
1727 const char *args1[] = {"prog", "-a", "-ab", "val1"};
1728 const char *args2[] = {"prog", "-a", "--ab", "val1"};
1729 const char *args3[] = {"prog", "-ab", "--ab", "val1"};
1732 // The following tests treat `-` and `--` the same, and always match the
1733 // longest string.
1736 EXPECT_TRUE(
1737 cl::ParseCommandLineOptions(4, args1, StringRef(), &OS)); OS.flush();
1738 EXPECT_TRUE(OptA);
1739 EXPECT_FALSE(OptBLong);
1740 EXPECT_STREQ("val1", OptAB.c_str());
1741 EXPECT_TRUE(Errs.empty()); Errs.clear();
1742 cl::ResetAllOptionOccurrences();
1744 EXPECT_TRUE(
1745 cl::ParseCommandLineOptions(4, args2, StringRef(), &OS)); OS.flush();
1746 EXPECT_TRUE(OptA);
1747 EXPECT_FALSE(OptBLong);
1748 EXPECT_STREQ("val1", OptAB.c_str());
1749 EXPECT_TRUE(Errs.empty()); Errs.clear();
1750 cl::ResetAllOptionOccurrences();
1752 // Fails because `-ab` and `--ab` are treated the same and appear more than
1753 // once. Also, `val1` is unexpected.
1754 EXPECT_FALSE(
1755 cl::ParseCommandLineOptions(4, args3, StringRef(), &OS)); OS.flush();
1756 outs()<< Errs << "\n";
1757 EXPECT_FALSE(Errs.empty()); Errs.clear();
1758 cl::ResetAllOptionOccurrences();
1761 // The following tests treat `-` and `--` differently, with `-` for short, and
1762 // `--` for long options.
1765 // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1766 // `val1` is unexpected.
1767 EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(),
1768 &OS, nullptr, true)); OS.flush();
1769 EXPECT_FALSE(Errs.empty()); Errs.clear();
1770 cl::ResetAllOptionOccurrences();
1772 // Works because `-a` is treated differently than `--ab`.
1773 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(),
1774 &OS, nullptr, true)); OS.flush();
1775 EXPECT_TRUE(Errs.empty()); Errs.clear();
1776 cl::ResetAllOptionOccurrences();
1778 // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1779 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(),
1780 &OS, nullptr, true));
1781 EXPECT_TRUE(OptA);
1782 EXPECT_TRUE(OptBLong);
1783 EXPECT_STREQ("val1", OptAB.c_str());
1784 OS.flush();
1785 EXPECT_TRUE(Errs.empty()); Errs.clear();
1786 cl::ResetAllOptionOccurrences();
1789 TEST(CommandLineTest, OptionErrorMessage) {
1790 // When there is an error, we expect some error message like:
1791 // prog: for the -a option: [...]
1793 // Test whether the "for the -a option"-part is correctly formatted.
1794 cl::ResetCommandLineParser();
1796 StackOption<bool> OptA("a", cl::desc("Some option"));
1797 StackOption<bool> OptLong("long", cl::desc("Some long option"));
1799 std::string Errs;
1800 raw_string_ostream OS(Errs);
1802 OptA.error("custom error", OS);
1803 OS.flush();
1804 EXPECT_NE(Errs.find("for the -a option:"), std::string::npos);
1805 Errs.clear();
1807 OptLong.error("custom error", OS);
1808 OS.flush();
1809 EXPECT_NE(Errs.find("for the --long option:"), std::string::npos);
1810 Errs.clear();
1812 cl::ResetAllOptionOccurrences();
1815 TEST(CommandLineTest, OptionErrorMessageSuggest) {
1816 // When there is an error, and the edit-distance is not very large,
1817 // we expect some error message like:
1818 // prog: did you mean '--option'?
1820 // Test whether this message is well-formatted.
1821 cl::ResetCommandLineParser();
1823 StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1825 const char *args[] = {"prog", "--aluminum"};
1827 std::string Errs;
1828 raw_string_ostream OS(Errs);
1830 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1831 OS.flush();
1832 EXPECT_NE(Errs.find("prog: Did you mean '--aluminium'?\n"),
1833 std::string::npos);
1834 Errs.clear();
1836 cl::ResetAllOptionOccurrences();
1839 TEST(CommandLineTest, OptionErrorMessageSuggestNoHidden) {
1840 // We expect that 'really hidden' option do not show up in option
1841 // suggestions.
1842 cl::ResetCommandLineParser();
1844 StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1845 StackOption<bool> OptLong2("aluminum", cl::desc("Bad option"),
1846 cl::ReallyHidden);
1848 const char *args[] = {"prog", "--alumnum"};
1850 std::string Errs;
1851 raw_string_ostream OS(Errs);
1853 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1854 OS.flush();
1855 EXPECT_NE(Errs.find("prog: Did you mean '--aluminium'?\n"),
1856 std::string::npos);
1857 Errs.clear();
1859 cl::ResetAllOptionOccurrences();
1862 TEST(CommandLineTest, Callback) {
1863 cl::ResetCommandLineParser();
1865 StackOption<bool> OptA("a", cl::desc("option a"));
1866 StackOption<bool> OptB(
1867 "b", cl::desc("option b -- This option turns on option a"),
1868 cl::callback([&](const bool &) { OptA = true; }));
1869 StackOption<bool> OptC(
1870 "c", cl::desc("option c -- This option turns on options a and b"),
1871 cl::callback([&](const bool &) { OptB = true; }));
1872 StackOption<std::string, cl::list<std::string>> List(
1873 "list",
1874 cl::desc("option list -- This option turns on options a, b, and c when "
1875 "'foo' is included in list"),
1876 cl::CommaSeparated,
1877 cl::callback([&](const std::string &Str) {
1878 if (Str == "foo")
1879 OptC = true;
1880 }));
1882 const char *args1[] = {"prog", "-a"};
1883 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args1));
1884 EXPECT_TRUE(OptA);
1885 EXPECT_FALSE(OptB);
1886 EXPECT_FALSE(OptC);
1887 EXPECT_EQ(List.size(), 0u);
1888 cl::ResetAllOptionOccurrences();
1890 const char *args2[] = {"prog", "-b"};
1891 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args2));
1892 EXPECT_TRUE(OptA);
1893 EXPECT_TRUE(OptB);
1894 EXPECT_FALSE(OptC);
1895 EXPECT_EQ(List.size(), 0u);
1896 cl::ResetAllOptionOccurrences();
1898 const char *args3[] = {"prog", "-c"};
1899 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args3));
1900 EXPECT_TRUE(OptA);
1901 EXPECT_TRUE(OptB);
1902 EXPECT_TRUE(OptC);
1903 EXPECT_EQ(List.size(), 0u);
1904 cl::ResetAllOptionOccurrences();
1906 const char *args4[] = {"prog", "--list=foo,bar"};
1907 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args4));
1908 EXPECT_TRUE(OptA);
1909 EXPECT_TRUE(OptB);
1910 EXPECT_TRUE(OptC);
1911 EXPECT_EQ(List.size(), 2u);
1912 cl::ResetAllOptionOccurrences();
1914 const char *args5[] = {"prog", "--list=bar"};
1915 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args5));
1916 EXPECT_FALSE(OptA);
1917 EXPECT_FALSE(OptB);
1918 EXPECT_FALSE(OptC);
1919 EXPECT_EQ(List.size(), 1u);
1921 cl::ResetAllOptionOccurrences();
1924 enum Enum { Val1, Val2 };
1925 static cl::bits<Enum> ExampleBits(
1926 cl::desc("An example cl::bits to ensure it compiles"),
1927 cl::values(
1928 clEnumValN(Val1, "bits-val1", "The Val1 value"),
1929 clEnumValN(Val1, "bits-val2", "The Val2 value")));
1931 TEST(CommandLineTest, ConsumeAfterOnePositional) {
1932 cl::ResetCommandLineParser();
1934 // input [args]
1935 StackOption<std::string, cl::opt<std::string>> Input(cl::Positional,
1936 cl::Required);
1937 StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
1939 const char *Args[] = {"prog", "input", "arg1", "arg2"};
1941 std::string Errs;
1942 raw_string_ostream OS(Errs);
1943 EXPECT_TRUE(cl::ParseCommandLineOptions(4, Args, StringRef(), &OS));
1944 OS.flush();
1945 EXPECT_EQ("input", Input);
1946 EXPECT_EQ(ExtraArgs.size(), 2u);
1947 EXPECT_EQ(ExtraArgs[0], "arg1");
1948 EXPECT_EQ(ExtraArgs[1], "arg2");
1949 EXPECT_TRUE(Errs.empty());
1952 TEST(CommandLineTest, ConsumeAfterTwoPositionals) {
1953 cl::ResetCommandLineParser();
1955 // input1 input2 [args]
1956 StackOption<std::string, cl::opt<std::string>> Input1(cl::Positional,
1957 cl::Required);
1958 StackOption<std::string, cl::opt<std::string>> Input2(cl::Positional,
1959 cl::Required);
1960 StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
1962 const char *Args[] = {"prog", "input1", "input2", "arg1", "arg2"};
1964 std::string Errs;
1965 raw_string_ostream OS(Errs);
1966 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args, StringRef(), &OS));
1967 OS.flush();
1968 EXPECT_EQ("input1", Input1);
1969 EXPECT_EQ("input2", Input2);
1970 EXPECT_EQ(ExtraArgs.size(), 2u);
1971 EXPECT_EQ(ExtraArgs[0], "arg1");
1972 EXPECT_EQ(ExtraArgs[1], "arg2");
1973 EXPECT_TRUE(Errs.empty());
1976 TEST(CommandLineTest, ResetAllOptionOccurrences) {
1977 cl::ResetCommandLineParser();
1979 // -option -str -enableA -enableC [sink] input [args]
1980 StackOption<bool> Option("option");
1981 StackOption<std::string> Str("str");
1982 enum Vals { ValA, ValB, ValC };
1983 StackOption<Vals, cl::bits<Vals>> Bits(
1984 cl::values(clEnumValN(ValA, "enableA", "Enable A"),
1985 clEnumValN(ValB, "enableB", "Enable B"),
1986 clEnumValN(ValC, "enableC", "Enable C")));
1987 StackOption<std::string, cl::list<std::string>> Sink(cl::Sink);
1988 StackOption<std::string> Input(cl::Positional);
1989 StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
1991 const char *Args[] = {"prog", "-option", "-str=STR", "-enableA",
1992 "-enableC", "-unknown", "input", "-arg"};
1994 std::string Errs;
1995 raw_string_ostream OS(Errs);
1996 EXPECT_TRUE(cl::ParseCommandLineOptions(8, Args, StringRef(), &OS));
1997 EXPECT_TRUE(OS.str().empty());
1999 EXPECT_TRUE(Option);
2000 EXPECT_EQ("STR", Str);
2001 EXPECT_EQ((1u << ValA) | (1u << ValC), Bits.getBits());
2002 EXPECT_EQ(1u, Sink.size());
2003 EXPECT_EQ("-unknown", Sink[0]);
2004 EXPECT_EQ("input", Input);
2005 EXPECT_EQ(1u, ExtraArgs.size());
2006 EXPECT_EQ("-arg", ExtraArgs[0]);
2008 cl::ResetAllOptionOccurrences();
2009 EXPECT_FALSE(Option);
2010 EXPECT_EQ("", Str);
2011 EXPECT_EQ(0u, Bits.getBits());
2012 EXPECT_EQ(0u, Sink.size());
2013 EXPECT_EQ(0, Input.getNumOccurrences());
2014 EXPECT_EQ(0u, ExtraArgs.size());
2017 TEST(CommandLineTest, DefaultValue) {
2018 cl::ResetCommandLineParser();
2020 StackOption<bool> BoolOption("bool-option");
2021 StackOption<std::string> StrOption("str-option");
2022 StackOption<bool> BoolInitOption("bool-init-option", cl::init(true));
2023 StackOption<std::string> StrInitOption("str-init-option",
2024 cl::init("str-default-value"));
2026 const char *Args[] = {"prog"}; // no options
2028 std::string Errs;
2029 raw_string_ostream OS(Errs);
2030 EXPECT_TRUE(cl::ParseCommandLineOptions(1, Args, StringRef(), &OS));
2031 EXPECT_TRUE(OS.str().empty());
2033 EXPECT_TRUE(!BoolOption);
2034 EXPECT_FALSE(BoolOption.Default.hasValue());
2035 EXPECT_EQ(0, BoolOption.getNumOccurrences());
2037 EXPECT_EQ("", StrOption);
2038 EXPECT_FALSE(StrOption.Default.hasValue());
2039 EXPECT_EQ(0, StrOption.getNumOccurrences());
2041 EXPECT_TRUE(BoolInitOption);
2042 EXPECT_TRUE(BoolInitOption.Default.hasValue());
2043 EXPECT_EQ(0, BoolInitOption.getNumOccurrences());
2045 EXPECT_EQ("str-default-value", StrInitOption);
2046 EXPECT_TRUE(StrInitOption.Default.hasValue());
2047 EXPECT_EQ(0, StrInitOption.getNumOccurrences());
2049 const char *Args2[] = {"prog", "-bool-option", "-str-option=str-value",
2050 "-bool-init-option=0",
2051 "-str-init-option=str-init-value"};
2053 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args2, StringRef(), &OS));
2054 EXPECT_TRUE(OS.str().empty());
2056 EXPECT_TRUE(BoolOption);
2057 EXPECT_FALSE(BoolOption.Default.hasValue());
2058 EXPECT_EQ(1, BoolOption.getNumOccurrences());
2060 EXPECT_EQ("str-value", StrOption);
2061 EXPECT_FALSE(StrOption.Default.hasValue());
2062 EXPECT_EQ(1, StrOption.getNumOccurrences());
2064 EXPECT_FALSE(BoolInitOption);
2065 EXPECT_TRUE(BoolInitOption.Default.hasValue());
2066 EXPECT_EQ(1, BoolInitOption.getNumOccurrences());
2068 EXPECT_EQ("str-init-value", StrInitOption);
2069 EXPECT_TRUE(StrInitOption.Default.hasValue());
2070 EXPECT_EQ(1, StrInitOption.getNumOccurrences());
2073 } // anonymous namespace