xref: /llvm-project/llvm/unittests/Support/CommandLineTest.cpp (revision 8eeb56d1333c846d7043fd6a5433782c20b81606)
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, DefaultOptions) {
624   cl::ResetCommandLineParser();
625 
626   StackOption<std::string> Bar("bar", cl::sub(*cl::AllSubCommands),
627                                cl::DefaultOption);
628   StackOption<std::string, cl::alias> Bar_Alias(
629       "b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption);
630 
631   StackOption<bool> Foo("foo", cl::init(false), cl::sub(*cl::AllSubCommands),
632                         cl::DefaultOption);
633   StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"),
634                                          cl::aliasopt(Foo), cl::DefaultOption);
635 
636   StackSubCommand SC1("sc1", "First Subcommand");
637   // Override "-b" and change type in sc1 SubCommand.
638   StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false));
639   StackSubCommand SC2("sc2", "Second subcommand");
640   // Override "-foo" and change type in sc2 SubCommand.  Note that this does not
641   // affect "-f" alias, which continues to work correctly.
642   StackOption<std::string> SC2_Foo("foo", cl::sub(SC2));
643 
644   const char *args0[] = {"prog", "-b", "args0 bar string", "-f"};
645   EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args0) / sizeof(char *), args0,
646                                           StringRef(), &llvm::nulls()));
647   EXPECT_TRUE(Bar == "args0 bar string");
648   EXPECT_TRUE(Foo);
649   EXPECT_FALSE(SC1_B);
650   EXPECT_TRUE(SC2_Foo.empty());
651 
652   cl::ResetAllOptionOccurrences();
653 
654   const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"};
655   EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args1) / sizeof(char *), args1,
656                                           StringRef(), &llvm::nulls()));
657   EXPECT_TRUE(Bar == "args1 bar string");
658   EXPECT_TRUE(Foo);
659   EXPECT_TRUE(SC1_B);
660   EXPECT_TRUE(SC2_Foo.empty());
661   for (auto *S : cl::getRegisteredSubcommands()) {
662     if (*S) {
663       EXPECT_EQ("sc1", S->getName());
664     }
665   }
666 
667   cl::ResetAllOptionOccurrences();
668 
669   const char *args2[] = {"prog", "sc2", "-b", "args2 bar string",
670                          "-f", "-foo", "foo string"};
671   EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args2) / sizeof(char *), args2,
672                                           StringRef(), &llvm::nulls()));
673   EXPECT_TRUE(Bar == "args2 bar string");
674   EXPECT_TRUE(Foo);
675   EXPECT_FALSE(SC1_B);
676   EXPECT_TRUE(SC2_Foo == "foo string");
677   for (auto *S : cl::getRegisteredSubcommands()) {
678     if (*S) {
679       EXPECT_EQ("sc2", S->getName());
680     }
681   }
682   cl::ResetCommandLineParser();
683 }
684 
685 TEST(CommandLineTest, ArgumentLimit) {
686   std::string args(32 * 4096, 'a');
687   EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data()));
688 }
689 
690 TEST(CommandLineTest, ResponseFileWindows) {
691   if (!Triple(sys::getProcessTriple()).isOSWindows())
692     return;
693 
694   StackOption<std::string, cl::list<std::string>> InputFilenames(
695       cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore);
696   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
697 
698   // Create response file.
699   int FileDescriptor;
700   SmallString<64> TempPath;
701   std::error_code EC =
702       llvm::sys::fs::createTemporaryFile("resp-", ".txt", FileDescriptor, TempPath);
703   EXPECT_TRUE(!EC);
704 
705   std::ofstream RspFile(TempPath.c_str());
706   EXPECT_TRUE(RspFile.is_open());
707   RspFile << "-top-level\npath\\dir\\file1\npath/dir/file2";
708   RspFile.close();
709 
710   llvm::SmallString<128> RspOpt;
711   RspOpt.append(1, '@');
712   RspOpt.append(TempPath.c_str());
713   const char *args[] = {"prog", RspOpt.c_str()};
714   EXPECT_FALSE(TopLevelOpt);
715   EXPECT_TRUE(
716       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
717   EXPECT_TRUE(TopLevelOpt);
718   EXPECT_TRUE(InputFilenames[0] == "path\\dir\\file1");
719   EXPECT_TRUE(InputFilenames[1] == "path/dir/file2");
720 
721   llvm::sys::fs::remove(TempPath.c_str());
722 }
723 
724 TEST(CommandLineTest, ResponseFiles) {
725   llvm::SmallString<128> TestDir;
726   std::error_code EC =
727     llvm::sys::fs::createUniqueDirectory("unittest", TestDir);
728   EXPECT_TRUE(!EC);
729 
730   // Create included response file of first level.
731   llvm::SmallString<128> IncludedFileName;
732   llvm::sys::path::append(IncludedFileName, TestDir, "resp1");
733   std::ofstream IncludedFile(IncludedFileName.c_str());
734   EXPECT_TRUE(IncludedFile.is_open());
735   IncludedFile << "-option_1 -option_2\n"
736                   "@incdir/resp2\n"
737                   "-option_3=abcd\n";
738   IncludedFile.close();
739 
740   // Directory for included file.
741   llvm::SmallString<128> IncDir;
742   llvm::sys::path::append(IncDir, TestDir, "incdir");
743   EC = llvm::sys::fs::create_directory(IncDir);
744   EXPECT_TRUE(!EC);
745 
746   // Create included response file of second level.
747   llvm::SmallString<128> IncludedFileName2;
748   llvm::sys::path::append(IncludedFileName2, IncDir, "resp2");
749   std::ofstream IncludedFile2(IncludedFileName2.c_str());
750   EXPECT_TRUE(IncludedFile2.is_open());
751   IncludedFile2 << "-option_21 -option_22\n";
752   IncludedFile2 << "-option_23=abcd\n";
753   IncludedFile2.close();
754 
755   // Prepare 'file' with reference to response file.
756   SmallString<128> IncRef;
757   IncRef.append(1, '@');
758   IncRef.append(IncludedFileName.c_str());
759   llvm::SmallVector<const char *, 4> Argv =
760                           { "test/test", "-flag_1", IncRef.c_str(), "-flag_2" };
761 
762   // Expand response files.
763   llvm::BumpPtrAllocator A;
764   llvm::StringSaver Saver(A);
765   bool Res = llvm::cl::ExpandResponseFiles(
766                     Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true);
767   EXPECT_TRUE(Res);
768   EXPECT_EQ(Argv.size(), 9U);
769   EXPECT_STREQ(Argv[0], "test/test");
770   EXPECT_STREQ(Argv[1], "-flag_1");
771   EXPECT_STREQ(Argv[2], "-option_1");
772   EXPECT_STREQ(Argv[3], "-option_2");
773   EXPECT_STREQ(Argv[4], "-option_21");
774   EXPECT_STREQ(Argv[5], "-option_22");
775   EXPECT_STREQ(Argv[6], "-option_23=abcd");
776   EXPECT_STREQ(Argv[7], "-option_3=abcd");
777   EXPECT_STREQ(Argv[8], "-flag_2");
778 
779   llvm::sys::fs::remove(IncludedFileName2);
780   llvm::sys::fs::remove(IncDir);
781   llvm::sys::fs::remove(IncludedFileName);
782   llvm::sys::fs::remove(TestDir);
783 }
784 
785 TEST(CommandLineTest, SetDefautValue) {
786   cl::ResetCommandLineParser();
787 
788   StackOption<std::string> Opt1("opt1", cl::init("true"));
789   StackOption<bool> Opt2("opt2", cl::init(true));
790   cl::alias Alias("alias", llvm::cl::aliasopt(Opt2));
791   StackOption<int> Opt3("opt3", cl::init(3));
792 
793   const char *args[] = {"prog", "-opt1=false", "-opt2", "-opt3"};
794 
795   EXPECT_TRUE(
796     cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
797 
798   EXPECT_TRUE(Opt1 == "false");
799   EXPECT_TRUE(Opt2);
800   EXPECT_TRUE(Opt3 == 3);
801 
802   Opt2 = false;
803   Opt3 = 1;
804 
805   cl::ResetAllOptionOccurrences();
806 
807   for (auto &OM : cl::getRegisteredOptions(*cl::TopLevelSubCommand)) {
808     cl::Option *O = OM.second;
809     if (O->ArgStr == "opt2") {
810       continue;
811     }
812     O->setDefault();
813   }
814 
815   EXPECT_TRUE(Opt1 == "true");
816   EXPECT_TRUE(Opt2);
817   EXPECT_TRUE(Opt3 == 3);
818   Alias.removeArgument();
819 }
820 
821 TEST(CommandLineTest, ReadConfigFile) {
822   llvm::SmallVector<const char *, 1> Argv;
823 
824   llvm::SmallString<128> TestDir;
825   std::error_code EC =
826       llvm::sys::fs::createUniqueDirectory("unittest", TestDir);
827   EXPECT_TRUE(!EC);
828 
829   llvm::SmallString<128> TestCfg;
830   llvm::sys::path::append(TestCfg, TestDir, "foo");
831   std::ofstream ConfigFile(TestCfg.c_str());
832   EXPECT_TRUE(ConfigFile.is_open());
833   ConfigFile << "# Comment\n"
834                 "-option_1\n"
835                 "@subconfig\n"
836                 "-option_3=abcd\n"
837                 "-option_4=\\\n"
838                 "cdef\n";
839   ConfigFile.close();
840 
841   llvm::SmallString<128> TestCfg2;
842   llvm::sys::path::append(TestCfg2, TestDir, "subconfig");
843   std::ofstream ConfigFile2(TestCfg2.c_str());
844   EXPECT_TRUE(ConfigFile2.is_open());
845   ConfigFile2 << "-option_2\n"
846                  "\n"
847                  "   # comment\n";
848   ConfigFile2.close();
849 
850   // Make sure the current directory is not the directory where config files
851   // resides. In this case the code that expands response files will not find
852   // 'subconfig' unless it resolves nested inclusions relative to the including
853   // file.
854   llvm::SmallString<128> CurrDir;
855   EC = llvm::sys::fs::current_path(CurrDir);
856   EXPECT_TRUE(!EC);
857   EXPECT_TRUE(StringRef(CurrDir) != StringRef(TestDir));
858 
859   llvm::BumpPtrAllocator A;
860   llvm::StringSaver Saver(A);
861   bool Result = llvm::cl::readConfigFile(TestCfg, Saver, Argv);
862 
863   EXPECT_TRUE(Result);
864   EXPECT_EQ(Argv.size(), 4U);
865   EXPECT_STREQ(Argv[0], "-option_1");
866   EXPECT_STREQ(Argv[1], "-option_2");
867   EXPECT_STREQ(Argv[2], "-option_3=abcd");
868   EXPECT_STREQ(Argv[3], "-option_4=cdef");
869 
870   llvm::sys::fs::remove(TestCfg2);
871   llvm::sys::fs::remove(TestCfg);
872   llvm::sys::fs::remove(TestDir);
873 }
874 
875 TEST(CommandLineTest, PositionalEatArgsError) {
876   StackOption<std::string, cl::list<std::string>> PosEatArgs(
877       "positional-eat-args", cl::Positional, cl::desc("<arguments>..."),
878       cl::ZeroOrMore, cl::PositionalEatsArgs);
879 
880   const char *args[] = {"prog", "-positional-eat-args=XXXX"};
881   const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
882   const char *args3[] = {"prog", "-positional-eat-args", "-foo"};
883 
884   std::string Errs;
885   raw_string_ostream OS(Errs);
886   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush();
887   EXPECT_FALSE(Errs.empty()); Errs.clear();
888   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush();
889   EXPECT_FALSE(Errs.empty()); Errs.clear();
890   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush();
891   EXPECT_TRUE(Errs.empty());
892 }
893 
894 #ifdef _WIN32
895 TEST(CommandLineTest, GetCommandLineArguments) {
896   int argc = __argc;
897   char **argv = __argv;
898 
899   // GetCommandLineArguments is called in InitLLVM.
900   llvm::InitLLVM X(argc, argv);
901 
902   EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]),
903             llvm::sys::path::is_absolute(__argv[0]));
904 
905   EXPECT_TRUE(llvm::sys::path::filename(argv[0])
906               .equals_lower("supporttests.exe"))
907       << "Filename of test executable is "
908       << llvm::sys::path::filename(argv[0]);
909 }
910 #endif
911 
912 class OutputRedirector {
913 public:
914   OutputRedirector(int RedirectFD)
915       : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) {
916     if (OldFD == -1 ||
917         sys::fs::createTemporaryFile("unittest-redirect", "", NewFD,
918                                      FilePath) ||
919         dup2(NewFD, RedirectFD) == -1)
920       Valid = false;
921   }
922 
923   ~OutputRedirector() {
924     dup2(OldFD, RedirectFD);
925     close(OldFD);
926     close(NewFD);
927   }
928 
929   SmallVector<char, 128> FilePath;
930   bool Valid = true;
931 
932 private:
933   int RedirectFD;
934   int OldFD;
935   int NewFD;
936 };
937 
938 struct AutoDeleteFile {
939   SmallVector<char, 128> FilePath;
940   ~AutoDeleteFile() {
941     if (!FilePath.empty())
942       sys::fs::remove(std::string(FilePath.data(), FilePath.size()));
943   }
944 };
945 
946 class PrintOptionInfoTest : public ::testing::Test {
947 public:
948   // Return std::string because the output of a failing EXPECT check is
949   // unreadable for StringRef. It also avoids any lifetime issues.
950   template <typename... Ts> std::string runTest(Ts... OptionAttributes) {
951     AutoDeleteFile File;
952     {
953       OutputRedirector Stdout(fileno(stdout));
954       if (!Stdout.Valid)
955         return "";
956       File.FilePath = Stdout.FilePath;
957 
958       StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText),
959                                           OptionAttributes...);
960       printOptionInfo(TestOption, 25);
961       outs().flush();
962     }
963     auto Buffer = MemoryBuffer::getFile(File.FilePath);
964     if (!Buffer)
965       return "";
966     return Buffer->get()->getBuffer().str();
967   }
968 
969   enum class OptionValue { Val };
970   const StringRef Opt = "some-option";
971   const StringRef HelpText = "some help";
972 
973 private:
974   // This is a workaround for cl::Option sub-classes having their
975   // printOptionInfo functions private.
976   void printOptionInfo(const cl::Option &O, size_t Width) {
977     O.printOptionInfo(Width);
978   }
979 };
980 
981 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) {
982   std::string Output =
983       runTest(cl::ValueOptional,
984               cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
985 
986   // clang-format off
987   EXPECT_EQ(Output, ("  -" + Opt + "=<value> - " + HelpText + "\n"
988                      "    =v1                -   desc1\n")
989                         .str());
990   // clang-format on
991 }
992 
993 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) {
994   std::string Output = runTest(
995       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
996                                     clEnumValN(OptionValue::Val, "", "")));
997 
998   // clang-format off
999   EXPECT_EQ(Output,
1000             ("  -" + Opt + "         - " + HelpText + "\n"
1001              "  -" + Opt + "=<value> - " + HelpText + "\n"
1002              "    =v1                -   desc1\n")
1003                 .str());
1004   // clang-format on
1005 }
1006 
1007 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) {
1008   std::string Output = runTest(
1009       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1010                                     clEnumValN(OptionValue::Val, "", "desc2")));
1011 
1012   // clang-format off
1013   EXPECT_EQ(Output, ("  -" + Opt + "         - " + HelpText + "\n"
1014                      "  -" + Opt + "=<value> - " + HelpText + "\n"
1015                      "    =v1                -   desc1\n"
1016                      "    =<empty>           -   desc2\n")
1017                         .str());
1018   // clang-format on
1019 }
1020 
1021 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) {
1022   std::string Output = runTest(
1023       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1024                                     clEnumValN(OptionValue::Val, "", "")));
1025 
1026   // clang-format off
1027   EXPECT_EQ(Output, ("  -" + Opt + "=<value> - " + HelpText + "\n"
1028                      "    =v1                -   desc1\n"
1029                      "    =<empty>\n")
1030                         .str());
1031   // clang-format on
1032 }
1033 
1034 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) {
1035   std::string Output = runTest(
1036       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "")));
1037 
1038   // clang-format off
1039   EXPECT_EQ(Output,
1040             ("  -" + Opt + "=<value> - " + HelpText + "\n"
1041              "    =v1\n").str());
1042   // clang-format on
1043 }
1044 
1045 class GetOptionWidthTest : public ::testing::Test {
1046 public:
1047   enum class OptionValue { Val };
1048 
1049   template <typename... Ts>
1050   size_t runTest(StringRef ArgName, Ts... OptionAttributes) {
1051     StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"),
1052                                         OptionAttributes...);
1053     return getOptionWidth(TestOption);
1054   }
1055 
1056 private:
1057   // This is a workaround for cl::Option sub-classes having their
1058   // printOptionInfo
1059   // functions private.
1060   size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); }
1061 };
1062 
1063 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) {
1064   StringRef ArgName("a-long-argument-name");
1065   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1066   EXPECT_EQ(
1067       runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))),
1068       ExpectedStrSize);
1069 }
1070 
1071 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) {
1072   StringRef OptName("a-long-option-name");
1073   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1074   EXPECT_EQ(
1075       runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"),
1076                               clEnumValN(OptionValue::Val, "b", "help"))),
1077       ExpectedStrSize);
1078 }
1079 
1080 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) {
1081   StringRef OptName("a-long-option-name");
1082   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1083   EXPECT_EQ(
1084       runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1085                               clEnumValN(OptionValue::Val, OptName, "help"))),
1086       ExpectedStrSize);
1087 }
1088 
1089 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) {
1090   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1091   // The length of a=<value> (including indentation) is actually the same as the
1092   // =<empty> string, so it is impossible to distinguish via testing the case
1093   // where the empty string is picked from where the option name is picked.
1094   EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1095                                     clEnumValN(OptionValue::Val, "", "help"))),
1096             ExpectedStrSize);
1097 }
1098 
1099 TEST_F(GetOptionWidthTest,
1100        GetOptionWidthValueOptionalEmptyOptionWithNoDescription) {
1101   StringRef ArgName("a");
1102   // The length of a=<value> (including indentation) is actually the same as the
1103   // =<empty> string, so it is impossible to distinguish via testing the case
1104   // where the empty string is ignored from where it is not ignored.
1105   // The dash will not actually be printed, but the space it would take up is
1106   // included to ensure a consistent column width.
1107   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1108   EXPECT_EQ(runTest(ArgName, cl::ValueOptional,
1109                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1110                                clEnumValN(OptionValue::Val, "", ""))),
1111             ExpectedStrSize);
1112 }
1113 
1114 TEST_F(GetOptionWidthTest,
1115        GetOptionWidthValueRequiredEmptyOptionWithNoDescription) {
1116   // The length of a=<value> (including indentation) is actually the same as the
1117   // =<empty> string, so it is impossible to distinguish via testing the case
1118   // where the empty string is picked from where the option name is picked
1119   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1120   EXPECT_EQ(runTest("a", cl::ValueRequired,
1121                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1122                                clEnumValN(OptionValue::Val, "", ""))),
1123             ExpectedStrSize);
1124 }
1125 
1126 TEST(CommandLineTest, PrefixOptions) {
1127   cl::ResetCommandLineParser();
1128 
1129   StackOption<std::string, cl::list<std::string>> IncludeDirs(
1130       "I", cl::Prefix, cl::desc("Declare an include directory"));
1131 
1132   // Test non-prefixed variant works with cl::Prefix options.
1133   EXPECT_TRUE(IncludeDirs.empty());
1134   const char *args[] = {"prog", "-I=/usr/include"};
1135   EXPECT_TRUE(
1136       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1137   EXPECT_TRUE(IncludeDirs.size() == 1);
1138   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1139 
1140   IncludeDirs.erase(IncludeDirs.begin());
1141   cl::ResetAllOptionOccurrences();
1142 
1143   // Test non-prefixed variant works with cl::Prefix options when value is
1144   // passed in following argument.
1145   EXPECT_TRUE(IncludeDirs.empty());
1146   const char *args2[] = {"prog", "-I", "/usr/include"};
1147   EXPECT_TRUE(
1148       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1149   EXPECT_TRUE(IncludeDirs.size() == 1);
1150   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1151 
1152   IncludeDirs.erase(IncludeDirs.begin());
1153   cl::ResetAllOptionOccurrences();
1154 
1155   // Test prefixed variant works with cl::Prefix options.
1156   EXPECT_TRUE(IncludeDirs.empty());
1157   const char *args3[] = {"prog", "-I/usr/include"};
1158   EXPECT_TRUE(
1159       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1160   EXPECT_TRUE(IncludeDirs.size() == 1);
1161   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1162 
1163   StackOption<std::string, cl::list<std::string>> MacroDefs(
1164       "D", cl::AlwaysPrefix, cl::desc("Define a macro"),
1165       cl::value_desc("MACRO[=VALUE]"));
1166 
1167   cl::ResetAllOptionOccurrences();
1168 
1169   // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1170   // equal sign is part of the value.
1171   EXPECT_TRUE(MacroDefs.empty());
1172   const char *args4[] = {"prog", "-D=HAVE_FOO"};
1173   EXPECT_TRUE(
1174       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1175   EXPECT_TRUE(MacroDefs.size() == 1);
1176   EXPECT_TRUE(MacroDefs.front().compare("=HAVE_FOO") == 0);
1177 
1178   MacroDefs.erase(MacroDefs.begin());
1179   cl::ResetAllOptionOccurrences();
1180 
1181   // Test non-prefixed variant does not allow value to be passed in following
1182   // argument with cl::AlwaysPrefix options.
1183   EXPECT_TRUE(MacroDefs.empty());
1184   const char *args5[] = {"prog", "-D", "HAVE_FOO"};
1185   EXPECT_FALSE(
1186       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1187   EXPECT_TRUE(MacroDefs.empty());
1188 
1189   cl::ResetAllOptionOccurrences();
1190 
1191   // Test prefixed variant works with cl::AlwaysPrefix options.
1192   EXPECT_TRUE(MacroDefs.empty());
1193   const char *args6[] = {"prog", "-DHAVE_FOO"};
1194   EXPECT_TRUE(
1195       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1196   EXPECT_TRUE(MacroDefs.size() == 1);
1197   EXPECT_TRUE(MacroDefs.front().compare("HAVE_FOO") == 0);
1198 }
1199 
1200 TEST(CommandLineTest, GroupingWithValue) {
1201   cl::ResetCommandLineParser();
1202 
1203   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1204   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1205   StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed,
1206                          cl::desc("ValueDisallowed option"));
1207   StackOption<std::string> OptV("v", cl::Grouping,
1208                                 cl::desc("ValueRequired option"));
1209   StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional,
1210                                 cl::desc("ValueOptional option"));
1211 
1212   // Should be possible to use an option which requires a value
1213   // at the end of a group.
1214   const char *args1[] = {"prog", "-fv", "val1"};
1215   EXPECT_TRUE(
1216       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
1217   EXPECT_TRUE(OptF);
1218   EXPECT_STREQ("val1", OptV.c_str());
1219   OptV.clear();
1220   cl::ResetAllOptionOccurrences();
1221 
1222   // Should not crash if it is accidentally used elsewhere in the group.
1223   const char *args2[] = {"prog", "-vf", "val2"};
1224   EXPECT_FALSE(
1225       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1226   OptV.clear();
1227   cl::ResetAllOptionOccurrences();
1228 
1229   // Should allow the "opt=value" form at the end of the group
1230   const char *args3[] = {"prog", "-fv=val3"};
1231   EXPECT_TRUE(
1232       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1233   EXPECT_TRUE(OptF);
1234   EXPECT_STREQ("val3", OptV.c_str());
1235   OptV.clear();
1236   cl::ResetAllOptionOccurrences();
1237 
1238   // Should allow assigning a value for a ValueOptional option
1239   // at the end of the group
1240   const char *args4[] = {"prog", "-fo=val4"};
1241   EXPECT_TRUE(
1242       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1243   EXPECT_TRUE(OptF);
1244   EXPECT_STREQ("val4", OptO.c_str());
1245   OptO.clear();
1246   cl::ResetAllOptionOccurrences();
1247 
1248   // Should assign an empty value if a ValueOptional option is used elsewhere
1249   // in the group.
1250   const char *args5[] = {"prog", "-fob"};
1251   EXPECT_TRUE(
1252       cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls()));
1253   EXPECT_TRUE(OptF);
1254   EXPECT_EQ(1, OptO.getNumOccurrences());
1255   EXPECT_EQ(1, OptB.getNumOccurrences());
1256   EXPECT_TRUE(OptO.empty());
1257   cl::ResetAllOptionOccurrences();
1258 
1259   // Should not allow an assignment for a ValueDisallowed option.
1260   const char *args6[] = {"prog", "-fd=false"};
1261   EXPECT_FALSE(
1262       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1263 }
1264 
1265 TEST(CommandLineTest, GroupingAndPrefix) {
1266   cl::ResetCommandLineParser();
1267 
1268   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1269   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1270   StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping,
1271                                 cl::desc("Prefix and Grouping"));
1272   StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping,
1273                                 cl::desc("AlwaysPrefix and Grouping"));
1274 
1275   // Should be possible to use a cl::Prefix option without grouping.
1276   const char *args1[] = {"prog", "-pval1"};
1277   EXPECT_TRUE(
1278       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
1279   EXPECT_STREQ("val1", OptP.c_str());
1280   OptP.clear();
1281   cl::ResetAllOptionOccurrences();
1282 
1283   // Should be possible to pass a value in a separate argument.
1284   const char *args2[] = {"prog", "-p", "val2"};
1285   EXPECT_TRUE(
1286       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1287   EXPECT_STREQ("val2", OptP.c_str());
1288   OptP.clear();
1289   cl::ResetAllOptionOccurrences();
1290 
1291   // The "-opt=value" form should work, too.
1292   const char *args3[] = {"prog", "-p=val3"};
1293   EXPECT_TRUE(
1294       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1295   EXPECT_STREQ("val3", OptP.c_str());
1296   OptP.clear();
1297   cl::ResetAllOptionOccurrences();
1298 
1299   // All three previous cases should work the same way if an option with both
1300   // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1301   const char *args4[] = {"prog", "-fpval4"};
1302   EXPECT_TRUE(
1303       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1304   EXPECT_TRUE(OptF);
1305   EXPECT_STREQ("val4", OptP.c_str());
1306   OptP.clear();
1307   cl::ResetAllOptionOccurrences();
1308 
1309   const char *args5[] = {"prog", "-fp", "val5"};
1310   EXPECT_TRUE(
1311       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1312   EXPECT_TRUE(OptF);
1313   EXPECT_STREQ("val5", OptP.c_str());
1314   OptP.clear();
1315   cl::ResetAllOptionOccurrences();
1316 
1317   const char *args6[] = {"prog", "-fp=val6"};
1318   EXPECT_TRUE(
1319       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1320   EXPECT_TRUE(OptF);
1321   EXPECT_STREQ("val6", OptP.c_str());
1322   OptP.clear();
1323   cl::ResetAllOptionOccurrences();
1324 
1325   // Should assign a value even if the part after a cl::Prefix option is equal
1326   // to the name of another option.
1327   const char *args7[] = {"prog", "-fpb"};
1328   EXPECT_TRUE(
1329       cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls()));
1330   EXPECT_TRUE(OptF);
1331   EXPECT_STREQ("b", OptP.c_str());
1332   EXPECT_FALSE(OptB);
1333   OptP.clear();
1334   cl::ResetAllOptionOccurrences();
1335 
1336   // Should be possible to use a cl::AlwaysPrefix option without grouping.
1337   const char *args8[] = {"prog", "-aval8"};
1338   EXPECT_TRUE(
1339       cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls()));
1340   EXPECT_STREQ("val8", OptA.c_str());
1341   OptA.clear();
1342   cl::ResetAllOptionOccurrences();
1343 
1344   // Should not be possible to pass a value in a separate argument.
1345   const char *args9[] = {"prog", "-a", "val9"};
1346   EXPECT_FALSE(
1347       cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls()));
1348   cl::ResetAllOptionOccurrences();
1349 
1350   // With the "-opt=value" form, the "=" symbol should be preserved.
1351   const char *args10[] = {"prog", "-a=val10"};
1352   EXPECT_TRUE(
1353       cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls()));
1354   EXPECT_STREQ("=val10", OptA.c_str());
1355   OptA.clear();
1356   cl::ResetAllOptionOccurrences();
1357 
1358   // All three previous cases should work the same way if an option with both
1359   // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1360   const char *args11[] = {"prog", "-faval11"};
1361   EXPECT_TRUE(
1362       cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls()));
1363   EXPECT_TRUE(OptF);
1364   EXPECT_STREQ("val11", OptA.c_str());
1365   OptA.clear();
1366   cl::ResetAllOptionOccurrences();
1367 
1368   const char *args12[] = {"prog", "-fa", "val12"};
1369   EXPECT_FALSE(
1370       cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls()));
1371   cl::ResetAllOptionOccurrences();
1372 
1373   const char *args13[] = {"prog", "-fa=val13"};
1374   EXPECT_TRUE(
1375       cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls()));
1376   EXPECT_TRUE(OptF);
1377   EXPECT_STREQ("=val13", OptA.c_str());
1378   OptA.clear();
1379   cl::ResetAllOptionOccurrences();
1380 
1381   // Should assign a value even if the part after a cl::AlwaysPrefix option
1382   // is equal to the name of another option.
1383   const char *args14[] = {"prog", "-fab"};
1384   EXPECT_TRUE(
1385       cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls()));
1386   EXPECT_TRUE(OptF);
1387   EXPECT_STREQ("b", OptA.c_str());
1388   EXPECT_FALSE(OptB);
1389   OptA.clear();
1390   cl::ResetAllOptionOccurrences();
1391 }
1392 
1393 }  // anonymous namespace
1394