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));
523 EXPECT_FALSE(Errs.empty());
526 TEST(CommandLineTest, TopLevelOptInSubcommand) {
527 enum LiteralOptionEnum {
533 cl::ResetCommandLineParser();
535 // This is a top-level option and not associated with a subcommand.
536 // A command line using subcommand should parse both subcommand options and
537 // top-level options. A valid use case is that users of llvm command line
538 // tools should be able to specify top-level options defined in any library.
539 StackOption<std::string> TopLevelOpt("str
", cl::init("txt
"),
540 cl::desc("A top
-level option
."));
542 StackSubCommand SC("sc
", "Subcommand
");
543 StackOption<std::string> PositionalOpt(
544 cl::Positional, cl::desc("positional argument test coverage
"),
546 StackOption<LiteralOptionEnum> LiteralOpt(
547 cl::desc("literal argument test coverage
"), cl::sub(SC), cl::init(bar),
548 cl::values(clEnumVal(foo, "foo
"), clEnumVal(bar, "bar
"),
549 clEnumVal(baz, "baz
")));
550 StackOption<bool> EnableOpt("enable
", cl::sub(SC), cl::init(false));
551 StackOption<int> ThresholdOpt("threshold
", cl::sub(SC), cl::init(1));
553 const char *PositionalOptVal = "input
-file
";
554 const char *args[] = {"prog
", "sc
", PositionalOptVal,
555 "-enable
", "--str
=csv
", "--threshold
=2"};
557 // cl::ParseCommandLineOptions returns true on success. Otherwise, it will
558 // print the error message to stderr and exit in this setting (`Errs` ostream
560 ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]), args,
562 EXPECT_STREQ(PositionalOpt.getValue().c_str(), PositionalOptVal);
563 EXPECT_TRUE(EnableOpt);
564 // Tests that the value of `str` option is `csv` as specified.
565 EXPECT_STREQ(TopLevelOpt.getValue().c_str(), "csv
");
566 EXPECT_EQ(ThresholdOpt, 2);
568 for (auto &[LiteralOptVal, WantLiteralOpt] :
569 {std::pair{"--bar
", bar}, {"--foo
", foo}, {"--baz
", baz}}) {
570 const char *args[] = {"prog
", "sc
", LiteralOptVal};
571 ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]),
574 // Tests that literal options are parsed correctly.
575 EXPECT_EQ(LiteralOpt, WantLiteralOpt);
579 TEST(CommandLineTest, AddToAllSubCommands) {
580 cl::ResetCommandLineParser();
582 StackSubCommand SC1("sc1
", "First subcommand
");
583 StackOption<bool> AllOpt("everywhere
", cl::sub(cl::SubCommand::getAll()),
585 StackSubCommand SC2("sc2
", "Second subcommand
");
587 EXPECT_TRUE(cl::SubCommand::getTopLevel().OptionsMap.contains("everywhere
"));
588 EXPECT_TRUE(cl::SubCommand::getAll().OptionsMap.contains("everywhere
"));
589 EXPECT_TRUE(SC1.OptionsMap.contains("everywhere
"));
590 EXPECT_TRUE(SC2.OptionsMap.contains("everywhere
"));
592 const char *args[] = {"prog
", "-everywhere
"};
593 const char *args2[] = {"prog
", "sc1
", "-everywhere
"};
594 const char *args3[] = {"prog
", "sc2
", "-everywhere
"};
597 raw_string_ostream OS(Errs);
599 EXPECT_FALSE(AllOpt);
600 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
605 cl::ResetAllOptionOccurrences();
606 EXPECT_FALSE(AllOpt);
607 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS));
612 cl::ResetAllOptionOccurrences();
613 EXPECT_FALSE(AllOpt);
614 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS));
617 // Since all parsing succeeded, the error message should be empty.
618 EXPECT_TRUE(Errs.empty());
621 TEST(CommandLineTest, ReparseCommandLineOptions) {
622 cl::ResetCommandLineParser();
624 StackOption<bool> TopLevelOpt(
625 "top
-level
", cl::sub(cl::SubCommand::getTopLevel()), cl::init(false));
627 const char *args[] = {"prog
", "-top
-level
"};
629 EXPECT_FALSE(TopLevelOpt);
631 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
632 EXPECT_TRUE(TopLevelOpt);
636 cl::ResetAllOptionOccurrences();
637 EXPECT_FALSE(TopLevelOpt);
639 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
640 EXPECT_TRUE(TopLevelOpt);
643 TEST(CommandLineTest, RemoveFromRegularSubCommand) {
644 cl::ResetCommandLineParser();
646 StackSubCommand SC("sc
", "Subcommand
");
647 StackOption<bool> RemoveOption("remove
-option
", cl::sub(SC), cl::init(false));
648 StackOption<bool> KeepOption("keep
-option
", cl::sub(SC), cl::init(false));
650 const char *args[] = {"prog
", "sc
", "-remove
-option
"};
653 raw_string_ostream OS(Errs);
655 EXPECT_FALSE(RemoveOption);
656 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
657 EXPECT_TRUE(RemoveOption);
658 EXPECT_TRUE(Errs.empty());
660 RemoveOption.removeArgument();
662 cl::ResetAllOptionOccurrences();
663 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
664 EXPECT_FALSE(Errs.empty());
667 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
668 cl::ResetCommandLineParser();
670 StackOption<bool> TopLevelRemove("top
-level
-remove
",
671 cl::sub(cl::SubCommand::getTopLevel()),
673 StackOption<bool> TopLevelKeep("top
-level
-keep
",
674 cl::sub(cl::SubCommand::getTopLevel()),
677 const char *args[] = {"prog
", "-top
-level
-remove
"};
679 EXPECT_FALSE(TopLevelRemove);
681 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
682 EXPECT_TRUE(TopLevelRemove);
684 TopLevelRemove.removeArgument();
686 cl::ResetAllOptionOccurrences();
688 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
691 TEST(CommandLineTest, RemoveFromAllSubCommands) {
692 cl::ResetCommandLineParser();
694 StackSubCommand SC1("sc1
", "First Subcommand
");
695 StackSubCommand SC2("sc2
", "Second Subcommand
");
696 StackOption<bool> RemoveOption(
697 "remove
-option
", cl::sub(cl::SubCommand::getAll()), cl::init(false));
698 StackOption<bool> KeepOption("keep
-option
", cl::sub(cl::SubCommand::getAll()),
701 const char *args0[] = {"prog
", "-remove
-option
"};
702 const char *args1[] = {"prog
", "sc1
", "-remove
-option
"};
703 const char *args2[] = {"prog
", "sc2
", "-remove
-option
"};
705 // It should work for all subcommands including the top-level.
706 EXPECT_FALSE(RemoveOption);
708 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
709 EXPECT_TRUE(RemoveOption);
711 RemoveOption = false;
713 cl::ResetAllOptionOccurrences();
714 EXPECT_FALSE(RemoveOption);
716 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
717 EXPECT_TRUE(RemoveOption);
719 RemoveOption = false;
721 cl::ResetAllOptionOccurrences();
722 EXPECT_FALSE(RemoveOption);
724 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
725 EXPECT_TRUE(RemoveOption);
727 RemoveOption.removeArgument();
729 // It should not work for any subcommands including the top-level.
730 cl::ResetAllOptionOccurrences();
732 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
733 cl::ResetAllOptionOccurrences();
735 cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
736 cl::ResetAllOptionOccurrences();
738 cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
741 TEST(CommandLineTest, GetRegisteredSubcommands) {
742 cl::ResetCommandLineParser();
744 StackSubCommand SC1("sc1
", "First Subcommand
");
745 StackOption<bool> Opt1("opt1
", cl::sub(SC1), cl::init(false));
746 StackSubCommand SC2("sc2
", "Second subcommand
");
747 StackOption<bool> Opt2("opt2
", cl::sub(SC2), cl::init(false));
749 const char *args0[] = {"prog
", "sc1
"};
750 const char *args1[] = {"prog
", "sc2
"};
753 cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
756 for (auto *S : cl::getRegisteredSubcommands()) {
758 EXPECT_EQ("sc1
", S->getName());
762 cl::ResetAllOptionOccurrences();
764 cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
767 for (auto *S : cl::getRegisteredSubcommands()) {
769 EXPECT_EQ("sc2
", S->getName());
774 TEST(CommandLineTest, DefaultOptions) {
775 cl::ResetCommandLineParser();
777 StackOption<std::string> Bar("bar
", cl::sub(cl::SubCommand::getAll()),
779 StackOption<std::string, cl::alias> Bar_Alias(
780 "b
", cl::desc("Alias
for -bar
"), cl::aliasopt(Bar), cl::DefaultOption);
782 StackOption<bool> Foo("foo
", cl::init(false),
783 cl::sub(cl::SubCommand::getAll()), cl::DefaultOption);
784 StackOption<bool, cl::alias> Foo_Alias("f
", cl::desc("Alias
for -foo
"),
785 cl::aliasopt(Foo), cl::DefaultOption);
787 StackSubCommand SC1("sc1
", "First Subcommand
");
788 // Override "-b
" and change type in sc1 SubCommand.
789 StackOption<bool> SC1_B("b
", cl::sub(SC1), cl::init(false));
790 StackSubCommand SC2("sc2
", "Second subcommand
");
791 // Override "-foo
" and change type in sc2 SubCommand. Note that this does not
792 // affect "-f
" alias, which continues to work correctly.
793 StackOption<std::string> SC2_Foo("foo
", cl::sub(SC2));
795 const char *args0[] = {"prog
", "-b
", "args0 bar string
", "-f
"};
796 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args0), args0,
797 StringRef(), &llvm::nulls()));
798 EXPECT_EQ(Bar, "args0 bar string
");
801 EXPECT_TRUE(SC2_Foo.empty());
803 cl::ResetAllOptionOccurrences();
805 const char *args1[] = {"prog
", "sc1
", "-b
", "-bar
", "args1 bar string
", "-f
"};
806 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args1), args1,
807 StringRef(), &llvm::nulls()));
808 EXPECT_EQ(Bar, "args1 bar string
");
811 EXPECT_TRUE(SC2_Foo.empty());
812 for (auto *S : cl::getRegisteredSubcommands()) {
814 EXPECT_EQ("sc1
", S->getName());
818 cl::ResetAllOptionOccurrences();
820 const char *args2[] = {"prog
", "sc2
", "-b
", "args2 bar string
",
821 "-f
", "-foo
", "foo string
"};
822 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args2), args2,
823 StringRef(), &llvm::nulls()));
824 EXPECT_EQ(Bar, "args2 bar string
");
827 EXPECT_EQ(SC2_Foo, "foo string
");
828 for (auto *S : cl::getRegisteredSubcommands()) {
830 EXPECT_EQ("sc2
", S->getName());
833 cl::ResetCommandLineParser();
836 TEST(CommandLineTest, ArgumentLimit) {
837 std::string args(32 * 4096, 'a');
838 EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl
", args.data()));
839 std::string args2(256, 'a');
840 EXPECT_TRUE(llvm::sys::commandLineFitsWithinSystemLimits("cl
", args2.data()));
843 TEST(CommandLineTest, ArgumentLimitWindows) {
844 if (!Triple(sys::getProcessTriple()).isOSWindows())
846 // We use 32000 as a limit for command line length. Program name ('cl'),
847 // separating spaces and termination null character occupy 5 symbols.
848 std::string long_arg(32000 - 5, 'b');
850 llvm::sys::commandLineFitsWithinSystemLimits("cl
", long_arg.data()));
853 llvm::sys::commandLineFitsWithinSystemLimits("cl
", long_arg.data()));
856 TEST(CommandLineTest, ResponseFileWindows) {
857 if (!Triple(sys::getProcessTriple()).isOSWindows())
860 StackOption<std::string, cl::list<std::string>> InputFilenames(
861 cl::Positional, cl::desc("<input files
>"));
862 StackOption<bool> TopLevelOpt("top
-level
", cl::init(false));
864 // Create response file.
865 TempFile ResponseFile("resp
-", ".txt
",
866 "-top
-level
\npath
\\dir
\\file1
\npath
/dir
/file2
",
869 llvm::SmallString<128> RspOpt;
870 RspOpt.append(1, '@');
871 RspOpt.append(ResponseFile.path());
872 const char *args[] = {"prog
", RspOpt.c_str()};
873 EXPECT_FALSE(TopLevelOpt);
875 cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
876 EXPECT_TRUE(TopLevelOpt);
877 EXPECT_EQ(InputFilenames[0], "path
\\dir
\\file1
");
878 EXPECT_EQ(InputFilenames[1], "path
/dir
/file2
");
881 TEST(CommandLineTest, ResponseFiles) {
882 vfs::InMemoryFileSystem FS;
884 const char *TestRoot = "C
:\\";
886 const char *TestRoot = "/";
888 FS.setCurrentWorkingDirectory(TestRoot);
890 // Create included response file of first level.
891 llvm::StringRef IncludedFileName = "resp1
";
892 FS.addFile(IncludedFileName, 0,
893 llvm::MemoryBuffer::getMemBuffer("-option_1
-option_2
\n"
897 "-option_4
=efjk
\n"));
899 // Directory for included file.
900 llvm::StringRef IncDir = "incdir
";
902 // Create included response file of second level.
903 llvm::SmallString<128> IncludedFileName2;
904 llvm::sys::path::append(IncludedFileName2, IncDir, "resp2
");
905 FS.addFile(IncludedFileName2, 0,
906 MemoryBuffer::getMemBuffer("-option_21
-option_22
\n"
907 "-option_23
=abcd
\n"));
909 // Create second included response file of second level.
910 llvm::SmallString<128> IncludedFileName3;
911 llvm::sys::path::append(IncludedFileName3, IncDir, "resp3
");
912 FS.addFile(IncludedFileName3, 0,
913 MemoryBuffer::getMemBuffer("-option_31
-option_32
\n"
914 "-option_33
=abcd
\n"));
916 // Prepare 'file' with reference to response file.
917 SmallString<128> IncRef;
918 IncRef.append(1, '@');
919 IncRef.append(IncludedFileName);
920 llvm::SmallVector<const char *, 4> Argv = {"test
/test
", "-flag_1
",
921 IncRef.c_str(), "-flag_2
"};
923 // Expand response files.
924 llvm::BumpPtrAllocator A;
925 llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine);
926 ECtx.setVFS(&FS).setCurrentDir(TestRoot).setRelativeNames(true);
927 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
928 EXPECT_THAT(Argv, testing::Pointwise(
930 {"test
/test
", "-flag_1
", "-option_1
", "-option_2
",
931 "-option_21
", "-option_22
", "-option_23
=abcd
",
932 "-option_3
=abcd
", "-option_31
", "-option_32
",
933 "-option_33
=abcd
", "-option_4
=efjk
", "-flag_2
"}));
936 TEST(CommandLineTest, RecursiveResponseFiles) {
937 vfs::InMemoryFileSystem FS;
939 const char *TestRoot = "C
:\\";
941 const char *TestRoot = "/";
943 FS.setCurrentWorkingDirectory(TestRoot);
945 StringRef SelfFilePath = "self
.rsp
";
946 std::string SelfFileRef = ("@
" + SelfFilePath).str();
948 StringRef NestedFilePath = "nested
.rsp
";
949 std::string NestedFileRef = ("@
" + NestedFilePath).str();
951 StringRef FlagFilePath = "flag
.rsp
";
952 std::string FlagFileRef = ("@
" + FlagFilePath).str();
954 std::string SelfFileContents;
955 raw_string_ostream SelfFile(SelfFileContents);
956 SelfFile << "-option_1
\n";
957 SelfFile << FlagFileRef << "\n";
958 SelfFile << NestedFileRef << "\n";
959 SelfFile << SelfFileRef << "\n";
960 FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str()));
962 std::string NestedFileContents;
963 raw_string_ostream NestedFile(NestedFileContents);
964 NestedFile << "-option_2
\n";
965 NestedFile << FlagFileRef << "\n";
966 NestedFile << SelfFileRef << "\n";
967 NestedFile << NestedFileRef << "\n";
968 FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str()));
970 std::string FlagFileContents;
971 raw_string_ostream FlagFile(FlagFileContents);
972 FlagFile << "-option_x
\n";
973 FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str()));
976 // Recursive expansion terminates
977 // Recursive files never expand
978 // Non-recursive repeats are allowed
979 SmallVector<const char *, 4> Argv = {"test
/test
", SelfFileRef.c_str(),
983 cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine;
985 cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
987 llvm::cl::ExpansionContext ECtx(A, Tokenizer);
988 ECtx.setVFS(&FS).setCurrentDir(TestRoot);
989 llvm::Error Err = ECtx.expandResponseFiles(Argv);
990 ASSERT_TRUE((bool)Err);
991 SmallString<128> FilePath = SelfFilePath;
992 std::error_code EC = FS.makeAbsolute(FilePath);
993 ASSERT_FALSE((bool)EC);
994 std::string ExpectedMessage =
995 std::string("recursive expansion of
: '") + std::string(FilePath) + "'";
996 ASSERT_TRUE(toString(std::move(Err)) == ExpectedMessage);
999 testing::Pointwise(StringEquality(),
1000 {"test
/test
", "-option_1
", "-option_x
",
1001 "-option_2
", "-option_x
", SelfFileRef.c_str(),
1002 NestedFileRef.c_str(), SelfFileRef.c_str(),
1006 TEST(CommandLineTest, ResponseFilesAtArguments) {
1007 vfs::InMemoryFileSystem FS;
1009 const char *TestRoot = "C
:\\";
1011 const char *TestRoot = "/";
1013 FS.setCurrentWorkingDirectory(TestRoot);
1015 StringRef ResponseFilePath = "test
.rsp
";
1017 std::string ResponseFileContents;
1018 raw_string_ostream ResponseFile(ResponseFileContents);
1019 ResponseFile << "-foo
" << "\n";
1020 ResponseFile << "-bar
" << "\n";
1021 FS.addFile(ResponseFilePath, 0,
1022 MemoryBuffer::getMemBuffer(ResponseFile.str()));
1024 // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
1025 constexpr size_t NON_RSP_AT_ARGS = 64;
1026 SmallVector<const char *, 4> Argv = {"test
/test
"};
1027 Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg
");
1028 std::string ResponseFileRef = ("@
" + ResponseFilePath).str();
1029 Argv.push_back(ResponseFileRef.c_str());
1032 llvm::cl::ExpansionContext ECtx(A, cl::TokenizeGNUCommandLine);
1033 ECtx.setVFS(&FS).setCurrentDir(TestRoot);
1034 ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
1036 // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
1037 ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2);
1039 EXPECT_STREQ(Argv[i++], "test
/test
");
1040 for (; i < 1 + NON_RSP_AT_ARGS; ++i)
1041 EXPECT_STREQ(Argv[i], "@non_rsp_at_arg
");
1042 EXPECT_STREQ(Argv[i++], "-foo
");
1043 EXPECT_STREQ(Argv[i++], "-bar
");
1046 TEST(CommandLineTest, ResponseFileRelativePath) {
1047 vfs::InMemoryFileSystem FS;
1049 const char *TestRoot = "C
:\\";
1051 const char *TestRoot = "//net";
1053 FS
.setCurrentWorkingDirectory(TestRoot
);
1055 StringRef OuterFile
= "dir/outer.rsp";
1056 StringRef OuterFileContents
= "@inner.rsp";
1057 FS
.addFile(OuterFile
, 0, MemoryBuffer::getMemBuffer(OuterFileContents
));
1059 StringRef InnerFile
= "dir/inner.rsp";
1060 StringRef InnerFileContents
= "-flag";
1061 FS
.addFile(InnerFile
, 0, MemoryBuffer::getMemBuffer(InnerFileContents
));
1063 SmallVector
<const char *, 2> Argv
= {"test/test", "@dir/outer.rsp"};
1066 llvm::cl::ExpansionContext
ECtx(A
, cl::TokenizeGNUCommandLine
);
1067 ECtx
.setVFS(&FS
).setCurrentDir(TestRoot
).setRelativeNames(true);
1068 ASSERT_FALSE((bool)ECtx
.expandResponseFiles(Argv
));
1070 testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
1073 TEST(CommandLineTest
, ResponseFileEOLs
) {
1074 vfs::InMemoryFileSystem FS
;
1076 const char *TestRoot
= "C:\\";
1078 const char *TestRoot
= "//net";
1080 FS
.setCurrentWorkingDirectory(TestRoot
);
1081 FS
.addFile("eols.rsp", 0,
1082 MemoryBuffer::getMemBuffer("-Xclang -Wno-whatever\n input.cpp"));
1083 SmallVector
<const char *, 2> Argv
= {"clang", "@eols.rsp"};
1085 llvm::cl::ExpansionContext
ECtx(A
, cl::TokenizeWindowsCommandLine
);
1086 ECtx
.setVFS(&FS
).setCurrentDir(TestRoot
).setMarkEOLs(true).setRelativeNames(
1088 ASSERT_FALSE((bool)ECtx
.expandResponseFiles(Argv
));
1089 const char *Expected
[] = {"clang", "-Xclang", "-Wno-whatever", nullptr,
1091 ASSERT_EQ(std::size(Expected
), Argv
.size());
1092 for (size_t I
= 0, E
= std::size(Expected
); I
< E
; ++I
) {
1093 if (Expected
[I
] == nullptr) {
1094 ASSERT_EQ(Argv
[I
], nullptr);
1096 ASSERT_STREQ(Expected
[I
], Argv
[I
]);
1101 TEST(CommandLineTest
, BadResponseFile
) {
1103 StringSaver
Saver(A
);
1104 TempDir
ADir("dir", /*Unique*/ true);
1105 SmallString
<128> AFilePath
= ADir
.path();
1106 llvm::sys::path::append(AFilePath
, "file.rsp");
1107 std::string AFileExp
= std::string("@") + std::string(AFilePath
.str());
1108 SmallVector
<const char *, 2> Argv
= {"clang", AFileExp
.c_str()};
1110 bool Res
= cl::ExpandResponseFiles(Saver
, cl::TokenizeGNUCommandLine
, Argv
);
1112 ASSERT_EQ(2U, Argv
.size());
1113 ASSERT_STREQ(Argv
[0], "clang");
1114 ASSERT_STREQ(Argv
[1], AFileExp
.c_str());
1116 std::string ADirExp
= std::string("@") + std::string(ADir
.path());
1117 Argv
= {"clang", ADirExp
.c_str()};
1118 Res
= cl::ExpandResponseFiles(Saver
, cl::TokenizeGNUCommandLine
, Argv
);
1120 ASSERT_EQ(2U, Argv
.size());
1121 ASSERT_STREQ(Argv
[0], "clang");
1122 ASSERT_STREQ(Argv
[1], ADirExp
.c_str());
1125 TEST(CommandLineTest
, SetDefaultValue
) {
1126 cl::ResetCommandLineParser();
1128 StackOption
<std::string
> Opt1("opt1", cl::init("true"));
1129 StackOption
<bool> Opt2("opt2", cl::init(true));
1130 cl::alias
Alias("alias", llvm::cl::aliasopt(Opt2
));
1131 StackOption
<int> Opt3("opt3", cl::init(3));
1133 llvm::SmallVector
<int, 3> IntVals
= {1, 2, 3};
1134 llvm::SmallVector
<std::string
, 3> StrVals
= {"foo", "bar", "baz"};
1136 StackOption
<int, cl::list
<int>> List1(
1137 "list1", cl::list_init
<int>(llvm::ArrayRef
<int>(IntVals
)),
1138 cl::CommaSeparated
);
1139 StackOption
<std::string
, cl::list
<std::string
>> List2(
1140 "list2", cl::list_init
<std::string
>(llvm::ArrayRef
<std::string
>(StrVals
)),
1141 cl::CommaSeparated
);
1142 cl::alias
ListAlias("list-alias", llvm::cl::aliasopt(List2
));
1144 const char *args
[] = {"prog", "-opt1=false", "-list1", "4",
1145 "-list1", "5,6", "-opt2", "-opt3"};
1148 cl::ParseCommandLineOptions(7, args
, StringRef(), &llvm::nulls()));
1150 EXPECT_EQ(Opt1
, "false");
1154 for (size_t I
= 0, E
= IntVals
.size(); I
< E
; ++I
) {
1155 EXPECT_EQ(IntVals
[I
] + 3, List1
[I
]);
1156 EXPECT_EQ(StrVals
[I
], List2
[I
]);
1162 cl::ResetAllOptionOccurrences();
1164 for (auto &OM
: cl::getRegisteredOptions(cl::SubCommand::getTopLevel())) {
1165 cl::Option
*O
= OM
.second
;
1166 if (O
->ArgStr
== "opt2") {
1172 EXPECT_EQ(Opt1
, "true");
1175 for (size_t I
= 0, E
= IntVals
.size(); I
< E
; ++I
) {
1176 EXPECT_EQ(IntVals
[I
], List1
[I
]);
1177 EXPECT_EQ(StrVals
[I
], List2
[I
]);
1180 Alias
.removeArgument();
1181 ListAlias
.removeArgument();
1184 TEST(CommandLineTest
, ReadConfigFile
) {
1185 llvm::SmallVector
<const char *, 1> Argv
;
1187 TempDir
TestDir("unittest", /*Unique*/ true);
1188 TempDir
TestSubDir(TestDir
.path("subdir"), /*Unique*/ false);
1190 llvm::SmallString
<128> TestCfg
= TestDir
.path("foo");
1191 TempFile
ConfigFile(TestCfg
, "",
1194 "-option_2=<CFGDIR>/dir1\n"
1195 "-option_3=<CFGDIR>\n"
1196 "-option_4 <CFGDIR>\n"
1197 "-option_5=<CFG\\\n"
1199 "-option_6=<CFGDIR>/dir1,<CFGDIR>/dir2\n"
1205 llvm::SmallString
<128> TestCfg2
= TestDir
.path("subconfig");
1206 TempFile
ConfigFile2(TestCfg2
, "",
1208 "-option_8=<CFGDIR>/dir2\n"
1213 llvm::SmallString
<128> TestCfg3
= TestSubDir
.path("subfoo");
1214 TempFile
ConfigFile3(TestCfg3
, "",
1215 "-option_9=<CFGDIR>/dir3\n"
1216 "@<CFGDIR>/subfoo2\n");
1218 llvm::SmallString
<128> TestCfg4
= TestSubDir
.path("subfoo2");
1219 TempFile
ConfigFile4(TestCfg4
, "", "-option_10\n");
1221 // Make sure the current directory is not the directory where config files
1222 // resides. In this case the code that expands response files will not find
1223 // 'subconfig' unless it resolves nested inclusions relative to the including
1225 llvm::SmallString
<128> CurrDir
;
1226 std::error_code EC
= llvm::sys::fs::current_path(CurrDir
);
1228 EXPECT_NE(CurrDir
.str(), TestDir
.path());
1230 llvm::BumpPtrAllocator A
;
1231 llvm::cl::ExpansionContext
ECtx(A
, cl::tokenizeConfigFile
);
1232 llvm::Error Result
= ECtx
.readConfigFile(ConfigFile
.path(), Argv
);
1234 EXPECT_FALSE((bool)Result
);
1235 EXPECT_EQ(Argv
.size(), 13U);
1236 EXPECT_STREQ(Argv
[0], "-option_1");
1237 EXPECT_STREQ(Argv
[1],
1238 ("-option_2=" + TestDir
.path() + "/dir1").str().c_str());
1239 EXPECT_STREQ(Argv
[2], ("-option_3=" + TestDir
.path()).str().c_str());
1240 EXPECT_STREQ(Argv
[3], "-option_4");
1241 EXPECT_STREQ(Argv
[4], TestDir
.path().str().c_str());
1242 EXPECT_STREQ(Argv
[5], ("-option_5=" + TestDir
.path()).str().c_str());
1243 EXPECT_STREQ(Argv
[6], ("-option_6=" + TestDir
.path() + "/dir1," +
1244 TestDir
.path() + "/dir2")
1247 EXPECT_STREQ(Argv
[7], "-option_7");
1248 EXPECT_STREQ(Argv
[8],
1249 ("-option_8=" + TestDir
.path() + "/dir2").str().c_str());
1250 EXPECT_STREQ(Argv
[9],
1251 ("-option_9=" + TestSubDir
.path() + "/dir3").str().c_str());
1252 EXPECT_STREQ(Argv
[10], "-option_10");
1253 EXPECT_STREQ(Argv
[11], "-option_11=abcd");
1254 EXPECT_STREQ(Argv
[12], "-option_12=cdef");
1257 TEST(CommandLineTest
, PositionalEatArgsError
) {
1258 cl::ResetCommandLineParser();
1260 StackOption
<std::string
, cl::list
<std::string
>> PosEatArgs(
1261 "positional-eat-args", cl::Positional
, cl::desc("<arguments>..."),
1262 cl::PositionalEatsArgs
);
1263 StackOption
<std::string
, cl::list
<std::string
>> PosEatArgs2(
1264 "positional-eat-args2", cl::Positional
, cl::desc("Some strings"),
1265 cl::PositionalEatsArgs
);
1267 const char *args
[] = {"prog", "-positional-eat-args=XXXX"};
1268 const char *args2
[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1269 const char *args3
[] = {"prog", "-positional-eat-args", "-foo"};
1270 const char *args4
[] = {"prog", "-positional-eat-args",
1271 "-foo", "-positional-eat-args2",
1275 raw_string_ostream
OS(Errs
);
1276 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
));
1277 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1278 EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2
, StringRef(), &OS
));
1279 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1280 EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3
, StringRef(), &OS
));
1281 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1283 cl::ResetAllOptionOccurrences();
1284 EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4
, StringRef(), &OS
));
1285 EXPECT_EQ(PosEatArgs
.size(), 1u);
1286 EXPECT_EQ(PosEatArgs2
.size(), 2u);
1287 EXPECT_TRUE(Errs
.empty());
1291 void checkSeparators(StringRef Path
) {
1292 char UndesiredSeparator
= sys::path::get_separator()[0] == '/' ? '\\' : '/';
1293 ASSERT_EQ(Path
.find(UndesiredSeparator
), StringRef::npos
);
1296 TEST(CommandLineTest
, GetCommandLineArguments
) {
1298 char **argv
= __argv
;
1300 // GetCommandLineArguments is called in InitLLVM.
1301 llvm::InitLLVM
X(argc
, argv
);
1303 EXPECT_EQ(llvm::sys::path::is_absolute(argv
[0]),
1304 llvm::sys::path::is_absolute(__argv
[0]));
1305 checkSeparators(argv
[0]);
1308 llvm::sys::path::filename(argv
[0]).equals_insensitive("supporttests.exe"))
1309 << "Filename of test executable is "
1310 << llvm::sys::path::filename(argv
[0]);
1314 class OutputRedirector
{
1316 OutputRedirector(int RedirectFD
)
1317 : RedirectFD(RedirectFD
), OldFD(dup(RedirectFD
)) {
1319 sys::fs::createTemporaryFile("unittest-redirect", "", NewFD
,
1321 dup2(NewFD
, RedirectFD
) == -1)
1325 ~OutputRedirector() {
1326 dup2(OldFD
, RedirectFD
);
1331 SmallVector
<char, 128> FilePath
;
1340 struct AutoDeleteFile
{
1341 SmallVector
<char, 128> FilePath
;
1343 if (!FilePath
.empty())
1344 sys::fs::remove(std::string(FilePath
.data(), FilePath
.size()));
1348 static std::string
interceptStdout(std::function
<void()> F
) {
1349 outs().flush(); // flush any output from previous tests
1350 AutoDeleteFile File
;
1352 OutputRedirector
Stdout(fileno(stdout
));
1355 File
.FilePath
= Stdout
.FilePath
;
1359 auto Buffer
= MemoryBuffer::getFile(File
.FilePath
);
1362 return Buffer
->get()->getBuffer().str();
1365 template <void (*Func
)(const cl::Option
&)>
1366 class PrintOptionTestBase
: public ::testing::Test
{
1368 // Return std::string because the output of a failing EXPECT check is
1369 // unreadable for StringRef. It also avoids any lifetime issues.
1370 template <typename
... Ts
> std::string
runTest(Ts
... OptionAttributes
) {
1371 StackOption
<OptionValue
> TestOption(Opt
, cl::desc(HelpText
),
1372 OptionAttributes
...);
1373 return interceptStdout([&]() { Func(TestOption
); });
1376 enum class OptionValue
{ Val
};
1377 const StringRef Opt
= "some-option";
1378 const StringRef HelpText
= "some help";
1381 // This is a workaround for cl::Option sub-classes having their
1382 // printOptionInfo functions private.
1383 void printOptionInfo(const cl::Option
&O
) {
1384 O
.printOptionInfo(/*GlobalWidth=*/26);
1387 using PrintOptionInfoTest
= PrintOptionTestBase
<printOptionInfo
>;
1389 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithoutSentinel
) {
1390 std::string Output
=
1391 runTest(cl::ValueOptional
,
1392 cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1395 EXPECT_EQ(Output
, (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1401 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithSentinel
) {
1402 std::string Output
= runTest(
1403 cl::ValueOptional
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1404 clEnumValN(OptionValue::Val
, "", "")));
1408 (" --" + Opt
+ " - " + HelpText
+ "\n"
1409 " --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1415 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueOptionalWithSentinelWithHelp
) {
1416 std::string Output
= runTest(
1417 cl::ValueOptional
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1418 clEnumValN(OptionValue::Val
, "", "desc2")));
1421 EXPECT_EQ(Output
, (" --" + Opt
+ " - " + HelpText
+ "\n"
1422 " --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1424 " =<empty> - desc2\n")
1429 TEST_F(PrintOptionInfoTest
, PrintOptionInfoValueRequiredWithEmptyValueName
) {
1430 std::string Output
= runTest(
1431 cl::ValueRequired
, cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1"),
1432 clEnumValN(OptionValue::Val
, "", "")));
1435 EXPECT_EQ(Output
, (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1442 TEST_F(PrintOptionInfoTest
, PrintOptionInfoEmptyValueDescription
) {
1443 std::string Output
= runTest(
1444 cl::ValueRequired
, cl::values(clEnumValN(OptionValue::Val
, "v1", "")));
1448 (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1453 TEST_F(PrintOptionInfoTest
, PrintOptionInfoMultilineValueDescription
) {
1454 std::string Output
=
1455 runTest(cl::ValueRequired
,
1456 cl::values(clEnumValN(OptionValue::Val
, "v1",
1457 "This is the first enum value\n"
1458 "which has a really long description\n"
1459 "thus it is multi-line."),
1460 clEnumValN(OptionValue::Val
, "",
1461 "This is an unnamed enum value\n"
1462 "Should be indented as well")));
1466 (" --" + Opt
+ "=<value> - " + HelpText
+ "\n"
1467 " =v1 - This is the first enum value\n"
1468 " which has a really long description\n"
1469 " thus it is multi-line.\n"
1470 " =<empty> - This is an unnamed enum value\n"
1471 " Should be indented as well\n").str());
1475 void printOptionValue(const cl::Option
&O
) {
1476 O
.printOptionValue(/*GlobalWidth=*/12, /*Force=*/true);
1479 using PrintOptionValueTest
= PrintOptionTestBase
<printOptionValue
>;
1481 TEST_F(PrintOptionValueTest
, PrintOptionDefaultValue
) {
1482 std::string Output
=
1483 runTest(cl::init(OptionValue::Val
),
1484 cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1486 EXPECT_EQ(Output
, (" --" + Opt
+ " = v1 (default: v1)\n").str());
1489 TEST_F(PrintOptionValueTest
, PrintOptionNoDefaultValue
) {
1490 std::string Output
=
1491 runTest(cl::values(clEnumValN(OptionValue::Val
, "v1", "desc1")));
1493 // Note: the option still has a (zero-initialized) value, but the default
1494 // is invalid and doesn't match any value.
1495 EXPECT_EQ(Output
, (" --" + Opt
+ " = v1 (default: )\n").str());
1498 TEST_F(PrintOptionValueTest
, PrintOptionUnknownValue
) {
1499 std::string Output
= runTest(cl::init(OptionValue::Val
));
1501 EXPECT_EQ(Output
, (" --" + Opt
+ " = *unknown option value*\n").str());
1504 class GetOptionWidthTest
: public ::testing::Test
{
1506 enum class OptionValue
{ Val
};
1508 template <typename
... Ts
>
1509 size_t runTest(StringRef ArgName
, Ts
... OptionAttributes
) {
1510 StackOption
<OptionValue
> TestOption(ArgName
, cl::desc("some help"),
1511 OptionAttributes
...);
1512 return getOptionWidth(TestOption
);
1516 // This is a workaround for cl::Option sub-classes having their
1518 // functions private.
1519 size_t getOptionWidth(const cl::Option
&O
) { return O
.getOptionWidth(); }
1522 TEST_F(GetOptionWidthTest
, GetOptionWidthArgNameLonger
) {
1523 StringRef
ArgName("a-long-argument-name");
1524 size_t ExpectedStrSize
= (" --" + ArgName
+ "=<value> - ").str().size();
1526 runTest(ArgName
, cl::values(clEnumValN(OptionValue::Val
, "v", "help"))),
1530 TEST_F(GetOptionWidthTest
, GetOptionWidthFirstOptionNameLonger
) {
1531 StringRef
OptName("a-long-option-name");
1532 size_t ExpectedStrSize
= (" =" + OptName
+ " - ").str().size();
1534 runTest("a", cl::values(clEnumValN(OptionValue::Val
, OptName
, "help"),
1535 clEnumValN(OptionValue::Val
, "b", "help"))),
1539 TEST_F(GetOptionWidthTest
, GetOptionWidthSecondOptionNameLonger
) {
1540 StringRef
OptName("a-long-option-name");
1541 size_t ExpectedStrSize
= (" =" + OptName
+ " - ").str().size();
1543 runTest("a", cl::values(clEnumValN(OptionValue::Val
, "b", "help"),
1544 clEnumValN(OptionValue::Val
, OptName
, "help"))),
1548 TEST_F(GetOptionWidthTest
, GetOptionWidthEmptyOptionNameLonger
) {
1549 size_t ExpectedStrSize
= StringRef(" =<empty> - ").size();
1550 // The length of a=<value> (including indentation) is actually the same as the
1551 // =<empty> string, so it is impossible to distinguish via testing the case
1552 // where the empty string is picked from where the option name is picked.
1553 EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val
, "b", "help"),
1554 clEnumValN(OptionValue::Val
, "", "help"))),
1558 TEST_F(GetOptionWidthTest
,
1559 GetOptionWidthValueOptionalEmptyOptionWithNoDescription
) {
1560 StringRef
ArgName("a");
1561 // The length of a=<value> (including indentation) is actually the same as the
1562 // =<empty> string, so it is impossible to distinguish via testing the case
1563 // where the empty string is ignored from where it is not ignored.
1564 // The dash will not actually be printed, but the space it would take up is
1565 // included to ensure a consistent column width.
1566 size_t ExpectedStrSize
= (" -" + ArgName
+ "=<value> - ").str().size();
1567 EXPECT_EQ(runTest(ArgName
, cl::ValueOptional
,
1568 cl::values(clEnumValN(OptionValue::Val
, "value", "help"),
1569 clEnumValN(OptionValue::Val
, "", ""))),
1573 TEST_F(GetOptionWidthTest
,
1574 GetOptionWidthValueRequiredEmptyOptionWithNoDescription
) {
1575 // The length of a=<value> (including indentation) is actually the same as the
1576 // =<empty> string, so it is impossible to distinguish via testing the case
1577 // where the empty string is picked from where the option name is picked
1578 size_t ExpectedStrSize
= StringRef(" =<empty> - ").size();
1579 EXPECT_EQ(runTest("a", cl::ValueRequired
,
1580 cl::values(clEnumValN(OptionValue::Val
, "value", "help"),
1581 clEnumValN(OptionValue::Val
, "", ""))),
1585 TEST(CommandLineTest
, PrefixOptions
) {
1586 cl::ResetCommandLineParser();
1588 StackOption
<std::string
, cl::list
<std::string
>> IncludeDirs(
1589 "I", cl::Prefix
, cl::desc("Declare an include directory"));
1591 // Test non-prefixed variant works with cl::Prefix options.
1592 EXPECT_TRUE(IncludeDirs
.empty());
1593 const char *args
[] = {"prog", "-I=/usr/include"};
1595 cl::ParseCommandLineOptions(2, args
, StringRef(), &llvm::nulls()));
1596 EXPECT_EQ(IncludeDirs
.size(), 1u);
1597 EXPECT_EQ(IncludeDirs
.front().compare("/usr/include"), 0);
1599 IncludeDirs
.erase(IncludeDirs
.begin());
1600 cl::ResetAllOptionOccurrences();
1602 // Test non-prefixed variant works with cl::Prefix options when value is
1603 // passed in following argument.
1604 EXPECT_TRUE(IncludeDirs
.empty());
1605 const char *args2
[] = {"prog", "-I", "/usr/include"};
1607 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1608 EXPECT_EQ(IncludeDirs
.size(), 1u);
1609 EXPECT_EQ(IncludeDirs
.front().compare("/usr/include"), 0);
1611 IncludeDirs
.erase(IncludeDirs
.begin());
1612 cl::ResetAllOptionOccurrences();
1614 // Test prefixed variant works with cl::Prefix options.
1615 EXPECT_TRUE(IncludeDirs
.empty());
1616 const char *args3
[] = {"prog", "-I/usr/include"};
1618 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1619 EXPECT_EQ(IncludeDirs
.size(), 1u);
1620 EXPECT_EQ(IncludeDirs
.front().compare("/usr/include"), 0);
1622 StackOption
<std::string
, cl::list
<std::string
>> MacroDefs(
1623 "D", cl::AlwaysPrefix
, cl::desc("Define a macro"),
1624 cl::value_desc("MACRO[=VALUE]"));
1626 cl::ResetAllOptionOccurrences();
1628 // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1629 // equal sign is part of the value.
1630 EXPECT_TRUE(MacroDefs
.empty());
1631 const char *args4
[] = {"prog", "-D=HAVE_FOO"};
1633 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1634 EXPECT_EQ(MacroDefs
.size(), 1u);
1635 EXPECT_EQ(MacroDefs
.front().compare("=HAVE_FOO"), 0);
1637 MacroDefs
.erase(MacroDefs
.begin());
1638 cl::ResetAllOptionOccurrences();
1640 // Test non-prefixed variant does not allow value to be passed in following
1641 // argument with cl::AlwaysPrefix options.
1642 EXPECT_TRUE(MacroDefs
.empty());
1643 const char *args5
[] = {"prog", "-D", "HAVE_FOO"};
1645 cl::ParseCommandLineOptions(3, args5
, StringRef(), &llvm::nulls()));
1646 EXPECT_TRUE(MacroDefs
.empty());
1648 cl::ResetAllOptionOccurrences();
1650 // Test prefixed variant works with cl::AlwaysPrefix options.
1651 EXPECT_TRUE(MacroDefs
.empty());
1652 const char *args6
[] = {"prog", "-DHAVE_FOO"};
1654 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1655 EXPECT_EQ(MacroDefs
.size(), 1u);
1656 EXPECT_EQ(MacroDefs
.front().compare("HAVE_FOO"), 0);
1659 TEST(CommandLineTest
, GroupingWithValue
) {
1660 cl::ResetCommandLineParser();
1662 StackOption
<bool> OptF("f", cl::Grouping
, cl::desc("Some flag"));
1663 StackOption
<bool> OptB("b", cl::Grouping
, cl::desc("Another flag"));
1664 StackOption
<bool> OptD("d", cl::Grouping
, cl::ValueDisallowed
,
1665 cl::desc("ValueDisallowed option"));
1666 StackOption
<std::string
> OptV("v", cl::Grouping
,
1667 cl::desc("ValueRequired option"));
1668 StackOption
<std::string
> OptO("o", cl::Grouping
, cl::ValueOptional
,
1669 cl::desc("ValueOptional option"));
1671 // Should be possible to use an option which requires a value
1672 // at the end of a group.
1673 const char *args1
[] = {"prog", "-fv", "val1"};
1675 cl::ParseCommandLineOptions(3, args1
, StringRef(), &llvm::nulls()));
1677 EXPECT_STREQ("val1", OptV
.c_str());
1679 cl::ResetAllOptionOccurrences();
1681 // Should not crash if it is accidentally used elsewhere in the group.
1682 const char *args2
[] = {"prog", "-vf", "val2"};
1684 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1686 cl::ResetAllOptionOccurrences();
1688 // Should allow the "opt=value" form at the end of the group
1689 const char *args3
[] = {"prog", "-fv=val3"};
1691 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1693 EXPECT_STREQ("val3", OptV
.c_str());
1695 cl::ResetAllOptionOccurrences();
1697 // Should allow assigning a value for a ValueOptional option
1698 // at the end of the group
1699 const char *args4
[] = {"prog", "-fo=val4"};
1701 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1703 EXPECT_STREQ("val4", OptO
.c_str());
1705 cl::ResetAllOptionOccurrences();
1707 // Should assign an empty value if a ValueOptional option is used elsewhere
1709 const char *args5
[] = {"prog", "-fob"};
1711 cl::ParseCommandLineOptions(2, args5
, StringRef(), &llvm::nulls()));
1713 EXPECT_EQ(1, OptO
.getNumOccurrences());
1714 EXPECT_EQ(1, OptB
.getNumOccurrences());
1715 EXPECT_TRUE(OptO
.empty());
1716 cl::ResetAllOptionOccurrences();
1718 // Should not allow an assignment for a ValueDisallowed option.
1719 const char *args6
[] = {"prog", "-fd=false"};
1721 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1724 TEST(CommandLineTest
, GroupingAndPrefix
) {
1725 cl::ResetCommandLineParser();
1727 StackOption
<bool> OptF("f", cl::Grouping
, cl::desc("Some flag"));
1728 StackOption
<bool> OptB("b", cl::Grouping
, cl::desc("Another flag"));
1729 StackOption
<std::string
> OptP("p", cl::Prefix
, cl::Grouping
,
1730 cl::desc("Prefix and Grouping"));
1731 StackOption
<std::string
> OptA("a", cl::AlwaysPrefix
, cl::Grouping
,
1732 cl::desc("AlwaysPrefix and Grouping"));
1734 // Should be possible to use a cl::Prefix option without grouping.
1735 const char *args1
[] = {"prog", "-pval1"};
1737 cl::ParseCommandLineOptions(2, args1
, StringRef(), &llvm::nulls()));
1738 EXPECT_STREQ("val1", OptP
.c_str());
1740 cl::ResetAllOptionOccurrences();
1742 // Should be possible to pass a value in a separate argument.
1743 const char *args2
[] = {"prog", "-p", "val2"};
1745 cl::ParseCommandLineOptions(3, args2
, StringRef(), &llvm::nulls()));
1746 EXPECT_STREQ("val2", OptP
.c_str());
1748 cl::ResetAllOptionOccurrences();
1750 // The "-opt=value" form should work, too.
1751 const char *args3
[] = {"prog", "-p=val3"};
1753 cl::ParseCommandLineOptions(2, args3
, StringRef(), &llvm::nulls()));
1754 EXPECT_STREQ("val3", OptP
.c_str());
1756 cl::ResetAllOptionOccurrences();
1758 // All three previous cases should work the same way if an option with both
1759 // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1760 const char *args4
[] = {"prog", "-fpval4"};
1762 cl::ParseCommandLineOptions(2, args4
, StringRef(), &llvm::nulls()));
1764 EXPECT_STREQ("val4", OptP
.c_str());
1766 cl::ResetAllOptionOccurrences();
1768 const char *args5
[] = {"prog", "-fp", "val5"};
1770 cl::ParseCommandLineOptions(3, args5
, StringRef(), &llvm::nulls()));
1772 EXPECT_STREQ("val5", OptP
.c_str());
1774 cl::ResetAllOptionOccurrences();
1776 const char *args6
[] = {"prog", "-fp=val6"};
1778 cl::ParseCommandLineOptions(2, args6
, StringRef(), &llvm::nulls()));
1780 EXPECT_STREQ("val6", OptP
.c_str());
1782 cl::ResetAllOptionOccurrences();
1784 // Should assign a value even if the part after a cl::Prefix option is equal
1785 // to the name of another option.
1786 const char *args7
[] = {"prog", "-fpb"};
1788 cl::ParseCommandLineOptions(2, args7
, StringRef(), &llvm::nulls()));
1790 EXPECT_STREQ("b", OptP
.c_str());
1793 cl::ResetAllOptionOccurrences();
1795 // Should be possible to use a cl::AlwaysPrefix option without grouping.
1796 const char *args8
[] = {"prog", "-aval8"};
1798 cl::ParseCommandLineOptions(2, args8
, StringRef(), &llvm::nulls()));
1799 EXPECT_STREQ("val8", OptA
.c_str());
1801 cl::ResetAllOptionOccurrences();
1803 // Should not be possible to pass a value in a separate argument.
1804 const char *args9
[] = {"prog", "-a", "val9"};
1806 cl::ParseCommandLineOptions(3, args9
, StringRef(), &llvm::nulls()));
1807 cl::ResetAllOptionOccurrences();
1809 // With the "-opt=value" form, the "=" symbol should be preserved.
1810 const char *args10
[] = {"prog", "-a=val10"};
1812 cl::ParseCommandLineOptions(2, args10
, StringRef(), &llvm::nulls()));
1813 EXPECT_STREQ("=val10", OptA
.c_str());
1815 cl::ResetAllOptionOccurrences();
1817 // All three previous cases should work the same way if an option with both
1818 // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1819 const char *args11
[] = {"prog", "-faval11"};
1821 cl::ParseCommandLineOptions(2, args11
, StringRef(), &llvm::nulls()));
1823 EXPECT_STREQ("val11", OptA
.c_str());
1825 cl::ResetAllOptionOccurrences();
1827 const char *args12
[] = {"prog", "-fa", "val12"};
1829 cl::ParseCommandLineOptions(3, args12
, StringRef(), &llvm::nulls()));
1830 cl::ResetAllOptionOccurrences();
1832 const char *args13
[] = {"prog", "-fa=val13"};
1834 cl::ParseCommandLineOptions(2, args13
, StringRef(), &llvm::nulls()));
1836 EXPECT_STREQ("=val13", OptA
.c_str());
1838 cl::ResetAllOptionOccurrences();
1840 // Should assign a value even if the part after a cl::AlwaysPrefix option
1841 // is equal to the name of another option.
1842 const char *args14
[] = {"prog", "-fab"};
1844 cl::ParseCommandLineOptions(2, args14
, StringRef(), &llvm::nulls()));
1846 EXPECT_STREQ("b", OptA
.c_str());
1849 cl::ResetAllOptionOccurrences();
1852 TEST(CommandLineTest
, LongOptions
) {
1853 cl::ResetCommandLineParser();
1855 StackOption
<bool> OptA("a", cl::desc("Some flag"));
1856 StackOption
<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1857 StackOption
<bool, cl::alias
> OptB("b", cl::desc("Alias to --long-flag"),
1858 cl::aliasopt(OptBLong
));
1859 StackOption
<std::string
> OptAB("ab", cl::desc("Another long option"));
1862 raw_string_ostream
OS(Errs
);
1864 const char *args1
[] = {"prog", "-a", "-ab", "val1"};
1865 const char *args2
[] = {"prog", "-a", "--ab", "val1"};
1866 const char *args3
[] = {"prog", "-ab", "--ab", "val1"};
1869 // The following tests treat `-` and `--` the same, and always match the
1874 cl::ParseCommandLineOptions(4, args1
, StringRef(), &OS
));
1876 EXPECT_FALSE(OptBLong
);
1877 EXPECT_STREQ("val1", OptAB
.c_str());
1878 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1879 cl::ResetAllOptionOccurrences();
1882 cl::ParseCommandLineOptions(4, args2
, StringRef(), &OS
));
1884 EXPECT_FALSE(OptBLong
);
1885 EXPECT_STREQ("val1", OptAB
.c_str());
1886 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1887 cl::ResetAllOptionOccurrences();
1889 // Fails because `-ab` and `--ab` are treated the same and appear more than
1890 // once. Also, `val1` is unexpected.
1892 cl::ParseCommandLineOptions(4, args3
, StringRef(), &OS
));
1893 outs()<< Errs
<< "\n";
1894 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1895 cl::ResetAllOptionOccurrences();
1898 // The following tests treat `-` and `--` differently, with `-` for short, and
1899 // `--` for long options.
1902 // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1903 // `val1` is unexpected.
1904 EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1
, StringRef(),
1905 &OS
, nullptr, true));
1906 EXPECT_FALSE(Errs
.empty()); Errs
.clear();
1907 cl::ResetAllOptionOccurrences();
1909 // Works because `-a` is treated differently than `--ab`.
1910 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2
, StringRef(),
1911 &OS
, nullptr, true));
1912 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1913 cl::ResetAllOptionOccurrences();
1915 // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1916 EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3
, StringRef(),
1917 &OS
, nullptr, true));
1919 EXPECT_TRUE(OptBLong
);
1920 EXPECT_STREQ("val1", OptAB
.c_str());
1921 EXPECT_TRUE(Errs
.empty()); Errs
.clear();
1922 cl::ResetAllOptionOccurrences();
1925 TEST(CommandLineTest
, OptionErrorMessage
) {
1926 // When there is an error, we expect some error message like:
1927 // prog: for the -a option: [...]
1929 // Test whether the "for the -a option"-part is correctly formatted.
1930 cl::ResetCommandLineParser();
1932 StackOption
<bool> OptA("a", cl::desc("Some option"));
1933 StackOption
<bool> OptLong("long", cl::desc("Some long option"));
1936 raw_string_ostream
OS(Errs
);
1938 OptA
.error("custom error", OS
);
1939 EXPECT_NE(Errs
.find("for the -a option:"), std::string::npos
);
1942 OptLong
.error("custom error", OS
);
1943 EXPECT_NE(Errs
.find("for the --long option:"), std::string::npos
);
1946 cl::ResetAllOptionOccurrences();
1949 TEST(CommandLineTest
, OptionErrorMessageSuggest
) {
1950 // When there is an error, and the edit-distance is not very large,
1951 // we expect some error message like:
1952 // prog: did you mean '--option'?
1954 // Test whether this message is well-formatted.
1955 cl::ResetCommandLineParser();
1957 StackOption
<bool> OptLong("aluminium", cl::desc("Some long option"));
1959 const char *args
[] = {"prog", "--aluminum"};
1962 raw_string_ostream
OS(Errs
);
1964 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
));
1965 EXPECT_NE(Errs
.find("prog: Did you mean '--aluminium'?\n"),
1969 cl::ResetAllOptionOccurrences();
1972 TEST(CommandLineTest
, OptionErrorMessageSuggestNoHidden
) {
1973 // We expect that 'really hidden' option do not show up in option
1975 cl::ResetCommandLineParser();
1977 StackOption
<bool> OptLong("aluminium", cl::desc("Some long option"));
1978 StackOption
<bool> OptLong2("aluminum", cl::desc("Bad option"),
1981 const char *args
[] = {"prog", "--alumnum"};
1984 raw_string_ostream
OS(Errs
);
1986 EXPECT_FALSE(cl::ParseCommandLineOptions(2, args
, StringRef(), &OS
));
1987 EXPECT_NE(Errs
.find("prog: Did you mean '--aluminium'?\n"),
1991 cl::ResetAllOptionOccurrences();
1994 TEST(CommandLineTest
, Callback
) {
1995 cl::ResetCommandLineParser();
1997 StackOption
<bool> OptA("a", cl::desc("option a"));
1998 StackOption
<bool> OptB(
1999 "b", cl::desc("option b -- This option turns on option a"),
2000 cl::callback([&](const bool &) { OptA
= true; }));
2001 StackOption
<bool> OptC(
2002 "c", cl::desc("option c -- This option turns on options a and b"),
2003 cl::callback([&](const bool &) { OptB
= true; }));
2004 StackOption
<std::string
, cl::list
<std::string
>> List(
2006 cl::desc("option list -- This option turns on options a, b, and c when "
2007 "'foo' is included in list"),
2009 cl::callback([&](const std::string
&Str
) {
2014 const char *args1
[] = {"prog", "-a"};
2015 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args1
));
2019 EXPECT_EQ(List
.size(), 0u);
2020 cl::ResetAllOptionOccurrences();
2022 const char *args2
[] = {"prog", "-b"};
2023 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args2
));
2027 EXPECT_EQ(List
.size(), 0u);
2028 cl::ResetAllOptionOccurrences();
2030 const char *args3
[] = {"prog", "-c"};
2031 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args3
));
2035 EXPECT_EQ(List
.size(), 0u);
2036 cl::ResetAllOptionOccurrences();
2038 const char *args4
[] = {"prog", "--list=foo,bar"};
2039 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args4
));
2043 EXPECT_EQ(List
.size(), 2u);
2044 cl::ResetAllOptionOccurrences();
2046 const char *args5
[] = {"prog", "--list=bar"};
2047 EXPECT_TRUE(cl::ParseCommandLineOptions(2, args5
));
2051 EXPECT_EQ(List
.size(), 1u);
2053 cl::ResetAllOptionOccurrences();
2056 enum Enum
{ Val1
, Val2
};
2057 static cl::bits
<Enum
> ExampleBits(
2058 cl::desc("An example cl::bits to ensure it compiles"),
2060 clEnumValN(Val1
, "bits-val1", "The Val1 value"),
2061 clEnumValN(Val1
, "bits-val2", "The Val2 value")));
2063 TEST(CommandLineTest
, ConsumeAfterOnePositional
) {
2064 cl::ResetCommandLineParser();
2067 StackOption
<std::string
, cl::opt
<std::string
>> Input(cl::Positional
,
2069 StackOption
<std::string
, cl::list
<std::string
>> ExtraArgs(cl::ConsumeAfter
);
2071 const char *Args
[] = {"prog", "input", "arg1", "arg2"};
2074 raw_string_ostream
OS(Errs
);
2075 EXPECT_TRUE(cl::ParseCommandLineOptions(4, Args
, StringRef(), &OS
));
2076 EXPECT_EQ("input", Input
);
2077 EXPECT_EQ(ExtraArgs
.size(), 2u);
2078 EXPECT_EQ(ExtraArgs
[0], "arg1");
2079 EXPECT_EQ(ExtraArgs
[1], "arg2");
2080 EXPECT_TRUE(Errs
.empty());
2083 TEST(CommandLineTest
, ConsumeAfterTwoPositionals
) {
2084 cl::ResetCommandLineParser();
2086 // input1 input2 [args]
2087 StackOption
<std::string
, cl::opt
<std::string
>> Input1(cl::Positional
,
2089 StackOption
<std::string
, cl::opt
<std::string
>> Input2(cl::Positional
,
2091 StackOption
<std::string
, cl::list
<std::string
>> ExtraArgs(cl::ConsumeAfter
);
2093 const char *Args
[] = {"prog", "input1", "input2", "arg1", "arg2"};
2096 raw_string_ostream
OS(Errs
);
2097 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args
, StringRef(), &OS
));
2098 EXPECT_EQ("input1", Input1
);
2099 EXPECT_EQ("input2", Input2
);
2100 EXPECT_EQ(ExtraArgs
.size(), 2u);
2101 EXPECT_EQ(ExtraArgs
[0], "arg1");
2102 EXPECT_EQ(ExtraArgs
[1], "arg2");
2103 EXPECT_TRUE(Errs
.empty());
2106 TEST(CommandLineTest
, ResetAllOptionOccurrences
) {
2107 cl::ResetCommandLineParser();
2109 // -option -str -enableA -enableC [sink] input [args]
2110 StackOption
<bool> Option("option");
2111 StackOption
<std::string
> Str("str");
2112 enum Vals
{ ValA
, ValB
, ValC
};
2113 StackOption
<Vals
, cl::bits
<Vals
>> Bits(
2114 cl::values(clEnumValN(ValA
, "enableA", "Enable A"),
2115 clEnumValN(ValB
, "enableB", "Enable B"),
2116 clEnumValN(ValC
, "enableC", "Enable C")));
2117 StackOption
<std::string
, cl::list
<std::string
>> Sink(cl::Sink
);
2118 StackOption
<std::string
> Input(cl::Positional
);
2119 StackOption
<std::string
, cl::list
<std::string
>> ExtraArgs(cl::ConsumeAfter
);
2121 const char *Args
[] = {"prog", "-option", "-str=STR", "-enableA",
2122 "-enableC", "-unknown", "input", "-arg"};
2125 raw_string_ostream
OS(Errs
);
2126 EXPECT_TRUE(cl::ParseCommandLineOptions(8, Args
, StringRef(), &OS
));
2127 EXPECT_TRUE(OS
.str().empty());
2129 EXPECT_TRUE(Option
);
2130 EXPECT_EQ("STR", Str
);
2131 EXPECT_EQ((1u << ValA
) | (1u << ValC
), Bits
.getBits());
2132 EXPECT_EQ(1u, Sink
.size());
2133 EXPECT_EQ("-unknown", Sink
[0]);
2134 EXPECT_EQ("input", Input
);
2135 EXPECT_EQ(1u, ExtraArgs
.size());
2136 EXPECT_EQ("-arg", ExtraArgs
[0]);
2138 cl::ResetAllOptionOccurrences();
2139 EXPECT_FALSE(Option
);
2141 EXPECT_EQ(0u, Bits
.getBits());
2142 EXPECT_EQ(0u, Sink
.size());
2143 EXPECT_EQ(0, Input
.getNumOccurrences());
2144 EXPECT_EQ(0u, ExtraArgs
.size());
2147 TEST(CommandLineTest
, DefaultValue
) {
2148 cl::ResetCommandLineParser();
2150 StackOption
<bool> BoolOption("bool-option");
2151 StackOption
<std::string
> StrOption("str-option");
2152 StackOption
<bool> BoolInitOption("bool-init-option", cl::init(true));
2153 StackOption
<std::string
> StrInitOption("str-init-option",
2154 cl::init("str-default-value"));
2156 const char *Args
[] = {"prog"}; // no options
2159 raw_string_ostream
OS(Errs
);
2160 EXPECT_TRUE(cl::ParseCommandLineOptions(1, Args
, StringRef(), &OS
));
2161 EXPECT_TRUE(OS
.str().empty());
2163 EXPECT_TRUE(!BoolOption
);
2164 EXPECT_FALSE(BoolOption
.Default
.hasValue());
2165 EXPECT_EQ(0, BoolOption
.getNumOccurrences());
2167 EXPECT_EQ("", StrOption
);
2168 EXPECT_FALSE(StrOption
.Default
.hasValue());
2169 EXPECT_EQ(0, StrOption
.getNumOccurrences());
2171 EXPECT_TRUE(BoolInitOption
);
2172 EXPECT_TRUE(BoolInitOption
.Default
.hasValue());
2173 EXPECT_EQ(0, BoolInitOption
.getNumOccurrences());
2175 EXPECT_EQ("str-default-value", StrInitOption
);
2176 EXPECT_TRUE(StrInitOption
.Default
.hasValue());
2177 EXPECT_EQ(0, StrInitOption
.getNumOccurrences());
2179 const char *Args2
[] = {"prog", "-bool-option", "-str-option=str-value",
2180 "-bool-init-option=0",
2181 "-str-init-option=str-init-value"};
2183 EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args2
, StringRef(), &OS
));
2184 EXPECT_TRUE(OS
.str().empty());
2186 EXPECT_TRUE(BoolOption
);
2187 EXPECT_FALSE(BoolOption
.Default
.hasValue());
2188 EXPECT_EQ(1, BoolOption
.getNumOccurrences());
2190 EXPECT_EQ("str-value", StrOption
);
2191 EXPECT_FALSE(StrOption
.Default
.hasValue());
2192 EXPECT_EQ(1, StrOption
.getNumOccurrences());
2194 EXPECT_FALSE(BoolInitOption
);
2195 EXPECT_TRUE(BoolInitOption
.Default
.hasValue());
2196 EXPECT_EQ(1, BoolInitOption
.getNumOccurrences());
2198 EXPECT_EQ("str-init-value", StrInitOption
);
2199 EXPECT_TRUE(StrInitOption
.Default
.hasValue());
2200 EXPECT_EQ(1, StrInitOption
.getNumOccurrences());
2203 TEST(CommandLineTest
, HelpWithoutSubcommands
) {
2204 // Check that the help message does not contain the "[subcommand]" placeholder
2205 // and the "SUBCOMMANDS" section if there are no subcommands.
2206 cl::ResetCommandLineParser();
2207 StackOption
<bool> Opt("opt", cl::init(false));
2208 const char *args
[] = {"prog"};
2209 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args
), args
, StringRef(),
2211 auto Output
= interceptStdout([]() { cl::PrintHelpMessage(); });
2212 EXPECT_NE(std::string::npos
, Output
.find("USAGE: prog [options]")) << Output
;
2213 EXPECT_EQ(std::string::npos
, Output
.find("SUBCOMMANDS:")) << Output
;
2214 cl::ResetCommandLineParser();
2217 TEST(CommandLineTest
, HelpWithSubcommands
) {
2218 // Check that the help message contains the "[subcommand]" placeholder in the
2219 // "USAGE" line and describes subcommands.
2220 cl::ResetCommandLineParser();
2221 StackSubCommand
SC1("sc1", "First Subcommand");
2222 StackSubCommand
SC2("sc2", "Second Subcommand");
2223 StackOption
<bool> SC1Opt("sc1", cl::sub(SC1
), cl::init(false));
2224 StackOption
<bool> SC2Opt("sc2", cl::sub(SC2
), cl::init(false));
2225 const char *args
[] = {"prog"};
2226 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args
), args
, StringRef(),
2228 auto Output
= interceptStdout([]() { cl::PrintHelpMessage(); });
2229 EXPECT_NE(std::string::npos
,
2230 Output
.find("USAGE: prog [subcommand] [options]"))
2232 EXPECT_NE(std::string::npos
, Output
.find("SUBCOMMANDS:")) << Output
;
2233 EXPECT_NE(std::string::npos
, Output
.find("sc1 - First Subcommand")) << Output
;
2234 EXPECT_NE(std::string::npos
, Output
.find("sc2 - Second Subcommand"))
2236 cl::ResetCommandLineParser();
2239 TEST(CommandLineTest
, UnknownCommands
) {
2240 cl::ResetCommandLineParser();
2242 StackSubCommand
SC1("foo", "Foo subcommand");
2243 StackSubCommand
SC2("bar", "Bar subcommand");
2244 StackOption
<bool> SC1Opt("put", cl::sub(SC1
));
2245 StackOption
<bool> SC2Opt("get", cl::sub(SC2
));
2246 StackOption
<bool> TopOpt1("peek");
2247 StackOption
<bool> TopOpt2("set");
2250 raw_string_ostream
OS(Errs
);
2252 const char *Args1
[] = {"prog", "baz", "--get"};
2254 cl::ParseCommandLineOptions(std::size(Args1
), Args1
, StringRef(), &OS
));
2256 "prog: Unknown subcommand 'baz'. Try: 'prog --help'\n"
2257 "prog: Did you mean 'bar'?\n"
2258 "prog: Unknown command line argument '--get'. Try: 'prog --help'\n"
2259 "prog: Did you mean '--set'?\n");
2261 // Do not show a suggestion if the subcommand is not similar to any known.
2263 const char *Args2
[] = {"prog", "faz"};
2265 cl::ParseCommandLineOptions(std::size(Args2
), Args2
, StringRef(), &OS
));
2266 EXPECT_EQ(Errs
, "prog: Unknown subcommand 'faz'. Try: 'prog --help'\n");
2269 TEST(CommandLineTest
, SubCommandGroups
) {
2270 // Check that options in subcommand groups are associated with expected
2273 cl::ResetCommandLineParser();
2275 StackSubCommand
SC1("sc1", "SC1 subcommand");
2276 StackSubCommand
SC2("sc2", "SC2 subcommand");
2277 StackSubCommand
SC3("sc3", "SC3 subcommand");
2278 cl::SubCommandGroup Group12
= {&SC1
, &SC2
};
2280 StackOption
<bool> Opt12("opt12", cl::sub(Group12
), cl::init(false));
2281 StackOption
<bool> Opt3("opt3", cl::sub(SC3
), cl::init(false));
2283 // The "--opt12" option is expected to be added to both subcommands in the
2284 // group, but not to the top-level "no subcommand" pseudo-subcommand or the
2285 // "sc3" subcommand.
2286 EXPECT_EQ(1U, SC1
.OptionsMap
.size());
2287 EXPECT_TRUE(SC1
.OptionsMap
.contains("opt12"));
2289 EXPECT_EQ(1U, SC2
.OptionsMap
.size());
2290 EXPECT_TRUE(SC2
.OptionsMap
.contains("opt12"));
2292 EXPECT_FALSE(cl::SubCommand::getTopLevel().OptionsMap
.contains("opt12"));
2293 EXPECT_FALSE(SC3
.OptionsMap
.contains("opt12"));
2296 TEST(CommandLineTest
, HelpWithEmptyCategory
) {
2297 cl::ResetCommandLineParser();
2299 cl::OptionCategory
Category1("First Category");
2300 cl::OptionCategory
Category2("Second Category");
2301 StackOption
<int> Opt1("opt1", cl::cat(Category1
));
2302 StackOption
<int> Opt2("opt2", cl::cat(Category2
));
2303 cl::HideUnrelatedOptions(Category2
);
2305 const char *args
[] = {"prog"};
2306 EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args
), args
, StringRef(),
2308 auto Output
= interceptStdout(
2309 []() { cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); });
2310 EXPECT_EQ(std::string::npos
, Output
.find("First Category"))
2311 << "An empty category should not be printed";
2313 Output
= interceptStdout(
2314 []() { cl::PrintHelpMessage(/*Hidden=*/true, /*Categorized=*/true); });
2315 EXPECT_EQ(std::string::npos
, Output
.find("First Category"))
2316 << "An empty category should not be printed";
2318 cl::ResetCommandLineParser();
2321 } // anonymous namespace