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