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/Triple.h"
13 #include "llvm/Config/config.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/InitLLVM.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/Program.h"
19 #include "llvm/Support/StringSaver.h"
20 #include "gtest/gtest.h"
31 TempEnvVar(const char *name
, const char *value
)
33 const char *old_value
= getenv(name
);
34 EXPECT_EQ(nullptr, old_value
) << old_value
;
36 setenv(name
, value
, true);
38 # define SKIP_ENVIRONMENT_TESTS
44 // Assume setenv and unsetenv come together.
47 (void)name
; // Suppress -Wunused-private-field.
52 const char *const name
;
55 template <typename T
, typename Base
= cl::opt
<T
>>
56 class StackOption
: public Base
{
58 template <class... Ts
>
59 explicit StackOption(Ts
&&... Ms
) : Base(std::forward
<Ts
>(Ms
)...) {}
61 ~StackOption() override
{ this->removeArgument(); }
63 template <class DT
> StackOption
<T
> &operator=(const DT
&V
) {
69 class StackSubCommand
: public cl::SubCommand
{
71 StackSubCommand(StringRef Name
,
72 StringRef Description
= StringRef())
73 : SubCommand(Name
, Description
) {}
75 StackSubCommand() : SubCommand() {}
77 ~StackSubCommand() { unregisterSubCommand(); }
81 cl::OptionCategory
TestCategory("Test Options", "Description");
82 TEST(CommandLineTest
, ModifyExisitingOption
) {
83 StackOption
<int> TestOption("test-option", cl::desc("old description"));
85 static const char Description
[] = "New description";
86 static const char ArgString
[] = "new-test-option";
87 static const char ValueString
[] = "Integer";
89 StringMap
<cl::Option
*> &Map
=
90 cl::getRegisteredOptions(*cl::TopLevelSubCommand
);
92 ASSERT_TRUE(Map
.count("test-option") == 1) <<
93 "Could not find option in map.";
95 cl::Option
*Retrieved
= Map
["test-option"];
96 ASSERT_EQ(&TestOption
, Retrieved
) << "Retrieved wrong option.";
98 ASSERT_NE(Retrieved
->Categories
.end(),
99 find_if(Retrieved
->Categories
,
100 [&](const llvm::cl::OptionCategory
*Cat
) {
101 return Cat
== &cl::GeneralCategory
;
103 << "Incorrect default option category.";
105 Retrieved
->addCategory(TestCategory
);
106 ASSERT_NE(Retrieved
->Categories
.end(),
107 find_if(Retrieved
->Categories
,
108 [&](const llvm::cl::OptionCategory
*Cat
) {
109 return Cat
== &TestCategory
;
111 << "Failed to modify option's option category.";
113 Retrieved
->setDescription(Description
);
114 ASSERT_STREQ(Retrieved
->HelpStr
.data(), Description
)
115 << "Changing option description failed.";
117 Retrieved
->setArgStr(ArgString
);
118 ASSERT_STREQ(ArgString
, Retrieved
->ArgStr
.data())
119 << "Failed to modify option's Argument string.";
121 Retrieved
->setValueStr(ValueString
);
122 ASSERT_STREQ(Retrieved
->ValueStr
.data(), ValueString
)
123 << "Failed to modify option's Value string.";
125 Retrieved
->setHiddenFlag(cl::Hidden
);
126 ASSERT_EQ(cl::Hidden
, TestOption
.getOptionHiddenFlag()) <<
127 "Failed to modify option's hidden flag.";
129 #ifndef SKIP_ENVIRONMENT_TESTS
131 const char test_env_var
[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
133 cl::opt
<std::string
> EnvironmentTestOption("env-test-opt");
134 TEST(CommandLineTest
, ParseEnvironment
) {
135 TempEnvVar
TEV(test_env_var
, "-env-test-opt=hello");
136 EXPECT_EQ("", EnvironmentTestOption
);
137 cl::ParseEnvironmentOptions("CommandLineTest", test_env_var
);
138 EXPECT_EQ("hello", EnvironmentTestOption
);
141 // This test used to make valgrind complain
142 // ("Conditional jump or move depends on uninitialised value(s)")
144 // Warning: Do not run any tests after this one that try to gain access to
145 // registered command line options because this will likely result in a
146 // SEGFAULT. This can occur because the cl::opt in the test below is declared
147 // on the stack which will be destroyed after the test completes but the
148 // command line system will still hold a pointer to a deallocated cl::Option.
149 TEST(CommandLineTest
, ParseEnvironmentToLocalVar
) {
150 // Put cl::opt on stack to check for proper initialization of fields.
151 StackOption
<std::string
> EnvironmentTestOptionLocal("env-test-opt-local");
152 TempEnvVar
TEV(test_env_var
, "-env-test-opt-local=hello-local");
153 EXPECT_EQ("", EnvironmentTestOptionLocal
);
154 cl::ParseEnvironmentOptions("CommandLineTest", test_env_var
);
155 EXPECT_EQ("hello-local", EnvironmentTestOptionLocal
);
158 #endif // SKIP_ENVIRONMENT_TESTS
160 TEST(CommandLineTest
, UseOptionCategory
) {
161 StackOption
<int> TestOption2("test-option", cl::cat(TestCategory
));
163 ASSERT_NE(TestOption2
.Categories
.end(),
164 find_if(TestOption2
.Categories
,
165 [&](const llvm::cl::OptionCategory
*Cat
) {
166 return Cat
== &TestCategory
;
168 << "Failed to assign Option Category.";
171 TEST(CommandLineTest
, UseMultipleCategories
) {
172 StackOption
<int> TestOption2("test-option2", cl::cat(TestCategory
),
173 cl::cat(cl::GeneralCategory
),
174 cl::cat(cl::GeneralCategory
));
176 // Make sure cl::GeneralCategory wasn't added twice.
177 ASSERT_EQ(TestOption2
.Categories
.size(), 2U);
179 ASSERT_NE(TestOption2
.Categories
.end(),
180 find_if(TestOption2
.Categories
,
181 [&](const llvm::cl::OptionCategory
*Cat
) {
182 return Cat
== &TestCategory
;
184 << "Failed to assign Option Category.";
185 ASSERT_NE(TestOption2
.Categories
.end(),
186 find_if(TestOption2
.Categories
,
187 [&](const llvm::cl::OptionCategory
*Cat
) {
188 return Cat
== &cl::GeneralCategory
;
190 << "Failed to assign General Category.";
192 cl::OptionCategory
AnotherCategory("Additional test Options", "Description");
193 StackOption
<int> TestOption("test-option", cl::cat(TestCategory
),
194 cl::cat(AnotherCategory
));
195 ASSERT_EQ(TestOption
.Categories
.end(),
196 find_if(TestOption
.Categories
,
197 [&](const llvm::cl::OptionCategory
*Cat
) {
198 return Cat
== &cl::GeneralCategory
;
200 << "Failed to remove General Category.";
201 ASSERT_NE(TestOption
.Categories
.end(),
202 find_if(TestOption
.Categories
,
203 [&](const llvm::cl::OptionCategory
*Cat
) {
204 return Cat
== &TestCategory
;
206 << "Failed to assign Option Category.";
207 ASSERT_NE(TestOption
.Categories
.end(),
208 find_if(TestOption
.Categories
,
209 [&](const llvm::cl::OptionCategory
*Cat
) {
210 return Cat
== &AnotherCategory
;
212 << "Failed to assign Another Category.";
215 typedef void ParserFunction(StringRef Source
, StringSaver
&Saver
,
216 SmallVectorImpl
<const char *> &NewArgv
,
219 void testCommandLineTokenizer(ParserFunction
*parse
, StringRef Input
,
220 const char *const Output
[], size_t OutputSize
) {
221 SmallVector
<const char *, 0> Actual
;
223 StringSaver
Saver(A
);
224 parse(Input
, Saver
, Actual
, /*MarkEOLs=*/false);
225 EXPECT_EQ(OutputSize
, Actual
.size());
226 for (unsigned I
= 0, E
= Actual
.size(); I
!= E
; ++I
) {
227 if (I
< OutputSize
) {
228 EXPECT_STREQ(Output
[I
], Actual
[I
]);
233 TEST(CommandLineTest
, TokenizeGNUCommandLine
) {
235 "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) "
236 "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\"";
237 const char *const Output
[] = {
238 "foo bar", "foo bar", "foo bar", "foo\\bar",
239 "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"};
240 testCommandLineTokenizer(cl::TokenizeGNUCommandLine
, Input
, Output
,
241 array_lengthof(Output
));
244 TEST(CommandLineTest
, TokenizeWindowsCommandLine1
) {
245 const char Input
[] = "a\\b c\\\\d e\\\\\"f g\" h\\\"i j\\\\\\\"k \"lmn\" o pqr "
247 const char *const Output
[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
248 "lmn", "o", "pqr", "st \"u", "\\v" };
249 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input
, Output
,
250 array_lengthof(Output
));
253 TEST(CommandLineTest
, TokenizeWindowsCommandLine2
) {
254 const char Input
[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp";
255 const char *const Output
[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"};
256 testCommandLineTokenizer(cl::TokenizeWindowsCommandLine
, Input
, Output
,
257 array_lengthof(Output
));
260 TEST(CommandLineTest
, TokenizeConfigFile1
) {
261 const char *Input
= "\\";
262 const char *const Output
[] = { "\\" };
263 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
264 array_lengthof(Output
));
267 TEST(CommandLineTest
, TokenizeConfigFile2
) {
268 const char *Input
= "\\abc";
269 const char *const Output
[] = { "abc" };
270 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
271 array_lengthof(Output
));
274 TEST(CommandLineTest
, TokenizeConfigFile3
) {
275 const char *Input
= "abc\\";
276 const char *const Output
[] = { "abc\\" };
277 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
278 array_lengthof(Output
));
281 TEST(CommandLineTest
, TokenizeConfigFile4
) {
282 const char *Input
= "abc\\\n123";
283 const char *const Output
[] = { "abc123" };
284 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
285 array_lengthof(Output
));
288 TEST(CommandLineTest
, TokenizeConfigFile5
) {
289 const char *Input
= "abc\\\r\n123";
290 const char *const Output
[] = { "abc123" };
291 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
292 array_lengthof(Output
));
295 TEST(CommandLineTest
, TokenizeConfigFile6
) {
296 const char *Input
= "abc\\\n";
297 const char *const Output
[] = { "abc" };
298 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
299 array_lengthof(Output
));
302 TEST(CommandLineTest
, TokenizeConfigFile7
) {
303 const char *Input
= "abc\\\r\n";
304 const char *const Output
[] = { "abc" };
305 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
306 array_lengthof(Output
));
309 TEST(CommandLineTest
, TokenizeConfigFile8
) {
310 SmallVector
<const char *, 0> Actual
;
312 StringSaver
Saver(A
);
313 cl::tokenizeConfigFile("\\\n", Saver
, Actual
, /*MarkEOLs=*/false);
314 EXPECT_TRUE(Actual
.empty());
317 TEST(CommandLineTest
, TokenizeConfigFile9
) {
318 SmallVector
<const char *, 0> Actual
;
320 StringSaver
Saver(A
);
321 cl::tokenizeConfigFile("\\\r\n", Saver
, Actual
, /*MarkEOLs=*/false);
322 EXPECT_TRUE(Actual
.empty());
325 TEST(CommandLineTest
, TokenizeConfigFile10
) {
326 const char *Input
= "\\\nabc";
327 const char *const Output
[] = { "abc" };
328 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
329 array_lengthof(Output
));
332 TEST(CommandLineTest
, TokenizeConfigFile11
) {
333 const char *Input
= "\\\r\nabc";
334 const char *const Output
[] = { "abc" };
335 testCommandLineTokenizer(cl::tokenizeConfigFile
, Input
, Output
,
336 array_lengthof(Output
));
339 TEST(CommandLineTest
, AliasesWithArguments
) {
340 static const size_t ARGC
= 3;
341 const char *const Inputs
[][ARGC
] = {
342 { "-tool", "-actual=x", "-extra" },
343 { "-tool", "-actual", "x" },
344 { "-tool", "-alias=x", "-extra" },
345 { "-tool", "-alias", "x" }
348 for (size_t i
= 0, e
= array_lengthof(Inputs
); i
< e
; ++i
) {
349 StackOption
<std::string
> Actual("actual");
350 StackOption
<bool> Extra("extra");
351 StackOption
<std::string
> Input(cl::Positional
);
353 cl::alias
Alias("alias", llvm::cl::aliasopt(Actual
));
355 cl::ParseCommandLineOptions(ARGC
, Inputs
[i
]);
356 EXPECT_EQ("x", Actual
);
357 EXPECT_EQ(0, Input
.getNumOccurrences());
359 Alias
.removeArgument();
363 void testAliasRequired(int argc
, const char *const *argv
) {
364 StackOption
<std::string
> Option("option", cl::Required
);
365 cl::alias
Alias("o", llvm::cl::aliasopt(Option
));
367 cl::ParseCommandLineOptions(argc
, argv
);
368 EXPECT_EQ("x", Option
);
369 EXPECT_EQ(1, Option
.getNumOccurrences());
371 Alias
.removeArgument();
374 TEST(CommandLineTest
, AliasRequired
) {
375 const char *opts1
[] = { "-tool", "-option=x" };
376 const char *opts2
[] = { "-tool", "-o", "x" };
377 testAliasRequired(array_lengthof(opts1
), opts1
);
378 testAliasRequired(array_lengthof(opts2
), opts2
);
381 TEST(CommandLineTest
, HideUnrelatedOptions
) {
382 StackOption
<int> TestOption1("hide-option-1");
383 StackOption
<int> TestOption2("hide-option-2", cl::cat(TestCategory
));
385 cl::HideUnrelatedOptions(TestCategory
);
387 ASSERT_EQ(cl::ReallyHidden
, TestOption1
.getOptionHiddenFlag())
388 << "Failed to hide extra option.";
389 ASSERT_EQ(cl::NotHidden
, TestOption2
.getOptionHiddenFlag())
390 << "Hid extra option that should be visable.";
392 StringMap
<cl::Option
*> &Map
=
393 cl::getRegisteredOptions(*cl::TopLevelSubCommand
);
394 ASSERT_EQ(cl::NotHidden
, Map
["help"]->getOptionHiddenFlag())
395 << "Hid default option that should be visable.";
398 cl::OptionCategory
TestCategory2("Test Options set 2", "Description");
400 TEST(CommandLineTest
, HideUnrelatedOptionsMulti
) {
401 StackOption
<int> TestOption1("multi-hide-option-1");
402 StackOption
<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory
));
403 StackOption
<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2
));
405 const cl::OptionCategory
*VisibleCategories
[] = {&TestCategory
,
408 cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories
));
410 ASSERT_EQ(cl::ReallyHidden
, TestOption1
.getOptionHiddenFlag())
411 << "Failed to hide extra option.";
412 ASSERT_EQ(cl::NotHidden
, TestOption2
.getOptionHiddenFlag())
413 << "Hid extra option that should be visable.";
414 ASSERT_EQ(cl::NotHidden
, TestOption3
.getOptionHiddenFlag())
415 << "Hid extra option that should be visable.";
417 StringMap
<cl::Option
*> &Map
=
418 cl::getRegisteredOptions(*cl::TopLevelSubCommand
);
419 ASSERT_EQ(cl::NotHidden
, Map
["help"]->getOptionHiddenFlag())
420 << "Hid default option that should be visable.";
423 TEST(CommandLineTest
, SetValueInSubcategories
) {
424 cl::ResetCommandLineParser();
426 StackSubCommand
SC1("sc1", "First subcommand");
427 StackSubCommand
SC2("sc2", "Second subcommand");
429 StackOption
<bool> TopLevelOpt("top-level", cl::init(false));
430 StackOption
<bool> SC1Opt("sc1", cl::sub(SC1
), cl::init(false));
431 StackOption
<bool> SC2Opt("sc2", cl::sub(SC2
), cl::init(false));
433 EXPECT_FALSE(TopLevelOpt
);
434 EXPECT_FALSE(SC1Opt
);
435 EXPECT_FALSE(SC2Opt
);
436 const char *args
[] = {"prog", "-top-level"};
438 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
439 EXPECT_TRUE(TopLevelOpt
);
440 EXPECT_FALSE(SC1Opt
);
441 EXPECT_FALSE(SC2Opt
);
445 cl::ResetAllOptionOccurrences();
446 EXPECT_FALSE(TopLevelOpt
);
447 EXPECT_FALSE(SC1Opt
);
448 EXPECT_FALSE(SC2Opt
);
449 const char *args2
[] = {"prog", "sc1", "-sc1"};
451 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
452 EXPECT_FALSE(TopLevelOpt
);
454 EXPECT_FALSE(SC2Opt
);
458 cl::ResetAllOptionOccurrences();
459 EXPECT_FALSE(TopLevelOpt
);
460 EXPECT_FALSE(SC1Opt
);
461 EXPECT_FALSE(SC2Opt
);
462 const char *args3
[] = {"prog", "sc2", "-sc2"};
464 cl::ParseCommandLineOptions(3, args3
, StringRef(), &llvm::nulls()));
465 EXPECT_FALSE(TopLevelOpt
);
466 EXPECT_FALSE(SC1Opt
);
470 TEST(CommandLineTest
, LookupFailsInWrongSubCommand
) {
471 cl::ResetCommandLineParser();
473 StackSubCommand
SC1("sc1", "First subcommand");
474 StackSubCommand
SC2("sc2", "Second subcommand");
476 StackOption
<bool> SC1Opt("sc1", cl::sub(SC1
), cl::init(false));
477 StackOption
<bool> SC2Opt("sc2", cl::sub(SC2
), cl::init(false));
480 raw_string_ostream
OS(Errs
);
482 const char *args
[] = {"prog", "sc1", "-sc2"};
483 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args
, StringRef(), &OS
));
485 EXPECT_FALSE(Errs
.empty());
488 TEST(CommandLineTest
, AddToAllSubCommands
) {
489 cl::ResetCommandLineParser();
491 StackSubCommand
SC1("sc1", "First subcommand");
492 StackOption
<bool> AllOpt("everywhere", cl::sub(*cl::AllSubCommands
),
494 StackSubCommand
SC2("sc2", "Second subcommand");
496 const char *args
[] = {"prog", "-everywhere"};
497 const char *args2
[] = {"prog", "sc1", "-everywhere"};
498 const char *args3
[] = {"prog", "sc2", "-everywhere"};
501 raw_string_ostream
OS(Errs
);
503 EXPECT_FALSE(AllOpt
);
504 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
));
509 cl::ResetAllOptionOccurrences();
510 EXPECT_FALSE(AllOpt
);
511 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2
, StringRef(), &OS
));
516 cl::ResetAllOptionOccurrences();
517 EXPECT_FALSE(AllOpt
);
518 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3
, StringRef(), &OS
));
521 // Since all parsing succeeded, the error message should be empty.
523 EXPECT_TRUE(Errs
.empty());
526 TEST(CommandLineTest
, ReparseCommandLineOptions
) {
527 cl::ResetCommandLineParser();
529 StackOption
<bool> TopLevelOpt("top-level", cl::sub(*cl::TopLevelSubCommand
),
532 const char *args
[] = {"prog", "-top-level"};
534 EXPECT_FALSE(TopLevelOpt
);
536 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
537 EXPECT_TRUE(TopLevelOpt
);
541 cl::ResetAllOptionOccurrences();
542 EXPECT_FALSE(TopLevelOpt
);
544 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
545 EXPECT_TRUE(TopLevelOpt
);
548 TEST(CommandLineTest
, RemoveFromRegularSubCommand
) {
549 cl::ResetCommandLineParser();
551 StackSubCommand
SC("sc", "Subcommand");
552 StackOption
<bool> RemoveOption("remove-option", cl::sub(SC
), cl::init(false));
553 StackOption
<bool> KeepOption("keep-option", cl::sub(SC
), cl::init(false));
555 const char *args
[] = {"prog", "sc", "-remove-option"};
558 raw_string_ostream
OS(Errs
);
560 EXPECT_FALSE(RemoveOption
);
561 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args
, StringRef(), &OS
));
562 EXPECT_TRUE(RemoveOption
);
564 EXPECT_TRUE(Errs
.empty());
566 RemoveOption
.removeArgument();
568 cl::ResetAllOptionOccurrences();
569 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args
, StringRef(), &OS
));
571 EXPECT_FALSE(Errs
.empty());
574 TEST(CommandLineTest
, RemoveFromTopLevelSubCommand
) {
575 cl::ResetCommandLineParser();
577 StackOption
<bool> TopLevelRemove(
578 "top-level-remove", cl::sub(*cl::TopLevelSubCommand
), cl::init(false));
579 StackOption
<bool> TopLevelKeep(
580 "top-level-keep", cl::sub(*cl::TopLevelSubCommand
), cl::init(false));
582 const char *args
[] = {"prog", "-top-level-remove"};
584 EXPECT_FALSE(TopLevelRemove
);
586 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
587 EXPECT_TRUE(TopLevelRemove
);
589 TopLevelRemove
.removeArgument();
591 cl::ResetAllOptionOccurrences();
593 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
596 TEST(CommandLineTest
, RemoveFromAllSubCommands
) {
597 cl::ResetCommandLineParser();
599 StackSubCommand
SC1("sc1", "First Subcommand");
600 StackSubCommand
SC2("sc2", "Second Subcommand");
601 StackOption
<bool> RemoveOption("remove-option", cl::sub(*cl::AllSubCommands
),
603 StackOption
<bool> KeepOption("keep-option", cl::sub(*cl::AllSubCommands
),
606 const char *args0
[] = {"prog", "-remove-option"};
607 const char *args1
[] = {"prog", "sc1", "-remove-option"};
608 const char *args2
[] = {"prog", "sc2", "-remove-option"};
610 // It should work for all subcommands including the top-level.
611 EXPECT_FALSE(RemoveOption
);
613 cl::ParseCommandLineOptions(2, args0
, StringRef(), &llvm::nulls()));
614 EXPECT_TRUE(RemoveOption
);
616 RemoveOption
= false;
618 cl::ResetAllOptionOccurrences();
619 EXPECT_FALSE(RemoveOption
);
621 cl::ParseCommandLineOptions(3, args1
, StringRef(), &llvm::nulls()));
622 EXPECT_TRUE(RemoveOption
);
624 RemoveOption
= false;
626 cl::ResetAllOptionOccurrences();
627 EXPECT_FALSE(RemoveOption
);
629 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
630 EXPECT_TRUE(RemoveOption
);
632 RemoveOption
.removeArgument();
634 // It should not work for any subcommands including the top-level.
635 cl::ResetAllOptionOccurrences();
637 cl::ParseCommandLineOptions(2, args0
, StringRef(), &llvm::nulls()));
638 cl::ResetAllOptionOccurrences();
640 cl::ParseCommandLineOptions(3, args1
, StringRef(), &llvm::nulls()));
641 cl::ResetAllOptionOccurrences();
643 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
646 TEST(CommandLineTest
, GetRegisteredSubcommands
) {
647 cl::ResetCommandLineParser();
649 StackSubCommand
SC1("sc1", "First Subcommand");
650 StackOption
<bool> Opt1("opt1", cl::sub(SC1
), cl::init(false));
651 StackSubCommand
SC2("sc2", "Second subcommand");
652 StackOption
<bool> Opt2("opt2", cl::sub(SC2
), cl::init(false));
654 const char *args0
[] = {"prog", "sc1"};
655 const char *args1
[] = {"prog", "sc2"};
658 cl::ParseCommandLineOptions(2, args0
, StringRef(), &llvm::nulls()));
661 for (auto *S
: cl::getRegisteredSubcommands()) {
663 EXPECT_EQ("sc1", S
->getName());
667 cl::ResetAllOptionOccurrences();
669 cl::ParseCommandLineOptions(2, args1
, StringRef(), &llvm::nulls()));
672 for (auto *S
: cl::getRegisteredSubcommands()) {
674 EXPECT_EQ("sc2", S
->getName());
679 TEST(CommandLineTest
, DefaultOptions
) {
680 cl::ResetCommandLineParser();
682 StackOption
<std::string
> Bar("bar", cl::sub(*cl::AllSubCommands
),
684 StackOption
<std::string
, cl::alias
> Bar_Alias(
685 "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar
), cl::DefaultOption
);
687 StackOption
<bool> Foo("foo", cl::init(false), cl::sub(*cl::AllSubCommands
),
689 StackOption
<bool, cl::alias
> Foo_Alias("f", cl::desc("Alias for -foo"),
690 cl::aliasopt(Foo
), cl::DefaultOption
);
692 StackSubCommand
SC1("sc1", "First Subcommand");
693 // Override "-b" and change type in sc1 SubCommand.
694 StackOption
<bool> SC1_B("b", cl::sub(SC1
), cl::init(false));
695 StackSubCommand
SC2("sc2", "Second subcommand");
696 // Override "-foo" and change type in sc2 SubCommand. Note that this does not
697 // affect "-f" alias, which continues to work correctly.
698 StackOption
<std::string
> SC2_Foo("foo", cl::sub(SC2
));
700 const char *args0
[] = {"prog", "-b", "args0 bar string", "-f"};
701 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args0
) / sizeof(char *), args0
,
702 StringRef(), &llvm::nulls()));
703 EXPECT_TRUE(Bar
== "args0 bar string");
706 EXPECT_TRUE(SC2_Foo
.empty());
708 cl::ResetAllOptionOccurrences();
710 const char *args1
[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"};
711 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args1
) / sizeof(char *), args1
,
712 StringRef(), &llvm::nulls()));
713 EXPECT_TRUE(Bar
== "args1 bar string");
716 EXPECT_TRUE(SC2_Foo
.empty());
717 for (auto *S
: cl::getRegisteredSubcommands()) {
719 EXPECT_EQ("sc1", S
->getName());
723 cl::ResetAllOptionOccurrences();
725 const char *args2
[] = {"prog", "sc2", "-b", "args2 bar string",
726 "-f", "-foo", "foo string"};
727 EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args2
) / sizeof(char *), args2
,
728 StringRef(), &llvm::nulls()));
729 EXPECT_TRUE(Bar
== "args2 bar string");
732 EXPECT_TRUE(SC2_Foo
== "foo string");
733 for (auto *S
: cl::getRegisteredSubcommands()) {
735 EXPECT_EQ("sc2", S
->getName());
738 cl::ResetCommandLineParser();
741 TEST(CommandLineTest
, ArgumentLimit
) {
742 std::string
args(32 * 4096, 'a');
743 EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args
.data()));
746 TEST(CommandLineTest
, ResponseFileWindows
) {
747 if (!Triple(sys::getProcessTriple()).isOSWindows())
750 StackOption
<std::string
, cl::list
<std::string
>> InputFilenames(
751 cl::Positional
, cl::desc("<input files>"), cl::ZeroOrMore
);
752 StackOption
<bool> TopLevelOpt("top-level", cl::init(false));
754 // Create response file.
756 SmallString
<64> TempPath
;
758 llvm::sys::fs::createTemporaryFile("resp-", ".txt", FileDescriptor
, TempPath
);
761 std::ofstream
RspFile(TempPath
.c_str());
762 EXPECT_TRUE(RspFile
.is_open());
763 RspFile
<< "-top-level\npath\\dir\\file1\npath/dir/file2";
766 llvm::SmallString
<128> RspOpt
;
767 RspOpt
.append(1, '@');
768 RspOpt
.append(TempPath
.c_str());
769 const char *args
[] = {"prog", RspOpt
.c_str()};
770 EXPECT_FALSE(TopLevelOpt
);
772 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
773 EXPECT_TRUE(TopLevelOpt
);
774 EXPECT_TRUE(InputFilenames
[0] == "path\\dir\\file1");
775 EXPECT_TRUE(InputFilenames
[1] == "path/dir/file2");
777 llvm::sys::fs::remove(TempPath
.c_str());
780 TEST(CommandLineTest
, ResponseFiles
) {
781 llvm::SmallString
<128> TestDir
;
783 llvm::sys::fs::createUniqueDirectory("unittest", TestDir
);
786 // Create included response file of first level.
787 llvm::SmallString
<128> IncludedFileName
;
788 llvm::sys::path::append(IncludedFileName
, TestDir
, "resp1");
789 std::ofstream
IncludedFile(IncludedFileName
.c_str());
790 EXPECT_TRUE(IncludedFile
.is_open());
791 IncludedFile
<< "-option_1 -option_2\n"
794 IncludedFile
.close();
796 // Directory for included file.
797 llvm::SmallString
<128> IncDir
;
798 llvm::sys::path::append(IncDir
, TestDir
, "incdir");
799 EC
= llvm::sys::fs::create_directory(IncDir
);
802 // Create included response file of second level.
803 llvm::SmallString
<128> IncludedFileName2
;
804 llvm::sys::path::append(IncludedFileName2
, IncDir
, "resp2");
805 std::ofstream
IncludedFile2(IncludedFileName2
.c_str());
806 EXPECT_TRUE(IncludedFile2
.is_open());
807 IncludedFile2
<< "-option_21 -option_22\n";
808 IncludedFile2
<< "-option_23=abcd\n";
809 IncludedFile2
.close();
811 // Prepare 'file' with reference to response file.
812 SmallString
<128> IncRef
;
813 IncRef
.append(1, '@');
814 IncRef
.append(IncludedFileName
.c_str());
815 llvm::SmallVector
<const char *, 4> Argv
=
816 { "test/test", "-flag_1", IncRef
.c_str(), "-flag_2" };
818 // Expand response files.
819 llvm::BumpPtrAllocator A
;
820 llvm::StringSaver
Saver(A
);
821 bool Res
= llvm::cl::ExpandResponseFiles(
822 Saver
, llvm::cl::TokenizeGNUCommandLine
, Argv
, false, true);
824 EXPECT_EQ(Argv
.size(), 9U);
825 EXPECT_STREQ(Argv
[0], "test/test");
826 EXPECT_STREQ(Argv
[1], "-flag_1");
827 EXPECT_STREQ(Argv
[2], "-option_1");
828 EXPECT_STREQ(Argv
[3], "-option_2");
829 EXPECT_STREQ(Argv
[4], "-option_21");
830 EXPECT_STREQ(Argv
[5], "-option_22");
831 EXPECT_STREQ(Argv
[6], "-option_23=abcd");
832 EXPECT_STREQ(Argv
[7], "-option_3=abcd");
833 EXPECT_STREQ(Argv
[8], "-flag_2");
835 llvm::sys::fs::remove(IncludedFileName2
);
836 llvm::sys::fs::remove(IncDir
);
837 llvm::sys::fs::remove(IncludedFileName
);
838 llvm::sys::fs::remove(TestDir
);
841 TEST(CommandLineTest
, RecursiveResponseFiles
) {
842 SmallString
<128> TestDir
;
843 std::error_code EC
= sys::fs::createUniqueDirectory("unittest", TestDir
);
846 SmallString
<128> ResponseFilePath
;
847 sys::path::append(ResponseFilePath
, TestDir
, "recursive.rsp");
848 std::string ResponseFileRef
= std::string("@") + ResponseFilePath
.c_str();
850 std::ofstream
ResponseFile(ResponseFilePath
.str());
851 EXPECT_TRUE(ResponseFile
.is_open());
852 ResponseFile
<< ResponseFileRef
<< "\n";
853 ResponseFile
<< ResponseFileRef
<< "\n";
854 ResponseFile
.close();
856 // Ensure the recursive expansion terminates.
857 SmallVector
<const char *, 4> Argv
= {"test/test", ResponseFileRef
.c_str()};
859 StringSaver
Saver(A
);
861 cl::TokenizerCallback Tokenizer
= cl::TokenizeWindowsCommandLine
;
863 cl::TokenizerCallback Tokenizer
= cl::TokenizeGNUCommandLine
;
865 bool Res
= cl::ExpandResponseFiles(Saver
, Tokenizer
, Argv
, false, false);
868 // Ensure some expansion took place.
869 EXPECT_GT(Argv
.size(), 2U);
870 EXPECT_STREQ(Argv
[0], "test/test");
871 for (size_t i
= 1; i
< Argv
.size(); ++i
)
872 EXPECT_STREQ(Argv
[i
], ResponseFileRef
.c_str());
875 TEST(CommandLineTest
, ResponseFilesAtArguments
) {
876 SmallString
<128> TestDir
;
877 std::error_code EC
= sys::fs::createUniqueDirectory("unittest", TestDir
);
880 SmallString
<128> ResponseFilePath
;
881 sys::path::append(ResponseFilePath
, TestDir
, "test.rsp");
883 std::ofstream
ResponseFile(ResponseFilePath
.c_str());
884 EXPECT_TRUE(ResponseFile
.is_open());
885 ResponseFile
<< "-foo" << "\n";
886 ResponseFile
<< "-bar" << "\n";
887 ResponseFile
.close();
889 // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
890 constexpr size_t NON_RSP_AT_ARGS
= 64;
891 SmallVector
<const char *, 4> Argv
= {"test/test"};
892 Argv
.append(NON_RSP_AT_ARGS
, "@non_rsp_at_arg");
893 std::string ResponseFileRef
= std::string("@") + ResponseFilePath
.c_str();
894 Argv
.push_back(ResponseFileRef
.c_str());
897 StringSaver
Saver(A
);
898 bool Res
= cl::ExpandResponseFiles(Saver
, cl::TokenizeGNUCommandLine
, Argv
,
902 // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
903 ASSERT_EQ(Argv
.size(), 1 + NON_RSP_AT_ARGS
+ 2);
905 EXPECT_STREQ(Argv
[i
++], "test/test");
906 for (; i
< 1 + NON_RSP_AT_ARGS
; ++i
)
907 EXPECT_STREQ(Argv
[i
], "@non_rsp_at_arg");
908 EXPECT_STREQ(Argv
[i
++], "-foo");
909 EXPECT_STREQ(Argv
[i
++], "-bar");
912 TEST(CommandLineTest
, SetDefautValue
) {
913 cl::ResetCommandLineParser();
915 StackOption
<std::string
> Opt1("opt1", cl::init("true"));
916 StackOption
<bool> Opt2("opt2", cl::init(true));
917 cl::alias
Alias("alias", llvm::cl::aliasopt(Opt2
));
918 StackOption
<int> Opt3("opt3", cl::init(3));
920 const char *args
[] = {"prog", "-opt1=false", "-opt2", "-opt3"};
923 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
925 EXPECT_TRUE(Opt1
== "false");
927 EXPECT_TRUE(Opt3
== 3);
932 cl::ResetAllOptionOccurrences();
934 for (auto &OM
: cl::getRegisteredOptions(*cl::TopLevelSubCommand
)) {
935 cl::Option
*O
= OM
.second
;
936 if (O
->ArgStr
== "opt2") {
942 EXPECT_TRUE(Opt1
== "true");
944 EXPECT_TRUE(Opt3
== 3);
945 Alias
.removeArgument();
948 TEST(CommandLineTest
, ReadConfigFile
) {
949 llvm::SmallVector
<const char *, 1> Argv
;
951 llvm::SmallString
<128> TestDir
;
953 llvm::sys::fs::createUniqueDirectory("unittest", TestDir
);
956 llvm::SmallString
<128> TestCfg
;
957 llvm::sys::path::append(TestCfg
, TestDir
, "foo");
958 std::ofstream
ConfigFile(TestCfg
.c_str());
959 EXPECT_TRUE(ConfigFile
.is_open());
960 ConfigFile
<< "# Comment\n"
968 llvm::SmallString
<128> TestCfg2
;
969 llvm::sys::path::append(TestCfg2
, TestDir
, "subconfig");
970 std::ofstream
ConfigFile2(TestCfg2
.c_str());
971 EXPECT_TRUE(ConfigFile2
.is_open());
972 ConfigFile2
<< "-option_2\n"
977 // Make sure the current directory is not the directory where config files
978 // resides. In this case the code that expands response files will not find
979 // 'subconfig' unless it resolves nested inclusions relative to the including
981 llvm::SmallString
<128> CurrDir
;
982 EC
= llvm::sys::fs::current_path(CurrDir
);
984 EXPECT_TRUE(StringRef(CurrDir
) != StringRef(TestDir
));
986 llvm::BumpPtrAllocator A
;
987 llvm::StringSaver
Saver(A
);
988 bool Result
= llvm::cl::readConfigFile(TestCfg
, Saver
, Argv
);
991 EXPECT_EQ(Argv
.size(), 4U);
992 EXPECT_STREQ(Argv
[0], "-option_1");
993 EXPECT_STREQ(Argv
[1], "-option_2");
994 EXPECT_STREQ(Argv
[2], "-option_3=abcd");
995 EXPECT_STREQ(Argv
[3], "-option_4=cdef");
997 llvm::sys::fs::remove(TestCfg2
);
998 llvm::sys::fs::remove(TestCfg
);
999 llvm::sys::fs::remove(TestDir
);
1002 TEST(CommandLineTest
, PositionalEatArgsError
) {
1003 cl::ResetCommandLineParser();
1005 StackOption
<std::string
, cl::list
<std::string
>> PosEatArgs(
1006 "positional-eat-args", cl::Positional
, cl::desc("<arguments>..."),
1007 cl::ZeroOrMore
, cl::PositionalEatsArgs
);
1008 StackOption
<std::string
, cl::list
<std::string
>> PosEatArgs2(
1009 "positional-eat-args2", cl::Positional
, cl::desc("Some strings"),
1010 cl::ZeroOrMore
, cl::PositionalEatsArgs
);
1012 const char *args
[] = {"prog", "-positional-eat-args=XXXX"};
1013 const char *args2
[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1014 const char *args3
[] = {"prog", "-positional-eat-args", "-foo"};
1015 const char *args4
[] = {"prog", "-positional-eat-args",
1016 "-foo", "-positional-eat-args2",
1020 raw_string_ostream
OS(Errs
);
1021 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
)); OS
.flush();
1022 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1023 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2
, StringRef(), &OS
)); OS
.flush();
1024 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1025 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3
, StringRef(), &OS
)); OS
.flush();
1026 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1028 cl::ResetAllOptionOccurrences();
1029 EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4
, StringRef(), &OS
)); OS
.flush();
1030 EXPECT_TRUE(PosEatArgs
.size() == 1);
1031 EXPECT_TRUE(PosEatArgs2
.size() == 2);
1032 EXPECT_TRUE(Errs
.empty());
1036 TEST(CommandLineTest
, GetCommandLineArguments
) {
1038 char **argv
= __argv
;
1040 // GetCommandLineArguments is called in InitLLVM.
1041 llvm::InitLLVM
X(argc
, argv
);
1043 EXPECT_EQ(llvm::sys::path::is_absolute(argv
[0]),
1044 llvm::sys::path::is_absolute(__argv
[0]));
1046 EXPECT_TRUE(llvm::sys::path::filename(argv
[0])
1047 .equals_lower("supporttests.exe"))
1048 << "Filename of test executable is "
1049 << llvm::sys::path::filename(argv
[0]);
1053 class OutputRedirector
{
1055 OutputRedirector(int RedirectFD
)
1056 : RedirectFD(RedirectFD
), OldFD(dup(RedirectFD
)) {
1058 sys::fs::createTemporaryFile("unittest-redirect", "", NewFD
,
1060 dup2(NewFD
, RedirectFD
) == -1)
1064 ~OutputRedirector() {
1065 dup2(OldFD
, RedirectFD
);
1070 SmallVector
<char, 128> FilePath
;
1079 struct AutoDeleteFile
{
1080 SmallVector
<char, 128> FilePath
;
1082 if (!FilePath
.empty())
1083 sys::fs::remove(std::string(FilePath
.data(), FilePath
.size()));
1087 class PrintOptionInfoTest
: public ::testing::Test
{
1089 // Return std::string because the output of a failing EXPECT check is
1090 // unreadable for StringRef. It also avoids any lifetime issues.
1091 template <typename
... Ts
> std::string
runTest(Ts
... OptionAttributes
) {
1092 outs().flush(); // flush any output from previous tests
1093 AutoDeleteFile File
;
1095 OutputRedirector
Stdout(fileno(stdout
));
1098 File
.FilePath
= Stdout
.FilePath
;
1100 StackOption
<OptionValue
> TestOption(Opt
, cl::desc(HelpText
),
1101 OptionAttributes
...);
1102 printOptionInfo(TestOption
, 26);
1105 auto Buffer
= MemoryBuffer::getFile(File
.FilePath
);
1108 return Buffer
->get()->getBuffer().str();
1111 enum class OptionValue
{ Val
};
1112 const StringRef Opt
= "some-option";
1113 const StringRef HelpText
= "some help";
1116 // This is a workaround for cl::Option sub-classes having their
1117 // printOptionInfo functions private.
1118 void printOptionInfo(const cl::Option
&O
, size_t Width
) {
1119 O
.printOptionInfo(Width
);
1123 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithoutSentinel
) {
1124 std::string Output
=
1125 runTest(cl::ValueOptional
,
1126 cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1129 EXPECT_EQ(Output
, (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1135 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithSentinel
) {
1136 std::string Output
= runTest(
1137 cl::ValueOptional
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1138 clEnumValN(OptionValue::Val
, "", "")));
1142 (" --" + Opt
+ " - " + HelpText
+ "\n"
1143 " --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1149 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithSentinelWithHelp
) {
1150 std::string Output
= runTest(
1151 cl::ValueOptional
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1152 clEnumValN(OptionValue::Val
, "", "desc2")));
1155 EXPECT_EQ(Output
, (" --" + Opt
+ " - " + HelpText
+ "\n"
1156 " --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1158 " =<empty> - desc2\n")
1163 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueRequiredWithEmptyValueName
) {
1164 std::string Output
= runTest(
1165 cl::ValueRequired
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1166 clEnumValN(OptionValue::Val
, "", "")));
1169 EXPECT_EQ(Output
, (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1176 TEST_F(PrintOptionInfoTest
, PrintOptionInfoEmptyValueDescription
) {
1177 std::string Output
= runTest(
1178 cl::ValueRequired
, cl::values(clEnumValN(OptionValue::Val
, "v1", "")));
1182 (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1187 class GetOptionWidthTest
: public ::testing::Test
{
1189 enum class OptionValue
{ Val
};
1191 template <typename
... Ts
>
1192 size_t runTest(StringRef ArgName
, Ts
... OptionAttributes
) {
1193 StackOption
<OptionValue
> TestOption(ArgName
, cl::desc("some help"),
1194 OptionAttributes
...);
1195 return getOptionWidth(TestOption
);
1199 // This is a workaround for cl::Option sub-classes having their
1201 // functions private.
1202 size_t getOptionWidth(const cl::Option
&O
) { return O
.getOptionWidth(); }
1205 TEST_F(GetOptionWidthTest
, GetOptionWidthArgNameLonger
) {
1206 StringRef
ArgName("a-long-argument-name");
1207 size_t ExpectedStrSize
= (" --" + ArgName
+ "=<value> - ").str().size();
1209 runTest(ArgName
, cl::values(clEnumValN(OptionValue::Val
, "v", "help"))),
1213 TEST_F(GetOptionWidthTest
, GetOptionWidthFirstOptionNameLonger
) {
1214 StringRef
OptName("a-long-option-name");
1215 size_t ExpectedStrSize
= (" =" + OptName
+ " - ").str().size();
1217 runTest("a", cl::values(clEnumValN(OptionValue::Val
, OptName
, "help"),
1218 clEnumValN(OptionValue::Val
, "b", "help"))),
1222 TEST_F(GetOptionWidthTest
, GetOptionWidthSecondOptionNameLonger
) {
1223 StringRef
OptName("a-long-option-name");
1224 size_t ExpectedStrSize
= (" =" + OptName
+ " - ").str().size();
1226 runTest("a", cl::values(clEnumValN(OptionValue::Val
, "b", "help"),
1227 clEnumValN(OptionValue::Val
, OptName
, "help"))),
1231 TEST_F(GetOptionWidthTest
, GetOptionWidthEmptyOptionNameLonger
) {
1232 size_t ExpectedStrSize
= StringRef(" =<empty> - ").size();
1233 // The length of a=<value> (including indentation) is actually the same as the
1234 // =<empty> string, so it is impossible to distinguish via testing the case
1235 // where the empty string is picked from where the option name is picked.
1236 EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val
, "b", "help"),
1237 clEnumValN(OptionValue::Val
, "", "help"))),
1241 TEST_F(GetOptionWidthTest
,
1242 GetOptionWidthValueOptionalEmptyOptionWithNoDescription
) {
1243 StringRef
ArgName("a");
1244 // The length of a=<value> (including indentation) is actually the same as the
1245 // =<empty> string, so it is impossible to distinguish via testing the case
1246 // where the empty string is ignored from where it is not ignored.
1247 // The dash will not actually be printed, but the space it would take up is
1248 // included to ensure a consistent column width.
1249 size_t ExpectedStrSize
= (" -" + ArgName
+ "=<value> - ").str().size();
1250 EXPECT_EQ(runTest(ArgName
, cl::ValueOptional
,
1251 cl::values(clEnumValN(OptionValue::Val
, "value", "help"),
1252 clEnumValN(OptionValue::Val
, "", ""))),
1256 TEST_F(GetOptionWidthTest
,
1257 GetOptionWidthValueRequiredEmptyOptionWithNoDescription
) {
1258 // The length of a=<value> (including indentation) is actually the same as the
1259 // =<empty> string, so it is impossible to distinguish via testing the case
1260 // where the empty string is picked from where the option name is picked
1261 size_t ExpectedStrSize
= StringRef(" =<empty> - ").size();
1262 EXPECT_EQ(runTest("a", cl::ValueRequired
,
1263 cl::values(clEnumValN(OptionValue::Val
, "value", "help"),
1264 clEnumValN(OptionValue::Val
, "", ""))),
1268 TEST(CommandLineTest
, PrefixOptions
) {
1269 cl::ResetCommandLineParser();
1271 StackOption
<std::string
, cl::list
<std::string
>> IncludeDirs(
1272 "I", cl::Prefix
, cl::desc("Declare an include directory"));
1274 // Test non-prefixed variant works with cl::Prefix options.
1275 EXPECT_TRUE(IncludeDirs
.empty());
1276 const char *args
[] = {"prog", "-I=/usr/include"};
1278 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
1279 EXPECT_TRUE(IncludeDirs
.size() == 1);
1280 EXPECT_TRUE(IncludeDirs
.front().compare("/usr/include") == 0);
1282 IncludeDirs
.erase(IncludeDirs
.begin());
1283 cl::ResetAllOptionOccurrences();
1285 // Test non-prefixed variant works with cl::Prefix options when value is
1286 // passed in following argument.
1287 EXPECT_TRUE(IncludeDirs
.empty());
1288 const char *args2
[] = {"prog", "-I", "/usr/include"};
1290 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1291 EXPECT_TRUE(IncludeDirs
.size() == 1);
1292 EXPECT_TRUE(IncludeDirs
.front().compare("/usr/include") == 0);
1294 IncludeDirs
.erase(IncludeDirs
.begin());
1295 cl::ResetAllOptionOccurrences();
1297 // Test prefixed variant works with cl::Prefix options.
1298 EXPECT_TRUE(IncludeDirs
.empty());
1299 const char *args3
[] = {"prog", "-I/usr/include"};
1301 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1302 EXPECT_TRUE(IncludeDirs
.size() == 1);
1303 EXPECT_TRUE(IncludeDirs
.front().compare("/usr/include") == 0);
1305 StackOption
<std::string
, cl::list
<std::string
>> MacroDefs(
1306 "D", cl::AlwaysPrefix
, cl::desc("Define a macro"),
1307 cl::value_desc("MACRO[=VALUE]"));
1309 cl::ResetAllOptionOccurrences();
1311 // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1312 // equal sign is part of the value.
1313 EXPECT_TRUE(MacroDefs
.empty());
1314 const char *args4
[] = {"prog", "-D=HAVE_FOO"};
1316 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1317 EXPECT_TRUE(MacroDefs
.size() == 1);
1318 EXPECT_TRUE(MacroDefs
.front().compare("=HAVE_FOO") == 0);
1320 MacroDefs
.erase(MacroDefs
.begin());
1321 cl::ResetAllOptionOccurrences();
1323 // Test non-prefixed variant does not allow value to be passed in following
1324 // argument with cl::AlwaysPrefix options.
1325 EXPECT_TRUE(MacroDefs
.empty());
1326 const char *args5
[] = {"prog", "-D", "HAVE_FOO"};
1328 cl::ParseCommandLineOptions(3, args5
, StringRef(), &llvm::nulls()));
1329 EXPECT_TRUE(MacroDefs
.empty());
1331 cl::ResetAllOptionOccurrences();
1333 // Test prefixed variant works with cl::AlwaysPrefix options.
1334 EXPECT_TRUE(MacroDefs
.empty());
1335 const char *args6
[] = {"prog", "-DHAVE_FOO"};
1337 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1338 EXPECT_TRUE(MacroDefs
.size() == 1);
1339 EXPECT_TRUE(MacroDefs
.front().compare("HAVE_FOO") == 0);
1342 TEST(CommandLineTest
, GroupingWithValue
) {
1343 cl::ResetCommandLineParser();
1345 StackOption
<bool> OptF("f", cl::Grouping
, cl::desc("Some flag"));
1346 StackOption
<bool> OptB("b", cl::Grouping
, cl::desc("Another flag"));
1347 StackOption
<bool> OptD("d", cl::Grouping
, cl::ValueDisallowed
,
1348 cl::desc("ValueDisallowed option"));
1349 StackOption
<std::string
> OptV("v", cl::Grouping
,
1350 cl::desc("ValueRequired option"));
1351 StackOption
<std::string
> OptO("o", cl::Grouping
, cl::ValueOptional
,
1352 cl::desc("ValueOptional option"));
1354 // Should be possible to use an option which requires a value
1355 // at the end of a group.
1356 const char *args1
[] = {"prog", "-fv", "val1"};
1358 cl::ParseCommandLineOptions(3, args1
, StringRef(), &llvm::nulls()));
1360 EXPECT_STREQ("val1", OptV
.c_str());
1362 cl::ResetAllOptionOccurrences();
1364 // Should not crash if it is accidentally used elsewhere in the group.
1365 const char *args2
[] = {"prog", "-vf", "val2"};
1367 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1369 cl::ResetAllOptionOccurrences();
1371 // Should allow the "opt=value" form at the end of the group
1372 const char *args3
[] = {"prog", "-fv=val3"};
1374 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1376 EXPECT_STREQ("val3", OptV
.c_str());
1378 cl::ResetAllOptionOccurrences();
1380 // Should allow assigning a value for a ValueOptional option
1381 // at the end of the group
1382 const char *args4
[] = {"prog", "-fo=val4"};
1384 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1386 EXPECT_STREQ("val4", OptO
.c_str());
1388 cl::ResetAllOptionOccurrences();
1390 // Should assign an empty value if a ValueOptional option is used elsewhere
1392 const char *args5
[] = {"prog", "-fob"};
1394 cl::ParseCommandLineOptions(2, args5
, StringRef(), &llvm::nulls()));
1396 EXPECT_EQ(1, OptO
.getNumOccurrences());
1397 EXPECT_EQ(1, OptB
.getNumOccurrences());
1398 EXPECT_TRUE(OptO
.empty());
1399 cl::ResetAllOptionOccurrences();
1401 // Should not allow an assignment for a ValueDisallowed option.
1402 const char *args6
[] = {"prog", "-fd=false"};
1404 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1407 TEST(CommandLineTest
, GroupingAndPrefix
) {
1408 cl::ResetCommandLineParser();
1410 StackOption
<bool> OptF("f", cl::Grouping
, cl::desc("Some flag"));
1411 StackOption
<bool> OptB("b", cl::Grouping
, cl::desc("Another flag"));
1412 StackOption
<std::string
> OptP("p", cl::Prefix
, cl::Grouping
,
1413 cl::desc("Prefix and Grouping"));
1414 StackOption
<std::string
> OptA("a", cl::AlwaysPrefix
, cl::Grouping
,
1415 cl::desc("AlwaysPrefix and Grouping"));
1417 // Should be possible to use a cl::Prefix option without grouping.
1418 const char *args1
[] = {"prog", "-pval1"};
1420 cl::ParseCommandLineOptions(2, args1
, StringRef(), &llvm::nulls()));
1421 EXPECT_STREQ("val1", OptP
.c_str());
1423 cl::ResetAllOptionOccurrences();
1425 // Should be possible to pass a value in a separate argument.
1426 const char *args2
[] = {"prog", "-p", "val2"};
1428 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1429 EXPECT_STREQ("val2", OptP
.c_str());
1431 cl::ResetAllOptionOccurrences();
1433 // The "-opt=value" form should work, too.
1434 const char *args3
[] = {"prog", "-p=val3"};
1436 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1437 EXPECT_STREQ("val3", OptP
.c_str());
1439 cl::ResetAllOptionOccurrences();
1441 // All three previous cases should work the same way if an option with both
1442 // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1443 const char *args4
[] = {"prog", "-fpval4"};
1445 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1447 EXPECT_STREQ("val4", OptP
.c_str());
1449 cl::ResetAllOptionOccurrences();
1451 const char *args5
[] = {"prog", "-fp", "val5"};
1453 cl::ParseCommandLineOptions(3, args5
, StringRef(), &llvm::nulls()));
1455 EXPECT_STREQ("val5", OptP
.c_str());
1457 cl::ResetAllOptionOccurrences();
1459 const char *args6
[] = {"prog", "-fp=val6"};
1461 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1463 EXPECT_STREQ("val6", OptP
.c_str());
1465 cl::ResetAllOptionOccurrences();
1467 // Should assign a value even if the part after a cl::Prefix option is equal
1468 // to the name of another option.
1469 const char *args7
[] = {"prog", "-fpb"};
1471 cl::ParseCommandLineOptions(2, args7
, StringRef(), &llvm::nulls()));
1473 EXPECT_STREQ("b", OptP
.c_str());
1476 cl::ResetAllOptionOccurrences();
1478 // Should be possible to use a cl::AlwaysPrefix option without grouping.
1479 const char *args8
[] = {"prog", "-aval8"};
1481 cl::ParseCommandLineOptions(2, args8
, StringRef(), &llvm::nulls()));
1482 EXPECT_STREQ("val8", OptA
.c_str());
1484 cl::ResetAllOptionOccurrences();
1486 // Should not be possible to pass a value in a separate argument.
1487 const char *args9
[] = {"prog", "-a", "val9"};
1489 cl::ParseCommandLineOptions(3, args9
, StringRef(), &llvm::nulls()));
1490 cl::ResetAllOptionOccurrences();
1492 // With the "-opt=value" form, the "=" symbol should be preserved.
1493 const char *args10
[] = {"prog", "-a=val10"};
1495 cl::ParseCommandLineOptions(2, args10
, StringRef(), &llvm::nulls()));
1496 EXPECT_STREQ("=val10", OptA
.c_str());
1498 cl::ResetAllOptionOccurrences();
1500 // All three previous cases should work the same way if an option with both
1501 // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1502 const char *args11
[] = {"prog", "-faval11"};
1504 cl::ParseCommandLineOptions(2, args11
, StringRef(), &llvm::nulls()));
1506 EXPECT_STREQ("val11", OptA
.c_str());
1508 cl::ResetAllOptionOccurrences();
1510 const char *args12
[] = {"prog", "-fa", "val12"};
1512 cl::ParseCommandLineOptions(3, args12
, StringRef(), &llvm::nulls()));
1513 cl::ResetAllOptionOccurrences();
1515 const char *args13
[] = {"prog", "-fa=val13"};
1517 cl::ParseCommandLineOptions(2, args13
, StringRef(), &llvm::nulls()));
1519 EXPECT_STREQ("=val13", OptA
.c_str());
1521 cl::ResetAllOptionOccurrences();
1523 // Should assign a value even if the part after a cl::AlwaysPrefix option
1524 // is equal to the name of another option.
1525 const char *args14
[] = {"prog", "-fab"};
1527 cl::ParseCommandLineOptions(2, args14
, StringRef(), &llvm::nulls()));
1529 EXPECT_STREQ("b", OptA
.c_str());
1532 cl::ResetAllOptionOccurrences();
1535 TEST(CommandLineTest
, LongOptions
) {
1536 cl::ResetCommandLineParser();
1538 StackOption
<bool> OptA("a", cl::desc("Some flag"));
1539 StackOption
<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1540 StackOption
<bool, cl::alias
> OptB("b", cl::desc("Alias to --long-flag"),
1541 cl::aliasopt(OptBLong
));
1542 StackOption
<std::string
> OptAB("ab", cl::desc("Another long option"));
1545 raw_string_ostream
OS(Errs
);
1547 const char *args1
[] = {"prog", "-a", "-ab", "val1"};
1548 const char *args2
[] = {"prog", "-a", "--ab", "val1"};
1549 const char *args3
[] = {"prog", "-ab", "--ab", "val1"};
1552 // The following tests treat `-` and `--` the same, and always match the
1557 cl::ParseCommandLineOptions(4, args1
, StringRef(), &OS
)); OS
.flush();
1559 EXPECT_FALSE(OptBLong
);
1560 EXPECT_STREQ("val1", OptAB
.c_str());
1561 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1562 cl::ResetAllOptionOccurrences();
1565 cl::ParseCommandLineOptions(4, args2
, StringRef(), &OS
)); OS
.flush();
1567 EXPECT_FALSE(OptBLong
);
1568 EXPECT_STREQ("val1", OptAB
.c_str());
1569 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1570 cl::ResetAllOptionOccurrences();
1572 // Fails because `-ab` and `--ab` are treated the same and appear more than
1573 // once. Also, `val1` is unexpected.
1575 cl::ParseCommandLineOptions(4, args3
, StringRef(), &OS
)); OS
.flush();
1576 outs()<< Errs
<< "\n";
1577 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1578 cl::ResetAllOptionOccurrences();
1581 // The following tests treat `-` and `--` differently, with `-` for short, and
1582 // `--` for long options.
1585 // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1586 // `val1` is unexpected.
1587 EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1
, StringRef(),
1588 &OS
, nullptr, true)); OS
.flush();
1589 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1590 cl::ResetAllOptionOccurrences();
1592 // Works because `-a` is treated differently than `--ab`.
1593 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2
, StringRef(),
1594 &OS
, nullptr, true)); OS
.flush();
1595 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1596 cl::ResetAllOptionOccurrences();
1598 // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1599 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3
, StringRef(),
1600 &OS
, nullptr, true));
1602 EXPECT_TRUE(OptBLong
);
1603 EXPECT_STREQ("val1", OptAB
.c_str());
1605 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1606 cl::ResetAllOptionOccurrences();
1608 } // anonymous namespace