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