1 //===- llvm/unittest/Support/CommandLineTest.cpp - CommandLine tests ------===//
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
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/Config/config.h"
14 #include "llvm/Support/Allocator.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/InitLLVM.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/Program.h"
20 #include "llvm/Support/StringSaver.h"
21 #include "llvm/Support/VirtualFileSystem.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/TargetParser/Host.h"
24 #include "llvm/TargetParser/Triple.h"
25 #include "llvm/Testing/Support/SupportHelpers.h"
26 #include "gmock/gmock.h"
27 #include "gtest/gtest.h"
33 using llvm::unittest::TempDir
;
34 using llvm::unittest::TempFile
;
38 MATCHER(StringEquality
, "Checks if two char* are equal as strings") {
39 return std::string(std::get
<0>(arg
)) == std::string(std::get
<1>(arg
));
44 TempEnvVar(const char *name
, const char *value
)
46 const char *old_value
= getenv(name
);
47 EXPECT_EQ(nullptr, old_value
) << old_value
;
49 setenv(name
, value
, true);
55 // Assume setenv and unsetenv come together.
58 (void)name
; // Suppress -Wunused-private-field.
63 const char *const name
;
66 template <typename T
, typename Base
= cl::opt
<T
>>
67 class StackOption
: public Base
{
69 template <class... Ts
>
70 explicit StackOption(Ts
&&... Ms
) : Base(std::forward
<Ts
>(Ms
)...) {}
72 ~StackOption() override
{ this->removeArgument(); }
74 template <class DT
> StackOption
<T
> &operator=(const DT
&V
) {
80 class StackSubCommand
: public cl::SubCommand
{
82 StackSubCommand(StringRef Name
,
83 StringRef Description
= StringRef())
84 : SubCommand(Name
, Description
) {}
86 StackSubCommand() : SubCommand() {}
88 ~StackSubCommand() { unregisterSubCommand(); }
92 cl::OptionCategory
TestCategory("Test Options", "Description");
93 TEST(CommandLineTest
, ModifyExisitingOption
) {
94 StackOption
<int> TestOption("test-option", cl::desc("old description"));
96 static const char Description
[] = "New description";
97 static const char ArgString
[] = "new-test-option";
98 static const char ValueString
[] = "Integer";
100 StringMap
<cl::Option
*> &Map
=
101 cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
103 ASSERT_EQ(Map
.count("test-option"), 1u) << "Could not find option in map.";
105 cl::Option
*Retrieved
= Map
["test-option"];
106 ASSERT_EQ(&TestOption
, Retrieved
) << "Retrieved wrong option.";
108 ASSERT_NE(Retrieved
->Categories
.end(),
109 find_if(Retrieved
->Categories
,
110 [&](const llvm::cl::OptionCategory
*Cat
) {
111 return Cat
== &cl::getGeneralCategory();
113 << "Incorrect default option category.";
115 Retrieved
->addCategory(TestCategory
);
116 ASSERT_NE(Retrieved
->Categories
.end(),
117 find_if(Retrieved
->Categories
,
118 [&](const llvm::cl::OptionCategory
*Cat
) {
119 return Cat
== &TestCategory
;
121 << "Failed to modify option's option category.";
123 Retrieved
->setDescription(Description
);
124 ASSERT_STREQ(Retrieved
->HelpStr
.data(), Description
)
125 << "Changing option description failed.";
127 Retrieved
->setArgStr(ArgString
);
128 ASSERT_STREQ(ArgString
, Retrieved
->ArgStr
.data())
129 << "Failed to modify option's Argument string.";
131 Retrieved
->setValueStr(ValueString
);
132 ASSERT_STREQ(Retrieved
->ValueStr
.data(), ValueString
)
133 << "Failed to modify option's Value string.";
135 Retrieved
->setHiddenFlag(cl::Hidden
);
136 ASSERT_EQ(cl::Hidden
, TestOption
.getOptionHiddenFlag()) <<
137 "Failed to modify option's hidden flag.";
140 TEST(CommandLineTest
, UseOptionCategory
) {
141 StackOption
<int> TestOption2("test-option", cl::cat(TestCategory
));
143 ASSERT_NE(TestOption2
.Categories
.end(),
144 find_if(TestOption2
.Categories
,
145 [&](const llvm::cl::OptionCategory
*Cat
) {
146 return Cat
== &TestCategory
;
148 << "Failed to assign Option Category.";
151 TEST(CommandLineTest
, UseMultipleCategories
) {
152 StackOption
<int> TestOption2("test-option2", cl::cat(TestCategory
),
153 cl::cat(cl::getGeneralCategory()),
154 cl::cat(cl::getGeneralCategory()));
156 // Make sure cl::getGeneralCategory() wasn't added twice.
157 ASSERT_EQ(TestOption2
.Categories
.size(), 2U);
159 ASSERT_NE(TestOption2
.Categories
.end(),
160 find_if(TestOption2
.Categories
,
161 [&](const llvm::cl::OptionCategory
*Cat
) {
162 return Cat
== &TestCategory
;
164 << "Failed to assign Option Category.";
165 ASSERT_NE(TestOption2
.Categories
.end(),
166 find_if(TestOption2
.Categories
,
167 [&](const llvm::cl::OptionCategory
*Cat
) {
168 return Cat
== &cl::getGeneralCategory();
170 << "Failed to assign General Category.";
172 cl::OptionCategory
AnotherCategory("Additional test Options", "Description");
173 StackOption
<int> TestOption("test-option", cl::cat(TestCategory
),
174 cl::cat(AnotherCategory
));
175 ASSERT_EQ(TestOption
.Categories
.end(),
176 find_if(TestOption
.Categories
,
177 [&](const llvm::cl::OptionCategory
*Cat
) {
178 return Cat
== &cl::getGeneralCategory();
180 << "Failed to remove General Category.";
181 ASSERT_NE(TestOption
.Categories
.end(),
182 find_if(TestOption
.Categories
,
183 [&](const llvm::cl::OptionCategory
*Cat
) {
184 return Cat
== &TestCategory
;
186 << "Failed to assign Option Category.";
187 ASSERT_NE(TestOption
.Categories
.end(),
188 find_if(TestOption
.Categories
,
189 [&](const llvm::cl::OptionCategory
*Cat
) {
190 return Cat
== &AnotherCategory
;
192 << "Failed to assign Another Category.";
195 typedef void ParserFunction(StringRef Source
, StringSaver
&Saver
,
196 SmallVectorImpl
<const char *> &NewArgv
,
199 void testCommandLineTokenizer(ParserFunction
*parse
, StringRef Input
,
200 ArrayRef
<const char *> Output
,
201 bool MarkEOLs
= false) {
202 SmallVector
<const char *, 0> Actual
;
204 StringSaver
Saver(A
);
205 parse(Input
, Saver
, Actual
, MarkEOLs
);
206 EXPECT_EQ(Output
.size(), Actual
.size());
207 for (unsigned I
= 0, E
= Actual
.size(); I
!= E
; ++I
) {
208 if (I
< Output
.size()) {
209 EXPECT_STREQ(Output
[I
], Actual
[I
]);
214 TEST(CommandLineTest
, TokenizeGNUCommandLine
) {
216 "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) "
217 "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\"";
218 const char *const Output
[] = {
219 "foo bar", "foo bar", "foo bar", "foo\\bar",
220 "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"};
221 testCommandLineTokenizer(cl::TokenizeGNUCommandLine
, Input
, Output
);
224 TEST(CommandLineTest
, TokenizeWindowsCommandLine1
) {
226 R
"(a\b c\\d e\\"f g
" h\"i j\\\"k "lmn
" o pqr "st
\"u
" \v)";
227 const char *const Output
[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
228 "lmn", "o", "pqr", "st \"u", "\\v" };
229 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input
, Output
);
232 TEST(CommandLineTest
, TokenizeWindowsCommandLine2
) {
233 const char Input
[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp";
234 const char *const Output
[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"};
235 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input
, Output
);
238 TEST(CommandLineTest
, TokenizeWindowsCommandLineQuotedLastArgument
) {
239 // Whitespace at the end of the command line doesn't cause an empty last word
240 const char Input0
[] = R
"(a b c d )";
241 const char *const Output0
[] = {"a", "b", "c", "d"};
242 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input0
, Output0
);
244 // But an explicit "" does
245 const char Input1
[] = R
"(a b c d "")";
246 const char *const Output1
[] = {"a", "b", "c", "d", ""};
247 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input1
, Output1
);
249 // An unterminated quoted string is also emitted as an argument word, empty
251 const char Input2
[] = R
"(a b c d ")";
252 const char *const Output2[] = {"a
", "b
", "c
", "d
", ""};
253 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input2, Output2);
254 const char Input3[] = R"(a b c d
"text)";
255 const char *const Output3
[] = {"a", "b", "c", "d", "text"};
256 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input3
, Output3
);
259 TEST(CommandLineTest
, TokenizeWindowsCommandLineExeName
) {
260 const char Input1
[] =
261 R
"("C
:\Program Files\Whatever
\"clang
.exe z
.c
-DY
=\"x
\")";
262 const char *const Output1[] = {"C
:\\Program Files
\\Whatever
\\clang
.exe
",
264 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input1, Output1);
266 const char Input2[] = "\"a
\\\"b c
\\\"d
\n\"e
\\\"f g
\\\"h
\n";
267 const char *const Output2[] = {"a
\\b
", "c
\"d
", nullptr,
268 "e
\\f
", "g
\"h
", nullptr};
269 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input2, Output2,
272 const char Input3[] = R"(\\server\share\subdir\clang
.exe
)";
273 const char *const Output3[] = {"\\\\server
\\share
\\subdir
\\clang
.exe
"};
274 testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input3, Output3);
277 TEST(CommandLineTest, TokenizeAndMarkEOLs) {
278 // Clang uses EOL marking in response files to support options that consume
279 // the rest of the arguments on the current line, but do not consume arguments
280 // from subsequent lines. For example, given these rsp files contents:
282 // /Oy- /link /debug /opt:ref
283 // /Zc:ThreadsafeStatics-
285 // clang-cl needs to treat "/debug
/opt
:ref
" as linker flags, and everything
286 // else as compiler flags. The tokenizer inserts nullptr sentinels into the
287 // output so that clang-cl can find the end of the current line.
288 const char Input[] = "clang
-Xclang foo
\n\nfoo
\"bar
\"baz
\n x
.cpp
\n";
289 const char *const Output[] = {"clang
", "-Xclang
", "foo
",
290 nullptr, nullptr, "foobarbaz
",
291 nullptr, "x
.cpp
", nullptr};
292 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
294 testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
298 TEST(CommandLineTest, TokenizeConfigFile1) {
299 const char *Input = "\\";
300 const char *const Output[] = { "\\" };
301 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
304 TEST(CommandLineTest, TokenizeConfigFile2) {
305 const char *Input = "\\abc
";
306 const char *const Output[] = { "abc
" };
307 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
310 TEST(CommandLineTest, TokenizeConfigFile3) {
311 const char *Input = "abc
\\";
312 const char *const Output[] = { "abc
\\" };
313 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
316 TEST(CommandLineTest, TokenizeConfigFile4) {
317 const char *Input = "abc
\\\n123";
318 const char *const Output[] = { "abc123
" };
319 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
322 TEST(CommandLineTest, TokenizeConfigFile5) {
323 const char *Input = "abc
\\\r\n123";
324 const char *const Output[] = { "abc123
" };
325 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
328 TEST(CommandLineTest, TokenizeConfigFile6) {
329 const char *Input = "abc
\\\n";
330 const char *const Output[] = { "abc
" };
331 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
334 TEST(CommandLineTest, TokenizeConfigFile7) {
335 const char *Input = "abc
\\\r\n";
336 const char *const Output[] = { "abc
" };
337 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
340 TEST(CommandLineTest, TokenizeConfigFile8) {
341 SmallVector<const char *, 0> Actual;
343 StringSaver Saver(A);
344 cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false);
345 EXPECT_TRUE(Actual.empty());
348 TEST(CommandLineTest, TokenizeConfigFile9) {
349 SmallVector<const char *, 0> Actual;
351 StringSaver Saver(A);
352 cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false);
353 EXPECT_TRUE(Actual.empty());
356 TEST(CommandLineTest, TokenizeConfigFile10) {
357 const char *Input = "\\\nabc
";
358 const char *const Output[] = { "abc
" };
359 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
362 TEST(CommandLineTest, TokenizeConfigFile11) {
363 const char *Input = "\\\r\nabc
";
364 const char *const Output[] = { "abc
" };
365 testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
368 TEST(CommandLineTest, AliasesWithArguments) {
369 static const size_t ARGC = 3;
370 const char *const Inputs[][ARGC] = {
371 { "-tool
", "-actual
=x
", "-extra
" },
372 { "-tool
", "-actual
", "x
" },
373 { "-tool
", "-alias
=x
", "-extra
" },
374 { "-tool
", "-alias
", "x
" }
377 for (size_t i = 0, e = std::size(Inputs); i < e; ++i) {
378 StackOption<std::string> Actual("actual
");
379 StackOption<bool> Extra("extra
");
380 StackOption<std::string> Input(cl::Positional);
382 cl::alias Alias("alias
", llvm::cl::aliasopt(Actual));
384 cl::ParseCommandLineOptions(ARGC, Inputs[i]);
385 EXPECT_EQ("x
", Actual);
386 EXPECT_EQ(0, Input.getNumOccurrences());
388 Alias.removeArgument();
392 void testAliasRequired(int argc, const char *const *argv) {
393 StackOption<std::string> Option("option
", cl::Required);
394 cl::alias Alias("o
", llvm::cl::aliasopt(Option));
396 cl::ParseCommandLineOptions(argc, argv);
397 EXPECT_EQ("x
", Option);
398 EXPECT_EQ(1, Option.getNumOccurrences());
400 Alias.removeArgument();
403 TEST(CommandLineTest, AliasRequired) {
404 const char *opts1[] = { "-tool
", "-option
=x
" };
405 const char *opts2[] = { "-tool
", "-o
", "x
" };
406 testAliasRequired(std::size(opts1), opts1);
407 testAliasRequired(std::size(opts2), opts2);
410 TEST(CommandLineTest, HideUnrelatedOptions) {
411 StackOption<int> TestOption1("hide
-option
-1");
412 StackOption<int> TestOption2("hide
-option
-2", cl::cat(TestCategory));
414 cl::HideUnrelatedOptions(TestCategory);
416 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
417 << "Failed to hide extra option
.";
418 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
419 << "Hid extra option that should be visable
.";
421 StringMap<cl::Option *> &Map =
422 cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
423 ASSERT_TRUE(Map.count("help
") == (size_t)0 ||
424 cl::NotHidden == Map["help
"]->getOptionHiddenFlag())
425 << "Hid
default option that should be visable
.";
428 cl::OptionCategory TestCategory2("Test Options set
2", "Description
");
430 TEST(CommandLineTest, HideUnrelatedOptionsMulti) {
431 StackOption<int> TestOption1("multi
-hide
-option
-1");
432 StackOption<int> TestOption2("multi
-hide
-option
-2", cl::cat(TestCategory));
433 StackOption<int> TestOption3("multi
-hide
-option
-3", cl::cat(TestCategory2));
435 const cl::OptionCategory *VisibleCategories[] = {&TestCategory,
438 cl::HideUnrelatedOptions(ArrayRef(VisibleCategories));
440 ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
441 << "Failed to hide extra option
.";
442 ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
443 << "Hid extra option that should be visable
.";
444 ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag())
445 << "Hid extra option that should be visable
.";
447 StringMap<cl::Option *> &Map =
448 cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
449 ASSERT_TRUE(Map.count("help
") == (size_t)0 ||
450 cl::NotHidden == Map["help
"]->getOptionHiddenFlag())
451 << "Hid
default option that should be visable
.";
454 TEST(CommandLineTest, SetMultiValues) {
455 StackOption<int> Option("option
");
456 const char *args[] = {"prog
", "-option
=1", "-option
=2"};
457 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(),
459 EXPECT_EQ(Option, 2);
462 TEST(CommandLineTest, SetValueInSubcategories) {
463 cl::ResetCommandLineParser();
465 StackSubCommand SC1("sc1
", "First subcommand
");
466 StackSubCommand SC2("sc2
", "Second subcommand
");
468 StackOption<bool> TopLevelOpt("top
-level
", cl::init(false));
469 StackOption<bool> SC1Opt("sc1
", cl::sub(SC1), cl::init(false));
470 StackOption<bool> SC2Opt("sc2
", cl::sub(SC2), cl::init(false));
472 EXPECT_FALSE(TopLevelOpt);
473 EXPECT_FALSE(SC1Opt);
474 EXPECT_FALSE(SC2Opt);
475 const char *args[] = {"prog
", "-top
-level
"};
477 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
478 EXPECT_TRUE(TopLevelOpt);
479 EXPECT_FALSE(SC1Opt);
480 EXPECT_FALSE(SC2Opt);
484 cl::ResetAllOptionOccurrences();
485 EXPECT_FALSE(TopLevelOpt);
486 EXPECT_FALSE(SC1Opt);
487 EXPECT_FALSE(SC2Opt);
488 const char *args2[] = {"prog
", "sc1
", "-sc1
"};
490 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
491 EXPECT_FALSE(TopLevelOpt);
493 EXPECT_FALSE(SC2Opt);
497 cl::ResetAllOptionOccurrences();
498 EXPECT_FALSE(TopLevelOpt);
499 EXPECT_FALSE(SC1Opt);
500 EXPECT_FALSE(SC2Opt);
501 const char *args3[] = {"prog
", "sc2
", "-sc2
"};
503 cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls()));
504 EXPECT_FALSE(TopLevelOpt);
505 EXPECT_FALSE(SC1Opt);
509 TEST(CommandLineTest, LookupFailsInWrongSubCommand) {
510 cl::ResetCommandLineParser();
512 StackSubCommand SC1("sc1
", "First subcommand
");
513 StackSubCommand SC2("sc2
", "Second subcommand
");
515 StackOption<bool> SC1Opt("sc1
", cl::sub(SC1), cl::init(false));
516 StackOption<bool> SC2Opt("sc2
", cl::sub(SC2), cl::init(false));
519 raw_string_ostream OS(Errs);
521 const char *args[] = {"prog
", "sc1
", "-sc2
"};
522 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
524 EXPECT_FALSE(Errs.empty());
527 TEST(CommandLineTest, TopLevelOptInSubcommand) {
528 enum LiteralOptionEnum {
534 cl::ResetCommandLineParser();
536 // This is a top-level option and not associated with a subcommand.
537 // A command line using subcommand should parse both subcommand options and
538 // top-level options. A valid use case is that users of llvm command line
539 // tools should be able to specify top-level options defined in any library.
540 StackOption<std::string> TopLevelOpt("str
", cl::init("txt
"),
541 cl::desc("A top
-level option
."));
543 StackSubCommand SC("sc
", "Subcommand
");
544 StackOption<std::string> PositionalOpt(
545 cl::Positional, cl::desc("positional argument test coverage
"),
547 StackOption<LiteralOptionEnum> LiteralOpt(
548 cl::desc("literal argument test coverage
"), cl::sub(SC), cl::init(bar),
549 cl::values(clEnumVal(foo, "foo
"), clEnumVal(bar, "bar
"),
550 clEnumVal(baz, "baz
")));
551 StackOption<bool> EnableOpt("enable
", cl::sub(SC), cl::init(false));
552 StackOption<int> ThresholdOpt("threshold
", cl::sub(SC), cl::init(1));
554 const char *PositionalOptVal = "input
-file
";
555 const char *args[] = {"prog
", "sc
", PositionalOptVal,
556 "-enable
", "--str
=csv
", "--threshold
=2"};
558 // cl::ParseCommandLineOptions returns true on success. Otherwise, it will
559 // print the error message to stderr and exit in this setting (`Errs` ostream
561 ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]), args,
563 EXPECT_STREQ(PositionalOpt.getValue().c_str(), PositionalOptVal);
564 EXPECT_TRUE(EnableOpt);
565 // Tests that the value of `str` option is `csv` as specified.
566 EXPECT_STREQ(TopLevelOpt.getValue().c_str(), "csv
");
567 EXPECT_EQ(ThresholdOpt, 2);
569 for (auto &[LiteralOptVal, WantLiteralOpt] :
570 {std::pair{"--bar
", bar}, {"--foo
", foo}, {"--baz
", baz}}) {
571 const char *args[] = {"prog
", "sc
", LiteralOptVal};
572 ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]),
575 // Tests that literal options are parsed correctly.
576 EXPECT_EQ(LiteralOpt, WantLiteralOpt);
580 TEST(CommandLineTest, AddToAllSubCommands) {
581 cl::ResetCommandLineParser();
583 StackSubCommand SC1("sc1
", "First subcommand
");
584 StackOption<bool> AllOpt("everywhere
", cl::sub(cl::SubCommand::getAll()),
586 StackSubCommand SC2("sc2
", "Second subcommand
");
588 EXPECT_TRUE(cl::SubCommand::getTopLevel().OptionsMap.contains("everywhere
"));
589 EXPECT_TRUE(cl::SubCommand::getAll().OptionsMap.contains("everywhere
"));
590 EXPECT_TRUE(SC1.OptionsMap.contains("everywhere
"));
591 EXPECT_TRUE(SC2.OptionsMap.contains("everywhere
"));
593 const char *args[] = {"prog
", "-everywhere
"};
594 const char *args2[] = {"prog
", "sc1
", "-everywhere
"};
595 const char *args3[] = {"prog
", "sc2
", "-everywhere
"};
598 raw_string_ostream OS(Errs);
600 EXPECT_FALSE(AllOpt);
601 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
606 cl::ResetAllOptionOccurrences();
607 EXPECT_FALSE(AllOpt);
608 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS));
613 cl::ResetAllOptionOccurrences();
614 EXPECT_FALSE(AllOpt);
615 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS));
618 // Since all parsing succeeded, the error message should be empty.
620 EXPECT_TRUE(Errs.empty());
623 TEST(CommandLineTest, ReparseCommandLineOptions) {
624 cl::ResetCommandLineParser();
626 StackOption<bool> TopLevelOpt(
627 "top
-level
", cl::sub(cl::SubCommand::getTopLevel()), cl::init(false));
629 const char *args[] = {"prog
", "-top
-level
"};
631 EXPECT_FALSE(TopLevelOpt);
633 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
634 EXPECT_TRUE(TopLevelOpt);
638 cl::ResetAllOptionOccurrences();
639 EXPECT_FALSE(TopLevelOpt);
641 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
642 EXPECT_TRUE(TopLevelOpt);
645 TEST(CommandLineTest, RemoveFromRegularSubCommand) {
646 cl::ResetCommandLineParser();
648 StackSubCommand SC("sc
", "Subcommand
");
649 StackOption<bool> RemoveOption("remove
-option
", cl::sub(SC), cl::init(false));
650 StackOption<bool> KeepOption("keep
-option
", cl::sub(SC), cl::init(false));
652 const char *args[] = {"prog
", "sc
", "-remove
-option
"};
655 raw_string_ostream OS(Errs);
657 EXPECT_FALSE(RemoveOption);
658 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
659 EXPECT_TRUE(RemoveOption);
661 EXPECT_TRUE(Errs.empty());
663 RemoveOption.removeArgument();
665 cl::ResetAllOptionOccurrences();
666 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
668 EXPECT_FALSE(Errs.empty());
671 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
672 cl::ResetCommandLineParser();
674 StackOption<bool> TopLevelRemove("top
-level
-remove
",
675 cl::sub(cl::SubCommand::getTopLevel()),
677 StackOption<bool> TopLevelKeep("top
-level
-keep
",
678 cl::sub(cl::SubCommand::getTopLevel()),
681 const char *args[] = {"prog
", "-top
-level
-remove
"};
683 EXPECT_FALSE(TopLevelRemove);
685 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
686 EXPECT_TRUE(TopLevelRemove);
688 TopLevelRemove.removeArgument();
690 cl::ResetAllOptionOccurrences();
692 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
695 TEST(CommandLineTest, RemoveFromAllSubCommands) {
696 cl::ResetCommandLineParser();
698 StackSubCommand SC1("sc1
", "First Subcommand
");
699 StackSubCommand SC2("sc2
", "Second Subcommand
");
700 StackOption<bool> RemoveOption(
701 "remove
-option
", cl::sub(cl::SubCommand::getAll()), cl::init(false));
702 StackOption<bool> KeepOption("keep
-option
", cl::sub(cl::SubCommand::getAll()),
705 const char *args0[] = {"prog
", "-remove
-option
"};
706 const char *args1[] = {"prog
", "sc1
", "-remove
-option
"};
707 const char *args2[] = {"prog
", "sc2
", "-remove
-option
"};
709 // It should work for all subcommands including the top-level.
710 EXPECT_FALSE(RemoveOption);
712 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
713 EXPECT_TRUE(RemoveOption);
715 RemoveOption = false;
717 cl::ResetAllOptionOccurrences();
718 EXPECT_FALSE(RemoveOption);
720 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
721 EXPECT_TRUE(RemoveOption);
723 RemoveOption = false;
725 cl::ResetAllOptionOccurrences();
726 EXPECT_FALSE(RemoveOption);
728 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
729 EXPECT_TRUE(RemoveOption);
731 RemoveOption.removeArgument();
733 // It should not work for any subcommands including the top-level.
734 cl::ResetAllOptionOccurrences();
736 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
737 cl::ResetAllOptionOccurrences();
739 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
740 cl::ResetAllOptionOccurrences();
742 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
745 TEST(CommandLineTest, GetRegisteredSubcommands) {
746 cl::ResetCommandLineParser();
748 StackSubCommand SC1("sc1
", "First Subcommand
");
749 StackOption<bool> Opt1("opt1
", cl::sub(SC1), cl::init(false));
750 StackSubCommand SC2("sc2
", "Second subcommand
");
751 StackOption<bool> Opt2("opt2
", cl::sub(SC2), cl::init(false));
753 const char *args0[] = {"prog
", "sc1
"};
754 const char *args1[] = {"prog
", "sc2
"};
757 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
760 for (auto *S : cl::getRegisteredSubcommands()) {
762 EXPECT_EQ("sc1
", S->getName());
766 cl::ResetAllOptionOccurrences();
768 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
771 for (auto *S : cl::getRegisteredSubcommands()) {
773 EXPECT_EQ("sc2
", S->getName());
778 TEST(CommandLineTest, DefaultOptions) {
779 cl::ResetCommandLineParser();
781 StackOption<std::string> Bar("bar
", cl::sub(cl::SubCommand::getAll()),
783 StackOption<std::string, cl::alias> Bar_Alias(
784 "b
", cl::desc("Alias
for -bar
"), cl::aliasopt(Bar), cl::DefaultOption);
786 StackOption<bool> Foo("foo
", cl::init(false),
787 cl::sub(cl::SubCommand::getAll()), cl::DefaultOption);
788 StackOption<bool, cl::alias> Foo_Alias("f
", cl::desc("Alias
for -foo
"),
789 cl::aliasopt(Foo), cl::DefaultOption);
791 StackSubCommand SC1("sc1
", "First Subcommand
");
792 // Override "-b
" and change type in sc1 SubCommand.
793 StackOption<bool> SC1_B("b
", cl::sub(SC1), cl::init(false));
794 StackSubCommand SC2("sc2
", "Second subcommand
");
795 // Override "-foo
" and change type in sc2 SubCommand. Note that this does not
796 // affect "-f
" alias, which continues to work correctly.
797 StackOption<std::string> SC2_Foo("foo
", cl::sub(SC2));
799 const char *args0[] = {"prog
", "-b
", "args0 bar string
", "-f
"};
800 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args0), args0,
801 StringRef(), &llvm::nulls()));
802 EXPECT_EQ(Bar, "args0 bar string
");
805 EXPECT_TRUE(SC2_Foo.empty());
807 cl::ResetAllOptionOccurrences();
809 const char *args1[] = {"prog
", "sc1
", "-b
", "-bar
", "args1 bar string
", "-f
"};
810 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args1), args1,
811 StringRef(), &llvm::nulls()));
812 EXPECT_EQ(Bar, "args1 bar string
");
815 EXPECT_TRUE(SC2_Foo.empty());
816 for (auto *S : cl::getRegisteredSubcommands()) {
818 EXPECT_EQ("sc1
", S->getName());
822 cl::ResetAllOptionOccurrences();
824 const char *args2[] = {"prog
", "sc2
", "-b
", "args2 bar string
",
825 "-f
", "-foo
", "foo string
"};
826 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args2), args2,
827 StringRef(), &llvm::nulls()));
828 EXPECT_EQ(Bar, "args2 bar string
");
831 EXPECT_EQ(SC2_Foo, "foo string
");
832 for (auto *S : cl::getRegisteredSubcommands()) {
834 EXPECT_EQ("sc2
", S->getName());
837 cl::ResetCommandLineParser();
840 TEST(CommandLineTest, ArgumentLimit) {
841 std::string args(32 * 4096, 'a');
842 EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl
", args.data()));
843 std::string args2(256, 'a');
844 EXPECT_TRUE(llvm::sys::commandLineFitsWithinSystemLimits("cl
", args2.data()));
847 TEST(CommandLineTest, ArgumentLimitWindows) {
848 if (!Triple(sys::getProcessTriple()).isOSWindows())
850 // We use 32000 as a limit for command line length. Program name ('cl'),
851 // separating spaces and termination null character occupy 5 symbols.
852 std::string long_arg(32000 - 5, 'b');
854 llvm::sys::commandLineFitsWithinSystemLimits("cl
", long_arg.data()));
857 llvm::sys::commandLineFitsWithinSystemLimits("cl
", long_arg.data()));
860 TEST(CommandLineTest, ResponseFileWindows) {
861 if (!Triple(sys::getProcessTriple()).isOSWindows())
864 StackOption<std::string, cl::list<std::string>> InputFilenames(
865 cl::Positional, cl::desc("<input files
>"));
866 StackOption<bool> TopLevelOpt("top
-level
", cl::init(false));
868 // Create response file.
869 TempFile ResponseFile("resp
-", ".txt
",
870 "-top
-level
\npath
\\dir
\\file1
\npath
/dir
/file2
",
873 llvm::SmallString<128> RspOpt;
874 RspOpt.append(1, '@');
875 RspOpt.append(ResponseFile.path());
876 const char *args[] = {"prog
", RspOpt.c_str()};
877 EXPECT_FALSE(TopLevelOpt);
879 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
880 EXPECT_TRUE(TopLevelOpt);
881 EXPECT_EQ(InputFilenames[0], "path
\\dir
\\file1
");
882 EXPECT_EQ(InputFilenames[1], "path
/dir
/file2
");
885 TEST(CommandLineTest, ResponseFiles) {
886 vfs::InMemoryFileSystem FS;
888 const char *TestRoot = "C
:\\";
890 const char *TestRoot = "/";
892 FS.setCurrentWorkingDirectory(TestRoot);
894 // Create included response file of first level.
895 llvm::StringRef IncludedFileName = "resp1
";
896 FS.addFile(IncludedFileName, 0,
897 llvm::MemoryBuffer::getMemBuffer("-option_1
-option_2
\n"
901 "-option_4
=efjk
\n"));
903 // Directory for included file.
904 llvm::StringRef IncDir = "incdir
";
906 // Create included response file of second level.
907 llvm::SmallString<128> IncludedFileName2;
908 llvm::sys::path::append(IncludedFileName2, IncDir, "resp2
");
909 FS.addFile(IncludedFileName2, 0,
910 MemoryBuffer::getMemBuffer("-option_21
-option_22
\n"
911 "-option_23
=abcd
\n"));
913 // Create second included response file of second level.
914 llvm::SmallString<128> IncludedFileName3;
915 llvm::sys::path::append(IncludedFileName3, IncDir, "resp3
");
916 FS.addFile(IncludedFileName3, 0,
917 MemoryBuffer::getMemBuffer("-option_31
-option_32
\n"
918 "-option_33
=abcd
\n"));
920 // Prepare 'file' with reference to response file.
921 SmallString<128> IncRef;
922 IncRef.append(1, '@');
923 IncRef.append(IncludedFileName);
924 llvm::SmallVector<const char *, 4> Argv = {"test
/test
", "-flag_1
",
925 IncRef.c_str(), "-flag_2
"};
927 // Expand response files.
928 llvm::BumpPtrAllocator A;
929 llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine);
930 ECtx.setVFS(&FS).setCurrentDir(TestRoot).setRelativeNames(true);
931 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
932 EXPECT_THAT(Argv, testing::Pointwise(
934 {"test
/test
", "-flag_1
", "-option_1
", "-option_2
",
935 "-option_21
", "-option_22
", "-option_23
=abcd
",
936 "-option_3
=abcd
", "-option_31
", "-option_32
",
937 "-option_33
=abcd
", "-option_4
=efjk
", "-flag_2
"}));
940 TEST(CommandLineTest, RecursiveResponseFiles) {
941 vfs::InMemoryFileSystem FS;
943 const char *TestRoot = "C
:\\";
945 const char *TestRoot = "/";
947 FS.setCurrentWorkingDirectory(TestRoot);
949 StringRef SelfFilePath = "self
.rsp
";
950 std::string SelfFileRef = ("@
" + SelfFilePath).str();
952 StringRef NestedFilePath = "nested
.rsp
";
953 std::string NestedFileRef = ("@
" + NestedFilePath).str();
955 StringRef FlagFilePath = "flag
.rsp
";
956 std::string FlagFileRef = ("@
" + FlagFilePath).str();
958 std::string SelfFileContents;
959 raw_string_ostream SelfFile(SelfFileContents);
960 SelfFile << "-option_1
\n";
961 SelfFile << FlagFileRef << "\n";
962 SelfFile << NestedFileRef << "\n";
963 SelfFile << SelfFileRef << "\n";
964 FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str()));
966 std::string NestedFileContents;
967 raw_string_ostream NestedFile(NestedFileContents);
968 NestedFile << "-option_2
\n";
969 NestedFile << FlagFileRef << "\n";
970 NestedFile << SelfFileRef << "\n";
971 NestedFile << NestedFileRef << "\n";
972 FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str()));
974 std::string FlagFileContents;
975 raw_string_ostream FlagFile(FlagFileContents);
976 FlagFile << "-option_x
\n";
977 FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str()));
980 // Recursive expansion terminates
981 // Recursive files never expand
982 // Non-recursive repeats are allowed
983 SmallVector<const char *, 4> Argv = {"test
/test
", SelfFileRef.c_str(),
987 cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine;
989 cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
991 llvm::cl::ExpansionContext ECtx(A, Tokenizer);
992 ECtx.setVFS(&FS).setCurrentDir(TestRoot);
993 llvm::Error Err = ECtx.expandResponseFiles(Argv);
994 ASSERT_TRUE((bool)Err);
995 SmallString<128> FilePath = SelfFilePath;
996 std::error_code EC = FS.makeAbsolute(FilePath);
997 ASSERT_FALSE((bool)EC);
998 std::string ExpectedMessage =
999 std::string("recursive expansion of
: '") + std::string(FilePath) + "'";
1000 ASSERT_TRUE(toString(std::move(Err)) == ExpectedMessage);
1003 testing::Pointwise(StringEquality(),
1004 {"test
/test
", "-option_1
", "-option_x
",
1005 "-option_2
", "-option_x
", SelfFileRef.c_str(),
1006 NestedFileRef.c_str(), SelfFileRef.c_str(),
1010 TEST(CommandLineTest, ResponseFilesAtArguments) {
1011 vfs::InMemoryFileSystem FS;
1013 const char *TestRoot = "C
:\\";
1015 const char *TestRoot = "/";
1017 FS.setCurrentWorkingDirectory(TestRoot);
1019 StringRef ResponseFilePath = "test
.rsp
";
1021 std::string ResponseFileContents;
1022 raw_string_ostream ResponseFile(ResponseFileContents);
1023 ResponseFile << "-foo
" << "\n";
1024 ResponseFile << "-bar
" << "\n";
1025 FS.addFile(ResponseFilePath, 0,
1026 MemoryBuffer::getMemBuffer(ResponseFile.str()));
1028 // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
1029 constexpr size_t NON_RSP_AT_ARGS = 64;
1030 SmallVector<const char *, 4> Argv = {"test
/test
"};
1031 Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg
");
1032 std::string ResponseFileRef = ("@
" + ResponseFilePath).str();
1033 Argv.push_back(ResponseFileRef.c_str());
1036 llvm::cl::ExpansionContext ECtx(A, cl::TokenizeGNUCommandLine);
1037 ECtx.setVFS(&FS).setCurrentDir(TestRoot);
1038 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
1040 // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
1041 ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2);
1043 EXPECT_STREQ(Argv[i++], "test
/test
");
1044 for (; i < 1 + NON_RSP_AT_ARGS; ++i)
1045 EXPECT_STREQ(Argv[i], "@non_rsp_at_arg
");
1046 EXPECT_STREQ(Argv[i++], "-foo
");
1047 EXPECT_STREQ(Argv[i++], "-bar
");
1050 TEST(CommandLineTest, ResponseFileRelativePath) {
1051 vfs::InMemoryFileSystem FS;
1053 const char *TestRoot = "C
:\\";
1055 const char *TestRoot = "//net";
1057 FS
.setCurrentWorkingDirectory(TestRoot
);
1059 StringRef OuterFile
= "dir/outer.rsp";
1060 StringRef OuterFileContents
= "@inner.rsp";
1061 FS
.addFile(OuterFile
, 0, MemoryBuffer::getMemBuffer(OuterFileContents
));
1063 StringRef InnerFile
= "dir/inner.rsp";
1064 StringRef InnerFileContents
= "-flag";
1065 FS
.addFile(InnerFile
, 0, MemoryBuffer::getMemBuffer(InnerFileContents
));
1067 SmallVector
<const char *, 2> Argv
= {"test/test", "@dir/outer.rsp"};
1070 llvm::cl::ExpansionContext
ECtx(A
, cl::TokenizeGNUCommandLine
);
1071 ECtx
.setVFS(&FS
).setCurrentDir(TestRoot
).setRelativeNames(true);
1072 ASSERT_FALSE((bool)ECtx
.expandResponseFiles(Argv
));
1074 testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
1077 TEST(CommandLineTest
, ResponseFileEOLs
) {
1078 vfs::InMemoryFileSystem FS
;
1080 const char *TestRoot
= "C:\\";
1082 const char *TestRoot
= "//net";
1084 FS
.setCurrentWorkingDirectory(TestRoot
);
1085 FS
.addFile("eols.rsp", 0,
1086 MemoryBuffer::getMemBuffer("-Xclang -Wno-whatever\n input.cpp"));
1087 SmallVector
<const char *, 2> Argv
= {"clang", "@eols.rsp"};
1089 llvm::cl::ExpansionContext
ECtx(A
, cl::TokenizeWindowsCommandLine
);
1090 ECtx
.setVFS(&FS
).setCurrentDir(TestRoot
).setMarkEOLs(true).setRelativeNames(
1092 ASSERT_FALSE((bool)ECtx
.expandResponseFiles(Argv
));
1093 const char *Expected
[] = {"clang", "-Xclang", "-Wno-whatever", nullptr,
1095 ASSERT_EQ(std::size(Expected
), Argv
.size());
1096 for (size_t I
= 0, E
= std::size(Expected
); I
< E
; ++I
) {
1097 if (Expected
[I
] == nullptr) {
1098 ASSERT_EQ(Argv
[I
], nullptr);
1100 ASSERT_STREQ(Expected
[I
], Argv
[I
]);
1105 TEST(CommandLineTest
, BadResponseFile
) {
1107 StringSaver
Saver(A
);
1108 TempDir
ADir("dir", /*Unique*/ true);
1109 SmallString
<128> AFilePath
= ADir
.path();
1110 llvm::sys::path::append(AFilePath
, "file.rsp");
1111 std::string AFileExp
= std::string("@") + std::string(AFilePath
.str());
1112 SmallVector
<const char *, 2> Argv
= {"clang", AFileExp
.c_str()};
1114 bool Res
= cl::ExpandResponseFiles(Saver
, cl::TokenizeGNUCommandLine
, Argv
);
1116 ASSERT_EQ(2U, Argv
.size());
1117 ASSERT_STREQ(Argv
[0], "clang");
1118 ASSERT_STREQ(Argv
[1], AFileExp
.c_str());
1120 std::string ADirExp
= std::string("@") + std::string(ADir
.path());
1121 Argv
= {"clang", ADirExp
.c_str()};
1122 Res
= cl::ExpandResponseFiles(Saver
, cl::TokenizeGNUCommandLine
, Argv
);
1124 ASSERT_EQ(2U, Argv
.size());
1125 ASSERT_STREQ(Argv
[0], "clang");
1126 ASSERT_STREQ(Argv
[1], ADirExp
.c_str());
1129 TEST(CommandLineTest
, SetDefaultValue
) {
1130 cl::ResetCommandLineParser();
1132 StackOption
<std::string
> Opt1("opt1", cl::init("true"));
1133 StackOption
<bool> Opt2("opt2", cl::init(true));
1134 cl::alias
Alias("alias", llvm::cl::aliasopt(Opt2
));
1135 StackOption
<int> Opt3("opt3", cl::init(3));
1137 llvm::SmallVector
<int, 3> IntVals
= {1, 2, 3};
1138 llvm::SmallVector
<std::string
, 3> StrVals
= {"foo", "bar", "baz"};
1140 StackOption
<int, cl::list
<int>> List1(
1141 "list1", cl::list_init
<int>(llvm::ArrayRef
<int>(IntVals
)),
1142 cl::CommaSeparated
);
1143 StackOption
<std::string
, cl::list
<std::string
>> List2(
1144 "list2", cl::list_init
<std::string
>(llvm::ArrayRef
<std::string
>(StrVals
)),
1145 cl::CommaSeparated
);
1146 cl::alias
ListAlias("list-alias", llvm::cl::aliasopt(List2
));
1148 const char *args
[] = {"prog", "-opt1=false", "-list1", "4",
1149 "-list1", "5,6", "-opt2", "-opt3"};
1152 cl::ParseCommandLineOptions(7, args
, StringRef(), &llvm::nulls()));
1154 EXPECT_EQ(Opt1
, "false");
1158 for (size_t I
= 0, E
= IntVals
.size(); I
< E
; ++I
) {
1159 EXPECT_EQ(IntVals
[I
] + 3, List1
[I
]);
1160 EXPECT_EQ(StrVals
[I
], List2
[I
]);
1166 cl::ResetAllOptionOccurrences();
1168 for (auto &OM
: cl::getRegisteredOptions(cl::SubCommand::getTopLevel())) {
1169 cl::Option
*O
= OM
.second
;
1170 if (O
->ArgStr
== "opt2") {
1176 EXPECT_EQ(Opt1
, "true");
1179 for (size_t I
= 0, E
= IntVals
.size(); I
< E
; ++I
) {
1180 EXPECT_EQ(IntVals
[I
], List1
[I
]);
1181 EXPECT_EQ(StrVals
[I
], List2
[I
]);
1184 Alias
.removeArgument();
1185 ListAlias
.removeArgument();
1188 TEST(CommandLineTest
, ReadConfigFile
) {
1189 llvm::SmallVector
<const char *, 1> Argv
;
1191 TempDir
TestDir("unittest", /*Unique*/ true);
1192 TempDir
TestSubDir(TestDir
.path("subdir"), /*Unique*/ false);
1194 llvm::SmallString
<128> TestCfg
= TestDir
.path("foo");
1195 TempFile
ConfigFile(TestCfg
, "",
1198 "-option_2=<CFGDIR>/dir1\n"
1199 "-option_3=<CFGDIR>\n"
1200 "-option_4 <CFGDIR>\n"
1201 "-option_5=<CFG\\\n"
1203 "-option_6=<CFGDIR>/dir1,<CFGDIR>/dir2\n"
1209 llvm::SmallString
<128> TestCfg2
= TestDir
.path("subconfig");
1210 TempFile
ConfigFile2(TestCfg2
, "",
1212 "-option_8=<CFGDIR>/dir2\n"
1217 llvm::SmallString
<128> TestCfg3
= TestSubDir
.path("subfoo");
1218 TempFile
ConfigFile3(TestCfg3
, "",
1219 "-option_9=<CFGDIR>/dir3\n"
1220 "@<CFGDIR>/subfoo2\n");
1222 llvm::SmallString
<128> TestCfg4
= TestSubDir
.path("subfoo2");
1223 TempFile
ConfigFile4(TestCfg4
, "", "-option_10\n");
1225 // Make sure the current directory is not the directory where config files
1226 // resides. In this case the code that expands response files will not find
1227 // 'subconfig' unless it resolves nested inclusions relative to the including
1229 llvm::SmallString
<128> CurrDir
;
1230 std::error_code EC
= llvm::sys::fs::current_path(CurrDir
);
1232 EXPECT_NE(CurrDir
.str(), TestDir
.path());
1234 llvm::BumpPtrAllocator A
;
1235 llvm::cl::ExpansionContext
ECtx(A
, cl::tokenizeConfigFile
);
1236 llvm::Error Result
= ECtx
.readConfigFile(ConfigFile
.path(), Argv
);
1238 EXPECT_FALSE((bool)Result
);
1239 EXPECT_EQ(Argv
.size(), 13U);
1240 EXPECT_STREQ(Argv
[0], "-option_1");
1241 EXPECT_STREQ(Argv
[1],
1242 ("-option_2=" + TestDir
.path() + "/dir1").str().c_str());
1243 EXPECT_STREQ(Argv
[2], ("-option_3=" + TestDir
.path()).str().c_str());
1244 EXPECT_STREQ(Argv
[3], "-option_4");
1245 EXPECT_STREQ(Argv
[4], TestDir
.path().str().c_str());
1246 EXPECT_STREQ(Argv
[5], ("-option_5=" + TestDir
.path()).str().c_str());
1247 EXPECT_STREQ(Argv
[6], ("-option_6=" + TestDir
.path() + "/dir1," +
1248 TestDir
.path() + "/dir2")
1251 EXPECT_STREQ(Argv
[7], "-option_7");
1252 EXPECT_STREQ(Argv
[8],
1253 ("-option_8=" + TestDir
.path() + "/dir2").str().c_str());
1254 EXPECT_STREQ(Argv
[9],
1255 ("-option_9=" + TestSubDir
.path() + "/dir3").str().c_str());
1256 EXPECT_STREQ(Argv
[10], "-option_10");
1257 EXPECT_STREQ(Argv
[11], "-option_11=abcd");
1258 EXPECT_STREQ(Argv
[12], "-option_12=cdef");
1261 TEST(CommandLineTest
, PositionalEatArgsError
) {
1262 cl::ResetCommandLineParser();
1264 StackOption
<std::string
, cl::list
<std::string
>> PosEatArgs(
1265 "positional-eat-args", cl::Positional
, cl::desc("<arguments>..."),
1266 cl::PositionalEatsArgs
);
1267 StackOption
<std::string
, cl::list
<std::string
>> PosEatArgs2(
1268 "positional-eat-args2", cl::Positional
, cl::desc("Some strings"),
1269 cl::PositionalEatsArgs
);
1271 const char *args
[] = {"prog", "-positional-eat-args=XXXX"};
1272 const char *args2
[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1273 const char *args3
[] = {"prog", "-positional-eat-args", "-foo"};
1274 const char *args4
[] = {"prog", "-positional-eat-args",
1275 "-foo", "-positional-eat-args2",
1279 raw_string_ostream
OS(Errs
);
1280 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
)); OS
.flush();
1281 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1282 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2
, StringRef(), &OS
)); OS
.flush();
1283 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1284 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3
, StringRef(), &OS
)); OS
.flush();
1285 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1287 cl::ResetAllOptionOccurrences();
1288 EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4
, StringRef(), &OS
)); OS
.flush();
1289 EXPECT_EQ(PosEatArgs
.size(), 1u);
1290 EXPECT_EQ(PosEatArgs2
.size(), 2u);
1291 EXPECT_TRUE(Errs
.empty());
1295 void checkSeparators(StringRef Path
) {
1296 char UndesiredSeparator
= sys::path::get_separator()[0] == '/' ? '\\' : '/';
1297 ASSERT_EQ(Path
.find(UndesiredSeparator
), StringRef::npos
);
1300 TEST(CommandLineTest
, GetCommandLineArguments
) {
1302 char **argv
= __argv
;
1304 // GetCommandLineArguments is called in InitLLVM.
1305 llvm::InitLLVM
X(argc
, argv
);
1307 EXPECT_EQ(llvm::sys::path::is_absolute(argv
[0]),
1308 llvm::sys::path::is_absolute(__argv
[0]));
1309 checkSeparators(argv
[0]);
1312 llvm::sys::path::filename(argv
[0]).equals_insensitive("supporttests.exe"))
1313 << "Filename of test executable is "
1314 << llvm::sys::path::filename(argv
[0]);
1318 class OutputRedirector
{
1320 OutputRedirector(int RedirectFD
)
1321 : RedirectFD(RedirectFD
), OldFD(dup(RedirectFD
)) {
1323 sys::fs::createTemporaryFile("unittest-redirect", "", NewFD
,
1325 dup2(NewFD
, RedirectFD
) == -1)
1329 ~OutputRedirector() {
1330 dup2(OldFD
, RedirectFD
);
1335 SmallVector
<char, 128> FilePath
;
1344 struct AutoDeleteFile
{
1345 SmallVector
<char, 128> FilePath
;
1347 if (!FilePath
.empty())
1348 sys::fs::remove(std::string(FilePath
.data(), FilePath
.size()));
1352 static std::string
interceptStdout(std::function
<void()> F
) {
1353 outs().flush(); // flush any output from previous tests
1354 AutoDeleteFile File
;
1356 OutputRedirector
Stdout(fileno(stdout
));
1359 File
.FilePath
= Stdout
.FilePath
;
1363 auto Buffer
= MemoryBuffer::getFile(File
.FilePath
);
1366 return Buffer
->get()->getBuffer().str();
1369 template <void (*Func
)(const cl::Option
&)>
1370 class PrintOptionTestBase
: public ::testing::Test
{
1372 // Return std::string because the output of a failing EXPECT check is
1373 // unreadable for StringRef. It also avoids any lifetime issues.
1374 template <typename
... Ts
> std::string
runTest(Ts
... OptionAttributes
) {
1375 StackOption
<OptionValue
> TestOption(Opt
, cl::desc(HelpText
),
1376 OptionAttributes
...);
1377 return interceptStdout([&]() { Func(TestOption
); });
1380 enum class OptionValue
{ Val
};
1381 const StringRef Opt
= "some-option";
1382 const StringRef HelpText
= "some help";
1385 // This is a workaround for cl::Option sub-classes having their
1386 // printOptionInfo functions private.
1387 void printOptionInfo(const cl::Option
&O
) {
1388 O
.printOptionInfo(/*GlobalWidth=*/26);
1391 using PrintOptionInfoTest
= PrintOptionTestBase
<printOptionInfo
>;
1393 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithoutSentinel
) {
1394 std::string Output
=
1395 runTest(cl::ValueOptional
,
1396 cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1399 EXPECT_EQ(Output
, (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1405 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithSentinel
) {
1406 std::string Output
= runTest(
1407 cl::ValueOptional
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1408 clEnumValN(OptionValue::Val
, "", "")));
1412 (" --" + Opt
+ " - " + HelpText
+ "\n"
1413 " --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1419 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithSentinelWithHelp
) {
1420 std::string Output
= runTest(
1421 cl::ValueOptional
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1422 clEnumValN(OptionValue::Val
, "", "desc2")));
1425 EXPECT_EQ(Output
, (" --" + Opt
+ " - " + HelpText
+ "\n"
1426 " --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1428 " =<empty> - desc2\n")
1433 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueRequiredWithEmptyValueName
) {
1434 std::string Output
= runTest(
1435 cl::ValueRequired
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1436 clEnumValN(OptionValue::Val
, "", "")));
1439 EXPECT_EQ(Output
, (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1446 TEST_F(PrintOptionInfoTest
, PrintOptionInfoEmptyValueDescription
) {
1447 std::string Output
= runTest(
1448 cl::ValueRequired
, cl::values(clEnumValN(OptionValue::Val
, "v1", "")));
1452 (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1457 TEST_F(PrintOptionInfoTest
, PrintOptionInfoMultilineValueDescription
) {
1458 std::string Output
=
1459 runTest(cl::ValueRequired
,
1460 cl::values(clEnumValN(OptionValue::Val
, "v1",
1461 "This is the first enum value\n"
1462 "which has a really long description\n"
1463 "thus it is multi-line."),
1464 clEnumValN(OptionValue::Val
, "",
1465 "This is an unnamed enum value\n"
1466 "Should be indented as well")));
1470 (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1471 " =v1 - This is the first enum value\n"
1472 " which has a really long description\n"
1473 " thus it is multi-line.\n"
1474 " =<empty> - This is an unnamed enum value\n"
1475 " Should be indented as well\n").str());
1479 void printOptionValue(const cl::Option
&O
) {
1480 O
.printOptionValue(/*GlobalWidth=*/12, /*Force=*/true);
1483 using PrintOptionValueTest
= PrintOptionTestBase
<printOptionValue
>;
1485 TEST_F(PrintOptionValueTest
, PrintOptionDefaultValue
) {
1486 std::string Output
=
1487 runTest(cl::init(OptionValue::Val
),
1488 cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1490 EXPECT_EQ(Output
, (" --" + Opt
+ " = v1 (default: v1)\n").str());
1493 TEST_F(PrintOptionValueTest
, PrintOptionNoDefaultValue
) {
1494 std::string Output
=
1495 runTest(cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1497 // Note: the option still has a (zero-initialized) value, but the default
1498 // is invalid and doesn't match any value.
1499 EXPECT_EQ(Output
, (" --" + Opt
+ " = v1 (default: )\n").str());
1502 TEST_F(PrintOptionValueTest
, PrintOptionUnknownValue
) {
1503 std::string Output
= runTest(cl::init(OptionValue::Val
));
1505 EXPECT_EQ(Output
, (" --" + Opt
+ " = *unknown option value*\n").str());
1508 class GetOptionWidthTest
: public ::testing::Test
{
1510 enum class OptionValue
{ Val
};
1512 template <typename
... Ts
>
1513 size_t runTest(StringRef ArgName
, Ts
... OptionAttributes
) {
1514 StackOption
<OptionValue
> TestOption(ArgName
, cl::desc("some help"),
1515 OptionAttributes
...);
1516 return getOptionWidth(TestOption
);
1520 // This is a workaround for cl::Option sub-classes having their
1522 // functions private.
1523 size_t getOptionWidth(const cl::Option
&O
) { return O
.getOptionWidth(); }
1526 TEST_F(GetOptionWidthTest
, GetOptionWidthArgNameLonger
) {
1527 StringRef
ArgName("a-long-argument-name");
1528 size_t ExpectedStrSize
= (" --" + ArgName
+ "=<value> - ").str().size();
1530 runTest(ArgName
, cl::values(clEnumValN(OptionValue::Val
, "v", "help"))),
1534 TEST_F(GetOptionWidthTest
, GetOptionWidthFirstOptionNameLonger
) {
1535 StringRef
OptName("a-long-option-name");
1536 size_t ExpectedStrSize
= (" =" + OptName
+ " - ").str().size();
1538 runTest("a", cl::values(clEnumValN(OptionValue::Val
, OptName
, "help"),
1539 clEnumValN(OptionValue::Val
, "b", "help"))),
1543 TEST_F(GetOptionWidthTest
, GetOptionWidthSecondOptionNameLonger
) {
1544 StringRef
OptName("a-long-option-name");
1545 size_t ExpectedStrSize
= (" =" + OptName
+ " - ").str().size();
1547 runTest("a", cl::values(clEnumValN(OptionValue::Val
, "b", "help"),
1548 clEnumValN(OptionValue::Val
, OptName
, "help"))),
1552 TEST_F(GetOptionWidthTest
, GetOptionWidthEmptyOptionNameLonger
) {
1553 size_t ExpectedStrSize
= StringRef(" =<empty> - ").size();
1554 // The length of a=<value> (including indentation) is actually the same as the
1555 // =<empty> string, so it is impossible to distinguish via testing the case
1556 // where the empty string is picked from where the option name is picked.
1557 EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val
, "b", "help"),
1558 clEnumValN(OptionValue::Val
, "", "help"))),
1562 TEST_F(GetOptionWidthTest
,
1563 GetOptionWidthValueOptionalEmptyOptionWithNoDescription
) {
1564 StringRef
ArgName("a");
1565 // The length of a=<value> (including indentation) is actually the same as the
1566 // =<empty> string, so it is impossible to distinguish via testing the case
1567 // where the empty string is ignored from where it is not ignored.
1568 // The dash will not actually be printed, but the space it would take up is
1569 // included to ensure a consistent column width.
1570 size_t ExpectedStrSize
= (" -" + ArgName
+ "=<value> - ").str().size();
1571 EXPECT_EQ(runTest(ArgName
, cl::ValueOptional
,
1572 cl::values(clEnumValN(OptionValue::Val
, "value", "help"),
1573 clEnumValN(OptionValue::Val
, "", ""))),
1577 TEST_F(GetOptionWidthTest
,
1578 GetOptionWidthValueRequiredEmptyOptionWithNoDescription
) {
1579 // The length of a=<value> (including indentation) is actually the same as the
1580 // =<empty> string, so it is impossible to distinguish via testing the case
1581 // where the empty string is picked from where the option name is picked
1582 size_t ExpectedStrSize
= StringRef(" =<empty> - ").size();
1583 EXPECT_EQ(runTest("a", cl::ValueRequired
,
1584 cl::values(clEnumValN(OptionValue::Val
, "value", "help"),
1585 clEnumValN(OptionValue::Val
, "", ""))),
1589 TEST(CommandLineTest
, PrefixOptions
) {
1590 cl::ResetCommandLineParser();
1592 StackOption
<std::string
, cl::list
<std::string
>> IncludeDirs(
1593 "I", cl::Prefix
, cl::desc("Declare an include directory"));
1595 // Test non-prefixed variant works with cl::Prefix options.
1596 EXPECT_TRUE(IncludeDirs
.empty());
1597 const char *args
[] = {"prog", "-I=/usr/include"};
1599 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
1600 EXPECT_EQ(IncludeDirs
.size(), 1u);
1601 EXPECT_EQ(IncludeDirs
.front().compare("/usr/include"), 0);
1603 IncludeDirs
.erase(IncludeDirs
.begin());
1604 cl::ResetAllOptionOccurrences();
1606 // Test non-prefixed variant works with cl::Prefix options when value is
1607 // passed in following argument.
1608 EXPECT_TRUE(IncludeDirs
.empty());
1609 const char *args2
[] = {"prog", "-I", "/usr/include"};
1611 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1612 EXPECT_EQ(IncludeDirs
.size(), 1u);
1613 EXPECT_EQ(IncludeDirs
.front().compare("/usr/include"), 0);
1615 IncludeDirs
.erase(IncludeDirs
.begin());
1616 cl::ResetAllOptionOccurrences();
1618 // Test prefixed variant works with cl::Prefix options.
1619 EXPECT_TRUE(IncludeDirs
.empty());
1620 const char *args3
[] = {"prog", "-I/usr/include"};
1622 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1623 EXPECT_EQ(IncludeDirs
.size(), 1u);
1624 EXPECT_EQ(IncludeDirs
.front().compare("/usr/include"), 0);
1626 StackOption
<std::string
, cl::list
<std::string
>> MacroDefs(
1627 "D", cl::AlwaysPrefix
, cl::desc("Define a macro"),
1628 cl::value_desc("MACRO[=VALUE]"));
1630 cl::ResetAllOptionOccurrences();
1632 // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1633 // equal sign is part of the value.
1634 EXPECT_TRUE(MacroDefs
.empty());
1635 const char *args4
[] = {"prog", "-D=HAVE_FOO"};
1637 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1638 EXPECT_EQ(MacroDefs
.size(), 1u);
1639 EXPECT_EQ(MacroDefs
.front().compare("=HAVE_FOO"), 0);
1641 MacroDefs
.erase(MacroDefs
.begin());
1642 cl::ResetAllOptionOccurrences();
1644 // Test non-prefixed variant does not allow value to be passed in following
1645 // argument with cl::AlwaysPrefix options.
1646 EXPECT_TRUE(MacroDefs
.empty());
1647 const char *args5
[] = {"prog", "-D", "HAVE_FOO"};
1649 cl::ParseCommandLineOptions(3, args5
, StringRef(), &llvm::nulls()));
1650 EXPECT_TRUE(MacroDefs
.empty());
1652 cl::ResetAllOptionOccurrences();
1654 // Test prefixed variant works with cl::AlwaysPrefix options.
1655 EXPECT_TRUE(MacroDefs
.empty());
1656 const char *args6
[] = {"prog", "-DHAVE_FOO"};
1658 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1659 EXPECT_EQ(MacroDefs
.size(), 1u);
1660 EXPECT_EQ(MacroDefs
.front().compare("HAVE_FOO"), 0);
1663 TEST(CommandLineTest
, GroupingWithValue
) {
1664 cl::ResetCommandLineParser();
1666 StackOption
<bool> OptF("f", cl::Grouping
, cl::desc("Some flag"));
1667 StackOption
<bool> OptB("b", cl::Grouping
, cl::desc("Another flag"));
1668 StackOption
<bool> OptD("d", cl::Grouping
, cl::ValueDisallowed
,
1669 cl::desc("ValueDisallowed option"));
1670 StackOption
<std::string
> OptV("v", cl::Grouping
,
1671 cl::desc("ValueRequired option"));
1672 StackOption
<std::string
> OptO("o", cl::Grouping
, cl::ValueOptional
,
1673 cl::desc("ValueOptional option"));
1675 // Should be possible to use an option which requires a value
1676 // at the end of a group.
1677 const char *args1
[] = {"prog", "-fv", "val1"};
1679 cl::ParseCommandLineOptions(3, args1
, StringRef(), &llvm::nulls()));
1681 EXPECT_STREQ("val1", OptV
.c_str());
1683 cl::ResetAllOptionOccurrences();
1685 // Should not crash if it is accidentally used elsewhere in the group.
1686 const char *args2
[] = {"prog", "-vf", "val2"};
1688 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1690 cl::ResetAllOptionOccurrences();
1692 // Should allow the "opt=value" form at the end of the group
1693 const char *args3
[] = {"prog", "-fv=val3"};
1695 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1697 EXPECT_STREQ("val3", OptV
.c_str());
1699 cl::ResetAllOptionOccurrences();
1701 // Should allow assigning a value for a ValueOptional option
1702 // at the end of the group
1703 const char *args4
[] = {"prog", "-fo=val4"};
1705 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1707 EXPECT_STREQ("val4", OptO
.c_str());
1709 cl::ResetAllOptionOccurrences();
1711 // Should assign an empty value if a ValueOptional option is used elsewhere
1713 const char *args5
[] = {"prog", "-fob"};
1715 cl::ParseCommandLineOptions(2, args5
, StringRef(), &llvm::nulls()));
1717 EXPECT_EQ(1, OptO
.getNumOccurrences());
1718 EXPECT_EQ(1, OptB
.getNumOccurrences());
1719 EXPECT_TRUE(OptO
.empty());
1720 cl::ResetAllOptionOccurrences();
1722 // Should not allow an assignment for a ValueDisallowed option.
1723 const char *args6
[] = {"prog", "-fd=false"};
1725 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1728 TEST(CommandLineTest
, GroupingAndPrefix
) {
1729 cl::ResetCommandLineParser();
1731 StackOption
<bool> OptF("f", cl::Grouping
, cl::desc("Some flag"));
1732 StackOption
<bool> OptB("b", cl::Grouping
, cl::desc("Another flag"));
1733 StackOption
<std::string
> OptP("p", cl::Prefix
, cl::Grouping
,
1734 cl::desc("Prefix and Grouping"));
1735 StackOption
<std::string
> OptA("a", cl::AlwaysPrefix
, cl::Grouping
,
1736 cl::desc("AlwaysPrefix and Grouping"));
1738 // Should be possible to use a cl::Prefix option without grouping.
1739 const char *args1
[] = {"prog", "-pval1"};
1741 cl::ParseCommandLineOptions(2, args1
, StringRef(), &llvm::nulls()));
1742 EXPECT_STREQ("val1", OptP
.c_str());
1744 cl::ResetAllOptionOccurrences();
1746 // Should be possible to pass a value in a separate argument.
1747 const char *args2
[] = {"prog", "-p", "val2"};
1749 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1750 EXPECT_STREQ("val2", OptP
.c_str());
1752 cl::ResetAllOptionOccurrences();
1754 // The "-opt=value" form should work, too.
1755 const char *args3
[] = {"prog", "-p=val3"};
1757 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1758 EXPECT_STREQ("val3", OptP
.c_str());
1760 cl::ResetAllOptionOccurrences();
1762 // All three previous cases should work the same way if an option with both
1763 // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1764 const char *args4
[] = {"prog", "-fpval4"};
1766 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1768 EXPECT_STREQ("val4", OptP
.c_str());
1770 cl::ResetAllOptionOccurrences();
1772 const char *args5
[] = {"prog", "-fp", "val5"};
1774 cl::ParseCommandLineOptions(3, args5
, StringRef(), &llvm::nulls()));
1776 EXPECT_STREQ("val5", OptP
.c_str());
1778 cl::ResetAllOptionOccurrences();
1780 const char *args6
[] = {"prog", "-fp=val6"};
1782 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1784 EXPECT_STREQ("val6", OptP
.c_str());
1786 cl::ResetAllOptionOccurrences();
1788 // Should assign a value even if the part after a cl::Prefix option is equal
1789 // to the name of another option.
1790 const char *args7
[] = {"prog", "-fpb"};
1792 cl::ParseCommandLineOptions(2, args7
, StringRef(), &llvm::nulls()));
1794 EXPECT_STREQ("b", OptP
.c_str());
1797 cl::ResetAllOptionOccurrences();
1799 // Should be possible to use a cl::AlwaysPrefix option without grouping.
1800 const char *args8
[] = {"prog", "-aval8"};
1802 cl::ParseCommandLineOptions(2, args8
, StringRef(), &llvm::nulls()));
1803 EXPECT_STREQ("val8", OptA
.c_str());
1805 cl::ResetAllOptionOccurrences();
1807 // Should not be possible to pass a value in a separate argument.
1808 const char *args9
[] = {"prog", "-a", "val9"};
1810 cl::ParseCommandLineOptions(3, args9
, StringRef(), &llvm::nulls()));
1811 cl::ResetAllOptionOccurrences();
1813 // With the "-opt=value" form, the "=" symbol should be preserved.
1814 const char *args10
[] = {"prog", "-a=val10"};
1816 cl::ParseCommandLineOptions(2, args10
, StringRef(), &llvm::nulls()));
1817 EXPECT_STREQ("=val10", OptA
.c_str());
1819 cl::ResetAllOptionOccurrences();
1821 // All three previous cases should work the same way if an option with both
1822 // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1823 const char *args11
[] = {"prog", "-faval11"};
1825 cl::ParseCommandLineOptions(2, args11
, StringRef(), &llvm::nulls()));
1827 EXPECT_STREQ("val11", OptA
.c_str());
1829 cl::ResetAllOptionOccurrences();
1831 const char *args12
[] = {"prog", "-fa", "val12"};
1833 cl::ParseCommandLineOptions(3, args12
, StringRef(), &llvm::nulls()));
1834 cl::ResetAllOptionOccurrences();
1836 const char *args13
[] = {"prog", "-fa=val13"};
1838 cl::ParseCommandLineOptions(2, args13
, StringRef(), &llvm::nulls()));
1840 EXPECT_STREQ("=val13", OptA
.c_str());
1842 cl::ResetAllOptionOccurrences();
1844 // Should assign a value even if the part after a cl::AlwaysPrefix option
1845 // is equal to the name of another option.
1846 const char *args14
[] = {"prog", "-fab"};
1848 cl::ParseCommandLineOptions(2, args14
, StringRef(), &llvm::nulls()));
1850 EXPECT_STREQ("b", OptA
.c_str());
1853 cl::ResetAllOptionOccurrences();
1856 TEST(CommandLineTest
, LongOptions
) {
1857 cl::ResetCommandLineParser();
1859 StackOption
<bool> OptA("a", cl::desc("Some flag"));
1860 StackOption
<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1861 StackOption
<bool, cl::alias
> OptB("b", cl::desc("Alias to --long-flag"),
1862 cl::aliasopt(OptBLong
));
1863 StackOption
<std::string
> OptAB("ab", cl::desc("Another long option"));
1866 raw_string_ostream
OS(Errs
);
1868 const char *args1
[] = {"prog", "-a", "-ab", "val1"};
1869 const char *args2
[] = {"prog", "-a", "--ab", "val1"};
1870 const char *args3
[] = {"prog", "-ab", "--ab", "val1"};
1873 // The following tests treat `-` and `--` the same, and always match the
1878 cl::ParseCommandLineOptions(4, args1
, StringRef(), &OS
)); OS
.flush();
1880 EXPECT_FALSE(OptBLong
);
1881 EXPECT_STREQ("val1", OptAB
.c_str());
1882 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1883 cl::ResetAllOptionOccurrences();
1886 cl::ParseCommandLineOptions(4, args2
, StringRef(), &OS
)); OS
.flush();
1888 EXPECT_FALSE(OptBLong
);
1889 EXPECT_STREQ("val1", OptAB
.c_str());
1890 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1891 cl::ResetAllOptionOccurrences();
1893 // Fails because `-ab` and `--ab` are treated the same and appear more than
1894 // once. Also, `val1` is unexpected.
1896 cl::ParseCommandLineOptions(4, args3
, StringRef(), &OS
)); OS
.flush();
1897 outs()<< Errs
<< "\n";
1898 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1899 cl::ResetAllOptionOccurrences();
1902 // The following tests treat `-` and `--` differently, with `-` for short, and
1903 // `--` for long options.
1906 // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1907 // `val1` is unexpected.
1908 EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1
, StringRef(),
1909 &OS
, nullptr, true)); OS
.flush();
1910 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1911 cl::ResetAllOptionOccurrences();
1913 // Works because `-a` is treated differently than `--ab`.
1914 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2
, StringRef(),
1915 &OS
, nullptr, true)); OS
.flush();
1916 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1917 cl::ResetAllOptionOccurrences();
1919 // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1920 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3
, StringRef(),
1921 &OS
, nullptr, true));
1923 EXPECT_TRUE(OptBLong
);
1924 EXPECT_STREQ("val1", OptAB
.c_str());
1926 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1927 cl::ResetAllOptionOccurrences();
1930 TEST(CommandLineTest
, OptionErrorMessage
) {
1931 // When there is an error, we expect some error message like:
1932 // prog: for the -a option: [...]
1934 // Test whether the "for the -a option"-part is correctly formatted.
1935 cl::ResetCommandLineParser();
1937 StackOption
<bool> OptA("a", cl::desc("Some option"));
1938 StackOption
<bool> OptLong("long", cl::desc("Some long option"));
1941 raw_string_ostream
OS(Errs
);
1943 OptA
.error("custom error", OS
);
1945 EXPECT_NE(Errs
.find("for the -a option:"), std::string::npos
);
1948 OptLong
.error("custom error", OS
);
1950 EXPECT_NE(Errs
.find("for the --long option:"), std::string::npos
);
1953 cl::ResetAllOptionOccurrences();
1956 TEST(CommandLineTest
, OptionErrorMessageSuggest
) {
1957 // When there is an error, and the edit-distance is not very large,
1958 // we expect some error message like:
1959 // prog: did you mean '--option'?
1961 // Test whether this message is well-formatted.
1962 cl::ResetCommandLineParser();
1964 StackOption
<bool> OptLong("aluminium", cl::desc("Some long option"));
1966 const char *args
[] = {"prog", "--aluminum"};
1969 raw_string_ostream
OS(Errs
);
1971 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
));
1973 EXPECT_NE(Errs
.find("prog: Did you mean '--aluminium'?\n"),
1977 cl::ResetAllOptionOccurrences();
1980 TEST(CommandLineTest
, OptionErrorMessageSuggestNoHidden
) {
1981 // We expect that 'really hidden' option do not show up in option
1983 cl::ResetCommandLineParser();
1985 StackOption
<bool> OptLong("aluminium", cl::desc("Some long option"));
1986 StackOption
<bool> OptLong2("aluminum", cl::desc("Bad option"),
1989 const char *args
[] = {"prog", "--alumnum"};
1992 raw_string_ostream
OS(Errs
);
1994 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
));
1996 EXPECT_NE(Errs
.find("prog: Did you mean '--aluminium'?\n"),
2000 cl::ResetAllOptionOccurrences();
2003 TEST(CommandLineTest
, Callback
) {
2004 cl::ResetCommandLineParser();
2006 StackOption
<bool> OptA("a", cl::desc("option a"));
2007 StackOption
<bool> OptB(
2008 "b", cl::desc("option b -- This option turns on option a"),
2009 cl::callback([&](const bool &) { OptA
= true; }));
2010 StackOption
<bool> OptC(
2011 "c", cl::desc("option c -- This option turns on options a and b"),
2012 cl::callback([&](const bool &) { OptB
= true; }));
2013 StackOption
<std::string
, cl::list
<std::string
>> List(
2015 cl::desc("option list -- This option turns on options a, b, and c when "
2016 "'foo' is included in list"),
2018 cl::callback([&](const std::string
&Str
) {
2023 const char *args1
[] = {"prog", "-a"};
2024 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args1
));
2028 EXPECT_EQ(List
.size(), 0u);
2029 cl::ResetAllOptionOccurrences();
2031 const char *args2
[] = {"prog", "-b"};
2032 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args2
));
2036 EXPECT_EQ(List
.size(), 0u);
2037 cl::ResetAllOptionOccurrences();
2039 const char *args3
[] = {"prog", "-c"};
2040 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args3
));
2044 EXPECT_EQ(List
.size(), 0u);
2045 cl::ResetAllOptionOccurrences();
2047 const char *args4
[] = {"prog", "--list=foo,bar"};
2048 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args4
));
2052 EXPECT_EQ(List
.size(), 2u);
2053 cl::ResetAllOptionOccurrences();
2055 const char *args5
[] = {"prog", "--list=bar"};
2056 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args5
));
2060 EXPECT_EQ(List
.size(), 1u);
2062 cl::ResetAllOptionOccurrences();
2065 enum Enum
{ Val1
, Val2
};
2066 static cl::bits
<Enum
> ExampleBits(
2067 cl::desc("An example cl::bits to ensure it compiles"),
2069 clEnumValN(Val1
, "bits-val1", "The Val1 value"),
2070 clEnumValN(Val1
, "bits-val2", "The Val2 value")));
2072 TEST(CommandLineTest
, ConsumeAfterOnePositional
) {
2073 cl::ResetCommandLineParser();
2076 StackOption
<std::string
, cl::opt
<std::string
>> Input(cl::Positional
,
2078 StackOption
<std::string
, cl::list
<std::string
>> ExtraArgs(cl::ConsumeAfter
);
2080 const char *Args
[] = {"prog", "input", "arg1", "arg2"};
2083 raw_string_ostream
OS(Errs
);
2084 EXPECT_TRUE(cl::ParseCommandLineOptions(4, Args
, StringRef(), &OS
));
2086 EXPECT_EQ("input", Input
);
2087 EXPECT_EQ(ExtraArgs
.size(), 2u);
2088 EXPECT_EQ(ExtraArgs
[0], "arg1");
2089 EXPECT_EQ(ExtraArgs
[1], "arg2");
2090 EXPECT_TRUE(Errs
.empty());
2093 TEST(CommandLineTest
, ConsumeAfterTwoPositionals
) {
2094 cl::ResetCommandLineParser();
2096 // input1 input2 [args]
2097 StackOption
<std::string
, cl::opt
<std::string
>> Input1(cl::Positional
,
2099 StackOption
<std::string
, cl::opt
<std::string
>> Input2(cl::Positional
,
2101 StackOption
<std::string
, cl::list
<std::string
>> ExtraArgs(cl::ConsumeAfter
);
2103 const char *Args
[] = {"prog", "input1", "input2", "arg1", "arg2"};
2106 raw_string_ostream
OS(Errs
);
2107 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args
, StringRef(), &OS
));
2109 EXPECT_EQ("input1", Input1
);
2110 EXPECT_EQ("input2", Input2
);
2111 EXPECT_EQ(ExtraArgs
.size(), 2u);
2112 EXPECT_EQ(ExtraArgs
[0], "arg1");
2113 EXPECT_EQ(ExtraArgs
[1], "arg2");
2114 EXPECT_TRUE(Errs
.empty());
2117 TEST(CommandLineTest
, ResetAllOptionOccurrences
) {
2118 cl::ResetCommandLineParser();
2120 // -option -str -enableA -enableC [sink] input [args]
2121 StackOption
<bool> Option("option");
2122 StackOption
<std::string
> Str("str");
2123 enum Vals
{ ValA
, ValB
, ValC
};
2124 StackOption
<Vals
, cl::bits
<Vals
>> Bits(
2125 cl::values(clEnumValN(ValA
, "enableA", "Enable A"),
2126 clEnumValN(ValB
, "enableB", "Enable B"),
2127 clEnumValN(ValC
, "enableC", "Enable C")));
2128 StackOption
<std::string
, cl::list
<std::string
>> Sink(cl::Sink
);
2129 StackOption
<std::string
> Input(cl::Positional
);
2130 StackOption
<std::string
, cl::list
<std::string
>> ExtraArgs(cl::ConsumeAfter
);
2132 const char *Args
[] = {"prog", "-option", "-str=STR", "-enableA",
2133 "-enableC", "-unknown", "input", "-arg"};
2136 raw_string_ostream
OS(Errs
);
2137 EXPECT_TRUE(cl::ParseCommandLineOptions(8, Args
, StringRef(), &OS
));
2138 EXPECT_TRUE(OS
.str().empty());
2140 EXPECT_TRUE(Option
);
2141 EXPECT_EQ("STR", Str
);
2142 EXPECT_EQ((1u << ValA
) | (1u << ValC
), Bits
.getBits());
2143 EXPECT_EQ(1u, Sink
.size());
2144 EXPECT_EQ("-unknown", Sink
[0]);
2145 EXPECT_EQ("input", Input
);
2146 EXPECT_EQ(1u, ExtraArgs
.size());
2147 EXPECT_EQ("-arg", ExtraArgs
[0]);
2149 cl::ResetAllOptionOccurrences();
2150 EXPECT_FALSE(Option
);
2152 EXPECT_EQ(0u, Bits
.getBits());
2153 EXPECT_EQ(0u, Sink
.size());
2154 EXPECT_EQ(0, Input
.getNumOccurrences());
2155 EXPECT_EQ(0u, ExtraArgs
.size());
2158 TEST(CommandLineTest
, DefaultValue
) {
2159 cl::ResetCommandLineParser();
2161 StackOption
<bool> BoolOption("bool-option");
2162 StackOption
<std::string
> StrOption("str-option");
2163 StackOption
<bool> BoolInitOption("bool-init-option", cl::init(true));
2164 StackOption
<std::string
> StrInitOption("str-init-option",
2165 cl::init("str-default-value"));
2167 const char *Args
[] = {"prog"}; // no options
2170 raw_string_ostream
OS(Errs
);
2171 EXPECT_TRUE(cl::ParseCommandLineOptions(1, Args
, StringRef(), &OS
));
2172 EXPECT_TRUE(OS
.str().empty());
2174 EXPECT_TRUE(!BoolOption
);
2175 EXPECT_FALSE(BoolOption
.Default
.hasValue());
2176 EXPECT_EQ(0, BoolOption
.getNumOccurrences());
2178 EXPECT_EQ("", StrOption
);
2179 EXPECT_FALSE(StrOption
.Default
.hasValue());
2180 EXPECT_EQ(0, StrOption
.getNumOccurrences());
2182 EXPECT_TRUE(BoolInitOption
);
2183 EXPECT_TRUE(BoolInitOption
.Default
.hasValue());
2184 EXPECT_EQ(0, BoolInitOption
.getNumOccurrences());
2186 EXPECT_EQ("str-default-value", StrInitOption
);
2187 EXPECT_TRUE(StrInitOption
.Default
.hasValue());
2188 EXPECT_EQ(0, StrInitOption
.getNumOccurrences());
2190 const char *Args2
[] = {"prog", "-bool-option", "-str-option=str-value",
2191 "-bool-init-option=0",
2192 "-str-init-option=str-init-value"};
2194 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args2
, StringRef(), &OS
));
2195 EXPECT_TRUE(OS
.str().empty());
2197 EXPECT_TRUE(BoolOption
);
2198 EXPECT_FALSE(BoolOption
.Default
.hasValue());
2199 EXPECT_EQ(1, BoolOption
.getNumOccurrences());
2201 EXPECT_EQ("str-value", StrOption
);
2202 EXPECT_FALSE(StrOption
.Default
.hasValue());
2203 EXPECT_EQ(1, StrOption
.getNumOccurrences());
2205 EXPECT_FALSE(BoolInitOption
);
2206 EXPECT_TRUE(BoolInitOption
.Default
.hasValue());
2207 EXPECT_EQ(1, BoolInitOption
.getNumOccurrences());
2209 EXPECT_EQ("str-init-value", StrInitOption
);
2210 EXPECT_TRUE(StrInitOption
.Default
.hasValue());
2211 EXPECT_EQ(1, StrInitOption
.getNumOccurrences());
2214 TEST(CommandLineTest
, HelpWithoutSubcommands
) {
2215 // Check that the help message does not contain the "[subcommand]" placeholder
2216 // and the "SUBCOMMANDS" section if there are no subcommands.
2217 cl::ResetCommandLineParser();
2218 StackOption
<bool> Opt("opt", cl::init(false));
2219 const char *args
[] = {"prog"};
2220 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args
), args
, StringRef(),
2222 auto Output
= interceptStdout([]() { cl::PrintHelpMessage(); });
2223 EXPECT_NE(std::string::npos
, Output
.find("USAGE: prog [options]")) << Output
;
2224 EXPECT_EQ(std::string::npos
, Output
.find("SUBCOMMANDS:")) << Output
;
2225 cl::ResetCommandLineParser();
2228 TEST(CommandLineTest
, HelpWithSubcommands
) {
2229 // Check that the help message contains the "[subcommand]" placeholder in the
2230 // "USAGE" line and describes subcommands.
2231 cl::ResetCommandLineParser();
2232 StackSubCommand
SC1("sc1", "First Subcommand");
2233 StackSubCommand
SC2("sc2", "Second Subcommand");
2234 StackOption
<bool> SC1Opt("sc1", cl::sub(SC1
), cl::init(false));
2235 StackOption
<bool> SC2Opt("sc2", cl::sub(SC2
), cl::init(false));
2236 const char *args
[] = {"prog"};
2237 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args
), args
, StringRef(),
2239 auto Output
= interceptStdout([]() { cl::PrintHelpMessage(); });
2240 EXPECT_NE(std::string::npos
,
2241 Output
.find("USAGE: prog [subcommand] [options]"))
2243 EXPECT_NE(std::string::npos
, Output
.find("SUBCOMMANDS:")) << Output
;
2244 EXPECT_NE(std::string::npos
, Output
.find("sc1 - First Subcommand")) << Output
;
2245 EXPECT_NE(std::string::npos
, Output
.find("sc2 - Second Subcommand"))
2247 cl::ResetCommandLineParser();
2250 TEST(CommandLineTest
, UnknownCommands
) {
2251 cl::ResetCommandLineParser();
2253 StackSubCommand
SC1("foo", "Foo subcommand");
2254 StackSubCommand
SC2("bar", "Bar subcommand");
2255 StackOption
<bool> SC1Opt("put", cl::sub(SC1
));
2256 StackOption
<bool> SC2Opt("get", cl::sub(SC2
));
2257 StackOption
<bool> TopOpt1("peek");
2258 StackOption
<bool> TopOpt2("set");
2261 raw_string_ostream
OS(Errs
);
2263 const char *Args1
[] = {"prog", "baz", "--get"};
2265 cl::ParseCommandLineOptions(std::size(Args1
), Args1
, StringRef(), &OS
));
2267 "prog: Unknown subcommand 'baz'. Try: 'prog --help'\n"
2268 "prog: Did you mean 'bar'?\n"
2269 "prog: Unknown command line argument '--get'. Try: 'prog --help'\n"
2270 "prog: Did you mean '--set'?\n");
2272 // Do not show a suggestion if the subcommand is not similar to any known.
2274 const char *Args2
[] = {"prog", "faz"};
2276 cl::ParseCommandLineOptions(std::size(Args2
), Args2
, StringRef(), &OS
));
2277 EXPECT_EQ(Errs
, "prog: Unknown subcommand 'faz'. Try: 'prog --help'\n");
2280 TEST(CommandLineTest
, SubCommandGroups
) {
2281 // Check that options in subcommand groups are associated with expected
2284 cl::ResetCommandLineParser();
2286 StackSubCommand
SC1("sc1", "SC1 subcommand");
2287 StackSubCommand
SC2("sc2", "SC2 subcommand");
2288 StackSubCommand
SC3("sc3", "SC3 subcommand");
2289 cl::SubCommandGroup Group12
= {&SC1
, &SC2
};
2291 StackOption
<bool> Opt12("opt12", cl::sub(Group12
), cl::init(false));
2292 StackOption
<bool> Opt3("opt3", cl::sub(SC3
), cl::init(false));
2294 // The "--opt12" option is expected to be added to both subcommands in the
2295 // group, but not to the top-level "no subcommand" pseudo-subcommand or the
2296 // "sc3" subcommand.
2297 EXPECT_EQ(1U, SC1
.OptionsMap
.size());
2298 EXPECT_TRUE(SC1
.OptionsMap
.contains("opt12"));
2300 EXPECT_EQ(1U, SC2
.OptionsMap
.size());
2301 EXPECT_TRUE(SC2
.OptionsMap
.contains("opt12"));
2303 EXPECT_FALSE(cl::SubCommand::getTopLevel().OptionsMap
.contains("opt12"));
2304 EXPECT_FALSE(SC3
.OptionsMap
.contains("opt12"));
2307 TEST(CommandLineTest
, HelpWithEmptyCategory
) {
2308 cl::ResetCommandLineParser();
2310 cl::OptionCategory
Category1("First Category");
2311 cl::OptionCategory
Category2("Second Category");
2312 StackOption
<int> Opt1("opt1", cl::cat(Category1
));
2313 StackOption
<int> Opt2("opt2", cl::cat(Category2
));
2314 cl::HideUnrelatedOptions(Category2
);
2316 const char *args
[] = {"prog"};
2317 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args
), args
, StringRef(),
2319 auto Output
= interceptStdout(
2320 []() { cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); });
2321 EXPECT_EQ(std::string::npos
, Output
.find("First Category"))
2322 << "An empty category should not be printed";
2324 Output
= interceptStdout(
2325 []() { cl::PrintHelpMessage(/*Hidden=*/true, /*Categorized=*/true); });
2326 EXPECT_EQ(std::string::npos
, Output
.find("First Category"))
2327 << "An empty category should not be printed";
2329 cl::ResetCommandLineParser();
2332 } // anonymous namespace