xref: /llvm-project/llvm/unittests/Support/CommandLineTest.cpp (revision 75656005dbc8866e1888932a68a830b0df403560)
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/ADT/Triple.h"
14 #include "llvm/Config/config.h"
15 #include "llvm/Support/Allocator.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/InitLLVM.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/StringSaver.h"
22 #include "llvm/Support/VirtualFileSystem.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "gmock/gmock.h"
25 #include "gtest/gtest.h"
26 #include <fstream>
27 #include <stdlib.h>
28 #include <string>
29 #include <tuple>
30 
31 using namespace llvm;
32 
33 namespace {
34 
35 MATCHER(StringEquality, "Checks if two char* are equal as strings") {
36   return std::string(std::get<0>(arg)) == std::string(std::get<1>(arg));
37 }
38 
39 class TempEnvVar {
40  public:
41   TempEnvVar(const char *name, const char *value)
42       : name(name) {
43     const char *old_value = getenv(name);
44     EXPECT_EQ(nullptr, old_value) << old_value;
45 #if HAVE_SETENV
46     setenv(name, value, true);
47 #else
48 #   define SKIP_ENVIRONMENT_TESTS
49 #endif
50   }
51 
52   ~TempEnvVar() {
53 #if HAVE_SETENV
54     // Assume setenv and unsetenv come together.
55     unsetenv(name);
56 #else
57     (void)name; // Suppress -Wunused-private-field.
58 #endif
59   }
60 
61  private:
62   const char *const name;
63 };
64 
65 template <typename T, typename Base = cl::opt<T>>
66 class StackOption : public Base {
67 public:
68   template <class... Ts>
69   explicit StackOption(Ts &&... Ms) : Base(std::forward<Ts>(Ms)...) {}
70 
71   ~StackOption() override { this->removeArgument(); }
72 
73   template <class DT> StackOption<T> &operator=(const DT &V) {
74     this->setValue(V);
75     return *this;
76   }
77 };
78 
79 class StackSubCommand : public cl::SubCommand {
80 public:
81   StackSubCommand(StringRef Name,
82                   StringRef Description = StringRef())
83       : SubCommand(Name, Description) {}
84 
85   StackSubCommand() : SubCommand() {}
86 
87   ~StackSubCommand() { unregisterSubCommand(); }
88 };
89 
90 
91 cl::OptionCategory TestCategory("Test Options", "Description");
92 TEST(CommandLineTest, ModifyExisitingOption) {
93   StackOption<int> TestOption("test-option", cl::desc("old description"));
94 
95   static const char Description[] = "New description";
96   static const char ArgString[] = "new-test-option";
97   static const char ValueString[] = "Integer";
98 
99   StringMap<cl::Option *> &Map =
100       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
101 
102   ASSERT_TRUE(Map.count("test-option") == 1) <<
103     "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::GeneralCategory;
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 #ifndef SKIP_ENVIRONMENT_TESTS
140 
141 const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
142 
143 cl::opt<std::string> EnvironmentTestOption("env-test-opt");
144 TEST(CommandLineTest, ParseEnvironment) {
145   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
146   EXPECT_EQ("", EnvironmentTestOption);
147   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
148   EXPECT_EQ("hello", EnvironmentTestOption);
149 }
150 
151 // This test used to make valgrind complain
152 // ("Conditional jump or move depends on uninitialised value(s)")
153 //
154 // Warning: Do not run any tests after this one that try to gain access to
155 // registered command line options because this will likely result in a
156 // SEGFAULT. This can occur because the cl::opt in the test below is declared
157 // on the stack which will be destroyed after the test completes but the
158 // command line system will still hold a pointer to a deallocated cl::Option.
159 TEST(CommandLineTest, ParseEnvironmentToLocalVar) {
160   // Put cl::opt on stack to check for proper initialization of fields.
161   StackOption<std::string> EnvironmentTestOptionLocal("env-test-opt-local");
162   TempEnvVar TEV(test_env_var, "-env-test-opt-local=hello-local");
163   EXPECT_EQ("", EnvironmentTestOptionLocal);
164   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
165   EXPECT_EQ("hello-local", EnvironmentTestOptionLocal);
166 }
167 
168 #endif  // SKIP_ENVIRONMENT_TESTS
169 
170 TEST(CommandLineTest, UseOptionCategory) {
171   StackOption<int> TestOption2("test-option", cl::cat(TestCategory));
172 
173   ASSERT_NE(TestOption2.Categories.end(),
174             find_if(TestOption2.Categories,
175                          [&](const llvm::cl::OptionCategory *Cat) {
176                            return Cat == &TestCategory;
177                          }))
178       << "Failed to assign Option Category.";
179 }
180 
181 TEST(CommandLineTest, UseMultipleCategories) {
182   StackOption<int> TestOption2("test-option2", cl::cat(TestCategory),
183                                cl::cat(cl::GeneralCategory),
184                                cl::cat(cl::GeneralCategory));
185 
186   // Make sure cl::GeneralCategory wasn't added twice.
187   ASSERT_EQ(TestOption2.Categories.size(), 2U);
188 
189   ASSERT_NE(TestOption2.Categories.end(),
190             find_if(TestOption2.Categories,
191                          [&](const llvm::cl::OptionCategory *Cat) {
192                            return Cat == &TestCategory;
193                          }))
194       << "Failed to assign Option Category.";
195   ASSERT_NE(TestOption2.Categories.end(),
196             find_if(TestOption2.Categories,
197                          [&](const llvm::cl::OptionCategory *Cat) {
198                            return Cat == &cl::GeneralCategory;
199                          }))
200       << "Failed to assign General Category.";
201 
202   cl::OptionCategory AnotherCategory("Additional test Options", "Description");
203   StackOption<int> TestOption("test-option", cl::cat(TestCategory),
204                               cl::cat(AnotherCategory));
205   ASSERT_EQ(TestOption.Categories.end(),
206             find_if(TestOption.Categories,
207                          [&](const llvm::cl::OptionCategory *Cat) {
208                            return Cat == &cl::GeneralCategory;
209                          }))
210       << "Failed to remove General Category.";
211   ASSERT_NE(TestOption.Categories.end(),
212             find_if(TestOption.Categories,
213                          [&](const llvm::cl::OptionCategory *Cat) {
214                            return Cat == &TestCategory;
215                          }))
216       << "Failed to assign Option Category.";
217   ASSERT_NE(TestOption.Categories.end(),
218             find_if(TestOption.Categories,
219                          [&](const llvm::cl::OptionCategory *Cat) {
220                            return Cat == &AnotherCategory;
221                          }))
222       << "Failed to assign Another Category.";
223 }
224 
225 typedef void ParserFunction(StringRef Source, StringSaver &Saver,
226                             SmallVectorImpl<const char *> &NewArgv,
227                             bool MarkEOLs);
228 
229 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input,
230                               const char *const Output[], size_t OutputSize) {
231   SmallVector<const char *, 0> Actual;
232   BumpPtrAllocator A;
233   StringSaver Saver(A);
234   parse(Input, Saver, Actual, /*MarkEOLs=*/false);
235   EXPECT_EQ(OutputSize, Actual.size());
236   for (unsigned I = 0, E = Actual.size(); I != E; ++I) {
237     if (I < OutputSize) {
238       EXPECT_STREQ(Output[I], Actual[I]);
239     }
240   }
241 }
242 
243 TEST(CommandLineTest, TokenizeGNUCommandLine) {
244   const char Input[] =
245       "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) "
246       "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\"";
247   const char *const Output[] = {
248       "foo bar",     "foo bar",   "foo bar",          "foo\\bar",
249       "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"};
250   testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
251                            array_lengthof(Output));
252 }
253 
254 TEST(CommandLineTest, TokenizeWindowsCommandLine1) {
255   const char Input[] = "a\\b c\\\\d e\\\\\"f g\" h\\\"i j\\\\\\\"k \"lmn\" o pqr "
256                       "\"st \\\"u\" \\v";
257   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
258                                  "lmn", "o", "pqr", "st \"u", "\\v" };
259   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
260                            array_lengthof(Output));
261 }
262 
263 TEST(CommandLineTest, TokenizeWindowsCommandLine2) {
264   const char Input[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp";
265   const char *const Output[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"};
266   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
267                            array_lengthof(Output));
268 }
269 
270 TEST(CommandLineTest, TokenizeConfigFile1) {
271   const char *Input = "\\";
272   const char *const Output[] = { "\\" };
273   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
274                            array_lengthof(Output));
275 }
276 
277 TEST(CommandLineTest, TokenizeConfigFile2) {
278   const char *Input = "\\abc";
279   const char *const Output[] = { "abc" };
280   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
281                            array_lengthof(Output));
282 }
283 
284 TEST(CommandLineTest, TokenizeConfigFile3) {
285   const char *Input = "abc\\";
286   const char *const Output[] = { "abc\\" };
287   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
288                            array_lengthof(Output));
289 }
290 
291 TEST(CommandLineTest, TokenizeConfigFile4) {
292   const char *Input = "abc\\\n123";
293   const char *const Output[] = { "abc123" };
294   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
295                            array_lengthof(Output));
296 }
297 
298 TEST(CommandLineTest, TokenizeConfigFile5) {
299   const char *Input = "abc\\\r\n123";
300   const char *const Output[] = { "abc123" };
301   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
302                            array_lengthof(Output));
303 }
304 
305 TEST(CommandLineTest, TokenizeConfigFile6) {
306   const char *Input = "abc\\\n";
307   const char *const Output[] = { "abc" };
308   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
309                            array_lengthof(Output));
310 }
311 
312 TEST(CommandLineTest, TokenizeConfigFile7) {
313   const char *Input = "abc\\\r\n";
314   const char *const Output[] = { "abc" };
315   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
316                            array_lengthof(Output));
317 }
318 
319 TEST(CommandLineTest, TokenizeConfigFile8) {
320   SmallVector<const char *, 0> Actual;
321   BumpPtrAllocator A;
322   StringSaver Saver(A);
323   cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false);
324   EXPECT_TRUE(Actual.empty());
325 }
326 
327 TEST(CommandLineTest, TokenizeConfigFile9) {
328   SmallVector<const char *, 0> Actual;
329   BumpPtrAllocator A;
330   StringSaver Saver(A);
331   cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false);
332   EXPECT_TRUE(Actual.empty());
333 }
334 
335 TEST(CommandLineTest, TokenizeConfigFile10) {
336   const char *Input = "\\\nabc";
337   const char *const Output[] = { "abc" };
338   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
339                            array_lengthof(Output));
340 }
341 
342 TEST(CommandLineTest, TokenizeConfigFile11) {
343   const char *Input = "\\\r\nabc";
344   const char *const Output[] = { "abc" };
345   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
346                            array_lengthof(Output));
347 }
348 
349 TEST(CommandLineTest, AliasesWithArguments) {
350   static const size_t ARGC = 3;
351   const char *const Inputs[][ARGC] = {
352     { "-tool", "-actual=x", "-extra" },
353     { "-tool", "-actual", "x" },
354     { "-tool", "-alias=x", "-extra" },
355     { "-tool", "-alias", "x" }
356   };
357 
358   for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) {
359     StackOption<std::string> Actual("actual");
360     StackOption<bool> Extra("extra");
361     StackOption<std::string> Input(cl::Positional);
362 
363     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
364 
365     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
366     EXPECT_EQ("x", Actual);
367     EXPECT_EQ(0, Input.getNumOccurrences());
368 
369     Alias.removeArgument();
370   }
371 }
372 
373 void testAliasRequired(int argc, const char *const *argv) {
374   StackOption<std::string> Option("option", cl::Required);
375   cl::alias Alias("o", llvm::cl::aliasopt(Option));
376 
377   cl::ParseCommandLineOptions(argc, argv);
378   EXPECT_EQ("x", Option);
379   EXPECT_EQ(1, Option.getNumOccurrences());
380 
381   Alias.removeArgument();
382 }
383 
384 TEST(CommandLineTest, AliasRequired) {
385   const char *opts1[] = { "-tool", "-option=x" };
386   const char *opts2[] = { "-tool", "-o", "x" };
387   testAliasRequired(array_lengthof(opts1), opts1);
388   testAliasRequired(array_lengthof(opts2), opts2);
389 }
390 
391 TEST(CommandLineTest, HideUnrelatedOptions) {
392   StackOption<int> TestOption1("hide-option-1");
393   StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory));
394 
395   cl::HideUnrelatedOptions(TestCategory);
396 
397   ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
398       << "Failed to hide extra option.";
399   ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
400       << "Hid extra option that should be visable.";
401 
402   StringMap<cl::Option *> &Map =
403       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
404   ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag())
405       << "Hid default option that should be visable.";
406 }
407 
408 cl::OptionCategory TestCategory2("Test Options set 2", "Description");
409 
410 TEST(CommandLineTest, HideUnrelatedOptionsMulti) {
411   StackOption<int> TestOption1("multi-hide-option-1");
412   StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory));
413   StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2));
414 
415   const cl::OptionCategory *VisibleCategories[] = {&TestCategory,
416                                                    &TestCategory2};
417 
418   cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
419 
420   ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
421       << "Failed to hide extra option.";
422   ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
423       << "Hid extra option that should be visable.";
424   ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag())
425       << "Hid extra option that should be visable.";
426 
427   StringMap<cl::Option *> &Map =
428       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
429   ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag())
430       << "Hid default option that should be visable.";
431 }
432 
433 TEST(CommandLineTest, SetValueInSubcategories) {
434   cl::ResetCommandLineParser();
435 
436   StackSubCommand SC1("sc1", "First subcommand");
437   StackSubCommand SC2("sc2", "Second subcommand");
438 
439   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
440   StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
441   StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
442 
443   EXPECT_FALSE(TopLevelOpt);
444   EXPECT_FALSE(SC1Opt);
445   EXPECT_FALSE(SC2Opt);
446   const char *args[] = {"prog", "-top-level"};
447   EXPECT_TRUE(
448       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
449   EXPECT_TRUE(TopLevelOpt);
450   EXPECT_FALSE(SC1Opt);
451   EXPECT_FALSE(SC2Opt);
452 
453   TopLevelOpt = false;
454 
455   cl::ResetAllOptionOccurrences();
456   EXPECT_FALSE(TopLevelOpt);
457   EXPECT_FALSE(SC1Opt);
458   EXPECT_FALSE(SC2Opt);
459   const char *args2[] = {"prog", "sc1", "-sc1"};
460   EXPECT_TRUE(
461       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
462   EXPECT_FALSE(TopLevelOpt);
463   EXPECT_TRUE(SC1Opt);
464   EXPECT_FALSE(SC2Opt);
465 
466   SC1Opt = false;
467 
468   cl::ResetAllOptionOccurrences();
469   EXPECT_FALSE(TopLevelOpt);
470   EXPECT_FALSE(SC1Opt);
471   EXPECT_FALSE(SC2Opt);
472   const char *args3[] = {"prog", "sc2", "-sc2"};
473   EXPECT_TRUE(
474       cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls()));
475   EXPECT_FALSE(TopLevelOpt);
476   EXPECT_FALSE(SC1Opt);
477   EXPECT_TRUE(SC2Opt);
478 }
479 
480 TEST(CommandLineTest, LookupFailsInWrongSubCommand) {
481   cl::ResetCommandLineParser();
482 
483   StackSubCommand SC1("sc1", "First subcommand");
484   StackSubCommand SC2("sc2", "Second subcommand");
485 
486   StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
487   StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
488 
489   std::string Errs;
490   raw_string_ostream OS(Errs);
491 
492   const char *args[] = {"prog", "sc1", "-sc2"};
493   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
494   OS.flush();
495   EXPECT_FALSE(Errs.empty());
496 }
497 
498 TEST(CommandLineTest, AddToAllSubCommands) {
499   cl::ResetCommandLineParser();
500 
501   StackSubCommand SC1("sc1", "First subcommand");
502   StackOption<bool> AllOpt("everywhere", cl::sub(*cl::AllSubCommands),
503                            cl::init(false));
504   StackSubCommand SC2("sc2", "Second subcommand");
505 
506   const char *args[] = {"prog", "-everywhere"};
507   const char *args2[] = {"prog", "sc1", "-everywhere"};
508   const char *args3[] = {"prog", "sc2", "-everywhere"};
509 
510   std::string Errs;
511   raw_string_ostream OS(Errs);
512 
513   EXPECT_FALSE(AllOpt);
514   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
515   EXPECT_TRUE(AllOpt);
516 
517   AllOpt = false;
518 
519   cl::ResetAllOptionOccurrences();
520   EXPECT_FALSE(AllOpt);
521   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS));
522   EXPECT_TRUE(AllOpt);
523 
524   AllOpt = false;
525 
526   cl::ResetAllOptionOccurrences();
527   EXPECT_FALSE(AllOpt);
528   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS));
529   EXPECT_TRUE(AllOpt);
530 
531   // Since all parsing succeeded, the error message should be empty.
532   OS.flush();
533   EXPECT_TRUE(Errs.empty());
534 }
535 
536 TEST(CommandLineTest, ReparseCommandLineOptions) {
537   cl::ResetCommandLineParser();
538 
539   StackOption<bool> TopLevelOpt("top-level", cl::sub(*cl::TopLevelSubCommand),
540                                 cl::init(false));
541 
542   const char *args[] = {"prog", "-top-level"};
543 
544   EXPECT_FALSE(TopLevelOpt);
545   EXPECT_TRUE(
546       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
547   EXPECT_TRUE(TopLevelOpt);
548 
549   TopLevelOpt = false;
550 
551   cl::ResetAllOptionOccurrences();
552   EXPECT_FALSE(TopLevelOpt);
553   EXPECT_TRUE(
554       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
555   EXPECT_TRUE(TopLevelOpt);
556 }
557 
558 TEST(CommandLineTest, RemoveFromRegularSubCommand) {
559   cl::ResetCommandLineParser();
560 
561   StackSubCommand SC("sc", "Subcommand");
562   StackOption<bool> RemoveOption("remove-option", cl::sub(SC), cl::init(false));
563   StackOption<bool> KeepOption("keep-option", cl::sub(SC), cl::init(false));
564 
565   const char *args[] = {"prog", "sc", "-remove-option"};
566 
567   std::string Errs;
568   raw_string_ostream OS(Errs);
569 
570   EXPECT_FALSE(RemoveOption);
571   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
572   EXPECT_TRUE(RemoveOption);
573   OS.flush();
574   EXPECT_TRUE(Errs.empty());
575 
576   RemoveOption.removeArgument();
577 
578   cl::ResetAllOptionOccurrences();
579   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
580   OS.flush();
581   EXPECT_FALSE(Errs.empty());
582 }
583 
584 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
585   cl::ResetCommandLineParser();
586 
587   StackOption<bool> TopLevelRemove(
588       "top-level-remove", cl::sub(*cl::TopLevelSubCommand), cl::init(false));
589   StackOption<bool> TopLevelKeep(
590       "top-level-keep", cl::sub(*cl::TopLevelSubCommand), cl::init(false));
591 
592   const char *args[] = {"prog", "-top-level-remove"};
593 
594   EXPECT_FALSE(TopLevelRemove);
595   EXPECT_TRUE(
596       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
597   EXPECT_TRUE(TopLevelRemove);
598 
599   TopLevelRemove.removeArgument();
600 
601   cl::ResetAllOptionOccurrences();
602   EXPECT_FALSE(
603       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
604 }
605 
606 TEST(CommandLineTest, RemoveFromAllSubCommands) {
607   cl::ResetCommandLineParser();
608 
609   StackSubCommand SC1("sc1", "First Subcommand");
610   StackSubCommand SC2("sc2", "Second Subcommand");
611   StackOption<bool> RemoveOption("remove-option", cl::sub(*cl::AllSubCommands),
612                                  cl::init(false));
613   StackOption<bool> KeepOption("keep-option", cl::sub(*cl::AllSubCommands),
614                                cl::init(false));
615 
616   const char *args0[] = {"prog", "-remove-option"};
617   const char *args1[] = {"prog", "sc1", "-remove-option"};
618   const char *args2[] = {"prog", "sc2", "-remove-option"};
619 
620   // It should work for all subcommands including the top-level.
621   EXPECT_FALSE(RemoveOption);
622   EXPECT_TRUE(
623       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
624   EXPECT_TRUE(RemoveOption);
625 
626   RemoveOption = false;
627 
628   cl::ResetAllOptionOccurrences();
629   EXPECT_FALSE(RemoveOption);
630   EXPECT_TRUE(
631       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
632   EXPECT_TRUE(RemoveOption);
633 
634   RemoveOption = false;
635 
636   cl::ResetAllOptionOccurrences();
637   EXPECT_FALSE(RemoveOption);
638   EXPECT_TRUE(
639       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
640   EXPECT_TRUE(RemoveOption);
641 
642   RemoveOption.removeArgument();
643 
644   // It should not work for any subcommands including the top-level.
645   cl::ResetAllOptionOccurrences();
646   EXPECT_FALSE(
647       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
648   cl::ResetAllOptionOccurrences();
649   EXPECT_FALSE(
650       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
651   cl::ResetAllOptionOccurrences();
652   EXPECT_FALSE(
653       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
654 }
655 
656 TEST(CommandLineTest, GetRegisteredSubcommands) {
657   cl::ResetCommandLineParser();
658 
659   StackSubCommand SC1("sc1", "First Subcommand");
660   StackOption<bool> Opt1("opt1", cl::sub(SC1), cl::init(false));
661   StackSubCommand SC2("sc2", "Second subcommand");
662   StackOption<bool> Opt2("opt2", cl::sub(SC2), cl::init(false));
663 
664   const char *args0[] = {"prog", "sc1"};
665   const char *args1[] = {"prog", "sc2"};
666 
667   EXPECT_TRUE(
668       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
669   EXPECT_FALSE(Opt1);
670   EXPECT_FALSE(Opt2);
671   for (auto *S : cl::getRegisteredSubcommands()) {
672     if (*S) {
673       EXPECT_EQ("sc1", S->getName());
674     }
675   }
676 
677   cl::ResetAllOptionOccurrences();
678   EXPECT_TRUE(
679       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
680   EXPECT_FALSE(Opt1);
681   EXPECT_FALSE(Opt2);
682   for (auto *S : cl::getRegisteredSubcommands()) {
683     if (*S) {
684       EXPECT_EQ("sc2", S->getName());
685     }
686   }
687 }
688 
689 TEST(CommandLineTest, DefaultOptions) {
690   cl::ResetCommandLineParser();
691 
692   StackOption<std::string> Bar("bar", cl::sub(*cl::AllSubCommands),
693                                cl::DefaultOption);
694   StackOption<std::string, cl::alias> Bar_Alias(
695       "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption);
696 
697   StackOption<bool> Foo("foo", cl::init(false), cl::sub(*cl::AllSubCommands),
698                         cl::DefaultOption);
699   StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"),
700                                          cl::aliasopt(Foo), cl::DefaultOption);
701 
702   StackSubCommand SC1("sc1", "First Subcommand");
703   // Override "-b" and change type in sc1 SubCommand.
704   StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false));
705   StackSubCommand SC2("sc2", "Second subcommand");
706   // Override "-foo" and change type in sc2 SubCommand.  Note that this does not
707   // affect "-f" alias, which continues to work correctly.
708   StackOption<std::string> SC2_Foo("foo", cl::sub(SC2));
709 
710   const char *args0[] = {"prog", "-b", "args0 bar string", "-f"};
711   EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args0) / sizeof(char *), args0,
712                                           StringRef(), &llvm::nulls()));
713   EXPECT_TRUE(Bar == "args0 bar string");
714   EXPECT_TRUE(Foo);
715   EXPECT_FALSE(SC1_B);
716   EXPECT_TRUE(SC2_Foo.empty());
717 
718   cl::ResetAllOptionOccurrences();
719 
720   const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"};
721   EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args1) / sizeof(char *), args1,
722                                           StringRef(), &llvm::nulls()));
723   EXPECT_TRUE(Bar == "args1 bar string");
724   EXPECT_TRUE(Foo);
725   EXPECT_TRUE(SC1_B);
726   EXPECT_TRUE(SC2_Foo.empty());
727   for (auto *S : cl::getRegisteredSubcommands()) {
728     if (*S) {
729       EXPECT_EQ("sc1", S->getName());
730     }
731   }
732 
733   cl::ResetAllOptionOccurrences();
734 
735   const char *args2[] = {"prog", "sc2", "-b", "args2 bar string",
736                          "-f", "-foo", "foo string"};
737   EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args2) / sizeof(char *), args2,
738                                           StringRef(), &llvm::nulls()));
739   EXPECT_TRUE(Bar == "args2 bar string");
740   EXPECT_TRUE(Foo);
741   EXPECT_FALSE(SC1_B);
742   EXPECT_TRUE(SC2_Foo == "foo string");
743   for (auto *S : cl::getRegisteredSubcommands()) {
744     if (*S) {
745       EXPECT_EQ("sc2", S->getName());
746     }
747   }
748   cl::ResetCommandLineParser();
749 }
750 
751 TEST(CommandLineTest, ArgumentLimit) {
752   std::string args(32 * 4096, 'a');
753   EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data()));
754 }
755 
756 TEST(CommandLineTest, ResponseFileWindows) {
757   if (!Triple(sys::getProcessTriple()).isOSWindows())
758     return;
759 
760   StackOption<std::string, cl::list<std::string>> InputFilenames(
761       cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore);
762   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
763 
764   // Create response file.
765   int FileDescriptor;
766   SmallString<64> TempPath;
767   std::error_code EC =
768       llvm::sys::fs::createTemporaryFile("resp-", ".txt", FileDescriptor, TempPath);
769   EXPECT_TRUE(!EC);
770 
771   std::ofstream RspFile(TempPath.c_str());
772   EXPECT_TRUE(RspFile.is_open());
773   RspFile << "-top-level\npath\\dir\\file1\npath/dir/file2";
774   RspFile.close();
775 
776   llvm::SmallString<128> RspOpt;
777   RspOpt.append(1, '@');
778   RspOpt.append(TempPath.c_str());
779   const char *args[] = {"prog", RspOpt.c_str()};
780   EXPECT_FALSE(TopLevelOpt);
781   EXPECT_TRUE(
782       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
783   EXPECT_TRUE(TopLevelOpt);
784   EXPECT_TRUE(InputFilenames[0] == "path\\dir\\file1");
785   EXPECT_TRUE(InputFilenames[1] == "path/dir/file2");
786 
787   llvm::sys::fs::remove(TempPath.c_str());
788 }
789 
790 TEST(CommandLineTest, ResponseFiles) {
791   vfs::InMemoryFileSystem FS;
792   FS.setCurrentWorkingDirectory("/");
793 
794   // Create included response file of first level.
795   llvm::StringRef IncludedFileName = "resp1";
796   FS.addFile(IncludedFileName, 0,
797              llvm::MemoryBuffer::getMemBuffer("-option_1 -option_2\n"
798                                               "@incdir/resp2\n"
799                                               "-option_3=abcd\n"
800                                               "@incdir/resp3\n"
801                                               "-option_4=efjk\n"));
802 
803   // Directory for included file.
804   llvm::StringRef IncDir = "incdir";
805 
806   // Create included response file of second level.
807   llvm::SmallString<128> IncludedFileName2;
808   llvm::sys::path::append(IncludedFileName2, IncDir, "resp2");
809   FS.addFile(IncludedFileName2, 0,
810              MemoryBuffer::getMemBuffer("-option_21 -option_22\n"
811                                         "-option_23=abcd\n"));
812   llvm::errs() << "Added: " << IncludedFileName2 << '\n';
813 
814   // Create second included response file of second level.
815   llvm::SmallString<128> IncludedFileName3;
816   llvm::sys::path::append(IncludedFileName3, IncDir, "resp3");
817   FS.addFile(IncludedFileName3, 0,
818              MemoryBuffer::getMemBuffer("-option_31 -option_32\n"
819                                         "-option_33=abcd\n"));
820 
821   // Prepare 'file' with reference to response file.
822   SmallString<128> IncRef;
823   IncRef.append(1, '@');
824   IncRef.append(IncludedFileName);
825   llvm::SmallVector<const char *, 4> Argv = {"test/test", "-flag_1",
826                                              IncRef.c_str(), "-flag_2"};
827 
828   // Expand response files.
829   llvm::BumpPtrAllocator A;
830   llvm::StringSaver Saver(A);
831   ASSERT_TRUE(llvm::cl::ExpandResponseFiles(
832       Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true, FS,
833       /*CurrentDir=*/StringRef("/")));
834   EXPECT_THAT(Argv, testing::Pointwise(
835                         StringEquality(),
836                         {"test/test", "-flag_1", "-option_1", "-option_2",
837                          "-option_21", "-option_22", "-option_23=abcd",
838                          "-option_3=abcd", "-option_31", "-option_32",
839                          "-option_33=abcd", "-option_4=efjk", "-flag_2"}));
840 }
841 
842 TEST(CommandLineTest, RecursiveResponseFiles) {
843   vfs::InMemoryFileSystem FS;
844   FS.setCurrentWorkingDirectory("/");
845 
846   StringRef SelfFilePath = "self.rsp";
847   std::string SelfFileRef = ("@" + SelfFilePath).str();
848 
849   StringRef NestedFilePath = "nested.rsp";
850   std::string NestedFileRef = ("@" + NestedFilePath).str();
851 
852   StringRef FlagFilePath = "flag.rsp";
853   std::string FlagFileRef = ("@" + FlagFilePath).str();
854 
855   std::string SelfFileContents;
856   raw_string_ostream SelfFile(SelfFileContents);
857   SelfFile << "-option_1\n";
858   SelfFile << FlagFileRef << "\n";
859   SelfFile << NestedFileRef << "\n";
860   SelfFile << SelfFileRef << "\n";
861   FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str()));
862 
863   std::string NestedFileContents;
864   raw_string_ostream NestedFile(NestedFileContents);
865   NestedFile << "-option_2\n";
866   NestedFile << FlagFileRef << "\n";
867   NestedFile << SelfFileRef << "\n";
868   NestedFile << NestedFileRef << "\n";
869   FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str()));
870 
871   std::string FlagFileContents;
872   raw_string_ostream FlagFile(FlagFileContents);
873   FlagFile << "-option_x\n";
874   FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str()));
875 
876   // Ensure:
877   // Recursive expansion terminates
878   // Recursive files never expand
879   // Non-recursive repeats are allowed
880   SmallVector<const char *, 4> Argv = {"test/test", SelfFileRef.c_str(),
881                                        "-option_3"};
882   BumpPtrAllocator A;
883   StringSaver Saver(A);
884 #ifdef _WIN32
885   cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine;
886 #else
887   cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
888 #endif
889   ASSERT_FALSE(cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false, FS,
890                                        /*CurrentDir=*/llvm::StringRef("/")));
891 
892   EXPECT_THAT(Argv,
893               testing::Pointwise(StringEquality(),
894                                  {"test/test", "-option_1", "-option_x",
895                                   "-option_2", "-option_x", SelfFileRef.c_str(),
896                                   NestedFileRef.c_str(), SelfFileRef.c_str(),
897                                   "-option_3"}));
898 }
899 
900 TEST(CommandLineTest, ResponseFilesAtArguments) {
901   vfs::InMemoryFileSystem FS;
902   FS.setCurrentWorkingDirectory("/");
903 
904   StringRef ResponseFilePath = "test.rsp";
905 
906   std::string ResponseFileContents;
907   raw_string_ostream ResponseFile(ResponseFileContents);
908   ResponseFile << "-foo" << "\n";
909   ResponseFile << "-bar" << "\n";
910   FS.addFile(ResponseFilePath, 0,
911              MemoryBuffer::getMemBuffer(ResponseFile.str()));
912 
913   // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
914   constexpr size_t NON_RSP_AT_ARGS = 64;
915   SmallVector<const char *, 4> Argv = {"test/test"};
916   Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg");
917   std::string ResponseFileRef = ("@" + ResponseFilePath).str();
918   Argv.push_back(ResponseFileRef.c_str());
919 
920   BumpPtrAllocator A;
921   StringSaver Saver(A);
922   ASSERT_FALSE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
923                                        false, false, FS,
924                                        /*CurrentDir=*/StringRef("/")));
925 
926   // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
927   ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2);
928   size_t i = 0;
929   EXPECT_STREQ(Argv[i++], "test/test");
930   for (; i < 1 + NON_RSP_AT_ARGS; ++i)
931     EXPECT_STREQ(Argv[i], "@non_rsp_at_arg");
932   EXPECT_STREQ(Argv[i++], "-foo");
933   EXPECT_STREQ(Argv[i++], "-bar");
934 }
935 
936 TEST(CommandLineTest, ResponseFileRelativePath) {
937   vfs::InMemoryFileSystem FS;
938 
939   StringRef OuterFile = "//net/dir/outer.rsp";
940   StringRef OuterFileContents = "@inner.rsp";
941   FS.addFile(OuterFile, 0, MemoryBuffer::getMemBuffer(OuterFileContents));
942 
943   StringRef InnerFile = "//net/dir/inner.rsp";
944   StringRef InnerFileContents = "-flag";
945   FS.addFile(InnerFile, 0, MemoryBuffer::getMemBuffer(InnerFileContents));
946 
947   SmallVector<const char *, 2> Argv = {"test/test", "@dir/outer.rsp"};
948 
949   BumpPtrAllocator A;
950   StringSaver Saver(A);
951   ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
952                                       false, true, FS,
953                                       /*CurrentDir=*/StringRef("//net")));
954   EXPECT_THAT(Argv,
955               testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
956 }
957 
958 TEST(CommandLineTest, SetDefautValue) {
959   cl::ResetCommandLineParser();
960 
961   StackOption<std::string> Opt1("opt1", cl::init("true"));
962   StackOption<bool> Opt2("opt2", cl::init(true));
963   cl::alias Alias("alias", llvm::cl::aliasopt(Opt2));
964   StackOption<int> Opt3("opt3", cl::init(3));
965 
966   const char *args[] = {"prog", "-opt1=false", "-opt2", "-opt3"};
967 
968   EXPECT_TRUE(
969     cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
970 
971   EXPECT_TRUE(Opt1 == "false");
972   EXPECT_TRUE(Opt2);
973   EXPECT_TRUE(Opt3 == 3);
974 
975   Opt2 = false;
976   Opt3 = 1;
977 
978   cl::ResetAllOptionOccurrences();
979 
980   for (auto &OM : cl::getRegisteredOptions(*cl::TopLevelSubCommand)) {
981     cl::Option *O = OM.second;
982     if (O->ArgStr == "opt2") {
983       continue;
984     }
985     O->setDefault();
986   }
987 
988   EXPECT_TRUE(Opt1 == "true");
989   EXPECT_TRUE(Opt2);
990   EXPECT_TRUE(Opt3 == 3);
991   Alias.removeArgument();
992 }
993 
994 TEST(CommandLineTest, ReadConfigFile) {
995   llvm::SmallVector<const char *, 1> Argv;
996 
997   llvm::SmallString<128> TestDir;
998   std::error_code EC =
999       llvm::sys::fs::createUniqueDirectory("unittest", TestDir);
1000   EXPECT_TRUE(!EC);
1001 
1002   llvm::SmallString<128> TestCfg;
1003   llvm::sys::path::append(TestCfg, TestDir, "foo");
1004   std::ofstream ConfigFile(TestCfg.c_str());
1005   EXPECT_TRUE(ConfigFile.is_open());
1006   ConfigFile << "# Comment\n"
1007                 "-option_1\n"
1008                 "@subconfig\n"
1009                 "-option_3=abcd\n"
1010                 "-option_4=\\\n"
1011                 "cdef\n";
1012   ConfigFile.close();
1013 
1014   llvm::SmallString<128> TestCfg2;
1015   llvm::sys::path::append(TestCfg2, TestDir, "subconfig");
1016   std::ofstream ConfigFile2(TestCfg2.c_str());
1017   EXPECT_TRUE(ConfigFile2.is_open());
1018   ConfigFile2 << "-option_2\n"
1019                  "\n"
1020                  "   # comment\n";
1021   ConfigFile2.close();
1022 
1023   // Make sure the current directory is not the directory where config files
1024   // resides. In this case the code that expands response files will not find
1025   // 'subconfig' unless it resolves nested inclusions relative to the including
1026   // file.
1027   llvm::SmallString<128> CurrDir;
1028   EC = llvm::sys::fs::current_path(CurrDir);
1029   EXPECT_TRUE(!EC);
1030   EXPECT_TRUE(StringRef(CurrDir) != StringRef(TestDir));
1031 
1032   llvm::BumpPtrAllocator A;
1033   llvm::StringSaver Saver(A);
1034   bool Result = llvm::cl::readConfigFile(TestCfg, Saver, Argv);
1035 
1036   EXPECT_TRUE(Result);
1037   EXPECT_EQ(Argv.size(), 4U);
1038   EXPECT_STREQ(Argv[0], "-option_1");
1039   EXPECT_STREQ(Argv[1], "-option_2");
1040   EXPECT_STREQ(Argv[2], "-option_3=abcd");
1041   EXPECT_STREQ(Argv[3], "-option_4=cdef");
1042 
1043   llvm::sys::fs::remove(TestCfg2);
1044   llvm::sys::fs::remove(TestCfg);
1045   llvm::sys::fs::remove(TestDir);
1046 }
1047 
1048 TEST(CommandLineTest, PositionalEatArgsError) {
1049   cl::ResetCommandLineParser();
1050 
1051   StackOption<std::string, cl::list<std::string>> PosEatArgs(
1052       "positional-eat-args", cl::Positional, cl::desc("<arguments>..."),
1053       cl::ZeroOrMore, cl::PositionalEatsArgs);
1054   StackOption<std::string, cl::list<std::string>> PosEatArgs2(
1055       "positional-eat-args2", cl::Positional, cl::desc("Some strings"),
1056       cl::ZeroOrMore, cl::PositionalEatsArgs);
1057 
1058   const char *args[] = {"prog", "-positional-eat-args=XXXX"};
1059   const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1060   const char *args3[] = {"prog", "-positional-eat-args", "-foo"};
1061   const char *args4[] = {"prog", "-positional-eat-args",
1062                          "-foo", "-positional-eat-args2",
1063                          "-bar", "foo"};
1064 
1065   std::string Errs;
1066   raw_string_ostream OS(Errs);
1067   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush();
1068   EXPECT_FALSE(Errs.empty()); Errs.clear();
1069   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush();
1070   EXPECT_FALSE(Errs.empty()); Errs.clear();
1071   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush();
1072   EXPECT_TRUE(Errs.empty()); Errs.clear();
1073 
1074   cl::ResetAllOptionOccurrences();
1075   EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4, StringRef(), &OS)); OS.flush();
1076   EXPECT_TRUE(PosEatArgs.size() == 1);
1077   EXPECT_TRUE(PosEatArgs2.size() == 2);
1078   EXPECT_TRUE(Errs.empty());
1079 }
1080 
1081 #ifdef _WIN32
1082 TEST(CommandLineTest, GetCommandLineArguments) {
1083   int argc = __argc;
1084   char **argv = __argv;
1085 
1086   // GetCommandLineArguments is called in InitLLVM.
1087   llvm::InitLLVM X(argc, argv);
1088 
1089   EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]),
1090             llvm::sys::path::is_absolute(__argv[0]));
1091 
1092   EXPECT_TRUE(llvm::sys::path::filename(argv[0])
1093               .equals_lower("supporttests.exe"))
1094       << "Filename of test executable is "
1095       << llvm::sys::path::filename(argv[0]);
1096 }
1097 #endif
1098 
1099 class OutputRedirector {
1100 public:
1101   OutputRedirector(int RedirectFD)
1102       : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) {
1103     if (OldFD == -1 ||
1104         sys::fs::createTemporaryFile("unittest-redirect", "", NewFD,
1105                                      FilePath) ||
1106         dup2(NewFD, RedirectFD) == -1)
1107       Valid = false;
1108   }
1109 
1110   ~OutputRedirector() {
1111     dup2(OldFD, RedirectFD);
1112     close(OldFD);
1113     close(NewFD);
1114   }
1115 
1116   SmallVector<char, 128> FilePath;
1117   bool Valid = true;
1118 
1119 private:
1120   int RedirectFD;
1121   int OldFD;
1122   int NewFD;
1123 };
1124 
1125 struct AutoDeleteFile {
1126   SmallVector<char, 128> FilePath;
1127   ~AutoDeleteFile() {
1128     if (!FilePath.empty())
1129       sys::fs::remove(std::string(FilePath.data(), FilePath.size()));
1130   }
1131 };
1132 
1133 class PrintOptionInfoTest : public ::testing::Test {
1134 public:
1135   // Return std::string because the output of a failing EXPECT check is
1136   // unreadable for StringRef. It also avoids any lifetime issues.
1137   template <typename... Ts> std::string runTest(Ts... OptionAttributes) {
1138     outs().flush();  // flush any output from previous tests
1139     AutoDeleteFile File;
1140     {
1141       OutputRedirector Stdout(fileno(stdout));
1142       if (!Stdout.Valid)
1143         return "";
1144       File.FilePath = Stdout.FilePath;
1145 
1146       StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText),
1147                                           OptionAttributes...);
1148       printOptionInfo(TestOption, 26);
1149       outs().flush();
1150     }
1151     auto Buffer = MemoryBuffer::getFile(File.FilePath);
1152     if (!Buffer)
1153       return "";
1154     return Buffer->get()->getBuffer().str();
1155   }
1156 
1157   enum class OptionValue { Val };
1158   const StringRef Opt = "some-option";
1159   const StringRef HelpText = "some help";
1160 
1161 private:
1162   // This is a workaround for cl::Option sub-classes having their
1163   // printOptionInfo functions private.
1164   void printOptionInfo(const cl::Option &O, size_t Width) {
1165     O.printOptionInfo(Width);
1166   }
1167 };
1168 
1169 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) {
1170   std::string Output =
1171       runTest(cl::ValueOptional,
1172               cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
1173 
1174   // clang-format off
1175   EXPECT_EQ(Output, ("  --" + Opt + "=<value> - " + HelpText + "\n"
1176                      "    =v1                 -   desc1\n")
1177                         .str());
1178   // clang-format on
1179 }
1180 
1181 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) {
1182   std::string Output = runTest(
1183       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1184                                     clEnumValN(OptionValue::Val, "", "")));
1185 
1186   // clang-format off
1187   EXPECT_EQ(Output,
1188             ("  --" + Opt + "         - " + HelpText + "\n"
1189              "  --" + Opt + "=<value> - " + HelpText + "\n"
1190              "    =v1                 -   desc1\n")
1191                 .str());
1192   // clang-format on
1193 }
1194 
1195 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) {
1196   std::string Output = runTest(
1197       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1198                                     clEnumValN(OptionValue::Val, "", "desc2")));
1199 
1200   // clang-format off
1201   EXPECT_EQ(Output, ("  --" + Opt + "         - " + HelpText + "\n"
1202                      "  --" + Opt + "=<value> - " + HelpText + "\n"
1203                      "    =v1                 -   desc1\n"
1204                      "    =<empty>            -   desc2\n")
1205                         .str());
1206   // clang-format on
1207 }
1208 
1209 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) {
1210   std::string Output = runTest(
1211       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1212                                     clEnumValN(OptionValue::Val, "", "")));
1213 
1214   // clang-format off
1215   EXPECT_EQ(Output, ("  --" + Opt + "=<value> - " + HelpText + "\n"
1216                      "    =v1                 -   desc1\n"
1217                      "    =<empty>\n")
1218                         .str());
1219   // clang-format on
1220 }
1221 
1222 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) {
1223   std::string Output = runTest(
1224       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "")));
1225 
1226   // clang-format off
1227   EXPECT_EQ(Output,
1228             ("  --" + Opt + "=<value> - " + HelpText + "\n"
1229              "    =v1\n").str());
1230   // clang-format on
1231 }
1232 
1233 class GetOptionWidthTest : public ::testing::Test {
1234 public:
1235   enum class OptionValue { Val };
1236 
1237   template <typename... Ts>
1238   size_t runTest(StringRef ArgName, Ts... OptionAttributes) {
1239     StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"),
1240                                         OptionAttributes...);
1241     return getOptionWidth(TestOption);
1242   }
1243 
1244 private:
1245   // This is a workaround for cl::Option sub-classes having their
1246   // printOptionInfo
1247   // functions private.
1248   size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); }
1249 };
1250 
1251 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) {
1252   StringRef ArgName("a-long-argument-name");
1253   size_t ExpectedStrSize = ("  --" + ArgName + "=<value> - ").str().size();
1254   EXPECT_EQ(
1255       runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))),
1256       ExpectedStrSize);
1257 }
1258 
1259 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) {
1260   StringRef OptName("a-long-option-name");
1261   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1262   EXPECT_EQ(
1263       runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"),
1264                               clEnumValN(OptionValue::Val, "b", "help"))),
1265       ExpectedStrSize);
1266 }
1267 
1268 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) {
1269   StringRef OptName("a-long-option-name");
1270   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1271   EXPECT_EQ(
1272       runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1273                               clEnumValN(OptionValue::Val, OptName, "help"))),
1274       ExpectedStrSize);
1275 }
1276 
1277 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) {
1278   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1279   // The length of a=<value> (including indentation) is actually the same as the
1280   // =<empty> string, so it is impossible to distinguish via testing the case
1281   // where the empty string is picked from where the option name is picked.
1282   EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1283                                     clEnumValN(OptionValue::Val, "", "help"))),
1284             ExpectedStrSize);
1285 }
1286 
1287 TEST_F(GetOptionWidthTest,
1288        GetOptionWidthValueOptionalEmptyOptionWithNoDescription) {
1289   StringRef ArgName("a");
1290   // The length of a=<value> (including indentation) is actually the same as the
1291   // =<empty> string, so it is impossible to distinguish via testing the case
1292   // where the empty string is ignored from where it is not ignored.
1293   // The dash will not actually be printed, but the space it would take up is
1294   // included to ensure a consistent column width.
1295   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1296   EXPECT_EQ(runTest(ArgName, cl::ValueOptional,
1297                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1298                                clEnumValN(OptionValue::Val, "", ""))),
1299             ExpectedStrSize);
1300 }
1301 
1302 TEST_F(GetOptionWidthTest,
1303        GetOptionWidthValueRequiredEmptyOptionWithNoDescription) {
1304   // The length of a=<value> (including indentation) is actually the same as the
1305   // =<empty> string, so it is impossible to distinguish via testing the case
1306   // where the empty string is picked from where the option name is picked
1307   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1308   EXPECT_EQ(runTest("a", cl::ValueRequired,
1309                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1310                                clEnumValN(OptionValue::Val, "", ""))),
1311             ExpectedStrSize);
1312 }
1313 
1314 TEST(CommandLineTest, PrefixOptions) {
1315   cl::ResetCommandLineParser();
1316 
1317   StackOption<std::string, cl::list<std::string>> IncludeDirs(
1318       "I", cl::Prefix, cl::desc("Declare an include directory"));
1319 
1320   // Test non-prefixed variant works with cl::Prefix options.
1321   EXPECT_TRUE(IncludeDirs.empty());
1322   const char *args[] = {"prog", "-I=/usr/include"};
1323   EXPECT_TRUE(
1324       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1325   EXPECT_TRUE(IncludeDirs.size() == 1);
1326   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1327 
1328   IncludeDirs.erase(IncludeDirs.begin());
1329   cl::ResetAllOptionOccurrences();
1330 
1331   // Test non-prefixed variant works with cl::Prefix options when value is
1332   // passed in following argument.
1333   EXPECT_TRUE(IncludeDirs.empty());
1334   const char *args2[] = {"prog", "-I", "/usr/include"};
1335   EXPECT_TRUE(
1336       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1337   EXPECT_TRUE(IncludeDirs.size() == 1);
1338   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1339 
1340   IncludeDirs.erase(IncludeDirs.begin());
1341   cl::ResetAllOptionOccurrences();
1342 
1343   // Test prefixed variant works with cl::Prefix options.
1344   EXPECT_TRUE(IncludeDirs.empty());
1345   const char *args3[] = {"prog", "-I/usr/include"};
1346   EXPECT_TRUE(
1347       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1348   EXPECT_TRUE(IncludeDirs.size() == 1);
1349   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1350 
1351   StackOption<std::string, cl::list<std::string>> MacroDefs(
1352       "D", cl::AlwaysPrefix, cl::desc("Define a macro"),
1353       cl::value_desc("MACRO[=VALUE]"));
1354 
1355   cl::ResetAllOptionOccurrences();
1356 
1357   // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1358   // equal sign is part of the value.
1359   EXPECT_TRUE(MacroDefs.empty());
1360   const char *args4[] = {"prog", "-D=HAVE_FOO"};
1361   EXPECT_TRUE(
1362       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1363   EXPECT_TRUE(MacroDefs.size() == 1);
1364   EXPECT_TRUE(MacroDefs.front().compare("=HAVE_FOO") == 0);
1365 
1366   MacroDefs.erase(MacroDefs.begin());
1367   cl::ResetAllOptionOccurrences();
1368 
1369   // Test non-prefixed variant does not allow value to be passed in following
1370   // argument with cl::AlwaysPrefix options.
1371   EXPECT_TRUE(MacroDefs.empty());
1372   const char *args5[] = {"prog", "-D", "HAVE_FOO"};
1373   EXPECT_FALSE(
1374       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1375   EXPECT_TRUE(MacroDefs.empty());
1376 
1377   cl::ResetAllOptionOccurrences();
1378 
1379   // Test prefixed variant works with cl::AlwaysPrefix options.
1380   EXPECT_TRUE(MacroDefs.empty());
1381   const char *args6[] = {"prog", "-DHAVE_FOO"};
1382   EXPECT_TRUE(
1383       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1384   EXPECT_TRUE(MacroDefs.size() == 1);
1385   EXPECT_TRUE(MacroDefs.front().compare("HAVE_FOO") == 0);
1386 }
1387 
1388 TEST(CommandLineTest, GroupingWithValue) {
1389   cl::ResetCommandLineParser();
1390 
1391   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1392   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1393   StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed,
1394                          cl::desc("ValueDisallowed option"));
1395   StackOption<std::string> OptV("v", cl::Grouping,
1396                                 cl::desc("ValueRequired option"));
1397   StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional,
1398                                 cl::desc("ValueOptional option"));
1399 
1400   // Should be possible to use an option which requires a value
1401   // at the end of a group.
1402   const char *args1[] = {"prog", "-fv", "val1"};
1403   EXPECT_TRUE(
1404       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
1405   EXPECT_TRUE(OptF);
1406   EXPECT_STREQ("val1", OptV.c_str());
1407   OptV.clear();
1408   cl::ResetAllOptionOccurrences();
1409 
1410   // Should not crash if it is accidentally used elsewhere in the group.
1411   const char *args2[] = {"prog", "-vf", "val2"};
1412   EXPECT_FALSE(
1413       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1414   OptV.clear();
1415   cl::ResetAllOptionOccurrences();
1416 
1417   // Should allow the "opt=value" form at the end of the group
1418   const char *args3[] = {"prog", "-fv=val3"};
1419   EXPECT_TRUE(
1420       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1421   EXPECT_TRUE(OptF);
1422   EXPECT_STREQ("val3", OptV.c_str());
1423   OptV.clear();
1424   cl::ResetAllOptionOccurrences();
1425 
1426   // Should allow assigning a value for a ValueOptional option
1427   // at the end of the group
1428   const char *args4[] = {"prog", "-fo=val4"};
1429   EXPECT_TRUE(
1430       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1431   EXPECT_TRUE(OptF);
1432   EXPECT_STREQ("val4", OptO.c_str());
1433   OptO.clear();
1434   cl::ResetAllOptionOccurrences();
1435 
1436   // Should assign an empty value if a ValueOptional option is used elsewhere
1437   // in the group.
1438   const char *args5[] = {"prog", "-fob"};
1439   EXPECT_TRUE(
1440       cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls()));
1441   EXPECT_TRUE(OptF);
1442   EXPECT_EQ(1, OptO.getNumOccurrences());
1443   EXPECT_EQ(1, OptB.getNumOccurrences());
1444   EXPECT_TRUE(OptO.empty());
1445   cl::ResetAllOptionOccurrences();
1446 
1447   // Should not allow an assignment for a ValueDisallowed option.
1448   const char *args6[] = {"prog", "-fd=false"};
1449   EXPECT_FALSE(
1450       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1451 }
1452 
1453 TEST(CommandLineTest, GroupingAndPrefix) {
1454   cl::ResetCommandLineParser();
1455 
1456   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1457   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1458   StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping,
1459                                 cl::desc("Prefix and Grouping"));
1460   StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping,
1461                                 cl::desc("AlwaysPrefix and Grouping"));
1462 
1463   // Should be possible to use a cl::Prefix option without grouping.
1464   const char *args1[] = {"prog", "-pval1"};
1465   EXPECT_TRUE(
1466       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
1467   EXPECT_STREQ("val1", OptP.c_str());
1468   OptP.clear();
1469   cl::ResetAllOptionOccurrences();
1470 
1471   // Should be possible to pass a value in a separate argument.
1472   const char *args2[] = {"prog", "-p", "val2"};
1473   EXPECT_TRUE(
1474       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1475   EXPECT_STREQ("val2", OptP.c_str());
1476   OptP.clear();
1477   cl::ResetAllOptionOccurrences();
1478 
1479   // The "-opt=value" form should work, too.
1480   const char *args3[] = {"prog", "-p=val3"};
1481   EXPECT_TRUE(
1482       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1483   EXPECT_STREQ("val3", OptP.c_str());
1484   OptP.clear();
1485   cl::ResetAllOptionOccurrences();
1486 
1487   // All three previous cases should work the same way if an option with both
1488   // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1489   const char *args4[] = {"prog", "-fpval4"};
1490   EXPECT_TRUE(
1491       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1492   EXPECT_TRUE(OptF);
1493   EXPECT_STREQ("val4", OptP.c_str());
1494   OptP.clear();
1495   cl::ResetAllOptionOccurrences();
1496 
1497   const char *args5[] = {"prog", "-fp", "val5"};
1498   EXPECT_TRUE(
1499       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1500   EXPECT_TRUE(OptF);
1501   EXPECT_STREQ("val5", OptP.c_str());
1502   OptP.clear();
1503   cl::ResetAllOptionOccurrences();
1504 
1505   const char *args6[] = {"prog", "-fp=val6"};
1506   EXPECT_TRUE(
1507       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1508   EXPECT_TRUE(OptF);
1509   EXPECT_STREQ("val6", OptP.c_str());
1510   OptP.clear();
1511   cl::ResetAllOptionOccurrences();
1512 
1513   // Should assign a value even if the part after a cl::Prefix option is equal
1514   // to the name of another option.
1515   const char *args7[] = {"prog", "-fpb"};
1516   EXPECT_TRUE(
1517       cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls()));
1518   EXPECT_TRUE(OptF);
1519   EXPECT_STREQ("b", OptP.c_str());
1520   EXPECT_FALSE(OptB);
1521   OptP.clear();
1522   cl::ResetAllOptionOccurrences();
1523 
1524   // Should be possible to use a cl::AlwaysPrefix option without grouping.
1525   const char *args8[] = {"prog", "-aval8"};
1526   EXPECT_TRUE(
1527       cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls()));
1528   EXPECT_STREQ("val8", OptA.c_str());
1529   OptA.clear();
1530   cl::ResetAllOptionOccurrences();
1531 
1532   // Should not be possible to pass a value in a separate argument.
1533   const char *args9[] = {"prog", "-a", "val9"};
1534   EXPECT_FALSE(
1535       cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls()));
1536   cl::ResetAllOptionOccurrences();
1537 
1538   // With the "-opt=value" form, the "=" symbol should be preserved.
1539   const char *args10[] = {"prog", "-a=val10"};
1540   EXPECT_TRUE(
1541       cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls()));
1542   EXPECT_STREQ("=val10", OptA.c_str());
1543   OptA.clear();
1544   cl::ResetAllOptionOccurrences();
1545 
1546   // All three previous cases should work the same way if an option with both
1547   // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1548   const char *args11[] = {"prog", "-faval11"};
1549   EXPECT_TRUE(
1550       cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls()));
1551   EXPECT_TRUE(OptF);
1552   EXPECT_STREQ("val11", OptA.c_str());
1553   OptA.clear();
1554   cl::ResetAllOptionOccurrences();
1555 
1556   const char *args12[] = {"prog", "-fa", "val12"};
1557   EXPECT_FALSE(
1558       cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls()));
1559   cl::ResetAllOptionOccurrences();
1560 
1561   const char *args13[] = {"prog", "-fa=val13"};
1562   EXPECT_TRUE(
1563       cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls()));
1564   EXPECT_TRUE(OptF);
1565   EXPECT_STREQ("=val13", OptA.c_str());
1566   OptA.clear();
1567   cl::ResetAllOptionOccurrences();
1568 
1569   // Should assign a value even if the part after a cl::AlwaysPrefix option
1570   // is equal to the name of another option.
1571   const char *args14[] = {"prog", "-fab"};
1572   EXPECT_TRUE(
1573       cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls()));
1574   EXPECT_TRUE(OptF);
1575   EXPECT_STREQ("b", OptA.c_str());
1576   EXPECT_FALSE(OptB);
1577   OptA.clear();
1578   cl::ResetAllOptionOccurrences();
1579 }
1580 
1581 TEST(CommandLineTest, LongOptions) {
1582   cl::ResetCommandLineParser();
1583 
1584   StackOption<bool> OptA("a", cl::desc("Some flag"));
1585   StackOption<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1586   StackOption<bool, cl::alias> OptB("b", cl::desc("Alias to --long-flag"),
1587                                     cl::aliasopt(OptBLong));
1588   StackOption<std::string> OptAB("ab", cl::desc("Another long option"));
1589 
1590   std::string Errs;
1591   raw_string_ostream OS(Errs);
1592 
1593   const char *args1[] = {"prog", "-a", "-ab", "val1"};
1594   const char *args2[] = {"prog", "-a", "--ab", "val1"};
1595   const char *args3[] = {"prog", "-ab", "--ab", "val1"};
1596 
1597   //
1598   // The following tests treat `-` and `--` the same, and always match the
1599   // longest string.
1600   //
1601 
1602   EXPECT_TRUE(
1603       cl::ParseCommandLineOptions(4, args1, StringRef(), &OS)); OS.flush();
1604   EXPECT_TRUE(OptA);
1605   EXPECT_FALSE(OptBLong);
1606   EXPECT_STREQ("val1", OptAB.c_str());
1607   EXPECT_TRUE(Errs.empty()); Errs.clear();
1608   cl::ResetAllOptionOccurrences();
1609 
1610   EXPECT_TRUE(
1611       cl::ParseCommandLineOptions(4, args2, StringRef(), &OS)); OS.flush();
1612   EXPECT_TRUE(OptA);
1613   EXPECT_FALSE(OptBLong);
1614   EXPECT_STREQ("val1", OptAB.c_str());
1615   EXPECT_TRUE(Errs.empty()); Errs.clear();
1616   cl::ResetAllOptionOccurrences();
1617 
1618   // Fails because `-ab` and `--ab` are treated the same and appear more than
1619   // once.  Also, `val1` is unexpected.
1620   EXPECT_FALSE(
1621       cl::ParseCommandLineOptions(4, args3, StringRef(), &OS)); OS.flush();
1622   outs()<< Errs << "\n";
1623   EXPECT_FALSE(Errs.empty()); Errs.clear();
1624   cl::ResetAllOptionOccurrences();
1625 
1626   //
1627   // The following tests treat `-` and `--` differently, with `-` for short, and
1628   // `--` for long options.
1629   //
1630 
1631   // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1632   // `val1` is unexpected.
1633   EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(),
1634                                            &OS, nullptr, true)); OS.flush();
1635   EXPECT_FALSE(Errs.empty()); Errs.clear();
1636   cl::ResetAllOptionOccurrences();
1637 
1638   // Works because `-a` is treated differently than `--ab`.
1639   EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(),
1640                                            &OS, nullptr, true)); OS.flush();
1641   EXPECT_TRUE(Errs.empty()); Errs.clear();
1642   cl::ResetAllOptionOccurrences();
1643 
1644   // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1645   EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(),
1646                                            &OS, nullptr, true));
1647   EXPECT_TRUE(OptA);
1648   EXPECT_TRUE(OptBLong);
1649   EXPECT_STREQ("val1", OptAB.c_str());
1650   OS.flush();
1651   EXPECT_TRUE(Errs.empty()); Errs.clear();
1652   cl::ResetAllOptionOccurrences();
1653 }
1654 
1655 TEST(CommandLineTest, OptionErrorMessage) {
1656   // When there is an error, we expect some error message like:
1657   //   prog: for the -a option: [...]
1658   //
1659   // Test whether the "for the -a option"-part is correctly formatted.
1660   cl::ResetCommandLineParser();
1661 
1662   StackOption<bool> OptA("a", cl::desc("Some option"));
1663   StackOption<bool> OptLong("long", cl::desc("Some long option"));
1664 
1665   std::string Errs;
1666   raw_string_ostream OS(Errs);
1667 
1668   OptA.error("custom error", OS);
1669   OS.flush();
1670   EXPECT_FALSE(Errs.find("for the -a option:") == std::string::npos);
1671   Errs.clear();
1672 
1673   OptLong.error("custom error", OS);
1674   OS.flush();
1675   EXPECT_FALSE(Errs.find("for the --long option:") == std::string::npos);
1676   Errs.clear();
1677 
1678   cl::ResetAllOptionOccurrences();
1679 }
1680 
1681 TEST(CommandLineTest, OptionErrorMessageSuggest) {
1682   // When there is an error, and the edit-distance is not very large,
1683   // we expect some error message like:
1684   //   prog: did you mean '--option'?
1685   //
1686   // Test whether this message is well-formatted.
1687   cl::ResetCommandLineParser();
1688 
1689   StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1690 
1691   const char *args[] = {"prog", "--aluminum"};
1692 
1693   std::string Errs;
1694   raw_string_ostream OS(Errs);
1695 
1696   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1697   OS.flush();
1698   EXPECT_FALSE(Errs.find("prog: Did you mean '--aluminium'?\n") ==
1699                std::string::npos);
1700   Errs.clear();
1701 
1702   cl::ResetAllOptionOccurrences();
1703 }
1704 }  // anonymous namespace
1705