xref: /llvm-project/llvm/unittests/Support/CommandLineTest.cpp (revision 8dd77fa5ae2c20cce903501e9090c663bf97d144)
1 //===- llvm/unittest/Support/CommandLineTest.cpp - CommandLine tests ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Support/CommandLine.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/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"
28 #include <fstream>
29 #include <stdlib.h>
30 #include <string>
31 
32 using namespace llvm;
33 using llvm::unittest::TempDir;
34 using llvm::unittest::TempFile;
35 
36 namespace {
37 
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));
40 }
41 
42 class TempEnvVar {
43  public:
44   TempEnvVar(const char *name, const char *value)
45       : name(name) {
46     const char *old_value = getenv(name);
47     EXPECT_EQ(nullptr, old_value) << old_value;
48 #if HAVE_SETENV
49     setenv(name, value, true);
50 #endif
51   }
52 
53   ~TempEnvVar() {
54 #if HAVE_SETENV
55     // Assume setenv and unsetenv come together.
56     unsetenv(name);
57 #else
58     (void)name; // Suppress -Wunused-private-field.
59 #endif
60   }
61 
62  private:
63   const char *const name;
64 };
65 
66 template <typename T, typename Base = cl::opt<T>>
67 class StackOption : public Base {
68 public:
69   template <class... Ts>
70   explicit StackOption(Ts &&... Ms) : Base(std::forward<Ts>(Ms)...) {}
71 
72   ~StackOption() override { this->removeArgument(); }
73 
74   template <class DT> StackOption<T> &operator=(const DT &V) {
75     Base::operator=(V);
76     return *this;
77   }
78 };
79 
80 class StackSubCommand : public cl::SubCommand {
81 public:
82   StackSubCommand(StringRef Name,
83                   StringRef Description = StringRef())
84       : SubCommand(Name, Description) {}
85 
86   StackSubCommand() : SubCommand() {}
87 
88   ~StackSubCommand() { unregisterSubCommand(); }
89 };
90 
91 
92 cl::OptionCategory TestCategory("Test Options", "Description");
93 TEST(CommandLineTest, ModifyExisitingOption) {
94   StackOption<int> TestOption("test-option", cl::desc("old description"));
95 
96   static const char Description[] = "New description";
97   static const char ArgString[] = "new-test-option";
98   static const char ValueString[] = "Integer";
99 
100   StringMap<cl::Option *> &Map =
101       cl::getRegisteredOptions(cl::SubCommand::getTopLevel());
102 
103   ASSERT_EQ(Map.count("test-option"), 1u) << "Could not find option in map.";
104 
105   cl::Option *Retrieved = Map["test-option"];
106   ASSERT_EQ(&TestOption, Retrieved) << "Retrieved wrong option.";
107 
108   ASSERT_NE(Retrieved->Categories.end(),
109             find_if(Retrieved->Categories,
110                     [&](const llvm::cl::OptionCategory *Cat) {
111                       return Cat == &cl::getGeneralCategory();
112                     }))
113       << "Incorrect default option category.";
114 
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;
120                     }))
121       << "Failed to modify option's option category.";
122 
123   Retrieved->setDescription(Description);
124   ASSERT_STREQ(Retrieved->HelpStr.data(), Description)
125       << "Changing option description failed.";
126 
127   Retrieved->setArgStr(ArgString);
128   ASSERT_STREQ(ArgString, Retrieved->ArgStr.data())
129       << "Failed to modify option's Argument string.";
130 
131   Retrieved->setValueStr(ValueString);
132   ASSERT_STREQ(Retrieved->ValueStr.data(), ValueString)
133       << "Failed to modify option's Value string.";
134 
135   Retrieved->setHiddenFlag(cl::Hidden);
136   ASSERT_EQ(cl::Hidden, TestOption.getOptionHiddenFlag()) <<
137     "Failed to modify option's hidden flag.";
138 }
139 
140 TEST(CommandLineTest, UseOptionCategory) {
141   StackOption<int> TestOption2("test-option", cl::cat(TestCategory));
142 
143   ASSERT_NE(TestOption2.Categories.end(),
144             find_if(TestOption2.Categories,
145                          [&](const llvm::cl::OptionCategory *Cat) {
146                            return Cat == &TestCategory;
147                          }))
148       << "Failed to assign Option Category.";
149 }
150 
151 TEST(CommandLineTest, UseMultipleCategories) {
152   StackOption<int> TestOption2("test-option2", cl::cat(TestCategory),
153                                cl::cat(cl::getGeneralCategory()),
154                                cl::cat(cl::getGeneralCategory()));
155 
156   // Make sure cl::getGeneralCategory() wasn't added twice.
157   ASSERT_EQ(TestOption2.Categories.size(), 2U);
158 
159   ASSERT_NE(TestOption2.Categories.end(),
160             find_if(TestOption2.Categories,
161                          [&](const llvm::cl::OptionCategory *Cat) {
162                            return Cat == &TestCategory;
163                          }))
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();
169                     }))
170       << "Failed to assign General Category.";
171 
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();
179                     }))
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;
185                          }))
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;
191                          }))
192       << "Failed to assign Another Category.";
193 }
194 
195 typedef void ParserFunction(StringRef Source, StringSaver &Saver,
196                             SmallVectorImpl<const char *> &NewArgv,
197                             bool MarkEOLs);
198 
199 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input,
200                               ArrayRef<const char *> Output,
201                               bool MarkEOLs = false) {
202   SmallVector<const char *, 0> Actual;
203   BumpPtrAllocator A;
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]);
210     }
211   }
212 }
213 
214 TEST(CommandLineTest, TokenizeGNUCommandLine) {
215   const char Input[] =
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);
222 }
223 
224 TEST(CommandLineTest, TokenizeWindowsCommandLine1) {
225   const char Input[] =
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);
230 }
231 
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);
236 }
237 
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);
243 
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);
248 
249   // An unterminated quoted string is also emitted as an argument word, empty
250   // or not
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);
257 }
258 
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",
263                                  "z.c", "-DY=\"x\""};
264   testCommandLineTokenizer(cl::TokenizeWindowsCommandLineFull, Input1, Output1);
265 
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,
270                            /*MarkEOLs=*/true);
271 
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);
275 }
276 
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:
281   // /c /Zi /O2
282   // /Oy- /link /debug /opt:ref
283   // /Zc:ThreadsafeStatics-
284   //
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,
293                            /*MarkEOLs=*/true);
294   testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
295                            /*MarkEOLs=*/true);
296 }
297 
298 TEST(CommandLineTest, TokenizeConfigFile1) {
299   const char *Input = "\\";
300   const char *const Output[] = { "\\" };
301   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
302 }
303 
304 TEST(CommandLineTest, TokenizeConfigFile2) {
305   const char *Input = "\\abc";
306   const char *const Output[] = { "abc" };
307   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
308 }
309 
310 TEST(CommandLineTest, TokenizeConfigFile3) {
311   const char *Input = "abc\\";
312   const char *const Output[] = { "abc\\" };
313   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
314 }
315 
316 TEST(CommandLineTest, TokenizeConfigFile4) {
317   const char *Input = "abc\\\n123";
318   const char *const Output[] = { "abc123" };
319   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
320 }
321 
322 TEST(CommandLineTest, TokenizeConfigFile5) {
323   const char *Input = "abc\\\r\n123";
324   const char *const Output[] = { "abc123" };
325   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
326 }
327 
328 TEST(CommandLineTest, TokenizeConfigFile6) {
329   const char *Input = "abc\\\n";
330   const char *const Output[] = { "abc" };
331   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
332 }
333 
334 TEST(CommandLineTest, TokenizeConfigFile7) {
335   const char *Input = "abc\\\r\n";
336   const char *const Output[] = { "abc" };
337   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
338 }
339 
340 TEST(CommandLineTest, TokenizeConfigFile8) {
341   SmallVector<const char *, 0> Actual;
342   BumpPtrAllocator A;
343   StringSaver Saver(A);
344   cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false);
345   EXPECT_TRUE(Actual.empty());
346 }
347 
348 TEST(CommandLineTest, TokenizeConfigFile9) {
349   SmallVector<const char *, 0> Actual;
350   BumpPtrAllocator A;
351   StringSaver Saver(A);
352   cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false);
353   EXPECT_TRUE(Actual.empty());
354 }
355 
356 TEST(CommandLineTest, TokenizeConfigFile10) {
357   const char *Input = "\\\nabc";
358   const char *const Output[] = { "abc" };
359   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
360 }
361 
362 TEST(CommandLineTest, TokenizeConfigFile11) {
363   const char *Input = "\\\r\nabc";
364   const char *const Output[] = { "abc" };
365   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output);
366 }
367 
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" }
375   };
376 
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);
381 
382     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
383 
384     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
385     EXPECT_EQ("x", Actual);
386     EXPECT_EQ(0, Input.getNumOccurrences());
387 
388     Alias.removeArgument();
389   }
390 }
391 
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));
395 
396   cl::ParseCommandLineOptions(argc, argv);
397   EXPECT_EQ("x", Option);
398   EXPECT_EQ(1, Option.getNumOccurrences());
399 
400   Alias.removeArgument();
401 }
402 
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);
408 }
409 
410 TEST(CommandLineTest, HideUnrelatedOptions) {
411   StackOption<int> TestOption1("hide-option-1");
412   StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory));
413 
414   cl::HideUnrelatedOptions(TestCategory);
415 
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.";
420 
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.";
426 }
427 
428 cl::OptionCategory TestCategory2("Test Options set 2", "Description");
429 
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));
434 
435   const cl::OptionCategory *VisibleCategories[] = {&TestCategory,
436                                                    &TestCategory2};
437 
438   cl::HideUnrelatedOptions(ArrayRef(VisibleCategories));
439 
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.";
446 
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.";
452 }
453 
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(),
458                                           &llvm::nulls()));
459   EXPECT_EQ(Option, 2);
460 }
461 
462 TEST(CommandLineTest, SetValueInSubcategories) {
463   cl::ResetCommandLineParser();
464 
465   StackSubCommand SC1("sc1", "First subcommand");
466   StackSubCommand SC2("sc2", "Second subcommand");
467 
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));
471 
472   EXPECT_FALSE(TopLevelOpt);
473   EXPECT_FALSE(SC1Opt);
474   EXPECT_FALSE(SC2Opt);
475   const char *args[] = {"prog", "-top-level"};
476   EXPECT_TRUE(
477       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
478   EXPECT_TRUE(TopLevelOpt);
479   EXPECT_FALSE(SC1Opt);
480   EXPECT_FALSE(SC2Opt);
481 
482   TopLevelOpt = false;
483 
484   cl::ResetAllOptionOccurrences();
485   EXPECT_FALSE(TopLevelOpt);
486   EXPECT_FALSE(SC1Opt);
487   EXPECT_FALSE(SC2Opt);
488   const char *args2[] = {"prog", "sc1", "-sc1"};
489   EXPECT_TRUE(
490       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
491   EXPECT_FALSE(TopLevelOpt);
492   EXPECT_TRUE(SC1Opt);
493   EXPECT_FALSE(SC2Opt);
494 
495   SC1Opt = false;
496 
497   cl::ResetAllOptionOccurrences();
498   EXPECT_FALSE(TopLevelOpt);
499   EXPECT_FALSE(SC1Opt);
500   EXPECT_FALSE(SC2Opt);
501   const char *args3[] = {"prog", "sc2", "-sc2"};
502   EXPECT_TRUE(
503       cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls()));
504   EXPECT_FALSE(TopLevelOpt);
505   EXPECT_FALSE(SC1Opt);
506   EXPECT_TRUE(SC2Opt);
507 }
508 
509 TEST(CommandLineTest, LookupFailsInWrongSubCommand) {
510   cl::ResetCommandLineParser();
511 
512   StackSubCommand SC1("sc1", "First subcommand");
513   StackSubCommand SC2("sc2", "Second subcommand");
514 
515   StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
516   StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
517 
518   std::string Errs;
519   raw_string_ostream OS(Errs);
520 
521   const char *args[] = {"prog", "sc1", "-sc2"};
522   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
523   OS.flush();
524   EXPECT_FALSE(Errs.empty());
525 }
526 
527 TEST(CommandLineTest, TopLevelOptInSubcommand) {
528   enum LiteralOptionEnum {
529     foo,
530     bar,
531     baz,
532   };
533 
534   cl::ResetCommandLineParser();
535 
536   // This is a top-level option and not associated with a subcommand.
537   // A command line using subcommand should parse both subcommand options and
538   // top-level options.  A valid use case is that users of llvm command line
539   // tools should be able to specify top-level options defined in any library.
540   StackOption<std::string> TopLevelOpt("str", cl::init("txt"),
541                                        cl::desc("A top-level option."));
542 
543   StackSubCommand SC("sc", "Subcommand");
544   StackOption<std::string> PositionalOpt(
545       cl::Positional, cl::desc("positional argument test coverage"),
546       cl::sub(SC));
547   StackOption<LiteralOptionEnum> LiteralOpt(
548       cl::desc("literal argument test coverage"), cl::sub(SC), cl::init(bar),
549       cl::values(clEnumVal(foo, "foo"), clEnumVal(bar, "bar"),
550                  clEnumVal(baz, "baz")));
551   StackOption<bool> EnableOpt("enable", cl::sub(SC), cl::init(false));
552   StackOption<int> ThresholdOpt("threshold", cl::sub(SC), cl::init(1));
553 
554   const char *PositionalOptVal = "input-file";
555   const char *args[] = {"prog",    "sc",        PositionalOptVal,
556                         "-enable", "--str=csv", "--threshold=2"};
557 
558   // cl::ParseCommandLineOptions returns true on success. Otherwise, it will
559   // print the error message to stderr and exit in this setting (`Errs` ostream
560   // is not set).
561   ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]), args,
562                                           StringRef()));
563   EXPECT_STREQ(PositionalOpt.getValue().c_str(), PositionalOptVal);
564   EXPECT_TRUE(EnableOpt);
565   // Tests that the value of `str` option is `csv` as specified.
566   EXPECT_STREQ(TopLevelOpt.getValue().c_str(), "csv");
567   EXPECT_EQ(ThresholdOpt, 2);
568 
569   for (auto &[LiteralOptVal, WantLiteralOpt] :
570        {std::pair{"--bar", bar}, {"--foo", foo}, {"--baz", baz}}) {
571     const char *args[] = {"prog", "sc", LiteralOptVal};
572     ASSERT_TRUE(cl::ParseCommandLineOptions(sizeof(args) / sizeof(args[0]),
573                                             args, StringRef()));
574 
575     // Tests that literal options are parsed correctly.
576     EXPECT_EQ(LiteralOpt, WantLiteralOpt);
577   }
578 }
579 
580 TEST(CommandLineTest, AddToAllSubCommands) {
581   cl::ResetCommandLineParser();
582 
583   StackSubCommand SC1("sc1", "First subcommand");
584   StackOption<bool> AllOpt("everywhere", cl::sub(cl::SubCommand::getAll()),
585                            cl::init(false));
586   StackSubCommand SC2("sc2", "Second subcommand");
587 
588   const char *args[] = {"prog", "-everywhere"};
589   const char *args2[] = {"prog", "sc1", "-everywhere"};
590   const char *args3[] = {"prog", "sc2", "-everywhere"};
591 
592   std::string Errs;
593   raw_string_ostream OS(Errs);
594 
595   EXPECT_FALSE(AllOpt);
596   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
597   EXPECT_TRUE(AllOpt);
598 
599   AllOpt = false;
600 
601   cl::ResetAllOptionOccurrences();
602   EXPECT_FALSE(AllOpt);
603   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS));
604   EXPECT_TRUE(AllOpt);
605 
606   AllOpt = false;
607 
608   cl::ResetAllOptionOccurrences();
609   EXPECT_FALSE(AllOpt);
610   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS));
611   EXPECT_TRUE(AllOpt);
612 
613   // Since all parsing succeeded, the error message should be empty.
614   OS.flush();
615   EXPECT_TRUE(Errs.empty());
616 }
617 
618 TEST(CommandLineTest, ReparseCommandLineOptions) {
619   cl::ResetCommandLineParser();
620 
621   StackOption<bool> TopLevelOpt(
622       "top-level", cl::sub(cl::SubCommand::getTopLevel()), cl::init(false));
623 
624   const char *args[] = {"prog", "-top-level"};
625 
626   EXPECT_FALSE(TopLevelOpt);
627   EXPECT_TRUE(
628       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
629   EXPECT_TRUE(TopLevelOpt);
630 
631   TopLevelOpt = false;
632 
633   cl::ResetAllOptionOccurrences();
634   EXPECT_FALSE(TopLevelOpt);
635   EXPECT_TRUE(
636       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
637   EXPECT_TRUE(TopLevelOpt);
638 }
639 
640 TEST(CommandLineTest, RemoveFromRegularSubCommand) {
641   cl::ResetCommandLineParser();
642 
643   StackSubCommand SC("sc", "Subcommand");
644   StackOption<bool> RemoveOption("remove-option", cl::sub(SC), cl::init(false));
645   StackOption<bool> KeepOption("keep-option", cl::sub(SC), cl::init(false));
646 
647   const char *args[] = {"prog", "sc", "-remove-option"};
648 
649   std::string Errs;
650   raw_string_ostream OS(Errs);
651 
652   EXPECT_FALSE(RemoveOption);
653   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
654   EXPECT_TRUE(RemoveOption);
655   OS.flush();
656   EXPECT_TRUE(Errs.empty());
657 
658   RemoveOption.removeArgument();
659 
660   cl::ResetAllOptionOccurrences();
661   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
662   OS.flush();
663   EXPECT_FALSE(Errs.empty());
664 }
665 
666 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
667   cl::ResetCommandLineParser();
668 
669   StackOption<bool> TopLevelRemove("top-level-remove",
670                                    cl::sub(cl::SubCommand::getTopLevel()),
671                                    cl::init(false));
672   StackOption<bool> TopLevelKeep("top-level-keep",
673                                  cl::sub(cl::SubCommand::getTopLevel()),
674                                  cl::init(false));
675 
676   const char *args[] = {"prog", "-top-level-remove"};
677 
678   EXPECT_FALSE(TopLevelRemove);
679   EXPECT_TRUE(
680       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
681   EXPECT_TRUE(TopLevelRemove);
682 
683   TopLevelRemove.removeArgument();
684 
685   cl::ResetAllOptionOccurrences();
686   EXPECT_FALSE(
687       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
688 }
689 
690 TEST(CommandLineTest, RemoveFromAllSubCommands) {
691   cl::ResetCommandLineParser();
692 
693   StackSubCommand SC1("sc1", "First Subcommand");
694   StackSubCommand SC2("sc2", "Second Subcommand");
695   StackOption<bool> RemoveOption(
696       "remove-option", cl::sub(cl::SubCommand::getAll()), cl::init(false));
697   StackOption<bool> KeepOption("keep-option", cl::sub(cl::SubCommand::getAll()),
698                                cl::init(false));
699 
700   const char *args0[] = {"prog", "-remove-option"};
701   const char *args1[] = {"prog", "sc1", "-remove-option"};
702   const char *args2[] = {"prog", "sc2", "-remove-option"};
703 
704   // It should work for all subcommands including the top-level.
705   EXPECT_FALSE(RemoveOption);
706   EXPECT_TRUE(
707       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
708   EXPECT_TRUE(RemoveOption);
709 
710   RemoveOption = false;
711 
712   cl::ResetAllOptionOccurrences();
713   EXPECT_FALSE(RemoveOption);
714   EXPECT_TRUE(
715       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
716   EXPECT_TRUE(RemoveOption);
717 
718   RemoveOption = false;
719 
720   cl::ResetAllOptionOccurrences();
721   EXPECT_FALSE(RemoveOption);
722   EXPECT_TRUE(
723       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
724   EXPECT_TRUE(RemoveOption);
725 
726   RemoveOption.removeArgument();
727 
728   // It should not work for any subcommands including the top-level.
729   cl::ResetAllOptionOccurrences();
730   EXPECT_FALSE(
731       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
732   cl::ResetAllOptionOccurrences();
733   EXPECT_FALSE(
734       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
735   cl::ResetAllOptionOccurrences();
736   EXPECT_FALSE(
737       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
738 }
739 
740 TEST(CommandLineTest, GetRegisteredSubcommands) {
741   cl::ResetCommandLineParser();
742 
743   StackSubCommand SC1("sc1", "First Subcommand");
744   StackOption<bool> Opt1("opt1", cl::sub(SC1), cl::init(false));
745   StackSubCommand SC2("sc2", "Second subcommand");
746   StackOption<bool> Opt2("opt2", cl::sub(SC2), cl::init(false));
747 
748   const char *args0[] = {"prog", "sc1"};
749   const char *args1[] = {"prog", "sc2"};
750 
751   EXPECT_TRUE(
752       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
753   EXPECT_FALSE(Opt1);
754   EXPECT_FALSE(Opt2);
755   for (auto *S : cl::getRegisteredSubcommands()) {
756     if (*S) {
757       EXPECT_EQ("sc1", S->getName());
758     }
759   }
760 
761   cl::ResetAllOptionOccurrences();
762   EXPECT_TRUE(
763       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
764   EXPECT_FALSE(Opt1);
765   EXPECT_FALSE(Opt2);
766   for (auto *S : cl::getRegisteredSubcommands()) {
767     if (*S) {
768       EXPECT_EQ("sc2", S->getName());
769     }
770   }
771 }
772 
773 TEST(CommandLineTest, DefaultOptions) {
774   cl::ResetCommandLineParser();
775 
776   StackOption<std::string> Bar("bar", cl::sub(cl::SubCommand::getAll()),
777                                cl::DefaultOption);
778   StackOption<std::string, cl::alias> Bar_Alias(
779       "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption);
780 
781   StackOption<bool> Foo("foo", cl::init(false),
782                         cl::sub(cl::SubCommand::getAll()), cl::DefaultOption);
783   StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"),
784                                          cl::aliasopt(Foo), cl::DefaultOption);
785 
786   StackSubCommand SC1("sc1", "First Subcommand");
787   // Override "-b" and change type in sc1 SubCommand.
788   StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false));
789   StackSubCommand SC2("sc2", "Second subcommand");
790   // Override "-foo" and change type in sc2 SubCommand.  Note that this does not
791   // affect "-f" alias, which continues to work correctly.
792   StackOption<std::string> SC2_Foo("foo", cl::sub(SC2));
793 
794   const char *args0[] = {"prog", "-b", "args0 bar string", "-f"};
795   EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args0), args0,
796                                           StringRef(), &llvm::nulls()));
797   EXPECT_EQ(Bar, "args0 bar string");
798   EXPECT_TRUE(Foo);
799   EXPECT_FALSE(SC1_B);
800   EXPECT_TRUE(SC2_Foo.empty());
801 
802   cl::ResetAllOptionOccurrences();
803 
804   const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"};
805   EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args1), args1,
806                                           StringRef(), &llvm::nulls()));
807   EXPECT_EQ(Bar, "args1 bar string");
808   EXPECT_TRUE(Foo);
809   EXPECT_TRUE(SC1_B);
810   EXPECT_TRUE(SC2_Foo.empty());
811   for (auto *S : cl::getRegisteredSubcommands()) {
812     if (*S) {
813       EXPECT_EQ("sc1", S->getName());
814     }
815   }
816 
817   cl::ResetAllOptionOccurrences();
818 
819   const char *args2[] = {"prog", "sc2", "-b", "args2 bar string",
820                          "-f", "-foo", "foo string"};
821   EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args2), args2,
822                                           StringRef(), &llvm::nulls()));
823   EXPECT_EQ(Bar, "args2 bar string");
824   EXPECT_TRUE(Foo);
825   EXPECT_FALSE(SC1_B);
826   EXPECT_EQ(SC2_Foo, "foo string");
827   for (auto *S : cl::getRegisteredSubcommands()) {
828     if (*S) {
829       EXPECT_EQ("sc2", S->getName());
830     }
831   }
832   cl::ResetCommandLineParser();
833 }
834 
835 TEST(CommandLineTest, ArgumentLimit) {
836   std::string args(32 * 4096, 'a');
837   EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data()));
838   std::string args2(256, 'a');
839   EXPECT_TRUE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args2.data()));
840 }
841 
842 TEST(CommandLineTest, ArgumentLimitWindows) {
843   if (!Triple(sys::getProcessTriple()).isOSWindows())
844     GTEST_SKIP();
845   // We use 32000 as a limit for command line length. Program name ('cl'),
846   // separating spaces and termination null character occupy 5 symbols.
847   std::string long_arg(32000 - 5, 'b');
848   EXPECT_TRUE(
849       llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data()));
850   long_arg += 'b';
851   EXPECT_FALSE(
852       llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data()));
853 }
854 
855 TEST(CommandLineTest, ResponseFileWindows) {
856   if (!Triple(sys::getProcessTriple()).isOSWindows())
857     GTEST_SKIP();
858 
859   StackOption<std::string, cl::list<std::string>> InputFilenames(
860       cl::Positional, cl::desc("<input files>"));
861   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
862 
863   // Create response file.
864   TempFile ResponseFile("resp-", ".txt",
865                         "-top-level\npath\\dir\\file1\npath/dir/file2",
866                         /*Unique*/ true);
867 
868   llvm::SmallString<128> RspOpt;
869   RspOpt.append(1, '@');
870   RspOpt.append(ResponseFile.path());
871   const char *args[] = {"prog", RspOpt.c_str()};
872   EXPECT_FALSE(TopLevelOpt);
873   EXPECT_TRUE(
874       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
875   EXPECT_TRUE(TopLevelOpt);
876   EXPECT_EQ(InputFilenames[0], "path\\dir\\file1");
877   EXPECT_EQ(InputFilenames[1], "path/dir/file2");
878 }
879 
880 TEST(CommandLineTest, ResponseFiles) {
881   vfs::InMemoryFileSystem FS;
882 #ifdef _WIN32
883   const char *TestRoot = "C:\\";
884 #else
885   const char *TestRoot = "/";
886 #endif
887   FS.setCurrentWorkingDirectory(TestRoot);
888 
889   // Create included response file of first level.
890   llvm::StringRef IncludedFileName = "resp1";
891   FS.addFile(IncludedFileName, 0,
892              llvm::MemoryBuffer::getMemBuffer("-option_1 -option_2\n"
893                                               "@incdir/resp2\n"
894                                               "-option_3=abcd\n"
895                                               "@incdir/resp3\n"
896                                               "-option_4=efjk\n"));
897 
898   // Directory for included file.
899   llvm::StringRef IncDir = "incdir";
900 
901   // Create included response file of second level.
902   llvm::SmallString<128> IncludedFileName2;
903   llvm::sys::path::append(IncludedFileName2, IncDir, "resp2");
904   FS.addFile(IncludedFileName2, 0,
905              MemoryBuffer::getMemBuffer("-option_21 -option_22\n"
906                                         "-option_23=abcd\n"));
907 
908   // Create second included response file of second level.
909   llvm::SmallString<128> IncludedFileName3;
910   llvm::sys::path::append(IncludedFileName3, IncDir, "resp3");
911   FS.addFile(IncludedFileName3, 0,
912              MemoryBuffer::getMemBuffer("-option_31 -option_32\n"
913                                         "-option_33=abcd\n"));
914 
915   // Prepare 'file' with reference to response file.
916   SmallString<128> IncRef;
917   IncRef.append(1, '@');
918   IncRef.append(IncludedFileName);
919   llvm::SmallVector<const char *, 4> Argv = {"test/test", "-flag_1",
920                                              IncRef.c_str(), "-flag_2"};
921 
922   // Expand response files.
923   llvm::BumpPtrAllocator A;
924   llvm::cl::ExpansionContext ECtx(A, llvm::cl::TokenizeGNUCommandLine);
925   ECtx.setVFS(&FS).setCurrentDir(TestRoot).setRelativeNames(true);
926   ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
927   EXPECT_THAT(Argv, testing::Pointwise(
928                         StringEquality(),
929                         {"test/test", "-flag_1", "-option_1", "-option_2",
930                          "-option_21", "-option_22", "-option_23=abcd",
931                          "-option_3=abcd", "-option_31", "-option_32",
932                          "-option_33=abcd", "-option_4=efjk", "-flag_2"}));
933 }
934 
935 TEST(CommandLineTest, RecursiveResponseFiles) {
936   vfs::InMemoryFileSystem FS;
937 #ifdef _WIN32
938   const char *TestRoot = "C:\\";
939 #else
940   const char *TestRoot = "/";
941 #endif
942   FS.setCurrentWorkingDirectory(TestRoot);
943 
944   StringRef SelfFilePath = "self.rsp";
945   std::string SelfFileRef = ("@" + SelfFilePath).str();
946 
947   StringRef NestedFilePath = "nested.rsp";
948   std::string NestedFileRef = ("@" + NestedFilePath).str();
949 
950   StringRef FlagFilePath = "flag.rsp";
951   std::string FlagFileRef = ("@" + FlagFilePath).str();
952 
953   std::string SelfFileContents;
954   raw_string_ostream SelfFile(SelfFileContents);
955   SelfFile << "-option_1\n";
956   SelfFile << FlagFileRef << "\n";
957   SelfFile << NestedFileRef << "\n";
958   SelfFile << SelfFileRef << "\n";
959   FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str()));
960 
961   std::string NestedFileContents;
962   raw_string_ostream NestedFile(NestedFileContents);
963   NestedFile << "-option_2\n";
964   NestedFile << FlagFileRef << "\n";
965   NestedFile << SelfFileRef << "\n";
966   NestedFile << NestedFileRef << "\n";
967   FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str()));
968 
969   std::string FlagFileContents;
970   raw_string_ostream FlagFile(FlagFileContents);
971   FlagFile << "-option_x\n";
972   FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str()));
973 
974   // Ensure:
975   // Recursive expansion terminates
976   // Recursive files never expand
977   // Non-recursive repeats are allowed
978   SmallVector<const char *, 4> Argv = {"test/test", SelfFileRef.c_str(),
979                                        "-option_3"};
980   BumpPtrAllocator A;
981 #ifdef _WIN32
982   cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine;
983 #else
984   cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
985 #endif
986   llvm::cl::ExpansionContext ECtx(A, Tokenizer);
987   ECtx.setVFS(&FS).setCurrentDir(TestRoot);
988   llvm::Error Err = ECtx.expandResponseFiles(Argv);
989   ASSERT_TRUE((bool)Err);
990   SmallString<128> FilePath = SelfFilePath;
991   std::error_code EC = FS.makeAbsolute(FilePath);
992   ASSERT_FALSE((bool)EC);
993   std::string ExpectedMessage =
994       std::string("recursive expansion of: '") + std::string(FilePath) + "'";
995   ASSERT_TRUE(toString(std::move(Err)) == ExpectedMessage);
996 
997   EXPECT_THAT(Argv,
998               testing::Pointwise(StringEquality(),
999                                  {"test/test", "-option_1", "-option_x",
1000                                   "-option_2", "-option_x", SelfFileRef.c_str(),
1001                                   NestedFileRef.c_str(), SelfFileRef.c_str(),
1002                                   "-option_3"}));
1003 }
1004 
1005 TEST(CommandLineTest, ResponseFilesAtArguments) {
1006   vfs::InMemoryFileSystem FS;
1007 #ifdef _WIN32
1008   const char *TestRoot = "C:\\";
1009 #else
1010   const char *TestRoot = "/";
1011 #endif
1012   FS.setCurrentWorkingDirectory(TestRoot);
1013 
1014   StringRef ResponseFilePath = "test.rsp";
1015 
1016   std::string ResponseFileContents;
1017   raw_string_ostream ResponseFile(ResponseFileContents);
1018   ResponseFile << "-foo" << "\n";
1019   ResponseFile << "-bar" << "\n";
1020   FS.addFile(ResponseFilePath, 0,
1021              MemoryBuffer::getMemBuffer(ResponseFile.str()));
1022 
1023   // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
1024   constexpr size_t NON_RSP_AT_ARGS = 64;
1025   SmallVector<const char *, 4> Argv = {"test/test"};
1026   Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg");
1027   std::string ResponseFileRef = ("@" + ResponseFilePath).str();
1028   Argv.push_back(ResponseFileRef.c_str());
1029 
1030   BumpPtrAllocator A;
1031   llvm::cl::ExpansionContext ECtx(A, cl::TokenizeGNUCommandLine);
1032   ECtx.setVFS(&FS).setCurrentDir(TestRoot);
1033   ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
1034 
1035   // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
1036   ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2);
1037   size_t i = 0;
1038   EXPECT_STREQ(Argv[i++], "test/test");
1039   for (; i < 1 + NON_RSP_AT_ARGS; ++i)
1040     EXPECT_STREQ(Argv[i], "@non_rsp_at_arg");
1041   EXPECT_STREQ(Argv[i++], "-foo");
1042   EXPECT_STREQ(Argv[i++], "-bar");
1043 }
1044 
1045 TEST(CommandLineTest, ResponseFileRelativePath) {
1046   vfs::InMemoryFileSystem FS;
1047 #ifdef _WIN32
1048   const char *TestRoot = "C:\\";
1049 #else
1050   const char *TestRoot = "//net";
1051 #endif
1052   FS.setCurrentWorkingDirectory(TestRoot);
1053 
1054   StringRef OuterFile = "dir/outer.rsp";
1055   StringRef OuterFileContents = "@inner.rsp";
1056   FS.addFile(OuterFile, 0, MemoryBuffer::getMemBuffer(OuterFileContents));
1057 
1058   StringRef InnerFile = "dir/inner.rsp";
1059   StringRef InnerFileContents = "-flag";
1060   FS.addFile(InnerFile, 0, MemoryBuffer::getMemBuffer(InnerFileContents));
1061 
1062   SmallVector<const char *, 2> Argv = {"test/test", "@dir/outer.rsp"};
1063 
1064   BumpPtrAllocator A;
1065   llvm::cl::ExpansionContext ECtx(A, cl::TokenizeGNUCommandLine);
1066   ECtx.setVFS(&FS).setCurrentDir(TestRoot).setRelativeNames(true);
1067   ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
1068   EXPECT_THAT(Argv,
1069               testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
1070 }
1071 
1072 TEST(CommandLineTest, ResponseFileEOLs) {
1073   vfs::InMemoryFileSystem FS;
1074 #ifdef _WIN32
1075   const char *TestRoot = "C:\\";
1076 #else
1077   const char *TestRoot = "//net";
1078 #endif
1079   FS.setCurrentWorkingDirectory(TestRoot);
1080   FS.addFile("eols.rsp", 0,
1081              MemoryBuffer::getMemBuffer("-Xclang -Wno-whatever\n input.cpp"));
1082   SmallVector<const char *, 2> Argv = {"clang", "@eols.rsp"};
1083   BumpPtrAllocator A;
1084   llvm::cl::ExpansionContext ECtx(A, cl::TokenizeWindowsCommandLine);
1085   ECtx.setVFS(&FS).setCurrentDir(TestRoot).setMarkEOLs(true).setRelativeNames(
1086       true);
1087   ASSERT_FALSE((bool)ECtx.expandResponseFiles(Argv));
1088   const char *Expected[] = {"clang", "-Xclang", "-Wno-whatever", nullptr,
1089                             "input.cpp"};
1090   ASSERT_EQ(std::size(Expected), Argv.size());
1091   for (size_t I = 0, E = std::size(Expected); I < E; ++I) {
1092     if (Expected[I] == nullptr) {
1093       ASSERT_EQ(Argv[I], nullptr);
1094     } else {
1095       ASSERT_STREQ(Expected[I], Argv[I]);
1096     }
1097   }
1098 }
1099 
1100 TEST(CommandLineTest, BadResponseFile) {
1101   BumpPtrAllocator A;
1102   StringSaver Saver(A);
1103   TempDir ADir("dir", /*Unique*/ true);
1104   SmallString<128> AFilePath = ADir.path();
1105   llvm::sys::path::append(AFilePath, "file.rsp");
1106   std::string AFileExp = std::string("@") + std::string(AFilePath.str());
1107   SmallVector<const char *, 2> Argv = {"clang", AFileExp.c_str()};
1108 
1109   bool Res = cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv);
1110   ASSERT_TRUE(Res);
1111   ASSERT_EQ(2U, Argv.size());
1112   ASSERT_STREQ(Argv[0], "clang");
1113   ASSERT_STREQ(Argv[1], AFileExp.c_str());
1114 
1115 #if !defined(_AIX) && !defined(__MVS__)
1116   std::string ADirExp = std::string("@") + std::string(ADir.path());
1117   Argv = {"clang", ADirExp.c_str()};
1118   Res = cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv);
1119   ASSERT_FALSE(Res);
1120   ASSERT_EQ(2U, Argv.size());
1121   ASSERT_STREQ(Argv[0], "clang");
1122   ASSERT_STREQ(Argv[1], ADirExp.c_str());
1123 #endif
1124 }
1125 
1126 TEST(CommandLineTest, SetDefaultValue) {
1127   cl::ResetCommandLineParser();
1128 
1129   StackOption<std::string> Opt1("opt1", cl::init("true"));
1130   StackOption<bool> Opt2("opt2", cl::init(true));
1131   cl::alias Alias("alias", llvm::cl::aliasopt(Opt2));
1132   StackOption<int> Opt3("opt3", cl::init(3));
1133 
1134   llvm::SmallVector<int, 3> IntVals = {1, 2, 3};
1135   llvm::SmallVector<std::string, 3> StrVals = {"foo", "bar", "baz"};
1136 
1137   StackOption<int, cl::list<int>> List1(
1138       "list1", cl::list_init<int>(llvm::ArrayRef<int>(IntVals)),
1139       cl::CommaSeparated);
1140   StackOption<std::string, cl::list<std::string>> List2(
1141       "list2", cl::list_init<std::string>(llvm::ArrayRef<std::string>(StrVals)),
1142       cl::CommaSeparated);
1143   cl::alias ListAlias("list-alias", llvm::cl::aliasopt(List2));
1144 
1145   const char *args[] = {"prog",   "-opt1=false", "-list1", "4",
1146                         "-list1", "5,6",         "-opt2",  "-opt3"};
1147 
1148   EXPECT_TRUE(
1149       cl::ParseCommandLineOptions(7, args, StringRef(), &llvm::nulls()));
1150 
1151   EXPECT_EQ(Opt1, "false");
1152   EXPECT_TRUE(Opt2);
1153   EXPECT_EQ(Opt3, 3);
1154 
1155   for (size_t I = 0, E = IntVals.size(); I < E; ++I) {
1156     EXPECT_EQ(IntVals[I] + 3, List1[I]);
1157     EXPECT_EQ(StrVals[I], List2[I]);
1158   }
1159 
1160   Opt2 = false;
1161   Opt3 = 1;
1162 
1163   cl::ResetAllOptionOccurrences();
1164 
1165   for (auto &OM : cl::getRegisteredOptions(cl::SubCommand::getTopLevel())) {
1166     cl::Option *O = OM.second;
1167     if (O->ArgStr == "opt2") {
1168       continue;
1169     }
1170     O->setDefault();
1171   }
1172 
1173   EXPECT_EQ(Opt1, "true");
1174   EXPECT_TRUE(Opt2);
1175   EXPECT_EQ(Opt3, 3);
1176   for (size_t I = 0, E = IntVals.size(); I < E; ++I) {
1177     EXPECT_EQ(IntVals[I], List1[I]);
1178     EXPECT_EQ(StrVals[I], List2[I]);
1179   }
1180 
1181   Alias.removeArgument();
1182   ListAlias.removeArgument();
1183 }
1184 
1185 TEST(CommandLineTest, ReadConfigFile) {
1186   llvm::SmallVector<const char *, 1> Argv;
1187 
1188   TempDir TestDir("unittest", /*Unique*/ true);
1189   TempDir TestSubDir(TestDir.path("subdir"), /*Unique*/ false);
1190 
1191   llvm::SmallString<128> TestCfg = TestDir.path("foo");
1192   TempFile ConfigFile(TestCfg, "",
1193                       "# Comment\n"
1194                       "-option_1\n"
1195                       "-option_2=<CFGDIR>/dir1\n"
1196                       "-option_3=<CFGDIR>\n"
1197                       "-option_4 <CFGDIR>\n"
1198                       "-option_5=<CFG\\\n"
1199                       "DIR>\n"
1200                       "-option_6=<CFGDIR>/dir1,<CFGDIR>/dir2\n"
1201                       "@subconfig\n"
1202                       "-option_11=abcd\n"
1203                       "-option_12=\\\n"
1204                       "cdef\n");
1205 
1206   llvm::SmallString<128> TestCfg2 = TestDir.path("subconfig");
1207   TempFile ConfigFile2(TestCfg2, "",
1208                        "-option_7\n"
1209                        "-option_8=<CFGDIR>/dir2\n"
1210                        "@subdir/subfoo\n"
1211                        "\n"
1212                        "   # comment\n");
1213 
1214   llvm::SmallString<128> TestCfg3 = TestSubDir.path("subfoo");
1215   TempFile ConfigFile3(TestCfg3, "",
1216                        "-option_9=<CFGDIR>/dir3\n"
1217                        "@<CFGDIR>/subfoo2\n");
1218 
1219   llvm::SmallString<128> TestCfg4 = TestSubDir.path("subfoo2");
1220   TempFile ConfigFile4(TestCfg4, "", "-option_10\n");
1221 
1222   // Make sure the current directory is not the directory where config files
1223   // resides. In this case the code that expands response files will not find
1224   // 'subconfig' unless it resolves nested inclusions relative to the including
1225   // file.
1226   llvm::SmallString<128> CurrDir;
1227   std::error_code EC = llvm::sys::fs::current_path(CurrDir);
1228   EXPECT_TRUE(!EC);
1229   EXPECT_NE(CurrDir.str(), TestDir.path());
1230 
1231   llvm::BumpPtrAllocator A;
1232   llvm::cl::ExpansionContext ECtx(A, cl::tokenizeConfigFile);
1233   llvm::Error Result = ECtx.readConfigFile(ConfigFile.path(), Argv);
1234 
1235   EXPECT_FALSE((bool)Result);
1236   EXPECT_EQ(Argv.size(), 13U);
1237   EXPECT_STREQ(Argv[0], "-option_1");
1238   EXPECT_STREQ(Argv[1],
1239                ("-option_2=" + TestDir.path() + "/dir1").str().c_str());
1240   EXPECT_STREQ(Argv[2], ("-option_3=" + TestDir.path()).str().c_str());
1241   EXPECT_STREQ(Argv[3], "-option_4");
1242   EXPECT_STREQ(Argv[4], TestDir.path().str().c_str());
1243   EXPECT_STREQ(Argv[5], ("-option_5=" + TestDir.path()).str().c_str());
1244   EXPECT_STREQ(Argv[6], ("-option_6=" + TestDir.path() + "/dir1," +
1245                          TestDir.path() + "/dir2")
1246                             .str()
1247                             .c_str());
1248   EXPECT_STREQ(Argv[7], "-option_7");
1249   EXPECT_STREQ(Argv[8],
1250                ("-option_8=" + TestDir.path() + "/dir2").str().c_str());
1251   EXPECT_STREQ(Argv[9],
1252                ("-option_9=" + TestSubDir.path() + "/dir3").str().c_str());
1253   EXPECT_STREQ(Argv[10], "-option_10");
1254   EXPECT_STREQ(Argv[11], "-option_11=abcd");
1255   EXPECT_STREQ(Argv[12], "-option_12=cdef");
1256 }
1257 
1258 TEST(CommandLineTest, PositionalEatArgsError) {
1259   cl::ResetCommandLineParser();
1260 
1261   StackOption<std::string, cl::list<std::string>> PosEatArgs(
1262       "positional-eat-args", cl::Positional, cl::desc("<arguments>..."),
1263       cl::PositionalEatsArgs);
1264   StackOption<std::string, cl::list<std::string>> PosEatArgs2(
1265       "positional-eat-args2", cl::Positional, cl::desc("Some strings"),
1266       cl::PositionalEatsArgs);
1267 
1268   const char *args[] = {"prog", "-positional-eat-args=XXXX"};
1269   const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1270   const char *args3[] = {"prog", "-positional-eat-args", "-foo"};
1271   const char *args4[] = {"prog", "-positional-eat-args",
1272                          "-foo", "-positional-eat-args2",
1273                          "-bar", "foo"};
1274 
1275   std::string Errs;
1276   raw_string_ostream OS(Errs);
1277   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush();
1278   EXPECT_FALSE(Errs.empty()); Errs.clear();
1279   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush();
1280   EXPECT_FALSE(Errs.empty()); Errs.clear();
1281   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush();
1282   EXPECT_TRUE(Errs.empty()); Errs.clear();
1283 
1284   cl::ResetAllOptionOccurrences();
1285   EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4, StringRef(), &OS)); OS.flush();
1286   EXPECT_EQ(PosEatArgs.size(), 1u);
1287   EXPECT_EQ(PosEatArgs2.size(), 2u);
1288   EXPECT_TRUE(Errs.empty());
1289 }
1290 
1291 #ifdef _WIN32
1292 void checkSeparators(StringRef Path) {
1293   char UndesiredSeparator = sys::path::get_separator()[0] == '/' ? '\\' : '/';
1294   ASSERT_EQ(Path.find(UndesiredSeparator), StringRef::npos);
1295 }
1296 
1297 TEST(CommandLineTest, GetCommandLineArguments) {
1298   int argc = __argc;
1299   char **argv = __argv;
1300 
1301   // GetCommandLineArguments is called in InitLLVM.
1302   llvm::InitLLVM X(argc, argv);
1303 
1304   EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]),
1305             llvm::sys::path::is_absolute(__argv[0]));
1306   checkSeparators(argv[0]);
1307 
1308   EXPECT_TRUE(
1309       llvm::sys::path::filename(argv[0]).equals_insensitive("supporttests.exe"))
1310       << "Filename of test executable is "
1311       << llvm::sys::path::filename(argv[0]);
1312 }
1313 #endif
1314 
1315 class OutputRedirector {
1316 public:
1317   OutputRedirector(int RedirectFD)
1318       : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) {
1319     if (OldFD == -1 ||
1320         sys::fs::createTemporaryFile("unittest-redirect", "", NewFD,
1321                                      FilePath) ||
1322         dup2(NewFD, RedirectFD) == -1)
1323       Valid = false;
1324   }
1325 
1326   ~OutputRedirector() {
1327     dup2(OldFD, RedirectFD);
1328     close(OldFD);
1329     close(NewFD);
1330   }
1331 
1332   SmallVector<char, 128> FilePath;
1333   bool Valid = true;
1334 
1335 private:
1336   int RedirectFD;
1337   int OldFD;
1338   int NewFD;
1339 };
1340 
1341 struct AutoDeleteFile {
1342   SmallVector<char, 128> FilePath;
1343   ~AutoDeleteFile() {
1344     if (!FilePath.empty())
1345       sys::fs::remove(std::string(FilePath.data(), FilePath.size()));
1346   }
1347 };
1348 
1349 static std::string interceptStdout(std::function<void()> F) {
1350   outs().flush(); // flush any output from previous tests
1351   AutoDeleteFile File;
1352   {
1353     OutputRedirector Stdout(fileno(stdout));
1354     if (!Stdout.Valid)
1355       return "";
1356     File.FilePath = Stdout.FilePath;
1357     F();
1358     outs().flush();
1359   }
1360   auto Buffer = MemoryBuffer::getFile(File.FilePath);
1361   if (!Buffer)
1362     return "";
1363   return Buffer->get()->getBuffer().str();
1364 }
1365 
1366 template <void (*Func)(const cl::Option &)>
1367 class PrintOptionTestBase : public ::testing::Test {
1368 public:
1369   // Return std::string because the output of a failing EXPECT check is
1370   // unreadable for StringRef. It also avoids any lifetime issues.
1371   template <typename... Ts> std::string runTest(Ts... OptionAttributes) {
1372     StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText),
1373                                         OptionAttributes...);
1374     return interceptStdout([&]() { Func(TestOption); });
1375   }
1376 
1377   enum class OptionValue { Val };
1378   const StringRef Opt = "some-option";
1379   const StringRef HelpText = "some help";
1380 };
1381 
1382   // This is a workaround for cl::Option sub-classes having their
1383   // printOptionInfo functions private.
1384 void printOptionInfo(const cl::Option &O) {
1385   O.printOptionInfo(/*GlobalWidth=*/26);
1386 }
1387 
1388 using PrintOptionInfoTest = PrintOptionTestBase<printOptionInfo>;
1389 
1390 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) {
1391   std::string Output =
1392       runTest(cl::ValueOptional,
1393               cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
1394 
1395   // clang-format off
1396   EXPECT_EQ(Output, ("  --" + Opt + "=<value> - " + HelpText + "\n"
1397                      "    =v1                 -   desc1\n")
1398                         .str());
1399   // clang-format on
1400 }
1401 
1402 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) {
1403   std::string Output = runTest(
1404       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1405                                     clEnumValN(OptionValue::Val, "", "")));
1406 
1407   // clang-format off
1408   EXPECT_EQ(Output,
1409             ("  --" + Opt + "         - " + HelpText + "\n"
1410              "  --" + Opt + "=<value> - " + HelpText + "\n"
1411              "    =v1                 -   desc1\n")
1412                 .str());
1413   // clang-format on
1414 }
1415 
1416 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) {
1417   std::string Output = runTest(
1418       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1419                                     clEnumValN(OptionValue::Val, "", "desc2")));
1420 
1421   // clang-format off
1422   EXPECT_EQ(Output, ("  --" + Opt + "         - " + HelpText + "\n"
1423                      "  --" + Opt + "=<value> - " + HelpText + "\n"
1424                      "    =v1                 -   desc1\n"
1425                      "    =<empty>            -   desc2\n")
1426                         .str());
1427   // clang-format on
1428 }
1429 
1430 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) {
1431   std::string Output = runTest(
1432       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1433                                     clEnumValN(OptionValue::Val, "", "")));
1434 
1435   // clang-format off
1436   EXPECT_EQ(Output, ("  --" + Opt + "=<value> - " + HelpText + "\n"
1437                      "    =v1                 -   desc1\n"
1438                      "    =<empty>\n")
1439                         .str());
1440   // clang-format on
1441 }
1442 
1443 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) {
1444   std::string Output = runTest(
1445       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "")));
1446 
1447   // clang-format off
1448   EXPECT_EQ(Output,
1449             ("  --" + Opt + "=<value> - " + HelpText + "\n"
1450              "    =v1\n").str());
1451   // clang-format on
1452 }
1453 
1454 TEST_F(PrintOptionInfoTest, PrintOptionInfoMultilineValueDescription) {
1455   std::string Output =
1456       runTest(cl::ValueRequired,
1457               cl::values(clEnumValN(OptionValue::Val, "v1",
1458                                     "This is the first enum value\n"
1459                                     "which has a really long description\n"
1460                                     "thus it is multi-line."),
1461                          clEnumValN(OptionValue::Val, "",
1462                                     "This is an unnamed enum value\n"
1463                                     "Should be indented as well")));
1464 
1465   // clang-format off
1466   EXPECT_EQ(Output,
1467             ("  --" + Opt + "=<value> - " + HelpText + "\n"
1468              "    =v1                 -   This is the first enum value\n"
1469              "                            which has a really long description\n"
1470              "                            thus it is multi-line.\n"
1471              "    =<empty>            -   This is an unnamed enum value\n"
1472              "                            Should be indented as well\n").str());
1473   // clang-format on
1474 }
1475 
1476 void printOptionValue(const cl::Option &O) {
1477   O.printOptionValue(/*GlobalWidth=*/12, /*Force=*/true);
1478 }
1479 
1480 using PrintOptionValueTest = PrintOptionTestBase<printOptionValue>;
1481 
1482 TEST_F(PrintOptionValueTest, PrintOptionDefaultValue) {
1483   std::string Output =
1484       runTest(cl::init(OptionValue::Val),
1485               cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
1486 
1487   EXPECT_EQ(Output, ("    --" + Opt + " = v1       (default: v1)\n").str());
1488 }
1489 
1490 TEST_F(PrintOptionValueTest, PrintOptionNoDefaultValue) {
1491   std::string Output =
1492       runTest(cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
1493 
1494   // Note: the option still has a (zero-initialized) value, but the default
1495   // is invalid and doesn't match any value.
1496   EXPECT_EQ(Output, ("    --" + Opt + " = v1       (default: )\n").str());
1497 }
1498 
1499 TEST_F(PrintOptionValueTest, PrintOptionUnknownValue) {
1500   std::string Output = runTest(cl::init(OptionValue::Val));
1501 
1502   EXPECT_EQ(Output, ("    --" + Opt + " = *unknown option value*\n").str());
1503 }
1504 
1505 class GetOptionWidthTest : public ::testing::Test {
1506 public:
1507   enum class OptionValue { Val };
1508 
1509   template <typename... Ts>
1510   size_t runTest(StringRef ArgName, Ts... OptionAttributes) {
1511     StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"),
1512                                         OptionAttributes...);
1513     return getOptionWidth(TestOption);
1514   }
1515 
1516 private:
1517   // This is a workaround for cl::Option sub-classes having their
1518   // printOptionInfo
1519   // functions private.
1520   size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); }
1521 };
1522 
1523 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) {
1524   StringRef ArgName("a-long-argument-name");
1525   size_t ExpectedStrSize = ("  --" + ArgName + "=<value> - ").str().size();
1526   EXPECT_EQ(
1527       runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))),
1528       ExpectedStrSize);
1529 }
1530 
1531 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) {
1532   StringRef OptName("a-long-option-name");
1533   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1534   EXPECT_EQ(
1535       runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"),
1536                               clEnumValN(OptionValue::Val, "b", "help"))),
1537       ExpectedStrSize);
1538 }
1539 
1540 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) {
1541   StringRef OptName("a-long-option-name");
1542   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1543   EXPECT_EQ(
1544       runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1545                               clEnumValN(OptionValue::Val, OptName, "help"))),
1546       ExpectedStrSize);
1547 }
1548 
1549 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) {
1550   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1551   // The length of a=<value> (including indentation) is actually the same as the
1552   // =<empty> string, so it is impossible to distinguish via testing the case
1553   // where the empty string is picked from where the option name is picked.
1554   EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1555                                     clEnumValN(OptionValue::Val, "", "help"))),
1556             ExpectedStrSize);
1557 }
1558 
1559 TEST_F(GetOptionWidthTest,
1560        GetOptionWidthValueOptionalEmptyOptionWithNoDescription) {
1561   StringRef ArgName("a");
1562   // The length of a=<value> (including indentation) is actually the same as the
1563   // =<empty> string, so it is impossible to distinguish via testing the case
1564   // where the empty string is ignored from where it is not ignored.
1565   // The dash will not actually be printed, but the space it would take up is
1566   // included to ensure a consistent column width.
1567   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1568   EXPECT_EQ(runTest(ArgName, cl::ValueOptional,
1569                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1570                                clEnumValN(OptionValue::Val, "", ""))),
1571             ExpectedStrSize);
1572 }
1573 
1574 TEST_F(GetOptionWidthTest,
1575        GetOptionWidthValueRequiredEmptyOptionWithNoDescription) {
1576   // The length of a=<value> (including indentation) is actually the same as the
1577   // =<empty> string, so it is impossible to distinguish via testing the case
1578   // where the empty string is picked from where the option name is picked
1579   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1580   EXPECT_EQ(runTest("a", cl::ValueRequired,
1581                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1582                                clEnumValN(OptionValue::Val, "", ""))),
1583             ExpectedStrSize);
1584 }
1585 
1586 TEST(CommandLineTest, PrefixOptions) {
1587   cl::ResetCommandLineParser();
1588 
1589   StackOption<std::string, cl::list<std::string>> IncludeDirs(
1590       "I", cl::Prefix, cl::desc("Declare an include directory"));
1591 
1592   // Test non-prefixed variant works with cl::Prefix options.
1593   EXPECT_TRUE(IncludeDirs.empty());
1594   const char *args[] = {"prog", "-I=/usr/include"};
1595   EXPECT_TRUE(
1596       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1597   EXPECT_EQ(IncludeDirs.size(), 1u);
1598   EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0);
1599 
1600   IncludeDirs.erase(IncludeDirs.begin());
1601   cl::ResetAllOptionOccurrences();
1602 
1603   // Test non-prefixed variant works with cl::Prefix options when value is
1604   // passed in following argument.
1605   EXPECT_TRUE(IncludeDirs.empty());
1606   const char *args2[] = {"prog", "-I", "/usr/include"};
1607   EXPECT_TRUE(
1608       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1609   EXPECT_EQ(IncludeDirs.size(), 1u);
1610   EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0);
1611 
1612   IncludeDirs.erase(IncludeDirs.begin());
1613   cl::ResetAllOptionOccurrences();
1614 
1615   // Test prefixed variant works with cl::Prefix options.
1616   EXPECT_TRUE(IncludeDirs.empty());
1617   const char *args3[] = {"prog", "-I/usr/include"};
1618   EXPECT_TRUE(
1619       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1620   EXPECT_EQ(IncludeDirs.size(), 1u);
1621   EXPECT_EQ(IncludeDirs.front().compare("/usr/include"), 0);
1622 
1623   StackOption<std::string, cl::list<std::string>> MacroDefs(
1624       "D", cl::AlwaysPrefix, cl::desc("Define a macro"),
1625       cl::value_desc("MACRO[=VALUE]"));
1626 
1627   cl::ResetAllOptionOccurrences();
1628 
1629   // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1630   // equal sign is part of the value.
1631   EXPECT_TRUE(MacroDefs.empty());
1632   const char *args4[] = {"prog", "-D=HAVE_FOO"};
1633   EXPECT_TRUE(
1634       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1635   EXPECT_EQ(MacroDefs.size(), 1u);
1636   EXPECT_EQ(MacroDefs.front().compare("=HAVE_FOO"), 0);
1637 
1638   MacroDefs.erase(MacroDefs.begin());
1639   cl::ResetAllOptionOccurrences();
1640 
1641   // Test non-prefixed variant does not allow value to be passed in following
1642   // argument with cl::AlwaysPrefix options.
1643   EXPECT_TRUE(MacroDefs.empty());
1644   const char *args5[] = {"prog", "-D", "HAVE_FOO"};
1645   EXPECT_FALSE(
1646       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1647   EXPECT_TRUE(MacroDefs.empty());
1648 
1649   cl::ResetAllOptionOccurrences();
1650 
1651   // Test prefixed variant works with cl::AlwaysPrefix options.
1652   EXPECT_TRUE(MacroDefs.empty());
1653   const char *args6[] = {"prog", "-DHAVE_FOO"};
1654   EXPECT_TRUE(
1655       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1656   EXPECT_EQ(MacroDefs.size(), 1u);
1657   EXPECT_EQ(MacroDefs.front().compare("HAVE_FOO"), 0);
1658 }
1659 
1660 TEST(CommandLineTest, GroupingWithValue) {
1661   cl::ResetCommandLineParser();
1662 
1663   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1664   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1665   StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed,
1666                          cl::desc("ValueDisallowed option"));
1667   StackOption<std::string> OptV("v", cl::Grouping,
1668                                 cl::desc("ValueRequired option"));
1669   StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional,
1670                                 cl::desc("ValueOptional option"));
1671 
1672   // Should be possible to use an option which requires a value
1673   // at the end of a group.
1674   const char *args1[] = {"prog", "-fv", "val1"};
1675   EXPECT_TRUE(
1676       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
1677   EXPECT_TRUE(OptF);
1678   EXPECT_STREQ("val1", OptV.c_str());
1679   OptV.clear();
1680   cl::ResetAllOptionOccurrences();
1681 
1682   // Should not crash if it is accidentally used elsewhere in the group.
1683   const char *args2[] = {"prog", "-vf", "val2"};
1684   EXPECT_FALSE(
1685       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1686   OptV.clear();
1687   cl::ResetAllOptionOccurrences();
1688 
1689   // Should allow the "opt=value" form at the end of the group
1690   const char *args3[] = {"prog", "-fv=val3"};
1691   EXPECT_TRUE(
1692       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1693   EXPECT_TRUE(OptF);
1694   EXPECT_STREQ("val3", OptV.c_str());
1695   OptV.clear();
1696   cl::ResetAllOptionOccurrences();
1697 
1698   // Should allow assigning a value for a ValueOptional option
1699   // at the end of the group
1700   const char *args4[] = {"prog", "-fo=val4"};
1701   EXPECT_TRUE(
1702       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1703   EXPECT_TRUE(OptF);
1704   EXPECT_STREQ("val4", OptO.c_str());
1705   OptO.clear();
1706   cl::ResetAllOptionOccurrences();
1707 
1708   // Should assign an empty value if a ValueOptional option is used elsewhere
1709   // in the group.
1710   const char *args5[] = {"prog", "-fob"};
1711   EXPECT_TRUE(
1712       cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls()));
1713   EXPECT_TRUE(OptF);
1714   EXPECT_EQ(1, OptO.getNumOccurrences());
1715   EXPECT_EQ(1, OptB.getNumOccurrences());
1716   EXPECT_TRUE(OptO.empty());
1717   cl::ResetAllOptionOccurrences();
1718 
1719   // Should not allow an assignment for a ValueDisallowed option.
1720   const char *args6[] = {"prog", "-fd=false"};
1721   EXPECT_FALSE(
1722       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1723 }
1724 
1725 TEST(CommandLineTest, GroupingAndPrefix) {
1726   cl::ResetCommandLineParser();
1727 
1728   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1729   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1730   StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping,
1731                                 cl::desc("Prefix and Grouping"));
1732   StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping,
1733                                 cl::desc("AlwaysPrefix and Grouping"));
1734 
1735   // Should be possible to use a cl::Prefix option without grouping.
1736   const char *args1[] = {"prog", "-pval1"};
1737   EXPECT_TRUE(
1738       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
1739   EXPECT_STREQ("val1", OptP.c_str());
1740   OptP.clear();
1741   cl::ResetAllOptionOccurrences();
1742 
1743   // Should be possible to pass a value in a separate argument.
1744   const char *args2[] = {"prog", "-p", "val2"};
1745   EXPECT_TRUE(
1746       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1747   EXPECT_STREQ("val2", OptP.c_str());
1748   OptP.clear();
1749   cl::ResetAllOptionOccurrences();
1750 
1751   // The "-opt=value" form should work, too.
1752   const char *args3[] = {"prog", "-p=val3"};
1753   EXPECT_TRUE(
1754       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1755   EXPECT_STREQ("val3", OptP.c_str());
1756   OptP.clear();
1757   cl::ResetAllOptionOccurrences();
1758 
1759   // All three previous cases should work the same way if an option with both
1760   // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1761   const char *args4[] = {"prog", "-fpval4"};
1762   EXPECT_TRUE(
1763       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1764   EXPECT_TRUE(OptF);
1765   EXPECT_STREQ("val4", OptP.c_str());
1766   OptP.clear();
1767   cl::ResetAllOptionOccurrences();
1768 
1769   const char *args5[] = {"prog", "-fp", "val5"};
1770   EXPECT_TRUE(
1771       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1772   EXPECT_TRUE(OptF);
1773   EXPECT_STREQ("val5", OptP.c_str());
1774   OptP.clear();
1775   cl::ResetAllOptionOccurrences();
1776 
1777   const char *args6[] = {"prog", "-fp=val6"};
1778   EXPECT_TRUE(
1779       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1780   EXPECT_TRUE(OptF);
1781   EXPECT_STREQ("val6", OptP.c_str());
1782   OptP.clear();
1783   cl::ResetAllOptionOccurrences();
1784 
1785   // Should assign a value even if the part after a cl::Prefix option is equal
1786   // to the name of another option.
1787   const char *args7[] = {"prog", "-fpb"};
1788   EXPECT_TRUE(
1789       cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls()));
1790   EXPECT_TRUE(OptF);
1791   EXPECT_STREQ("b", OptP.c_str());
1792   EXPECT_FALSE(OptB);
1793   OptP.clear();
1794   cl::ResetAllOptionOccurrences();
1795 
1796   // Should be possible to use a cl::AlwaysPrefix option without grouping.
1797   const char *args8[] = {"prog", "-aval8"};
1798   EXPECT_TRUE(
1799       cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls()));
1800   EXPECT_STREQ("val8", OptA.c_str());
1801   OptA.clear();
1802   cl::ResetAllOptionOccurrences();
1803 
1804   // Should not be possible to pass a value in a separate argument.
1805   const char *args9[] = {"prog", "-a", "val9"};
1806   EXPECT_FALSE(
1807       cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls()));
1808   cl::ResetAllOptionOccurrences();
1809 
1810   // With the "-opt=value" form, the "=" symbol should be preserved.
1811   const char *args10[] = {"prog", "-a=val10"};
1812   EXPECT_TRUE(
1813       cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls()));
1814   EXPECT_STREQ("=val10", OptA.c_str());
1815   OptA.clear();
1816   cl::ResetAllOptionOccurrences();
1817 
1818   // All three previous cases should work the same way if an option with both
1819   // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1820   const char *args11[] = {"prog", "-faval11"};
1821   EXPECT_TRUE(
1822       cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls()));
1823   EXPECT_TRUE(OptF);
1824   EXPECT_STREQ("val11", OptA.c_str());
1825   OptA.clear();
1826   cl::ResetAllOptionOccurrences();
1827 
1828   const char *args12[] = {"prog", "-fa", "val12"};
1829   EXPECT_FALSE(
1830       cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls()));
1831   cl::ResetAllOptionOccurrences();
1832 
1833   const char *args13[] = {"prog", "-fa=val13"};
1834   EXPECT_TRUE(
1835       cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls()));
1836   EXPECT_TRUE(OptF);
1837   EXPECT_STREQ("=val13", OptA.c_str());
1838   OptA.clear();
1839   cl::ResetAllOptionOccurrences();
1840 
1841   // Should assign a value even if the part after a cl::AlwaysPrefix option
1842   // is equal to the name of another option.
1843   const char *args14[] = {"prog", "-fab"};
1844   EXPECT_TRUE(
1845       cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls()));
1846   EXPECT_TRUE(OptF);
1847   EXPECT_STREQ("b", OptA.c_str());
1848   EXPECT_FALSE(OptB);
1849   OptA.clear();
1850   cl::ResetAllOptionOccurrences();
1851 }
1852 
1853 TEST(CommandLineTest, LongOptions) {
1854   cl::ResetCommandLineParser();
1855 
1856   StackOption<bool> OptA("a", cl::desc("Some flag"));
1857   StackOption<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1858   StackOption<bool, cl::alias> OptB("b", cl::desc("Alias to --long-flag"),
1859                                     cl::aliasopt(OptBLong));
1860   StackOption<std::string> OptAB("ab", cl::desc("Another long option"));
1861 
1862   std::string Errs;
1863   raw_string_ostream OS(Errs);
1864 
1865   const char *args1[] = {"prog", "-a", "-ab", "val1"};
1866   const char *args2[] = {"prog", "-a", "--ab", "val1"};
1867   const char *args3[] = {"prog", "-ab", "--ab", "val1"};
1868 
1869   //
1870   // The following tests treat `-` and `--` the same, and always match the
1871   // longest string.
1872   //
1873 
1874   EXPECT_TRUE(
1875       cl::ParseCommandLineOptions(4, args1, StringRef(), &OS)); OS.flush();
1876   EXPECT_TRUE(OptA);
1877   EXPECT_FALSE(OptBLong);
1878   EXPECT_STREQ("val1", OptAB.c_str());
1879   EXPECT_TRUE(Errs.empty()); Errs.clear();
1880   cl::ResetAllOptionOccurrences();
1881 
1882   EXPECT_TRUE(
1883       cl::ParseCommandLineOptions(4, args2, StringRef(), &OS)); OS.flush();
1884   EXPECT_TRUE(OptA);
1885   EXPECT_FALSE(OptBLong);
1886   EXPECT_STREQ("val1", OptAB.c_str());
1887   EXPECT_TRUE(Errs.empty()); Errs.clear();
1888   cl::ResetAllOptionOccurrences();
1889 
1890   // Fails because `-ab` and `--ab` are treated the same and appear more than
1891   // once.  Also, `val1` is unexpected.
1892   EXPECT_FALSE(
1893       cl::ParseCommandLineOptions(4, args3, StringRef(), &OS)); OS.flush();
1894   outs()<< Errs << "\n";
1895   EXPECT_FALSE(Errs.empty()); Errs.clear();
1896   cl::ResetAllOptionOccurrences();
1897 
1898   //
1899   // The following tests treat `-` and `--` differently, with `-` for short, and
1900   // `--` for long options.
1901   //
1902 
1903   // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1904   // `val1` is unexpected.
1905   EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(),
1906                                            &OS, nullptr, true)); OS.flush();
1907   EXPECT_FALSE(Errs.empty()); Errs.clear();
1908   cl::ResetAllOptionOccurrences();
1909 
1910   // Works because `-a` is treated differently than `--ab`.
1911   EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(),
1912                                            &OS, nullptr, true)); OS.flush();
1913   EXPECT_TRUE(Errs.empty()); Errs.clear();
1914   cl::ResetAllOptionOccurrences();
1915 
1916   // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1917   EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(),
1918                                            &OS, nullptr, true));
1919   EXPECT_TRUE(OptA);
1920   EXPECT_TRUE(OptBLong);
1921   EXPECT_STREQ("val1", OptAB.c_str());
1922   OS.flush();
1923   EXPECT_TRUE(Errs.empty()); Errs.clear();
1924   cl::ResetAllOptionOccurrences();
1925 }
1926 
1927 TEST(CommandLineTest, OptionErrorMessage) {
1928   // When there is an error, we expect some error message like:
1929   //   prog: for the -a option: [...]
1930   //
1931   // Test whether the "for the -a option"-part is correctly formatted.
1932   cl::ResetCommandLineParser();
1933 
1934   StackOption<bool> OptA("a", cl::desc("Some option"));
1935   StackOption<bool> OptLong("long", cl::desc("Some long option"));
1936 
1937   std::string Errs;
1938   raw_string_ostream OS(Errs);
1939 
1940   OptA.error("custom error", OS);
1941   OS.flush();
1942   EXPECT_NE(Errs.find("for the -a option:"), std::string::npos);
1943   Errs.clear();
1944 
1945   OptLong.error("custom error", OS);
1946   OS.flush();
1947   EXPECT_NE(Errs.find("for the --long option:"), std::string::npos);
1948   Errs.clear();
1949 
1950   cl::ResetAllOptionOccurrences();
1951 }
1952 
1953 TEST(CommandLineTest, OptionErrorMessageSuggest) {
1954   // When there is an error, and the edit-distance is not very large,
1955   // we expect some error message like:
1956   //   prog: did you mean '--option'?
1957   //
1958   // Test whether this message is well-formatted.
1959   cl::ResetCommandLineParser();
1960 
1961   StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1962 
1963   const char *args[] = {"prog", "--aluminum"};
1964 
1965   std::string Errs;
1966   raw_string_ostream OS(Errs);
1967 
1968   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1969   OS.flush();
1970   EXPECT_NE(Errs.find("prog: Did you mean '--aluminium'?\n"),
1971             std::string::npos);
1972   Errs.clear();
1973 
1974   cl::ResetAllOptionOccurrences();
1975 }
1976 
1977 TEST(CommandLineTest, OptionErrorMessageSuggestNoHidden) {
1978   // We expect that 'really hidden' option do not show up in option
1979   // suggestions.
1980   cl::ResetCommandLineParser();
1981 
1982   StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1983   StackOption<bool> OptLong2("aluminum", cl::desc("Bad option"),
1984                              cl::ReallyHidden);
1985 
1986   const char *args[] = {"prog", "--alumnum"};
1987 
1988   std::string Errs;
1989   raw_string_ostream OS(Errs);
1990 
1991   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1992   OS.flush();
1993   EXPECT_NE(Errs.find("prog: Did you mean '--aluminium'?\n"),
1994             std::string::npos);
1995   Errs.clear();
1996 
1997   cl::ResetAllOptionOccurrences();
1998 }
1999 
2000 TEST(CommandLineTest, Callback) {
2001   cl::ResetCommandLineParser();
2002 
2003   StackOption<bool> OptA("a", cl::desc("option a"));
2004   StackOption<bool> OptB(
2005       "b", cl::desc("option b -- This option turns on option a"),
2006       cl::callback([&](const bool &) { OptA = true; }));
2007   StackOption<bool> OptC(
2008       "c", cl::desc("option c -- This option turns on options a and b"),
2009       cl::callback([&](const bool &) { OptB = true; }));
2010   StackOption<std::string, cl::list<std::string>> List(
2011       "list",
2012       cl::desc("option list -- This option turns on options a, b, and c when "
2013                "'foo' is included in list"),
2014       cl::CommaSeparated,
2015       cl::callback([&](const std::string &Str) {
2016         if (Str == "foo")
2017           OptC = true;
2018       }));
2019 
2020   const char *args1[] = {"prog", "-a"};
2021   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args1));
2022   EXPECT_TRUE(OptA);
2023   EXPECT_FALSE(OptB);
2024   EXPECT_FALSE(OptC);
2025   EXPECT_EQ(List.size(), 0u);
2026   cl::ResetAllOptionOccurrences();
2027 
2028   const char *args2[] = {"prog", "-b"};
2029   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args2));
2030   EXPECT_TRUE(OptA);
2031   EXPECT_TRUE(OptB);
2032   EXPECT_FALSE(OptC);
2033   EXPECT_EQ(List.size(), 0u);
2034   cl::ResetAllOptionOccurrences();
2035 
2036   const char *args3[] = {"prog", "-c"};
2037   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args3));
2038   EXPECT_TRUE(OptA);
2039   EXPECT_TRUE(OptB);
2040   EXPECT_TRUE(OptC);
2041   EXPECT_EQ(List.size(), 0u);
2042   cl::ResetAllOptionOccurrences();
2043 
2044   const char *args4[] = {"prog", "--list=foo,bar"};
2045   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args4));
2046   EXPECT_TRUE(OptA);
2047   EXPECT_TRUE(OptB);
2048   EXPECT_TRUE(OptC);
2049   EXPECT_EQ(List.size(), 2u);
2050   cl::ResetAllOptionOccurrences();
2051 
2052   const char *args5[] = {"prog", "--list=bar"};
2053   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args5));
2054   EXPECT_FALSE(OptA);
2055   EXPECT_FALSE(OptB);
2056   EXPECT_FALSE(OptC);
2057   EXPECT_EQ(List.size(), 1u);
2058 
2059   cl::ResetAllOptionOccurrences();
2060 }
2061 
2062 enum Enum { Val1, Val2 };
2063 static cl::bits<Enum> ExampleBits(
2064     cl::desc("An example cl::bits to ensure it compiles"),
2065     cl::values(
2066       clEnumValN(Val1, "bits-val1", "The Val1 value"),
2067       clEnumValN(Val1, "bits-val2", "The Val2 value")));
2068 
2069 TEST(CommandLineTest, ConsumeAfterOnePositional) {
2070   cl::ResetCommandLineParser();
2071 
2072   // input [args]
2073   StackOption<std::string, cl::opt<std::string>> Input(cl::Positional,
2074                                                        cl::Required);
2075   StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
2076 
2077   const char *Args[] = {"prog", "input", "arg1", "arg2"};
2078 
2079   std::string Errs;
2080   raw_string_ostream OS(Errs);
2081   EXPECT_TRUE(cl::ParseCommandLineOptions(4, Args, StringRef(), &OS));
2082   OS.flush();
2083   EXPECT_EQ("input", Input);
2084   EXPECT_EQ(ExtraArgs.size(), 2u);
2085   EXPECT_EQ(ExtraArgs[0], "arg1");
2086   EXPECT_EQ(ExtraArgs[1], "arg2");
2087   EXPECT_TRUE(Errs.empty());
2088 }
2089 
2090 TEST(CommandLineTest, ConsumeAfterTwoPositionals) {
2091   cl::ResetCommandLineParser();
2092 
2093   // input1 input2 [args]
2094   StackOption<std::string, cl::opt<std::string>> Input1(cl::Positional,
2095                                                         cl::Required);
2096   StackOption<std::string, cl::opt<std::string>> Input2(cl::Positional,
2097                                                         cl::Required);
2098   StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
2099 
2100   const char *Args[] = {"prog", "input1", "input2", "arg1", "arg2"};
2101 
2102   std::string Errs;
2103   raw_string_ostream OS(Errs);
2104   EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args, StringRef(), &OS));
2105   OS.flush();
2106   EXPECT_EQ("input1", Input1);
2107   EXPECT_EQ("input2", Input2);
2108   EXPECT_EQ(ExtraArgs.size(), 2u);
2109   EXPECT_EQ(ExtraArgs[0], "arg1");
2110   EXPECT_EQ(ExtraArgs[1], "arg2");
2111   EXPECT_TRUE(Errs.empty());
2112 }
2113 
2114 TEST(CommandLineTest, ResetAllOptionOccurrences) {
2115   cl::ResetCommandLineParser();
2116 
2117   // -option -str -enableA -enableC [sink] input [args]
2118   StackOption<bool> Option("option");
2119   StackOption<std::string> Str("str");
2120   enum Vals { ValA, ValB, ValC };
2121   StackOption<Vals, cl::bits<Vals>> Bits(
2122       cl::values(clEnumValN(ValA, "enableA", "Enable A"),
2123                  clEnumValN(ValB, "enableB", "Enable B"),
2124                  clEnumValN(ValC, "enableC", "Enable C")));
2125   StackOption<std::string, cl::list<std::string>> Sink(cl::Sink);
2126   StackOption<std::string> Input(cl::Positional);
2127   StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
2128 
2129   const char *Args[] = {"prog",     "-option",  "-str=STR", "-enableA",
2130                         "-enableC", "-unknown", "input",    "-arg"};
2131 
2132   std::string Errs;
2133   raw_string_ostream OS(Errs);
2134   EXPECT_TRUE(cl::ParseCommandLineOptions(8, Args, StringRef(), &OS));
2135   EXPECT_TRUE(OS.str().empty());
2136 
2137   EXPECT_TRUE(Option);
2138   EXPECT_EQ("STR", Str);
2139   EXPECT_EQ((1u << ValA) | (1u << ValC), Bits.getBits());
2140   EXPECT_EQ(1u, Sink.size());
2141   EXPECT_EQ("-unknown", Sink[0]);
2142   EXPECT_EQ("input", Input);
2143   EXPECT_EQ(1u, ExtraArgs.size());
2144   EXPECT_EQ("-arg", ExtraArgs[0]);
2145 
2146   cl::ResetAllOptionOccurrences();
2147   EXPECT_FALSE(Option);
2148   EXPECT_EQ("", Str);
2149   EXPECT_EQ(0u, Bits.getBits());
2150   EXPECT_EQ(0u, Sink.size());
2151   EXPECT_EQ(0, Input.getNumOccurrences());
2152   EXPECT_EQ(0u, ExtraArgs.size());
2153 }
2154 
2155 TEST(CommandLineTest, DefaultValue) {
2156   cl::ResetCommandLineParser();
2157 
2158   StackOption<bool> BoolOption("bool-option");
2159   StackOption<std::string> StrOption("str-option");
2160   StackOption<bool> BoolInitOption("bool-init-option", cl::init(true));
2161   StackOption<std::string> StrInitOption("str-init-option",
2162                                          cl::init("str-default-value"));
2163 
2164   const char *Args[] = {"prog"}; // no options
2165 
2166   std::string Errs;
2167   raw_string_ostream OS(Errs);
2168   EXPECT_TRUE(cl::ParseCommandLineOptions(1, Args, StringRef(), &OS));
2169   EXPECT_TRUE(OS.str().empty());
2170 
2171   EXPECT_TRUE(!BoolOption);
2172   EXPECT_FALSE(BoolOption.Default.hasValue());
2173   EXPECT_EQ(0, BoolOption.getNumOccurrences());
2174 
2175   EXPECT_EQ("", StrOption);
2176   EXPECT_FALSE(StrOption.Default.hasValue());
2177   EXPECT_EQ(0, StrOption.getNumOccurrences());
2178 
2179   EXPECT_TRUE(BoolInitOption);
2180   EXPECT_TRUE(BoolInitOption.Default.hasValue());
2181   EXPECT_EQ(0, BoolInitOption.getNumOccurrences());
2182 
2183   EXPECT_EQ("str-default-value", StrInitOption);
2184   EXPECT_TRUE(StrInitOption.Default.hasValue());
2185   EXPECT_EQ(0, StrInitOption.getNumOccurrences());
2186 
2187   const char *Args2[] = {"prog", "-bool-option", "-str-option=str-value",
2188                          "-bool-init-option=0",
2189                          "-str-init-option=str-init-value"};
2190 
2191   EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args2, StringRef(), &OS));
2192   EXPECT_TRUE(OS.str().empty());
2193 
2194   EXPECT_TRUE(BoolOption);
2195   EXPECT_FALSE(BoolOption.Default.hasValue());
2196   EXPECT_EQ(1, BoolOption.getNumOccurrences());
2197 
2198   EXPECT_EQ("str-value", StrOption);
2199   EXPECT_FALSE(StrOption.Default.hasValue());
2200   EXPECT_EQ(1, StrOption.getNumOccurrences());
2201 
2202   EXPECT_FALSE(BoolInitOption);
2203   EXPECT_TRUE(BoolInitOption.Default.hasValue());
2204   EXPECT_EQ(1, BoolInitOption.getNumOccurrences());
2205 
2206   EXPECT_EQ("str-init-value", StrInitOption);
2207   EXPECT_TRUE(StrInitOption.Default.hasValue());
2208   EXPECT_EQ(1, StrInitOption.getNumOccurrences());
2209 }
2210 
2211 TEST(CommandLineTest, HelpWithoutSubcommands) {
2212   // Check that the help message does not contain the "[subcommand]" placeholder
2213   // and the "SUBCOMMANDS" section if there are no subcommands.
2214   cl::ResetCommandLineParser();
2215   StackOption<bool> Opt("opt", cl::init(false));
2216   const char *args[] = {"prog"};
2217   EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(),
2218                                           &llvm::nulls()));
2219   auto Output = interceptStdout([]() { cl::PrintHelpMessage(); });
2220   EXPECT_NE(std::string::npos, Output.find("USAGE: prog [options]")) << Output;
2221   EXPECT_EQ(std::string::npos, Output.find("SUBCOMMANDS:")) << Output;
2222   cl::ResetCommandLineParser();
2223 }
2224 
2225 TEST(CommandLineTest, HelpWithSubcommands) {
2226   // Check that the help message contains the "[subcommand]" placeholder in the
2227   // "USAGE" line and describes subcommands.
2228   cl::ResetCommandLineParser();
2229   StackSubCommand SC1("sc1", "First Subcommand");
2230   StackSubCommand SC2("sc2", "Second Subcommand");
2231   StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
2232   StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
2233   const char *args[] = {"prog"};
2234   EXPECT_TRUE(cl::ParseCommandLineOptions(std::size(args), args, StringRef(),
2235                                           &llvm::nulls()));
2236   auto Output = interceptStdout([]() { cl::PrintHelpMessage(); });
2237   EXPECT_NE(std::string::npos,
2238             Output.find("USAGE: prog [subcommand] [options]"))
2239       << Output;
2240   EXPECT_NE(std::string::npos, Output.find("SUBCOMMANDS:")) << Output;
2241   EXPECT_NE(std::string::npos, Output.find("sc1 - First Subcommand")) << Output;
2242   EXPECT_NE(std::string::npos, Output.find("sc2 - Second Subcommand"))
2243       << Output;
2244   cl::ResetCommandLineParser();
2245 }
2246 
2247 TEST(CommandLineTest, UnknownCommands) {
2248   cl::ResetCommandLineParser();
2249 
2250   StackSubCommand SC1("foo", "Foo subcommand");
2251   StackSubCommand SC2("bar", "Bar subcommand");
2252   StackOption<bool> SC1Opt("put", cl::sub(SC1));
2253   StackOption<bool> SC2Opt("get", cl::sub(SC2));
2254   StackOption<bool> TopOpt1("peek");
2255   StackOption<bool> TopOpt2("set");
2256 
2257   std::string Errs;
2258   raw_string_ostream OS(Errs);
2259 
2260   const char *Args1[] = {"prog", "baz", "--get"};
2261   EXPECT_FALSE(
2262       cl::ParseCommandLineOptions(std::size(Args1), Args1, StringRef(), &OS));
2263   EXPECT_EQ(Errs,
2264             "prog: Unknown subcommand 'baz'.  Try: 'prog --help'\n"
2265             "prog: Did you mean 'bar'?\n"
2266             "prog: Unknown command line argument '--get'.  Try: 'prog --help'\n"
2267             "prog: Did you mean '--set'?\n");
2268 
2269   // Do not show a suggestion if the subcommand is not similar to any known.
2270   Errs.clear();
2271   const char *Args2[] = {"prog", "faz"};
2272   EXPECT_FALSE(
2273       cl::ParseCommandLineOptions(std::size(Args2), Args2, StringRef(), &OS));
2274   EXPECT_EQ(Errs, "prog: Unknown subcommand 'faz'.  Try: 'prog --help'\n");
2275 }
2276 
2277 TEST(CommandLineTest, SubCommandGroups) {
2278   // Check that options in subcommand groups are associated with expected
2279   // subcommands.
2280 
2281   cl::ResetCommandLineParser();
2282 
2283   StackSubCommand SC1("sc1", "SC1 subcommand");
2284   StackSubCommand SC2("sc2", "SC2 subcommand");
2285   StackSubCommand SC3("sc3", "SC3 subcommand");
2286   cl::SubCommandGroup Group12 = {&SC1, &SC2};
2287 
2288   StackOption<bool> Opt12("opt12", cl::sub(Group12), cl::init(false));
2289   StackOption<bool> Opt3("opt3", cl::sub(SC3), cl::init(false));
2290 
2291   // The "--opt12" option is expected to be added to both subcommands in the
2292   // group, but not to the top-level "no subcommand" pseudo-subcommand or the
2293   // "sc3" subcommand.
2294   EXPECT_EQ(1U, SC1.OptionsMap.size());
2295   EXPECT_TRUE(SC1.OptionsMap.contains("opt12"));
2296 
2297   EXPECT_EQ(1U, SC2.OptionsMap.size());
2298   EXPECT_TRUE(SC2.OptionsMap.contains("opt12"));
2299 
2300   EXPECT_FALSE(cl::SubCommand::getTopLevel().OptionsMap.contains("opt12"));
2301   EXPECT_FALSE(SC3.OptionsMap.contains("opt12"));
2302 }
2303 
2304 } // anonymous namespace
2305