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