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/Triple.h"
13 #include "llvm/Config/config.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/InitLLVM.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/Program.h"
19 #include "llvm/Support/StringSaver.h"
20 #include "gtest/gtest.h"
21 #include <fstream>
22 #include <stdlib.h>
23 #include <string>
24 
25 using namespace llvm;
26 
27 namespace {
28 
29 class TempEnvVar {
30  public:
31   TempEnvVar(const char *name, const char *value)
32       : name(name) {
33     const char *old_value = getenv(name);
34     EXPECT_EQ(nullptr, old_value) << old_value;
35 #if HAVE_SETENV
36     setenv(name, value, true);
37 #else
38 #   define SKIP_ENVIRONMENT_TESTS
39 #endif
40   }
41 
42   ~TempEnvVar() {
43 #if HAVE_SETENV
44     // Assume setenv and unsetenv come together.
45     unsetenv(name);
46 #else
47     (void)name; // Suppress -Wunused-private-field.
48 #endif
49   }
50 
51  private:
52   const char *const name;
53 };
54 
55 template <typename T, typename Base = cl::opt<T>>
56 class StackOption : public Base {
57 public:
58   template <class... Ts>
59   explicit StackOption(Ts &&... Ms) : Base(std::forward<Ts>(Ms)...) {}
60 
61   ~StackOption() override { this->removeArgument(); }
62 
63   template <class DT> StackOption<T> &operator=(const DT &V) {
64     this->setValue(V);
65     return *this;
66   }
67 };
68 
69 class StackSubCommand : public cl::SubCommand {
70 public:
71   StackSubCommand(StringRef Name,
72                   StringRef Description = StringRef())
73       : SubCommand(Name, Description) {}
74 
75   StackSubCommand() : SubCommand() {}
76 
77   ~StackSubCommand() { unregisterSubCommand(); }
78 };
79 
80 
81 cl::OptionCategory TestCategory("Test Options", "Description");
82 TEST(CommandLineTest, ModifyExisitingOption) {
83   StackOption<int> TestOption("test-option", cl::desc("old description"));
84 
85   static const char Description[] = "New description";
86   static const char ArgString[] = "new-test-option";
87   static const char ValueString[] = "Integer";
88 
89   StringMap<cl::Option *> &Map =
90       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
91 
92   ASSERT_TRUE(Map.count("test-option") == 1) <<
93     "Could not find option in map.";
94 
95   cl::Option *Retrieved = Map["test-option"];
96   ASSERT_EQ(&TestOption, Retrieved) << "Retrieved wrong option.";
97 
98   ASSERT_EQ(&cl::GeneralCategory,Retrieved->Category) <<
99     "Incorrect default option category.";
100 
101   Retrieved->setCategory(TestCategory);
102   ASSERT_EQ(&TestCategory,Retrieved->Category) <<
103     "Failed to modify option's option category.";
104 
105   Retrieved->setDescription(Description);
106   ASSERT_STREQ(Retrieved->HelpStr.data(), Description)
107       << "Changing option description failed.";
108 
109   Retrieved->setArgStr(ArgString);
110   ASSERT_STREQ(ArgString, Retrieved->ArgStr.data())
111       << "Failed to modify option's Argument string.";
112 
113   Retrieved->setValueStr(ValueString);
114   ASSERT_STREQ(Retrieved->ValueStr.data(), ValueString)
115       << "Failed to modify option's Value string.";
116 
117   Retrieved->setHiddenFlag(cl::Hidden);
118   ASSERT_EQ(cl::Hidden, TestOption.getOptionHiddenFlag()) <<
119     "Failed to modify option's hidden flag.";
120 }
121 #ifndef SKIP_ENVIRONMENT_TESTS
122 
123 const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
124 
125 cl::opt<std::string> EnvironmentTestOption("env-test-opt");
126 TEST(CommandLineTest, ParseEnvironment) {
127   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
128   EXPECT_EQ("", EnvironmentTestOption);
129   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
130   EXPECT_EQ("hello", EnvironmentTestOption);
131 }
132 
133 // This test used to make valgrind complain
134 // ("Conditional jump or move depends on uninitialised value(s)")
135 //
136 // Warning: Do not run any tests after this one that try to gain access to
137 // registered command line options because this will likely result in a
138 // SEGFAULT. This can occur because the cl::opt in the test below is declared
139 // on the stack which will be destroyed after the test completes but the
140 // command line system will still hold a pointer to a deallocated cl::Option.
141 TEST(CommandLineTest, ParseEnvironmentToLocalVar) {
142   // Put cl::opt on stack to check for proper initialization of fields.
143   StackOption<std::string> EnvironmentTestOptionLocal("env-test-opt-local");
144   TempEnvVar TEV(test_env_var, "-env-test-opt-local=hello-local");
145   EXPECT_EQ("", EnvironmentTestOptionLocal);
146   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
147   EXPECT_EQ("hello-local", EnvironmentTestOptionLocal);
148 }
149 
150 #endif  // SKIP_ENVIRONMENT_TESTS
151 
152 TEST(CommandLineTest, UseOptionCategory) {
153   StackOption<int> TestOption2("test-option", cl::cat(TestCategory));
154 
155   ASSERT_EQ(&TestCategory,TestOption2.Category) << "Failed to assign Option "
156                                                   "Category.";
157 }
158 
159 typedef void ParserFunction(StringRef Source, StringSaver &Saver,
160                             SmallVectorImpl<const char *> &NewArgv,
161                             bool MarkEOLs);
162 
163 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input,
164                               const char *const Output[], size_t OutputSize) {
165   SmallVector<const char *, 0> Actual;
166   BumpPtrAllocator A;
167   StringSaver Saver(A);
168   parse(Input, Saver, Actual, /*MarkEOLs=*/false);
169   EXPECT_EQ(OutputSize, Actual.size());
170   for (unsigned I = 0, E = Actual.size(); I != E; ++I) {
171     if (I < OutputSize) {
172       EXPECT_STREQ(Output[I], Actual[I]);
173     }
174   }
175 }
176 
177 TEST(CommandLineTest, TokenizeGNUCommandLine) {
178   const char Input[] =
179       "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) "
180       "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\"";
181   const char *const Output[] = {
182       "foo bar",     "foo bar",   "foo bar",          "foo\\bar",
183       "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"};
184   testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
185                            array_lengthof(Output));
186 }
187 
188 TEST(CommandLineTest, TokenizeWindowsCommandLine1) {
189   const char Input[] = "a\\b c\\\\d e\\\\\"f g\" h\\\"i j\\\\\\\"k \"lmn\" o pqr "
190                       "\"st \\\"u\" \\v";
191   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
192                                  "lmn", "o", "pqr", "st \"u", "\\v" };
193   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
194                            array_lengthof(Output));
195 }
196 
197 TEST(CommandLineTest, TokenizeWindowsCommandLine2) {
198   const char Input[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp";
199   const char *const Output[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"};
200   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
201                            array_lengthof(Output));
202 }
203 
204 TEST(CommandLineTest, TokenizeConfigFile1) {
205   const char *Input = "\\";
206   const char *const Output[] = { "\\" };
207   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
208                            array_lengthof(Output));
209 }
210 
211 TEST(CommandLineTest, TokenizeConfigFile2) {
212   const char *Input = "\\abc";
213   const char *const Output[] = { "abc" };
214   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
215                            array_lengthof(Output));
216 }
217 
218 TEST(CommandLineTest, TokenizeConfigFile3) {
219   const char *Input = "abc\\";
220   const char *const Output[] = { "abc\\" };
221   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
222                            array_lengthof(Output));
223 }
224 
225 TEST(CommandLineTest, TokenizeConfigFile4) {
226   const char *Input = "abc\\\n123";
227   const char *const Output[] = { "abc123" };
228   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
229                            array_lengthof(Output));
230 }
231 
232 TEST(CommandLineTest, TokenizeConfigFile5) {
233   const char *Input = "abc\\\r\n123";
234   const char *const Output[] = { "abc123" };
235   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
236                            array_lengthof(Output));
237 }
238 
239 TEST(CommandLineTest, TokenizeConfigFile6) {
240   const char *Input = "abc\\\n";
241   const char *const Output[] = { "abc" };
242   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
243                            array_lengthof(Output));
244 }
245 
246 TEST(CommandLineTest, TokenizeConfigFile7) {
247   const char *Input = "abc\\\r\n";
248   const char *const Output[] = { "abc" };
249   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
250                            array_lengthof(Output));
251 }
252 
253 TEST(CommandLineTest, TokenizeConfigFile8) {
254   SmallVector<const char *, 0> Actual;
255   BumpPtrAllocator A;
256   StringSaver Saver(A);
257   cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false);
258   EXPECT_TRUE(Actual.empty());
259 }
260 
261 TEST(CommandLineTest, TokenizeConfigFile9) {
262   SmallVector<const char *, 0> Actual;
263   BumpPtrAllocator A;
264   StringSaver Saver(A);
265   cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false);
266   EXPECT_TRUE(Actual.empty());
267 }
268 
269 TEST(CommandLineTest, TokenizeConfigFile10) {
270   const char *Input = "\\\nabc";
271   const char *const Output[] = { "abc" };
272   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
273                            array_lengthof(Output));
274 }
275 
276 TEST(CommandLineTest, TokenizeConfigFile11) {
277   const char *Input = "\\\r\nabc";
278   const char *const Output[] = { "abc" };
279   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
280                            array_lengthof(Output));
281 }
282 
283 TEST(CommandLineTest, AliasesWithArguments) {
284   static const size_t ARGC = 3;
285   const char *const Inputs[][ARGC] = {
286     { "-tool", "-actual=x", "-extra" },
287     { "-tool", "-actual", "x" },
288     { "-tool", "-alias=x", "-extra" },
289     { "-tool", "-alias", "x" }
290   };
291 
292   for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) {
293     StackOption<std::string> Actual("actual");
294     StackOption<bool> Extra("extra");
295     StackOption<std::string> Input(cl::Positional);
296 
297     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
298 
299     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
300     EXPECT_EQ("x", Actual);
301     EXPECT_EQ(0, Input.getNumOccurrences());
302 
303     Alias.removeArgument();
304   }
305 }
306 
307 void testAliasRequired(int argc, const char *const *argv) {
308   StackOption<std::string> Option("option", cl::Required);
309   cl::alias Alias("o", llvm::cl::aliasopt(Option));
310 
311   cl::ParseCommandLineOptions(argc, argv);
312   EXPECT_EQ("x", Option);
313   EXPECT_EQ(1, Option.getNumOccurrences());
314 
315   Alias.removeArgument();
316 }
317 
318 TEST(CommandLineTest, AliasRequired) {
319   const char *opts1[] = { "-tool", "-option=x" };
320   const char *opts2[] = { "-tool", "-o", "x" };
321   testAliasRequired(array_lengthof(opts1), opts1);
322   testAliasRequired(array_lengthof(opts2), opts2);
323 }
324 
325 TEST(CommandLineTest, HideUnrelatedOptions) {
326   StackOption<int> TestOption1("hide-option-1");
327   StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory));
328 
329   cl::HideUnrelatedOptions(TestCategory);
330 
331   ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
332       << "Failed to hide extra option.";
333   ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
334       << "Hid extra option that should be visable.";
335 
336   StringMap<cl::Option *> &Map =
337       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
338   ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag())
339       << "Hid default option that should be visable.";
340 }
341 
342 cl::OptionCategory TestCategory2("Test Options set 2", "Description");
343 
344 TEST(CommandLineTest, HideUnrelatedOptionsMulti) {
345   StackOption<int> TestOption1("multi-hide-option-1");
346   StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory));
347   StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2));
348 
349   const cl::OptionCategory *VisibleCategories[] = {&TestCategory,
350                                                    &TestCategory2};
351 
352   cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
353 
354   ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
355       << "Failed to hide extra option.";
356   ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
357       << "Hid extra option that should be visable.";
358   ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag())
359       << "Hid extra option that should be visable.";
360 
361   StringMap<cl::Option *> &Map =
362       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
363   ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag())
364       << "Hid default option that should be visable.";
365 }
366 
367 TEST(CommandLineTest, SetValueInSubcategories) {
368   cl::ResetCommandLineParser();
369 
370   StackSubCommand SC1("sc1", "First subcommand");
371   StackSubCommand SC2("sc2", "Second subcommand");
372 
373   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
374   StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
375   StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
376 
377   EXPECT_FALSE(TopLevelOpt);
378   EXPECT_FALSE(SC1Opt);
379   EXPECT_FALSE(SC2Opt);
380   const char *args[] = {"prog", "-top-level"};
381   EXPECT_TRUE(
382       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
383   EXPECT_TRUE(TopLevelOpt);
384   EXPECT_FALSE(SC1Opt);
385   EXPECT_FALSE(SC2Opt);
386 
387   TopLevelOpt = false;
388 
389   cl::ResetAllOptionOccurrences();
390   EXPECT_FALSE(TopLevelOpt);
391   EXPECT_FALSE(SC1Opt);
392   EXPECT_FALSE(SC2Opt);
393   const char *args2[] = {"prog", "sc1", "-sc1"};
394   EXPECT_TRUE(
395       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
396   EXPECT_FALSE(TopLevelOpt);
397   EXPECT_TRUE(SC1Opt);
398   EXPECT_FALSE(SC2Opt);
399 
400   SC1Opt = false;
401 
402   cl::ResetAllOptionOccurrences();
403   EXPECT_FALSE(TopLevelOpt);
404   EXPECT_FALSE(SC1Opt);
405   EXPECT_FALSE(SC2Opt);
406   const char *args3[] = {"prog", "sc2", "-sc2"};
407   EXPECT_TRUE(
408       cl::ParseCommandLineOptions(3, args3, StringRef(), &llvm::nulls()));
409   EXPECT_FALSE(TopLevelOpt);
410   EXPECT_FALSE(SC1Opt);
411   EXPECT_TRUE(SC2Opt);
412 }
413 
414 TEST(CommandLineTest, LookupFailsInWrongSubCommand) {
415   cl::ResetCommandLineParser();
416 
417   StackSubCommand SC1("sc1", "First subcommand");
418   StackSubCommand SC2("sc2", "Second subcommand");
419 
420   StackOption<bool> SC1Opt("sc1", cl::sub(SC1), cl::init(false));
421   StackOption<bool> SC2Opt("sc2", cl::sub(SC2), cl::init(false));
422 
423   std::string Errs;
424   raw_string_ostream OS(Errs);
425 
426   const char *args[] = {"prog", "sc1", "-sc2"};
427   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
428   OS.flush();
429   EXPECT_FALSE(Errs.empty());
430 }
431 
432 TEST(CommandLineTest, AddToAllSubCommands) {
433   cl::ResetCommandLineParser();
434 
435   StackSubCommand SC1("sc1", "First subcommand");
436   StackOption<bool> AllOpt("everywhere", cl::sub(*cl::AllSubCommands),
437                            cl::init(false));
438   StackSubCommand SC2("sc2", "Second subcommand");
439 
440   const char *args[] = {"prog", "-everywhere"};
441   const char *args2[] = {"prog", "sc1", "-everywhere"};
442   const char *args3[] = {"prog", "sc2", "-everywhere"};
443 
444   std::string Errs;
445   raw_string_ostream OS(Errs);
446 
447   EXPECT_FALSE(AllOpt);
448   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
449   EXPECT_TRUE(AllOpt);
450 
451   AllOpt = false;
452 
453   cl::ResetAllOptionOccurrences();
454   EXPECT_FALSE(AllOpt);
455   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS));
456   EXPECT_TRUE(AllOpt);
457 
458   AllOpt = false;
459 
460   cl::ResetAllOptionOccurrences();
461   EXPECT_FALSE(AllOpt);
462   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS));
463   EXPECT_TRUE(AllOpt);
464 
465   // Since all parsing succeeded, the error message should be empty.
466   OS.flush();
467   EXPECT_TRUE(Errs.empty());
468 }
469 
470 TEST(CommandLineTest, ReparseCommandLineOptions) {
471   cl::ResetCommandLineParser();
472 
473   StackOption<bool> TopLevelOpt("top-level", cl::sub(*cl::TopLevelSubCommand),
474                                 cl::init(false));
475 
476   const char *args[] = {"prog", "-top-level"};
477 
478   EXPECT_FALSE(TopLevelOpt);
479   EXPECT_TRUE(
480       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
481   EXPECT_TRUE(TopLevelOpt);
482 
483   TopLevelOpt = false;
484 
485   cl::ResetAllOptionOccurrences();
486   EXPECT_FALSE(TopLevelOpt);
487   EXPECT_TRUE(
488       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
489   EXPECT_TRUE(TopLevelOpt);
490 }
491 
492 TEST(CommandLineTest, RemoveFromRegularSubCommand) {
493   cl::ResetCommandLineParser();
494 
495   StackSubCommand SC("sc", "Subcommand");
496   StackOption<bool> RemoveOption("remove-option", cl::sub(SC), cl::init(false));
497   StackOption<bool> KeepOption("keep-option", cl::sub(SC), cl::init(false));
498 
499   const char *args[] = {"prog", "sc", "-remove-option"};
500 
501   std::string Errs;
502   raw_string_ostream OS(Errs);
503 
504   EXPECT_FALSE(RemoveOption);
505   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
506   EXPECT_TRUE(RemoveOption);
507   OS.flush();
508   EXPECT_TRUE(Errs.empty());
509 
510   RemoveOption.removeArgument();
511 
512   cl::ResetAllOptionOccurrences();
513   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args, StringRef(), &OS));
514   OS.flush();
515   EXPECT_FALSE(Errs.empty());
516 }
517 
518 TEST(CommandLineTest, RemoveFromTopLevelSubCommand) {
519   cl::ResetCommandLineParser();
520 
521   StackOption<bool> TopLevelRemove(
522       "top-level-remove", cl::sub(*cl::TopLevelSubCommand), cl::init(false));
523   StackOption<bool> TopLevelKeep(
524       "top-level-keep", cl::sub(*cl::TopLevelSubCommand), cl::init(false));
525 
526   const char *args[] = {"prog", "-top-level-remove"};
527 
528   EXPECT_FALSE(TopLevelRemove);
529   EXPECT_TRUE(
530       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
531   EXPECT_TRUE(TopLevelRemove);
532 
533   TopLevelRemove.removeArgument();
534 
535   cl::ResetAllOptionOccurrences();
536   EXPECT_FALSE(
537       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
538 }
539 
540 TEST(CommandLineTest, RemoveFromAllSubCommands) {
541   cl::ResetCommandLineParser();
542 
543   StackSubCommand SC1("sc1", "First Subcommand");
544   StackSubCommand SC2("sc2", "Second Subcommand");
545   StackOption<bool> RemoveOption("remove-option", cl::sub(*cl::AllSubCommands),
546                                  cl::init(false));
547   StackOption<bool> KeepOption("keep-option", cl::sub(*cl::AllSubCommands),
548                                cl::init(false));
549 
550   const char *args0[] = {"prog", "-remove-option"};
551   const char *args1[] = {"prog", "sc1", "-remove-option"};
552   const char *args2[] = {"prog", "sc2", "-remove-option"};
553 
554   // It should work for all subcommands including the top-level.
555   EXPECT_FALSE(RemoveOption);
556   EXPECT_TRUE(
557       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
558   EXPECT_TRUE(RemoveOption);
559 
560   RemoveOption = false;
561 
562   cl::ResetAllOptionOccurrences();
563   EXPECT_FALSE(RemoveOption);
564   EXPECT_TRUE(
565       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
566   EXPECT_TRUE(RemoveOption);
567 
568   RemoveOption = false;
569 
570   cl::ResetAllOptionOccurrences();
571   EXPECT_FALSE(RemoveOption);
572   EXPECT_TRUE(
573       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
574   EXPECT_TRUE(RemoveOption);
575 
576   RemoveOption.removeArgument();
577 
578   // It should not work for any subcommands including the top-level.
579   cl::ResetAllOptionOccurrences();
580   EXPECT_FALSE(
581       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
582   cl::ResetAllOptionOccurrences();
583   EXPECT_FALSE(
584       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
585   cl::ResetAllOptionOccurrences();
586   EXPECT_FALSE(
587       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
588 }
589 
590 TEST(CommandLineTest, GetRegisteredSubcommands) {
591   cl::ResetCommandLineParser();
592 
593   StackSubCommand SC1("sc1", "First Subcommand");
594   StackOption<bool> Opt1("opt1", cl::sub(SC1), cl::init(false));
595   StackSubCommand SC2("sc2", "Second subcommand");
596   StackOption<bool> Opt2("opt2", cl::sub(SC2), cl::init(false));
597 
598   const char *args0[] = {"prog", "sc1"};
599   const char *args1[] = {"prog", "sc2"};
600 
601   EXPECT_TRUE(
602       cl::ParseCommandLineOptions(2, args0, StringRef(), &llvm::nulls()));
603   EXPECT_FALSE(Opt1);
604   EXPECT_FALSE(Opt2);
605   for (auto *S : cl::getRegisteredSubcommands()) {
606     if (*S) {
607       EXPECT_EQ("sc1", S->getName());
608     }
609   }
610 
611   cl::ResetAllOptionOccurrences();
612   EXPECT_TRUE(
613       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
614   EXPECT_FALSE(Opt1);
615   EXPECT_FALSE(Opt2);
616   for (auto *S : cl::getRegisteredSubcommands()) {
617     if (*S) {
618       EXPECT_EQ("sc2", S->getName());
619     }
620   }
621 }
622 
623 TEST(CommandLineTest, ArgumentLimit) {
624   std::string args(32 * 4096, 'a');
625   EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data()));
626 }
627 
628 TEST(CommandLineTest, ResponseFileWindows) {
629   if (!Triple(sys::getProcessTriple()).isOSWindows())
630     return;
631 
632   StackOption<std::string, cl::list<std::string>> InputFilenames(
633       cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore);
634   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
635 
636   // Create response file.
637   int FileDescriptor;
638   SmallString<64> TempPath;
639   std::error_code EC =
640       llvm::sys::fs::createTemporaryFile("resp-", ".txt", FileDescriptor, TempPath);
641   EXPECT_TRUE(!EC);
642 
643   std::ofstream RspFile(TempPath.c_str());
644   EXPECT_TRUE(RspFile.is_open());
645   RspFile << "-top-level\npath\\dir\\file1\npath/dir/file2";
646   RspFile.close();
647 
648   llvm::SmallString<128> RspOpt;
649   RspOpt.append(1, '@');
650   RspOpt.append(TempPath.c_str());
651   const char *args[] = {"prog", RspOpt.c_str()};
652   EXPECT_FALSE(TopLevelOpt);
653   EXPECT_TRUE(
654       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
655   EXPECT_TRUE(TopLevelOpt);
656   EXPECT_TRUE(InputFilenames[0] == "path\\dir\\file1");
657   EXPECT_TRUE(InputFilenames[1] == "path/dir/file2");
658 
659   llvm::sys::fs::remove(TempPath.c_str());
660 }
661 
662 TEST(CommandLineTest, ResponseFiles) {
663   llvm::SmallString<128> TestDir;
664   std::error_code EC =
665     llvm::sys::fs::createUniqueDirectory("unittest", TestDir);
666   EXPECT_TRUE(!EC);
667 
668   // Create included response file of first level.
669   llvm::SmallString<128> IncludedFileName;
670   llvm::sys::path::append(IncludedFileName, TestDir, "resp1");
671   std::ofstream IncludedFile(IncludedFileName.c_str());
672   EXPECT_TRUE(IncludedFile.is_open());
673   IncludedFile << "-option_1 -option_2\n"
674                   "@incdir/resp2\n"
675                   "-option_3=abcd\n";
676   IncludedFile.close();
677 
678   // Directory for included file.
679   llvm::SmallString<128> IncDir;
680   llvm::sys::path::append(IncDir, TestDir, "incdir");
681   EC = llvm::sys::fs::create_directory(IncDir);
682   EXPECT_TRUE(!EC);
683 
684   // Create included response file of second level.
685   llvm::SmallString<128> IncludedFileName2;
686   llvm::sys::path::append(IncludedFileName2, IncDir, "resp2");
687   std::ofstream IncludedFile2(IncludedFileName2.c_str());
688   EXPECT_TRUE(IncludedFile2.is_open());
689   IncludedFile2 << "-option_21 -option_22\n";
690   IncludedFile2 << "-option_23=abcd\n";
691   IncludedFile2.close();
692 
693   // Prepare 'file' with reference to response file.
694   SmallString<128> IncRef;
695   IncRef.append(1, '@');
696   IncRef.append(IncludedFileName.c_str());
697   llvm::SmallVector<const char *, 4> Argv =
698                           { "test/test", "-flag_1", IncRef.c_str(), "-flag_2" };
699 
700   // Expand response files.
701   llvm::BumpPtrAllocator A;
702   llvm::StringSaver Saver(A);
703   bool Res = llvm::cl::ExpandResponseFiles(
704                     Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true);
705   EXPECT_TRUE(Res);
706   EXPECT_EQ(Argv.size(), 9U);
707   EXPECT_STREQ(Argv[0], "test/test");
708   EXPECT_STREQ(Argv[1], "-flag_1");
709   EXPECT_STREQ(Argv[2], "-option_1");
710   EXPECT_STREQ(Argv[3], "-option_2");
711   EXPECT_STREQ(Argv[4], "-option_21");
712   EXPECT_STREQ(Argv[5], "-option_22");
713   EXPECT_STREQ(Argv[6], "-option_23=abcd");
714   EXPECT_STREQ(Argv[7], "-option_3=abcd");
715   EXPECT_STREQ(Argv[8], "-flag_2");
716 
717   llvm::sys::fs::remove(IncludedFileName2);
718   llvm::sys::fs::remove(IncDir);
719   llvm::sys::fs::remove(IncludedFileName);
720   llvm::sys::fs::remove(TestDir);
721 }
722 
723 TEST(CommandLineTest, SetDefautValue) {
724   cl::ResetCommandLineParser();
725 
726   StackOption<std::string> Opt1("opt1", cl::init("true"));
727   StackOption<bool> Opt2("opt2", cl::init(true));
728   cl::alias Alias("alias", llvm::cl::aliasopt(Opt2));
729   StackOption<int> Opt3("opt3", cl::init(3));
730 
731   const char *args[] = {"prog", "-opt1=false", "-opt2", "-opt3"};
732 
733   EXPECT_TRUE(
734     cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
735 
736   EXPECT_TRUE(Opt1 == "false");
737   EXPECT_TRUE(Opt2);
738   EXPECT_TRUE(Opt3 == 3);
739 
740   Opt2 = false;
741   Opt3 = 1;
742 
743   cl::ResetAllOptionOccurrences();
744 
745   for (auto &OM : cl::getRegisteredOptions(*cl::TopLevelSubCommand)) {
746     cl::Option *O = OM.second;
747     if (O->ArgStr == "opt2") {
748       continue;
749     }
750     O->setDefault();
751   }
752 
753   EXPECT_TRUE(Opt1 == "true");
754   EXPECT_TRUE(Opt2);
755   EXPECT_TRUE(Opt3 == 3);
756   Alias.removeArgument();
757 }
758 
759 TEST(CommandLineTest, ReadConfigFile) {
760   llvm::SmallVector<const char *, 1> Argv;
761 
762   llvm::SmallString<128> TestDir;
763   std::error_code EC =
764       llvm::sys::fs::createUniqueDirectory("unittest", TestDir);
765   EXPECT_TRUE(!EC);
766 
767   llvm::SmallString<128> TestCfg;
768   llvm::sys::path::append(TestCfg, TestDir, "foo");
769   std::ofstream ConfigFile(TestCfg.c_str());
770   EXPECT_TRUE(ConfigFile.is_open());
771   ConfigFile << "# Comment\n"
772                 "-option_1\n"
773                 "@subconfig\n"
774                 "-option_3=abcd\n"
775                 "-option_4=\\\n"
776                 "cdef\n";
777   ConfigFile.close();
778 
779   llvm::SmallString<128> TestCfg2;
780   llvm::sys::path::append(TestCfg2, TestDir, "subconfig");
781   std::ofstream ConfigFile2(TestCfg2.c_str());
782   EXPECT_TRUE(ConfigFile2.is_open());
783   ConfigFile2 << "-option_2\n"
784                  "\n"
785                  "   # comment\n";
786   ConfigFile2.close();
787 
788   // Make sure the current directory is not the directory where config files
789   // resides. In this case the code that expands response files will not find
790   // 'subconfig' unless it resolves nested inclusions relative to the including
791   // file.
792   llvm::SmallString<128> CurrDir;
793   EC = llvm::sys::fs::current_path(CurrDir);
794   EXPECT_TRUE(!EC);
795   EXPECT_TRUE(StringRef(CurrDir) != StringRef(TestDir));
796 
797   llvm::BumpPtrAllocator A;
798   llvm::StringSaver Saver(A);
799   bool Result = llvm::cl::readConfigFile(TestCfg, Saver, Argv);
800 
801   EXPECT_TRUE(Result);
802   EXPECT_EQ(Argv.size(), 4U);
803   EXPECT_STREQ(Argv[0], "-option_1");
804   EXPECT_STREQ(Argv[1], "-option_2");
805   EXPECT_STREQ(Argv[2], "-option_3=abcd");
806   EXPECT_STREQ(Argv[3], "-option_4=cdef");
807 
808   llvm::sys::fs::remove(TestCfg2);
809   llvm::sys::fs::remove(TestCfg);
810   llvm::sys::fs::remove(TestDir);
811 }
812 
813 TEST(CommandLineTest, PositionalEatArgsError) {
814   StackOption<std::string, cl::list<std::string>> PosEatArgs(
815       "positional-eat-args", cl::Positional, cl::desc("<arguments>..."),
816       cl::ZeroOrMore, cl::PositionalEatsArgs);
817 
818   const char *args[] = {"prog", "-positional-eat-args=XXXX"};
819   const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
820   const char *args3[] = {"prog", "-positional-eat-args", "-foo"};
821 
822   std::string Errs;
823   raw_string_ostream OS(Errs);
824   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush();
825   EXPECT_FALSE(Errs.empty()); Errs.clear();
826   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush();
827   EXPECT_FALSE(Errs.empty()); Errs.clear();
828   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush();
829   EXPECT_TRUE(Errs.empty());
830 }
831 
832 #ifdef _WIN32
833 TEST(CommandLineTest, GetCommandLineArguments) {
834   int argc = __argc;
835   char **argv = __argv;
836 
837   // GetCommandLineArguments is called in InitLLVM.
838   llvm::InitLLVM X(argc, argv);
839 
840   EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]),
841             llvm::sys::path::is_absolute(__argv[0]));
842 
843   EXPECT_TRUE(llvm::sys::path::filename(argv[0])
844               .equals_lower("supporttests.exe"))
845       << "Filename of test executable is "
846       << llvm::sys::path::filename(argv[0]);
847 }
848 #endif
849 
850 class OutputRedirector {
851 public:
852   OutputRedirector(int RedirectFD)
853       : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) {
854     if (OldFD == -1 ||
855         sys::fs::createTemporaryFile("unittest-redirect", "", NewFD,
856                                      FilePath) ||
857         dup2(NewFD, RedirectFD) == -1)
858       Valid = false;
859   }
860 
861   ~OutputRedirector() {
862     dup2(OldFD, RedirectFD);
863     close(OldFD);
864     close(NewFD);
865   }
866 
867   SmallVector<char, 128> FilePath;
868   bool Valid = true;
869 
870 private:
871   int RedirectFD;
872   int OldFD;
873   int NewFD;
874 };
875 
876 struct AutoDeleteFile {
877   SmallVector<char, 128> FilePath;
878   ~AutoDeleteFile() {
879     if (!FilePath.empty())
880       sys::fs::remove(std::string(FilePath.data(), FilePath.size()));
881   }
882 };
883 
884 class PrintOptionInfoTest : public ::testing::Test {
885 public:
886   // Return std::string because the output of a failing EXPECT check is
887   // unreadable for StringRef. It also avoids any lifetime issues.
888   template <typename... Ts> std::string runTest(Ts... OptionAttributes) {
889     AutoDeleteFile File;
890     {
891       OutputRedirector Stdout(fileno(stdout));
892       if (!Stdout.Valid)
893         return "";
894       File.FilePath = Stdout.FilePath;
895 
896       StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText),
897                                           OptionAttributes...);
898       printOptionInfo(TestOption, 25);
899       outs().flush();
900     }
901     auto Buffer = MemoryBuffer::getFile(File.FilePath);
902     if (!Buffer)
903       return "";
904     return Buffer->get()->getBuffer().str();
905   }
906 
907   enum class OptionValue { Val };
908   const StringRef Opt = "some-option";
909   const StringRef HelpText = "some help";
910 
911 private:
912   // This is a workaround for cl::Option sub-classes having their
913   // printOptionInfo functions private.
914   void printOptionInfo(const cl::Option &O, size_t Width) {
915     O.printOptionInfo(Width);
916   }
917 };
918 
919 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) {
920   std::string Output =
921       runTest(cl::ValueOptional,
922               cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
923 
924   // clang-format off
925   EXPECT_EQ(Output, ("  -" + Opt + "=<value> - " + HelpText + "\n"
926                      "    =v1                -   desc1\n")
927                         .str());
928   // clang-format on
929 }
930 
931 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) {
932   std::string Output = runTest(
933       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
934                                     clEnumValN(OptionValue::Val, "", "")));
935 
936   // clang-format off
937   EXPECT_EQ(Output,
938             ("  -" + Opt + "         - " + HelpText + "\n"
939              "  -" + Opt + "=<value> - " + HelpText + "\n"
940              "    =v1                -   desc1\n")
941                 .str());
942   // clang-format on
943 }
944 
945 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) {
946   std::string Output = runTest(
947       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
948                                     clEnumValN(OptionValue::Val, "", "desc2")));
949 
950   // clang-format off
951   EXPECT_EQ(Output, ("  -" + Opt + "         - " + HelpText + "\n"
952                      "  -" + Opt + "=<value> - " + HelpText + "\n"
953                      "    =v1                -   desc1\n"
954                      "    =<empty>           -   desc2\n")
955                         .str());
956   // clang-format on
957 }
958 
959 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) {
960   std::string Output = runTest(
961       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
962                                     clEnumValN(OptionValue::Val, "", "")));
963 
964   // clang-format off
965   EXPECT_EQ(Output, ("  -" + Opt + "=<value> - " + HelpText + "\n"
966                      "    =v1                -   desc1\n"
967                      "    =<empty>\n")
968                         .str());
969   // clang-format on
970 }
971 
972 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) {
973   std::string Output = runTest(
974       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "")));
975 
976   // clang-format off
977   EXPECT_EQ(Output,
978             ("  -" + Opt + "=<value> - " + HelpText + "\n"
979              "    =v1\n").str());
980   // clang-format on
981 }
982 
983 class GetOptionWidthTest : public ::testing::Test {
984 public:
985   enum class OptionValue { Val };
986 
987   template <typename... Ts>
988   size_t runTest(StringRef ArgName, Ts... OptionAttributes) {
989     StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"),
990                                         OptionAttributes...);
991     return getOptionWidth(TestOption);
992   }
993 
994 private:
995   // This is a workaround for cl::Option sub-classes having their
996   // printOptionInfo
997   // functions private.
998   size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); }
999 };
1000 
1001 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) {
1002   StringRef ArgName("a-long-argument-name");
1003   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1004   EXPECT_EQ(
1005       runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))),
1006       ExpectedStrSize);
1007 }
1008 
1009 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) {
1010   StringRef OptName("a-long-option-name");
1011   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1012   EXPECT_EQ(
1013       runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"),
1014                               clEnumValN(OptionValue::Val, "b", "help"))),
1015       ExpectedStrSize);
1016 }
1017 
1018 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) {
1019   StringRef OptName("a-long-option-name");
1020   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1021   EXPECT_EQ(
1022       runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1023                               clEnumValN(OptionValue::Val, OptName, "help"))),
1024       ExpectedStrSize);
1025 }
1026 
1027 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) {
1028   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1029   // The length of a=<value> (including indentation) is actually the same as the
1030   // =<empty> string, so it is impossible to distinguish via testing the case
1031   // where the empty string is picked from where the option name is picked.
1032   EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1033                                     clEnumValN(OptionValue::Val, "", "help"))),
1034             ExpectedStrSize);
1035 }
1036 
1037 TEST_F(GetOptionWidthTest,
1038        GetOptionWidthValueOptionalEmptyOptionWithNoDescription) {
1039   StringRef ArgName("a");
1040   // The length of a=<value> (including indentation) is actually the same as the
1041   // =<empty> string, so it is impossible to distinguish via testing the case
1042   // where the empty string is ignored from where it is not ignored.
1043   // The dash will not actually be printed, but the space it would take up is
1044   // included to ensure a consistent column width.
1045   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1046   EXPECT_EQ(runTest(ArgName, cl::ValueOptional,
1047                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1048                                clEnumValN(OptionValue::Val, "", ""))),
1049             ExpectedStrSize);
1050 }
1051 
1052 TEST_F(GetOptionWidthTest,
1053        GetOptionWidthValueRequiredEmptyOptionWithNoDescription) {
1054   // The length of a=<value> (including indentation) is actually the same as the
1055   // =<empty> string, so it is impossible to distinguish via testing the case
1056   // where the empty string is picked from where the option name is picked
1057   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1058   EXPECT_EQ(runTest("a", cl::ValueRequired,
1059                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1060                                clEnumValN(OptionValue::Val, "", ""))),
1061             ExpectedStrSize);
1062 }
1063 
1064 TEST(CommandLineTest, PrefixOptions) {
1065   cl::ResetCommandLineParser();
1066 
1067   StackOption<std::string, cl::list<std::string>> IncludeDirs(
1068       "I", cl::Prefix, cl::desc("Declare an include directory"));
1069 
1070   // Test non-prefixed variant works with cl::Prefix options.
1071   EXPECT_TRUE(IncludeDirs.empty());
1072   const char *args[] = {"prog", "-I=/usr/include"};
1073   EXPECT_TRUE(
1074       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1075   EXPECT_TRUE(IncludeDirs.size() == 1);
1076   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1077 
1078   IncludeDirs.erase(IncludeDirs.begin());
1079   cl::ResetAllOptionOccurrences();
1080 
1081   // Test non-prefixed variant works with cl::Prefix options when value is
1082   // passed in following argument.
1083   EXPECT_TRUE(IncludeDirs.empty());
1084   const char *args2[] = {"prog", "-I", "/usr/include"};
1085   EXPECT_TRUE(
1086       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1087   EXPECT_TRUE(IncludeDirs.size() == 1);
1088   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1089 
1090   IncludeDirs.erase(IncludeDirs.begin());
1091   cl::ResetAllOptionOccurrences();
1092 
1093   // Test prefixed variant works with cl::Prefix options.
1094   EXPECT_TRUE(IncludeDirs.empty());
1095   const char *args3[] = {"prog", "-I/usr/include"};
1096   EXPECT_TRUE(
1097       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1098   EXPECT_TRUE(IncludeDirs.size() == 1);
1099   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1100 
1101   StackOption<std::string, cl::list<std::string>> MacroDefs(
1102       "D", cl::AlwaysPrefix, cl::desc("Define a macro"),
1103       cl::value_desc("MACRO[=VALUE]"));
1104 
1105   cl::ResetAllOptionOccurrences();
1106 
1107   // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1108   // equal sign is part of the value.
1109   EXPECT_TRUE(MacroDefs.empty());
1110   const char *args4[] = {"prog", "-D=HAVE_FOO"};
1111   EXPECT_TRUE(
1112       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1113   EXPECT_TRUE(MacroDefs.size() == 1);
1114   EXPECT_TRUE(MacroDefs.front().compare("=HAVE_FOO") == 0);
1115 
1116   MacroDefs.erase(MacroDefs.begin());
1117   cl::ResetAllOptionOccurrences();
1118 
1119   // Test non-prefixed variant does not allow value to be passed in following
1120   // argument with cl::AlwaysPrefix options.
1121   EXPECT_TRUE(MacroDefs.empty());
1122   const char *args5[] = {"prog", "-D", "HAVE_FOO"};
1123   EXPECT_FALSE(
1124       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1125   EXPECT_TRUE(MacroDefs.empty());
1126 
1127   cl::ResetAllOptionOccurrences();
1128 
1129   // Test prefixed variant works with cl::AlwaysPrefix options.
1130   EXPECT_TRUE(MacroDefs.empty());
1131   const char *args6[] = {"prog", "-DHAVE_FOO"};
1132   EXPECT_TRUE(
1133       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1134   EXPECT_TRUE(MacroDefs.size() == 1);
1135   EXPECT_TRUE(MacroDefs.front().compare("HAVE_FOO") == 0);
1136 }
1137 
1138 TEST(CommandLineTest, GroupingWithValue) {
1139   cl::ResetCommandLineParser();
1140 
1141   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1142   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1143   StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed,
1144                          cl::desc("ValueDisallowed option"));
1145   StackOption<std::string> OptV("v", cl::Grouping,
1146                                 cl::desc("ValueRequired option"));
1147   StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional,
1148                                 cl::desc("ValueOptional option"));
1149 
1150   // Should be possible to use an option which requires a value
1151   // at the end of a group.
1152   const char *args1[] = {"prog", "-fv", "val1"};
1153   EXPECT_TRUE(
1154       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
1155   EXPECT_TRUE(OptF);
1156   EXPECT_STREQ("val1", OptV.c_str());
1157   OptV.clear();
1158   cl::ResetAllOptionOccurrences();
1159 
1160   // Should not crash if it is accidentally used elsewhere in the group.
1161   const char *args2[] = {"prog", "-vf", "val2"};
1162   EXPECT_FALSE(
1163       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1164   OptV.clear();
1165   cl::ResetAllOptionOccurrences();
1166 
1167   // Should allow the "opt=value" form at the end of the group
1168   const char *args3[] = {"prog", "-fv=val3"};
1169   EXPECT_TRUE(
1170       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1171   EXPECT_TRUE(OptF);
1172   EXPECT_STREQ("val3", OptV.c_str());
1173   OptV.clear();
1174   cl::ResetAllOptionOccurrences();
1175 
1176   // Should allow assigning a value for a ValueOptional option
1177   // at the end of the group
1178   const char *args4[] = {"prog", "-fo=val4"};
1179   EXPECT_TRUE(
1180       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1181   EXPECT_TRUE(OptF);
1182   EXPECT_STREQ("val4", OptO.c_str());
1183   OptO.clear();
1184   cl::ResetAllOptionOccurrences();
1185 
1186   // Should assign an empty value if a ValueOptional option is used elsewhere
1187   // in the group.
1188   const char *args5[] = {"prog", "-fob"};
1189   EXPECT_TRUE(
1190       cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls()));
1191   EXPECT_TRUE(OptF);
1192   EXPECT_EQ(1, OptO.getNumOccurrences());
1193   EXPECT_EQ(1, OptB.getNumOccurrences());
1194   EXPECT_TRUE(OptO.empty());
1195   cl::ResetAllOptionOccurrences();
1196 
1197   // Should not allow an assignment for a ValueDisallowed option.
1198   const char *args6[] = {"prog", "-fd=false"};
1199   EXPECT_FALSE(
1200       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1201 }
1202 
1203 TEST(CommandLineTest, GroupingAndPrefix) {
1204   cl::ResetCommandLineParser();
1205 
1206   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1207   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1208   StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping,
1209                                 cl::desc("Prefix and Grouping"));
1210   StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping,
1211                                 cl::desc("AlwaysPrefix and Grouping"));
1212 
1213   // Should be possible to use a cl::Prefix option without grouping.
1214   const char *args1[] = {"prog", "-pval1"};
1215   EXPECT_TRUE(
1216       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
1217   EXPECT_STREQ("val1", OptP.c_str());
1218   OptP.clear();
1219   cl::ResetAllOptionOccurrences();
1220 
1221   // Should be possible to pass a value in a separate argument.
1222   const char *args2[] = {"prog", "-p", "val2"};
1223   EXPECT_TRUE(
1224       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1225   EXPECT_STREQ("val2", OptP.c_str());
1226   OptP.clear();
1227   cl::ResetAllOptionOccurrences();
1228 
1229   // The "-opt=value" form should work, too.
1230   const char *args3[] = {"prog", "-p=val3"};
1231   EXPECT_TRUE(
1232       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1233   EXPECT_STREQ("val3", OptP.c_str());
1234   OptP.clear();
1235   cl::ResetAllOptionOccurrences();
1236 
1237   // All three previous cases should work the same way if an option with both
1238   // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1239   const char *args4[] = {"prog", "-fpval4"};
1240   EXPECT_TRUE(
1241       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1242   EXPECT_TRUE(OptF);
1243   EXPECT_STREQ("val4", OptP.c_str());
1244   OptP.clear();
1245   cl::ResetAllOptionOccurrences();
1246 
1247   const char *args5[] = {"prog", "-fp", "val5"};
1248   EXPECT_TRUE(
1249       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1250   EXPECT_TRUE(OptF);
1251   EXPECT_STREQ("val5", OptP.c_str());
1252   OptP.clear();
1253   cl::ResetAllOptionOccurrences();
1254 
1255   const char *args6[] = {"prog", "-fp=val6"};
1256   EXPECT_TRUE(
1257       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1258   EXPECT_TRUE(OptF);
1259   EXPECT_STREQ("val6", OptP.c_str());
1260   OptP.clear();
1261   cl::ResetAllOptionOccurrences();
1262 
1263   // Should assign a value even if the part after a cl::Prefix option is equal
1264   // to the name of another option.
1265   const char *args7[] = {"prog", "-fpb"};
1266   EXPECT_TRUE(
1267       cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls()));
1268   EXPECT_TRUE(OptF);
1269   EXPECT_STREQ("b", OptP.c_str());
1270   EXPECT_FALSE(OptB);
1271   OptP.clear();
1272   cl::ResetAllOptionOccurrences();
1273 
1274   // Should be possible to use a cl::AlwaysPrefix option without grouping.
1275   const char *args8[] = {"prog", "-aval8"};
1276   EXPECT_TRUE(
1277       cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls()));
1278   EXPECT_STREQ("val8", OptA.c_str());
1279   OptA.clear();
1280   cl::ResetAllOptionOccurrences();
1281 
1282   // Should not be possible to pass a value in a separate argument.
1283   const char *args9[] = {"prog", "-a", "val9"};
1284   EXPECT_FALSE(
1285       cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls()));
1286   cl::ResetAllOptionOccurrences();
1287 
1288   // With the "-opt=value" form, the "=" symbol should be preserved.
1289   const char *args10[] = {"prog", "-a=val10"};
1290   EXPECT_TRUE(
1291       cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls()));
1292   EXPECT_STREQ("=val10", OptA.c_str());
1293   OptA.clear();
1294   cl::ResetAllOptionOccurrences();
1295 
1296   // All three previous cases should work the same way if an option with both
1297   // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1298   const char *args11[] = {"prog", "-faval11"};
1299   EXPECT_TRUE(
1300       cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls()));
1301   EXPECT_TRUE(OptF);
1302   EXPECT_STREQ("val11", OptA.c_str());
1303   OptA.clear();
1304   cl::ResetAllOptionOccurrences();
1305 
1306   const char *args12[] = {"prog", "-fa", "val12"};
1307   EXPECT_FALSE(
1308       cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls()));
1309   cl::ResetAllOptionOccurrences();
1310 
1311   const char *args13[] = {"prog", "-fa=val13"};
1312   EXPECT_TRUE(
1313       cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls()));
1314   EXPECT_TRUE(OptF);
1315   EXPECT_STREQ("=val13", OptA.c_str());
1316   OptA.clear();
1317   cl::ResetAllOptionOccurrences();
1318 
1319   // Should assign a value even if the part after a cl::AlwaysPrefix option
1320   // is equal to the name of another option.
1321   const char *args14[] = {"prog", "-fab"};
1322   EXPECT_TRUE(
1323       cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls()));
1324   EXPECT_TRUE(OptF);
1325   EXPECT_STREQ("b", OptA.c_str());
1326   EXPECT_FALSE(OptB);
1327   OptA.clear();
1328   cl::ResetAllOptionOccurrences();
1329 }
1330 
1331 }  // anonymous namespace
1332