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 "gmock/gmock.h"
26 #include "gtest/gtest.h"
27 #include <fstream>
28 #include <stdlib.h>
29 #include <string>
30 #include <tuple>
31 
32 using namespace llvm;
33 
34 namespace {
35 
36 MATCHER(StringEquality, "Checks if two char* are equal as strings") {
37   return std::string(std::get<0>(arg)) == std::string(std::get<1>(arg));
38 }
39 
40 class TempEnvVar {
41  public:
42   TempEnvVar(const char *name, const char *value)
43       : name(name) {
44     const char *old_value = getenv(name);
45     EXPECT_EQ(nullptr, old_value) << old_value;
46 #if HAVE_SETENV
47     setenv(name, value, true);
48 #else
49 #   define SKIP_ENVIRONMENT_TESTS
50 #endif
51   }
52 
53   ~TempEnvVar() {
54 #if HAVE_SETENV
55     // Assume setenv and unsetenv come together.
56     unsetenv(name);
57 #else
58     (void)name; // Suppress -Wunused-private-field.
59 #endif
60   }
61 
62  private:
63   const char *const name;
64 };
65 
66 template <typename T, typename Base = cl::opt<T>>
67 class StackOption : public Base {
68 public:
69   template <class... Ts>
70   explicit StackOption(Ts &&... Ms) : Base(std::forward<Ts>(Ms)...) {}
71 
72   ~StackOption() override { this->removeArgument(); }
73 
74   template <class DT> StackOption<T> &operator=(const DT &V) {
75     Base::operator=(V);
76     return *this;
77   }
78 };
79 
80 class StackSubCommand : public cl::SubCommand {
81 public:
82   StackSubCommand(StringRef Name,
83                   StringRef Description = StringRef())
84       : SubCommand(Name, Description) {}
85 
86   StackSubCommand() : SubCommand() {}
87 
88   ~StackSubCommand() { unregisterSubCommand(); }
89 };
90 
91 
92 cl::OptionCategory TestCategory("Test Options", "Description");
93 TEST(CommandLineTest, ModifyExisitingOption) {
94   StackOption<int> TestOption("test-option", cl::desc("old description"));
95 
96   static const char Description[] = "New description";
97   static const char ArgString[] = "new-test-option";
98   static const char ValueString[] = "Integer";
99 
100   StringMap<cl::Option *> &Map =
101       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
102 
103   ASSERT_TRUE(Map.count("test-option") == 1) <<
104     "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::GeneralCategory;
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 #ifndef SKIP_ENVIRONMENT_TESTS
141 
142 const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
143 
144 cl::opt<std::string> EnvironmentTestOption("env-test-opt");
145 TEST(CommandLineTest, ParseEnvironment) {
146   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
147   EXPECT_EQ("", EnvironmentTestOption);
148   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
149   EXPECT_EQ("hello", EnvironmentTestOption);
150 }
151 
152 // This test used to make valgrind complain
153 // ("Conditional jump or move depends on uninitialised value(s)")
154 //
155 // Warning: Do not run any tests after this one that try to gain access to
156 // registered command line options because this will likely result in a
157 // SEGFAULT. This can occur because the cl::opt in the test below is declared
158 // on the stack which will be destroyed after the test completes but the
159 // command line system will still hold a pointer to a deallocated cl::Option.
160 TEST(CommandLineTest, ParseEnvironmentToLocalVar) {
161   // Put cl::opt on stack to check for proper initialization of fields.
162   StackOption<std::string> EnvironmentTestOptionLocal("env-test-opt-local");
163   TempEnvVar TEV(test_env_var, "-env-test-opt-local=hello-local");
164   EXPECT_EQ("", EnvironmentTestOptionLocal);
165   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
166   EXPECT_EQ("hello-local", EnvironmentTestOptionLocal);
167 }
168 
169 #endif  // SKIP_ENVIRONMENT_TESTS
170 
171 TEST(CommandLineTest, UseOptionCategory) {
172   StackOption<int> TestOption2("test-option", cl::cat(TestCategory));
173 
174   ASSERT_NE(TestOption2.Categories.end(),
175             find_if(TestOption2.Categories,
176                          [&](const llvm::cl::OptionCategory *Cat) {
177                            return Cat == &TestCategory;
178                          }))
179       << "Failed to assign Option Category.";
180 }
181 
182 TEST(CommandLineTest, UseMultipleCategories) {
183   StackOption<int> TestOption2("test-option2", cl::cat(TestCategory),
184                                cl::cat(cl::GeneralCategory),
185                                cl::cat(cl::GeneralCategory));
186 
187   // Make sure cl::GeneralCategory wasn't added twice.
188   ASSERT_EQ(TestOption2.Categories.size(), 2U);
189 
190   ASSERT_NE(TestOption2.Categories.end(),
191             find_if(TestOption2.Categories,
192                          [&](const llvm::cl::OptionCategory *Cat) {
193                            return Cat == &TestCategory;
194                          }))
195       << "Failed to assign Option Category.";
196   ASSERT_NE(TestOption2.Categories.end(),
197             find_if(TestOption2.Categories,
198                          [&](const llvm::cl::OptionCategory *Cat) {
199                            return Cat == &cl::GeneralCategory;
200                          }))
201       << "Failed to assign General Category.";
202 
203   cl::OptionCategory AnotherCategory("Additional test Options", "Description");
204   StackOption<int> TestOption("test-option", cl::cat(TestCategory),
205                               cl::cat(AnotherCategory));
206   ASSERT_EQ(TestOption.Categories.end(),
207             find_if(TestOption.Categories,
208                          [&](const llvm::cl::OptionCategory *Cat) {
209                            return Cat == &cl::GeneralCategory;
210                          }))
211       << "Failed to remove General Category.";
212   ASSERT_NE(TestOption.Categories.end(),
213             find_if(TestOption.Categories,
214                          [&](const llvm::cl::OptionCategory *Cat) {
215                            return Cat == &TestCategory;
216                          }))
217       << "Failed to assign Option Category.";
218   ASSERT_NE(TestOption.Categories.end(),
219             find_if(TestOption.Categories,
220                          [&](const llvm::cl::OptionCategory *Cat) {
221                            return Cat == &AnotherCategory;
222                          }))
223       << "Failed to assign Another Category.";
224 }
225 
226 typedef void ParserFunction(StringRef Source, StringSaver &Saver,
227                             SmallVectorImpl<const char *> &NewArgv,
228                             bool MarkEOLs);
229 
230 void testCommandLineTokenizer(ParserFunction *parse, StringRef Input,
231                               const char *const Output[], size_t OutputSize) {
232   SmallVector<const char *, 0> Actual;
233   BumpPtrAllocator A;
234   StringSaver Saver(A);
235   parse(Input, Saver, Actual, /*MarkEOLs=*/false);
236   EXPECT_EQ(OutputSize, Actual.size());
237   for (unsigned I = 0, E = Actual.size(); I != E; ++I) {
238     if (I < OutputSize) {
239       EXPECT_STREQ(Output[I], Actual[I]);
240     }
241   }
242 }
243 
244 TEST(CommandLineTest, TokenizeGNUCommandLine) {
245   const char Input[] =
246       "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' -DFOO=bar\\(\\) "
247       "foo\"bar\"baz C:\\\\src\\\\foo.cpp \"C:\\src\\foo.cpp\"";
248   const char *const Output[] = {
249       "foo bar",     "foo bar",   "foo bar",          "foo\\bar",
250       "-DFOO=bar()", "foobarbaz", "C:\\src\\foo.cpp", "C:srcfoo.cpp"};
251   testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
252                            array_lengthof(Output));
253 }
254 
255 TEST(CommandLineTest, TokenizeWindowsCommandLine1) {
256   const char Input[] =
257       R"(a\b c\\d e\\"f g" h\"i j\\\"k "lmn" o pqr "st \"u" \v)";
258   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
259                                  "lmn", "o", "pqr", "st \"u", "\\v" };
260   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
261                            array_lengthof(Output));
262 }
263 
264 TEST(CommandLineTest, TokenizeWindowsCommandLine2) {
265   const char Input[] = "clang -c -DFOO=\"\"\"ABC\"\"\" x.cpp";
266   const char *const Output[] = { "clang", "-c", "-DFOO=\"ABC\"", "x.cpp"};
267   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
268                            array_lengthof(Output));
269 }
270 
271 TEST(CommandLineTest, TokenizeWindowsCommandLineQuotedLastArgument) {
272   const char Input1[] = R"(a b c d "")";
273   const char *const Output1[] = {"a", "b", "c", "d", ""};
274   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input1, Output1,
275                            array_lengthof(Output1));
276   const char Input2[] = R"(a b c d ")";
277   const char *const Output2[] = {"a", "b", "c", "d"};
278   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input2, Output2,
279                            array_lengthof(Output2));
280 }
281 
282 TEST(CommandLineTest, TokenizeConfigFile1) {
283   const char *Input = "\\";
284   const char *const Output[] = { "\\" };
285   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
286                            array_lengthof(Output));
287 }
288 
289 TEST(CommandLineTest, TokenizeConfigFile2) {
290   const char *Input = "\\abc";
291   const char *const Output[] = { "abc" };
292   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
293                            array_lengthof(Output));
294 }
295 
296 TEST(CommandLineTest, TokenizeConfigFile3) {
297   const char *Input = "abc\\";
298   const char *const Output[] = { "abc\\" };
299   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
300                            array_lengthof(Output));
301 }
302 
303 TEST(CommandLineTest, TokenizeConfigFile4) {
304   const char *Input = "abc\\\n123";
305   const char *const Output[] = { "abc123" };
306   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
307                            array_lengthof(Output));
308 }
309 
310 TEST(CommandLineTest, TokenizeConfigFile5) {
311   const char *Input = "abc\\\r\n123";
312   const char *const Output[] = { "abc123" };
313   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
314                            array_lengthof(Output));
315 }
316 
317 TEST(CommandLineTest, TokenizeConfigFile6) {
318   const char *Input = "abc\\\n";
319   const char *const Output[] = { "abc" };
320   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
321                            array_lengthof(Output));
322 }
323 
324 TEST(CommandLineTest, TokenizeConfigFile7) {
325   const char *Input = "abc\\\r\n";
326   const char *const Output[] = { "abc" };
327   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
328                            array_lengthof(Output));
329 }
330 
331 TEST(CommandLineTest, TokenizeConfigFile8) {
332   SmallVector<const char *, 0> Actual;
333   BumpPtrAllocator A;
334   StringSaver Saver(A);
335   cl::tokenizeConfigFile("\\\n", Saver, Actual, /*MarkEOLs=*/false);
336   EXPECT_TRUE(Actual.empty());
337 }
338 
339 TEST(CommandLineTest, TokenizeConfigFile9) {
340   SmallVector<const char *, 0> Actual;
341   BumpPtrAllocator A;
342   StringSaver Saver(A);
343   cl::tokenizeConfigFile("\\\r\n", Saver, Actual, /*MarkEOLs=*/false);
344   EXPECT_TRUE(Actual.empty());
345 }
346 
347 TEST(CommandLineTest, TokenizeConfigFile10) {
348   const char *Input = "\\\nabc";
349   const char *const Output[] = { "abc" };
350   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
351                            array_lengthof(Output));
352 }
353 
354 TEST(CommandLineTest, TokenizeConfigFile11) {
355   const char *Input = "\\\r\nabc";
356   const char *const Output[] = { "abc" };
357   testCommandLineTokenizer(cl::tokenizeConfigFile, Input, Output,
358                            array_lengthof(Output));
359 }
360 
361 TEST(CommandLineTest, AliasesWithArguments) {
362   static const size_t ARGC = 3;
363   const char *const Inputs[][ARGC] = {
364     { "-tool", "-actual=x", "-extra" },
365     { "-tool", "-actual", "x" },
366     { "-tool", "-alias=x", "-extra" },
367     { "-tool", "-alias", "x" }
368   };
369 
370   for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) {
371     StackOption<std::string> Actual("actual");
372     StackOption<bool> Extra("extra");
373     StackOption<std::string> Input(cl::Positional);
374 
375     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
376 
377     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
378     EXPECT_EQ("x", Actual);
379     EXPECT_EQ(0, Input.getNumOccurrences());
380 
381     Alias.removeArgument();
382   }
383 }
384 
385 void testAliasRequired(int argc, const char *const *argv) {
386   StackOption<std::string> Option("option", cl::Required);
387   cl::alias Alias("o", llvm::cl::aliasopt(Option));
388 
389   cl::ParseCommandLineOptions(argc, argv);
390   EXPECT_EQ("x", Option);
391   EXPECT_EQ(1, Option.getNumOccurrences());
392 
393   Alias.removeArgument();
394 }
395 
396 TEST(CommandLineTest, AliasRequired) {
397   const char *opts1[] = { "-tool", "-option=x" };
398   const char *opts2[] = { "-tool", "-o", "x" };
399   testAliasRequired(array_lengthof(opts1), opts1);
400   testAliasRequired(array_lengthof(opts2), opts2);
401 }
402 
403 TEST(CommandLineTest, HideUnrelatedOptions) {
404   StackOption<int> TestOption1("hide-option-1");
405   StackOption<int> TestOption2("hide-option-2", cl::cat(TestCategory));
406 
407   cl::HideUnrelatedOptions(TestCategory);
408 
409   ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
410       << "Failed to hide extra option.";
411   ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
412       << "Hid extra option that should be visable.";
413 
414   StringMap<cl::Option *> &Map =
415       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
416   ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag())
417       << "Hid default option that should be visable.";
418 }
419 
420 cl::OptionCategory TestCategory2("Test Options set 2", "Description");
421 
422 TEST(CommandLineTest, HideUnrelatedOptionsMulti) {
423   StackOption<int> TestOption1("multi-hide-option-1");
424   StackOption<int> TestOption2("multi-hide-option-2", cl::cat(TestCategory));
425   StackOption<int> TestOption3("multi-hide-option-3", cl::cat(TestCategory2));
426 
427   const cl::OptionCategory *VisibleCategories[] = {&TestCategory,
428                                                    &TestCategory2};
429 
430   cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
431 
432   ASSERT_EQ(cl::ReallyHidden, TestOption1.getOptionHiddenFlag())
433       << "Failed to hide extra option.";
434   ASSERT_EQ(cl::NotHidden, TestOption2.getOptionHiddenFlag())
435       << "Hid extra option that should be visable.";
436   ASSERT_EQ(cl::NotHidden, TestOption3.getOptionHiddenFlag())
437       << "Hid extra option that should be visable.";
438 
439   StringMap<cl::Option *> &Map =
440       cl::getRegisteredOptions(*cl::TopLevelSubCommand);
441   ASSERT_EQ(cl::NotHidden, Map["help"]->getOptionHiddenFlag())
442       << "Hid default option that should be visable.";
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_TRUE(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_TRUE(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_TRUE(Bar == "args2 bar string");
752   EXPECT_TRUE(Foo);
753   EXPECT_FALSE(SC1_B);
754   EXPECT_TRUE(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   if (Triple(sys::getProcessTriple()).isOSWindows()) {
769     // We use 32000 as a limit for command line length. Program name ('cl'),
770     // separating spaces and termination null character occupy 5 symbols.
771     std::string long_arg(32000 - 5, 'b');
772     EXPECT_TRUE(
773         llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data()));
774     long_arg += 'b';
775     EXPECT_FALSE(
776         llvm::sys::commandLineFitsWithinSystemLimits("cl", long_arg.data()));
777   }
778 }
779 
780 TEST(CommandLineTest, ResponseFileWindows) {
781   if (!Triple(sys::getProcessTriple()).isOSWindows())
782     return;
783 
784   StackOption<std::string, cl::list<std::string>> InputFilenames(
785       cl::Positional, cl::desc("<input files>"), cl::ZeroOrMore);
786   StackOption<bool> TopLevelOpt("top-level", cl::init(false));
787 
788   // Create response file.
789   int FileDescriptor;
790   SmallString<64> TempPath;
791   std::error_code EC =
792       llvm::sys::fs::createTemporaryFile("resp-", ".txt", FileDescriptor, TempPath);
793   EXPECT_TRUE(!EC);
794 
795   std::ofstream RspFile(TempPath.c_str());
796   EXPECT_TRUE(RspFile.is_open());
797   RspFile << "-top-level\npath\\dir\\file1\npath/dir/file2";
798   RspFile.close();
799 
800   llvm::SmallString<128> RspOpt;
801   RspOpt.append(1, '@');
802   RspOpt.append(TempPath.c_str());
803   const char *args[] = {"prog", RspOpt.c_str()};
804   EXPECT_FALSE(TopLevelOpt);
805   EXPECT_TRUE(
806       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
807   EXPECT_TRUE(TopLevelOpt);
808   EXPECT_TRUE(InputFilenames[0] == "path\\dir\\file1");
809   EXPECT_TRUE(InputFilenames[1] == "path/dir/file2");
810 
811   llvm::sys::fs::remove(TempPath.c_str());
812 }
813 
814 TEST(CommandLineTest, ResponseFiles) {
815   vfs::InMemoryFileSystem FS;
816 #ifdef _WIN32
817   const char *TestRoot = "C:\\";
818 #else
819   const char *TestRoot = "/";
820 #endif
821   FS.setCurrentWorkingDirectory(TestRoot);
822 
823   // Create included response file of first level.
824   llvm::StringRef IncludedFileName = "resp1";
825   FS.addFile(IncludedFileName, 0,
826              llvm::MemoryBuffer::getMemBuffer("-option_1 -option_2\n"
827                                               "@incdir/resp2\n"
828                                               "-option_3=abcd\n"
829                                               "@incdir/resp3\n"
830                                               "-option_4=efjk\n"));
831 
832   // Directory for included file.
833   llvm::StringRef IncDir = "incdir";
834 
835   // Create included response file of second level.
836   llvm::SmallString<128> IncludedFileName2;
837   llvm::sys::path::append(IncludedFileName2, IncDir, "resp2");
838   FS.addFile(IncludedFileName2, 0,
839              MemoryBuffer::getMemBuffer("-option_21 -option_22\n"
840                                         "-option_23=abcd\n"));
841 
842   // Create second included response file of second level.
843   llvm::SmallString<128> IncludedFileName3;
844   llvm::sys::path::append(IncludedFileName3, IncDir, "resp3");
845   FS.addFile(IncludedFileName3, 0,
846              MemoryBuffer::getMemBuffer("-option_31 -option_32\n"
847                                         "-option_33=abcd\n"));
848 
849   // Prepare 'file' with reference to response file.
850   SmallString<128> IncRef;
851   IncRef.append(1, '@');
852   IncRef.append(IncludedFileName);
853   llvm::SmallVector<const char *, 4> Argv = {"test/test", "-flag_1",
854                                              IncRef.c_str(), "-flag_2"};
855 
856   // Expand response files.
857   llvm::BumpPtrAllocator A;
858   llvm::StringSaver Saver(A);
859   ASSERT_TRUE(llvm::cl::ExpandResponseFiles(
860       Saver, llvm::cl::TokenizeGNUCommandLine, Argv, false, true, FS,
861       /*CurrentDir=*/StringRef(TestRoot)));
862   EXPECT_THAT(Argv, testing::Pointwise(
863                         StringEquality(),
864                         {"test/test", "-flag_1", "-option_1", "-option_2",
865                          "-option_21", "-option_22", "-option_23=abcd",
866                          "-option_3=abcd", "-option_31", "-option_32",
867                          "-option_33=abcd", "-option_4=efjk", "-flag_2"}));
868 }
869 
870 TEST(CommandLineTest, RecursiveResponseFiles) {
871   vfs::InMemoryFileSystem FS;
872 #ifdef _WIN32
873   const char *TestRoot = "C:\\";
874 #else
875   const char *TestRoot = "/";
876 #endif
877   FS.setCurrentWorkingDirectory(TestRoot);
878 
879   StringRef SelfFilePath = "self.rsp";
880   std::string SelfFileRef = ("@" + SelfFilePath).str();
881 
882   StringRef NestedFilePath = "nested.rsp";
883   std::string NestedFileRef = ("@" + NestedFilePath).str();
884 
885   StringRef FlagFilePath = "flag.rsp";
886   std::string FlagFileRef = ("@" + FlagFilePath).str();
887 
888   std::string SelfFileContents;
889   raw_string_ostream SelfFile(SelfFileContents);
890   SelfFile << "-option_1\n";
891   SelfFile << FlagFileRef << "\n";
892   SelfFile << NestedFileRef << "\n";
893   SelfFile << SelfFileRef << "\n";
894   FS.addFile(SelfFilePath, 0, MemoryBuffer::getMemBuffer(SelfFile.str()));
895 
896   std::string NestedFileContents;
897   raw_string_ostream NestedFile(NestedFileContents);
898   NestedFile << "-option_2\n";
899   NestedFile << FlagFileRef << "\n";
900   NestedFile << SelfFileRef << "\n";
901   NestedFile << NestedFileRef << "\n";
902   FS.addFile(NestedFilePath, 0, MemoryBuffer::getMemBuffer(NestedFile.str()));
903 
904   std::string FlagFileContents;
905   raw_string_ostream FlagFile(FlagFileContents);
906   FlagFile << "-option_x\n";
907   FS.addFile(FlagFilePath, 0, MemoryBuffer::getMemBuffer(FlagFile.str()));
908 
909   // Ensure:
910   // Recursive expansion terminates
911   // Recursive files never expand
912   // Non-recursive repeats are allowed
913   SmallVector<const char *, 4> Argv = {"test/test", SelfFileRef.c_str(),
914                                        "-option_3"};
915   BumpPtrAllocator A;
916   StringSaver Saver(A);
917 #ifdef _WIN32
918   cl::TokenizerCallback Tokenizer = cl::TokenizeWindowsCommandLine;
919 #else
920   cl::TokenizerCallback Tokenizer = cl::TokenizeGNUCommandLine;
921 #endif
922   ASSERT_FALSE(
923       cl::ExpandResponseFiles(Saver, Tokenizer, Argv, false, false, FS,
924                               /*CurrentDir=*/llvm::StringRef(TestRoot)));
925 
926   EXPECT_THAT(Argv,
927               testing::Pointwise(StringEquality(),
928                                  {"test/test", "-option_1", "-option_x",
929                                   "-option_2", "-option_x", SelfFileRef.c_str(),
930                                   NestedFileRef.c_str(), SelfFileRef.c_str(),
931                                   "-option_3"}));
932 }
933 
934 TEST(CommandLineTest, ResponseFilesAtArguments) {
935   vfs::InMemoryFileSystem FS;
936 #ifdef _WIN32
937   const char *TestRoot = "C:\\";
938 #else
939   const char *TestRoot = "/";
940 #endif
941   FS.setCurrentWorkingDirectory(TestRoot);
942 
943   StringRef ResponseFilePath = "test.rsp";
944 
945   std::string ResponseFileContents;
946   raw_string_ostream ResponseFile(ResponseFileContents);
947   ResponseFile << "-foo" << "\n";
948   ResponseFile << "-bar" << "\n";
949   FS.addFile(ResponseFilePath, 0,
950              MemoryBuffer::getMemBuffer(ResponseFile.str()));
951 
952   // Ensure we expand rsp files after lots of non-rsp arguments starting with @.
953   constexpr size_t NON_RSP_AT_ARGS = 64;
954   SmallVector<const char *, 4> Argv = {"test/test"};
955   Argv.append(NON_RSP_AT_ARGS, "@non_rsp_at_arg");
956   std::string ResponseFileRef = ("@" + ResponseFilePath).str();
957   Argv.push_back(ResponseFileRef.c_str());
958 
959   BumpPtrAllocator A;
960   StringSaver Saver(A);
961   ASSERT_FALSE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
962                                        false, false, FS,
963                                        /*CurrentDir=*/StringRef(TestRoot)));
964 
965   // ASSERT instead of EXPECT to prevent potential out-of-bounds access.
966   ASSERT_EQ(Argv.size(), 1 + NON_RSP_AT_ARGS + 2);
967   size_t i = 0;
968   EXPECT_STREQ(Argv[i++], "test/test");
969   for (; i < 1 + NON_RSP_AT_ARGS; ++i)
970     EXPECT_STREQ(Argv[i], "@non_rsp_at_arg");
971   EXPECT_STREQ(Argv[i++], "-foo");
972   EXPECT_STREQ(Argv[i++], "-bar");
973 }
974 
975 TEST(CommandLineTest, ResponseFileRelativePath) {
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 
984   StringRef OuterFile = "dir/outer.rsp";
985   StringRef OuterFileContents = "@inner.rsp";
986   FS.addFile(OuterFile, 0, MemoryBuffer::getMemBuffer(OuterFileContents));
987 
988   StringRef InnerFile = "dir/inner.rsp";
989   StringRef InnerFileContents = "-flag";
990   FS.addFile(InnerFile, 0, MemoryBuffer::getMemBuffer(InnerFileContents));
991 
992   SmallVector<const char *, 2> Argv = {"test/test", "@dir/outer.rsp"};
993 
994   BumpPtrAllocator A;
995   StringSaver Saver(A);
996   ASSERT_TRUE(cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv,
997                                       false, true, FS,
998                                       /*CurrentDir=*/StringRef(TestRoot)));
999   EXPECT_THAT(Argv,
1000               testing::Pointwise(StringEquality(), {"test/test", "-flag"}));
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_TRUE(Opt1 == "false");
1017   EXPECT_TRUE(Opt2);
1018   EXPECT_TRUE(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_TRUE(Opt1 == "true");
1034   EXPECT_TRUE(Opt2);
1035   EXPECT_TRUE(Opt3 == 3);
1036   Alias.removeArgument();
1037 }
1038 
1039 TEST(CommandLineTest, ReadConfigFile) {
1040   llvm::SmallVector<const char *, 1> Argv;
1041 
1042   llvm::SmallString<128> TestDir;
1043   std::error_code EC =
1044       llvm::sys::fs::createUniqueDirectory("unittest", TestDir);
1045   EXPECT_TRUE(!EC);
1046 
1047   llvm::SmallString<128> TestCfg;
1048   llvm::sys::path::append(TestCfg, TestDir, "foo");
1049   std::ofstream ConfigFile(TestCfg.c_str());
1050   EXPECT_TRUE(ConfigFile.is_open());
1051   ConfigFile << "# Comment\n"
1052                 "-option_1\n"
1053                 "@subconfig\n"
1054                 "-option_3=abcd\n"
1055                 "-option_4=\\\n"
1056                 "cdef\n";
1057   ConfigFile.close();
1058 
1059   llvm::SmallString<128> TestCfg2;
1060   llvm::sys::path::append(TestCfg2, TestDir, "subconfig");
1061   std::ofstream ConfigFile2(TestCfg2.c_str());
1062   EXPECT_TRUE(ConfigFile2.is_open());
1063   ConfigFile2 << "-option_2\n"
1064                  "\n"
1065                  "   # comment\n";
1066   ConfigFile2.close();
1067 
1068   // Make sure the current directory is not the directory where config files
1069   // resides. In this case the code that expands response files will not find
1070   // 'subconfig' unless it resolves nested inclusions relative to the including
1071   // file.
1072   llvm::SmallString<128> CurrDir;
1073   EC = llvm::sys::fs::current_path(CurrDir);
1074   EXPECT_TRUE(!EC);
1075   EXPECT_TRUE(StringRef(CurrDir) != StringRef(TestDir));
1076 
1077   llvm::BumpPtrAllocator A;
1078   llvm::StringSaver Saver(A);
1079   bool Result = llvm::cl::readConfigFile(TestCfg, Saver, Argv);
1080 
1081   EXPECT_TRUE(Result);
1082   EXPECT_EQ(Argv.size(), 4U);
1083   EXPECT_STREQ(Argv[0], "-option_1");
1084   EXPECT_STREQ(Argv[1], "-option_2");
1085   EXPECT_STREQ(Argv[2], "-option_3=abcd");
1086   EXPECT_STREQ(Argv[3], "-option_4=cdef");
1087 
1088   llvm::sys::fs::remove(TestCfg2);
1089   llvm::sys::fs::remove(TestCfg);
1090   llvm::sys::fs::remove(TestDir);
1091 }
1092 
1093 TEST(CommandLineTest, PositionalEatArgsError) {
1094   cl::ResetCommandLineParser();
1095 
1096   StackOption<std::string, cl::list<std::string>> PosEatArgs(
1097       "positional-eat-args", cl::Positional, cl::desc("<arguments>..."),
1098       cl::ZeroOrMore, cl::PositionalEatsArgs);
1099   StackOption<std::string, cl::list<std::string>> PosEatArgs2(
1100       "positional-eat-args2", cl::Positional, cl::desc("Some strings"),
1101       cl::ZeroOrMore, cl::PositionalEatsArgs);
1102 
1103   const char *args[] = {"prog", "-positional-eat-args=XXXX"};
1104   const char *args2[] = {"prog", "-positional-eat-args=XXXX", "-foo"};
1105   const char *args3[] = {"prog", "-positional-eat-args", "-foo"};
1106   const char *args4[] = {"prog", "-positional-eat-args",
1107                          "-foo", "-positional-eat-args2",
1108                          "-bar", "foo"};
1109 
1110   std::string Errs;
1111   raw_string_ostream OS(Errs);
1112   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS)); OS.flush();
1113   EXPECT_FALSE(Errs.empty()); Errs.clear();
1114   EXPECT_FALSE(cl::ParseCommandLineOptions(3, args2, StringRef(), &OS)); OS.flush();
1115   EXPECT_FALSE(Errs.empty()); Errs.clear();
1116   EXPECT_TRUE(cl::ParseCommandLineOptions(3, args3, StringRef(), &OS)); OS.flush();
1117   EXPECT_TRUE(Errs.empty()); Errs.clear();
1118 
1119   cl::ResetAllOptionOccurrences();
1120   EXPECT_TRUE(cl::ParseCommandLineOptions(6, args4, StringRef(), &OS)); OS.flush();
1121   EXPECT_TRUE(PosEatArgs.size() == 1);
1122   EXPECT_TRUE(PosEatArgs2.size() == 2);
1123   EXPECT_TRUE(Errs.empty());
1124 }
1125 
1126 #ifdef _WIN32
1127 TEST(CommandLineTest, GetCommandLineArguments) {
1128   int argc = __argc;
1129   char **argv = __argv;
1130 
1131   // GetCommandLineArguments is called in InitLLVM.
1132   llvm::InitLLVM X(argc, argv);
1133 
1134   EXPECT_EQ(llvm::sys::path::is_absolute(argv[0]),
1135             llvm::sys::path::is_absolute(__argv[0]));
1136 
1137   EXPECT_TRUE(llvm::sys::path::filename(argv[0])
1138               .equals_lower("supporttests.exe"))
1139       << "Filename of test executable is "
1140       << llvm::sys::path::filename(argv[0]);
1141 }
1142 #endif
1143 
1144 class OutputRedirector {
1145 public:
1146   OutputRedirector(int RedirectFD)
1147       : RedirectFD(RedirectFD), OldFD(dup(RedirectFD)) {
1148     if (OldFD == -1 ||
1149         sys::fs::createTemporaryFile("unittest-redirect", "", NewFD,
1150                                      FilePath) ||
1151         dup2(NewFD, RedirectFD) == -1)
1152       Valid = false;
1153   }
1154 
1155   ~OutputRedirector() {
1156     dup2(OldFD, RedirectFD);
1157     close(OldFD);
1158     close(NewFD);
1159   }
1160 
1161   SmallVector<char, 128> FilePath;
1162   bool Valid = true;
1163 
1164 private:
1165   int RedirectFD;
1166   int OldFD;
1167   int NewFD;
1168 };
1169 
1170 struct AutoDeleteFile {
1171   SmallVector<char, 128> FilePath;
1172   ~AutoDeleteFile() {
1173     if (!FilePath.empty())
1174       sys::fs::remove(std::string(FilePath.data(), FilePath.size()));
1175   }
1176 };
1177 
1178 class PrintOptionInfoTest : public ::testing::Test {
1179 public:
1180   // Return std::string because the output of a failing EXPECT check is
1181   // unreadable for StringRef. It also avoids any lifetime issues.
1182   template <typename... Ts> std::string runTest(Ts... OptionAttributes) {
1183     outs().flush();  // flush any output from previous tests
1184     AutoDeleteFile File;
1185     {
1186       OutputRedirector Stdout(fileno(stdout));
1187       if (!Stdout.Valid)
1188         return "";
1189       File.FilePath = Stdout.FilePath;
1190 
1191       StackOption<OptionValue> TestOption(Opt, cl::desc(HelpText),
1192                                           OptionAttributes...);
1193       printOptionInfo(TestOption, 26);
1194       outs().flush();
1195     }
1196     auto Buffer = MemoryBuffer::getFile(File.FilePath);
1197     if (!Buffer)
1198       return "";
1199     return Buffer->get()->getBuffer().str();
1200   }
1201 
1202   enum class OptionValue { Val };
1203   const StringRef Opt = "some-option";
1204   const StringRef HelpText = "some help";
1205 
1206 private:
1207   // This is a workaround for cl::Option sub-classes having their
1208   // printOptionInfo functions private.
1209   void printOptionInfo(const cl::Option &O, size_t Width) {
1210     O.printOptionInfo(Width);
1211   }
1212 };
1213 
1214 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithoutSentinel) {
1215   std::string Output =
1216       runTest(cl::ValueOptional,
1217               cl::values(clEnumValN(OptionValue::Val, "v1", "desc1")));
1218 
1219   // clang-format off
1220   EXPECT_EQ(Output, ("  --" + Opt + "=<value> - " + HelpText + "\n"
1221                      "    =v1                 -   desc1\n")
1222                         .str());
1223   // clang-format on
1224 }
1225 
1226 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinel) {
1227   std::string Output = runTest(
1228       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1229                                     clEnumValN(OptionValue::Val, "", "")));
1230 
1231   // clang-format off
1232   EXPECT_EQ(Output,
1233             ("  --" + Opt + "         - " + HelpText + "\n"
1234              "  --" + Opt + "=<value> - " + HelpText + "\n"
1235              "    =v1                 -   desc1\n")
1236                 .str());
1237   // clang-format on
1238 }
1239 
1240 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueOptionalWithSentinelWithHelp) {
1241   std::string Output = runTest(
1242       cl::ValueOptional, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1243                                     clEnumValN(OptionValue::Val, "", "desc2")));
1244 
1245   // clang-format off
1246   EXPECT_EQ(Output, ("  --" + Opt + "         - " + HelpText + "\n"
1247                      "  --" + Opt + "=<value> - " + HelpText + "\n"
1248                      "    =v1                 -   desc1\n"
1249                      "    =<empty>            -   desc2\n")
1250                         .str());
1251   // clang-format on
1252 }
1253 
1254 TEST_F(PrintOptionInfoTest, PrintOptionInfoValueRequiredWithEmptyValueName) {
1255   std::string Output = runTest(
1256       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "desc1"),
1257                                     clEnumValN(OptionValue::Val, "", "")));
1258 
1259   // clang-format off
1260   EXPECT_EQ(Output, ("  --" + Opt + "=<value> - " + HelpText + "\n"
1261                      "    =v1                 -   desc1\n"
1262                      "    =<empty>\n")
1263                         .str());
1264   // clang-format on
1265 }
1266 
1267 TEST_F(PrintOptionInfoTest, PrintOptionInfoEmptyValueDescription) {
1268   std::string Output = runTest(
1269       cl::ValueRequired, cl::values(clEnumValN(OptionValue::Val, "v1", "")));
1270 
1271   // clang-format off
1272   EXPECT_EQ(Output,
1273             ("  --" + Opt + "=<value> - " + HelpText + "\n"
1274              "    =v1\n").str());
1275   // clang-format on
1276 }
1277 
1278 class GetOptionWidthTest : public ::testing::Test {
1279 public:
1280   enum class OptionValue { Val };
1281 
1282   template <typename... Ts>
1283   size_t runTest(StringRef ArgName, Ts... OptionAttributes) {
1284     StackOption<OptionValue> TestOption(ArgName, cl::desc("some help"),
1285                                         OptionAttributes...);
1286     return getOptionWidth(TestOption);
1287   }
1288 
1289 private:
1290   // This is a workaround for cl::Option sub-classes having their
1291   // printOptionInfo
1292   // functions private.
1293   size_t getOptionWidth(const cl::Option &O) { return O.getOptionWidth(); }
1294 };
1295 
1296 TEST_F(GetOptionWidthTest, GetOptionWidthArgNameLonger) {
1297   StringRef ArgName("a-long-argument-name");
1298   size_t ExpectedStrSize = ("  --" + ArgName + "=<value> - ").str().size();
1299   EXPECT_EQ(
1300       runTest(ArgName, cl::values(clEnumValN(OptionValue::Val, "v", "help"))),
1301       ExpectedStrSize);
1302 }
1303 
1304 TEST_F(GetOptionWidthTest, GetOptionWidthFirstOptionNameLonger) {
1305   StringRef OptName("a-long-option-name");
1306   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1307   EXPECT_EQ(
1308       runTest("a", cl::values(clEnumValN(OptionValue::Val, OptName, "help"),
1309                               clEnumValN(OptionValue::Val, "b", "help"))),
1310       ExpectedStrSize);
1311 }
1312 
1313 TEST_F(GetOptionWidthTest, GetOptionWidthSecondOptionNameLonger) {
1314   StringRef OptName("a-long-option-name");
1315   size_t ExpectedStrSize = ("    =" + OptName + " - ").str().size();
1316   EXPECT_EQ(
1317       runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1318                               clEnumValN(OptionValue::Val, OptName, "help"))),
1319       ExpectedStrSize);
1320 }
1321 
1322 TEST_F(GetOptionWidthTest, GetOptionWidthEmptyOptionNameLonger) {
1323   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1324   // The length of a=<value> (including indentation) is actually the same as the
1325   // =<empty> string, so it is impossible to distinguish via testing the case
1326   // where the empty string is picked from where the option name is picked.
1327   EXPECT_EQ(runTest("a", cl::values(clEnumValN(OptionValue::Val, "b", "help"),
1328                                     clEnumValN(OptionValue::Val, "", "help"))),
1329             ExpectedStrSize);
1330 }
1331 
1332 TEST_F(GetOptionWidthTest,
1333        GetOptionWidthValueOptionalEmptyOptionWithNoDescription) {
1334   StringRef ArgName("a");
1335   // The length of a=<value> (including indentation) is actually the same as the
1336   // =<empty> string, so it is impossible to distinguish via testing the case
1337   // where the empty string is ignored from where it is not ignored.
1338   // The dash will not actually be printed, but the space it would take up is
1339   // included to ensure a consistent column width.
1340   size_t ExpectedStrSize = ("  -" + ArgName + "=<value> - ").str().size();
1341   EXPECT_EQ(runTest(ArgName, cl::ValueOptional,
1342                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1343                                clEnumValN(OptionValue::Val, "", ""))),
1344             ExpectedStrSize);
1345 }
1346 
1347 TEST_F(GetOptionWidthTest,
1348        GetOptionWidthValueRequiredEmptyOptionWithNoDescription) {
1349   // The length of a=<value> (including indentation) is actually the same as the
1350   // =<empty> string, so it is impossible to distinguish via testing the case
1351   // where the empty string is picked from where the option name is picked
1352   size_t ExpectedStrSize = StringRef("    =<empty> - ").size();
1353   EXPECT_EQ(runTest("a", cl::ValueRequired,
1354                     cl::values(clEnumValN(OptionValue::Val, "value", "help"),
1355                                clEnumValN(OptionValue::Val, "", ""))),
1356             ExpectedStrSize);
1357 }
1358 
1359 TEST(CommandLineTest, PrefixOptions) {
1360   cl::ResetCommandLineParser();
1361 
1362   StackOption<std::string, cl::list<std::string>> IncludeDirs(
1363       "I", cl::Prefix, cl::desc("Declare an include directory"));
1364 
1365   // Test non-prefixed variant works with cl::Prefix options.
1366   EXPECT_TRUE(IncludeDirs.empty());
1367   const char *args[] = {"prog", "-I=/usr/include"};
1368   EXPECT_TRUE(
1369       cl::ParseCommandLineOptions(2, args, StringRef(), &llvm::nulls()));
1370   EXPECT_TRUE(IncludeDirs.size() == 1);
1371   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1372 
1373   IncludeDirs.erase(IncludeDirs.begin());
1374   cl::ResetAllOptionOccurrences();
1375 
1376   // Test non-prefixed variant works with cl::Prefix options when value is
1377   // passed in following argument.
1378   EXPECT_TRUE(IncludeDirs.empty());
1379   const char *args2[] = {"prog", "-I", "/usr/include"};
1380   EXPECT_TRUE(
1381       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1382   EXPECT_TRUE(IncludeDirs.size() == 1);
1383   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1384 
1385   IncludeDirs.erase(IncludeDirs.begin());
1386   cl::ResetAllOptionOccurrences();
1387 
1388   // Test prefixed variant works with cl::Prefix options.
1389   EXPECT_TRUE(IncludeDirs.empty());
1390   const char *args3[] = {"prog", "-I/usr/include"};
1391   EXPECT_TRUE(
1392       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1393   EXPECT_TRUE(IncludeDirs.size() == 1);
1394   EXPECT_TRUE(IncludeDirs.front().compare("/usr/include") == 0);
1395 
1396   StackOption<std::string, cl::list<std::string>> MacroDefs(
1397       "D", cl::AlwaysPrefix, cl::desc("Define a macro"),
1398       cl::value_desc("MACRO[=VALUE]"));
1399 
1400   cl::ResetAllOptionOccurrences();
1401 
1402   // Test non-prefixed variant does not work with cl::AlwaysPrefix options:
1403   // equal sign is part of the value.
1404   EXPECT_TRUE(MacroDefs.empty());
1405   const char *args4[] = {"prog", "-D=HAVE_FOO"};
1406   EXPECT_TRUE(
1407       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1408   EXPECT_TRUE(MacroDefs.size() == 1);
1409   EXPECT_TRUE(MacroDefs.front().compare("=HAVE_FOO") == 0);
1410 
1411   MacroDefs.erase(MacroDefs.begin());
1412   cl::ResetAllOptionOccurrences();
1413 
1414   // Test non-prefixed variant does not allow value to be passed in following
1415   // argument with cl::AlwaysPrefix options.
1416   EXPECT_TRUE(MacroDefs.empty());
1417   const char *args5[] = {"prog", "-D", "HAVE_FOO"};
1418   EXPECT_FALSE(
1419       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1420   EXPECT_TRUE(MacroDefs.empty());
1421 
1422   cl::ResetAllOptionOccurrences();
1423 
1424   // Test prefixed variant works with cl::AlwaysPrefix options.
1425   EXPECT_TRUE(MacroDefs.empty());
1426   const char *args6[] = {"prog", "-DHAVE_FOO"};
1427   EXPECT_TRUE(
1428       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1429   EXPECT_TRUE(MacroDefs.size() == 1);
1430   EXPECT_TRUE(MacroDefs.front().compare("HAVE_FOO") == 0);
1431 }
1432 
1433 TEST(CommandLineTest, GroupingWithValue) {
1434   cl::ResetCommandLineParser();
1435 
1436   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1437   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1438   StackOption<bool> OptD("d", cl::Grouping, cl::ValueDisallowed,
1439                          cl::desc("ValueDisallowed option"));
1440   StackOption<std::string> OptV("v", cl::Grouping,
1441                                 cl::desc("ValueRequired option"));
1442   StackOption<std::string> OptO("o", cl::Grouping, cl::ValueOptional,
1443                                 cl::desc("ValueOptional option"));
1444 
1445   // Should be possible to use an option which requires a value
1446   // at the end of a group.
1447   const char *args1[] = {"prog", "-fv", "val1"};
1448   EXPECT_TRUE(
1449       cl::ParseCommandLineOptions(3, args1, StringRef(), &llvm::nulls()));
1450   EXPECT_TRUE(OptF);
1451   EXPECT_STREQ("val1", OptV.c_str());
1452   OptV.clear();
1453   cl::ResetAllOptionOccurrences();
1454 
1455   // Should not crash if it is accidentally used elsewhere in the group.
1456   const char *args2[] = {"prog", "-vf", "val2"};
1457   EXPECT_FALSE(
1458       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1459   OptV.clear();
1460   cl::ResetAllOptionOccurrences();
1461 
1462   // Should allow the "opt=value" form at the end of the group
1463   const char *args3[] = {"prog", "-fv=val3"};
1464   EXPECT_TRUE(
1465       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1466   EXPECT_TRUE(OptF);
1467   EXPECT_STREQ("val3", OptV.c_str());
1468   OptV.clear();
1469   cl::ResetAllOptionOccurrences();
1470 
1471   // Should allow assigning a value for a ValueOptional option
1472   // at the end of the group
1473   const char *args4[] = {"prog", "-fo=val4"};
1474   EXPECT_TRUE(
1475       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1476   EXPECT_TRUE(OptF);
1477   EXPECT_STREQ("val4", OptO.c_str());
1478   OptO.clear();
1479   cl::ResetAllOptionOccurrences();
1480 
1481   // Should assign an empty value if a ValueOptional option is used elsewhere
1482   // in the group.
1483   const char *args5[] = {"prog", "-fob"};
1484   EXPECT_TRUE(
1485       cl::ParseCommandLineOptions(2, args5, StringRef(), &llvm::nulls()));
1486   EXPECT_TRUE(OptF);
1487   EXPECT_EQ(1, OptO.getNumOccurrences());
1488   EXPECT_EQ(1, OptB.getNumOccurrences());
1489   EXPECT_TRUE(OptO.empty());
1490   cl::ResetAllOptionOccurrences();
1491 
1492   // Should not allow an assignment for a ValueDisallowed option.
1493   const char *args6[] = {"prog", "-fd=false"};
1494   EXPECT_FALSE(
1495       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1496 }
1497 
1498 TEST(CommandLineTest, GroupingAndPrefix) {
1499   cl::ResetCommandLineParser();
1500 
1501   StackOption<bool> OptF("f", cl::Grouping, cl::desc("Some flag"));
1502   StackOption<bool> OptB("b", cl::Grouping, cl::desc("Another flag"));
1503   StackOption<std::string> OptP("p", cl::Prefix, cl::Grouping,
1504                                 cl::desc("Prefix and Grouping"));
1505   StackOption<std::string> OptA("a", cl::AlwaysPrefix, cl::Grouping,
1506                                 cl::desc("AlwaysPrefix and Grouping"));
1507 
1508   // Should be possible to use a cl::Prefix option without grouping.
1509   const char *args1[] = {"prog", "-pval1"};
1510   EXPECT_TRUE(
1511       cl::ParseCommandLineOptions(2, args1, StringRef(), &llvm::nulls()));
1512   EXPECT_STREQ("val1", OptP.c_str());
1513   OptP.clear();
1514   cl::ResetAllOptionOccurrences();
1515 
1516   // Should be possible to pass a value in a separate argument.
1517   const char *args2[] = {"prog", "-p", "val2"};
1518   EXPECT_TRUE(
1519       cl::ParseCommandLineOptions(3, args2, StringRef(), &llvm::nulls()));
1520   EXPECT_STREQ("val2", OptP.c_str());
1521   OptP.clear();
1522   cl::ResetAllOptionOccurrences();
1523 
1524   // The "-opt=value" form should work, too.
1525   const char *args3[] = {"prog", "-p=val3"};
1526   EXPECT_TRUE(
1527       cl::ParseCommandLineOptions(2, args3, StringRef(), &llvm::nulls()));
1528   EXPECT_STREQ("val3", OptP.c_str());
1529   OptP.clear();
1530   cl::ResetAllOptionOccurrences();
1531 
1532   // All three previous cases should work the same way if an option with both
1533   // cl::Prefix and cl::Grouping modifiers is used at the end of a group.
1534   const char *args4[] = {"prog", "-fpval4"};
1535   EXPECT_TRUE(
1536       cl::ParseCommandLineOptions(2, args4, StringRef(), &llvm::nulls()));
1537   EXPECT_TRUE(OptF);
1538   EXPECT_STREQ("val4", OptP.c_str());
1539   OptP.clear();
1540   cl::ResetAllOptionOccurrences();
1541 
1542   const char *args5[] = {"prog", "-fp", "val5"};
1543   EXPECT_TRUE(
1544       cl::ParseCommandLineOptions(3, args5, StringRef(), &llvm::nulls()));
1545   EXPECT_TRUE(OptF);
1546   EXPECT_STREQ("val5", OptP.c_str());
1547   OptP.clear();
1548   cl::ResetAllOptionOccurrences();
1549 
1550   const char *args6[] = {"prog", "-fp=val6"};
1551   EXPECT_TRUE(
1552       cl::ParseCommandLineOptions(2, args6, StringRef(), &llvm::nulls()));
1553   EXPECT_TRUE(OptF);
1554   EXPECT_STREQ("val6", OptP.c_str());
1555   OptP.clear();
1556   cl::ResetAllOptionOccurrences();
1557 
1558   // Should assign a value even if the part after a cl::Prefix option is equal
1559   // to the name of another option.
1560   const char *args7[] = {"prog", "-fpb"};
1561   EXPECT_TRUE(
1562       cl::ParseCommandLineOptions(2, args7, StringRef(), &llvm::nulls()));
1563   EXPECT_TRUE(OptF);
1564   EXPECT_STREQ("b", OptP.c_str());
1565   EXPECT_FALSE(OptB);
1566   OptP.clear();
1567   cl::ResetAllOptionOccurrences();
1568 
1569   // Should be possible to use a cl::AlwaysPrefix option without grouping.
1570   const char *args8[] = {"prog", "-aval8"};
1571   EXPECT_TRUE(
1572       cl::ParseCommandLineOptions(2, args8, StringRef(), &llvm::nulls()));
1573   EXPECT_STREQ("val8", OptA.c_str());
1574   OptA.clear();
1575   cl::ResetAllOptionOccurrences();
1576 
1577   // Should not be possible to pass a value in a separate argument.
1578   const char *args9[] = {"prog", "-a", "val9"};
1579   EXPECT_FALSE(
1580       cl::ParseCommandLineOptions(3, args9, StringRef(), &llvm::nulls()));
1581   cl::ResetAllOptionOccurrences();
1582 
1583   // With the "-opt=value" form, the "=" symbol should be preserved.
1584   const char *args10[] = {"prog", "-a=val10"};
1585   EXPECT_TRUE(
1586       cl::ParseCommandLineOptions(2, args10, StringRef(), &llvm::nulls()));
1587   EXPECT_STREQ("=val10", OptA.c_str());
1588   OptA.clear();
1589   cl::ResetAllOptionOccurrences();
1590 
1591   // All three previous cases should work the same way if an option with both
1592   // cl::AlwaysPrefix and cl::Grouping modifiers is used at the end of a group.
1593   const char *args11[] = {"prog", "-faval11"};
1594   EXPECT_TRUE(
1595       cl::ParseCommandLineOptions(2, args11, StringRef(), &llvm::nulls()));
1596   EXPECT_TRUE(OptF);
1597   EXPECT_STREQ("val11", OptA.c_str());
1598   OptA.clear();
1599   cl::ResetAllOptionOccurrences();
1600 
1601   const char *args12[] = {"prog", "-fa", "val12"};
1602   EXPECT_FALSE(
1603       cl::ParseCommandLineOptions(3, args12, StringRef(), &llvm::nulls()));
1604   cl::ResetAllOptionOccurrences();
1605 
1606   const char *args13[] = {"prog", "-fa=val13"};
1607   EXPECT_TRUE(
1608       cl::ParseCommandLineOptions(2, args13, StringRef(), &llvm::nulls()));
1609   EXPECT_TRUE(OptF);
1610   EXPECT_STREQ("=val13", OptA.c_str());
1611   OptA.clear();
1612   cl::ResetAllOptionOccurrences();
1613 
1614   // Should assign a value even if the part after a cl::AlwaysPrefix option
1615   // is equal to the name of another option.
1616   const char *args14[] = {"prog", "-fab"};
1617   EXPECT_TRUE(
1618       cl::ParseCommandLineOptions(2, args14, StringRef(), &llvm::nulls()));
1619   EXPECT_TRUE(OptF);
1620   EXPECT_STREQ("b", OptA.c_str());
1621   EXPECT_FALSE(OptB);
1622   OptA.clear();
1623   cl::ResetAllOptionOccurrences();
1624 }
1625 
1626 TEST(CommandLineTest, LongOptions) {
1627   cl::ResetCommandLineParser();
1628 
1629   StackOption<bool> OptA("a", cl::desc("Some flag"));
1630   StackOption<bool> OptBLong("long-flag", cl::desc("Some long flag"));
1631   StackOption<bool, cl::alias> OptB("b", cl::desc("Alias to --long-flag"),
1632                                     cl::aliasopt(OptBLong));
1633   StackOption<std::string> OptAB("ab", cl::desc("Another long option"));
1634 
1635   std::string Errs;
1636   raw_string_ostream OS(Errs);
1637 
1638   const char *args1[] = {"prog", "-a", "-ab", "val1"};
1639   const char *args2[] = {"prog", "-a", "--ab", "val1"};
1640   const char *args3[] = {"prog", "-ab", "--ab", "val1"};
1641 
1642   //
1643   // The following tests treat `-` and `--` the same, and always match the
1644   // longest string.
1645   //
1646 
1647   EXPECT_TRUE(
1648       cl::ParseCommandLineOptions(4, args1, StringRef(), &OS)); OS.flush();
1649   EXPECT_TRUE(OptA);
1650   EXPECT_FALSE(OptBLong);
1651   EXPECT_STREQ("val1", OptAB.c_str());
1652   EXPECT_TRUE(Errs.empty()); Errs.clear();
1653   cl::ResetAllOptionOccurrences();
1654 
1655   EXPECT_TRUE(
1656       cl::ParseCommandLineOptions(4, args2, StringRef(), &OS)); OS.flush();
1657   EXPECT_TRUE(OptA);
1658   EXPECT_FALSE(OptBLong);
1659   EXPECT_STREQ("val1", OptAB.c_str());
1660   EXPECT_TRUE(Errs.empty()); Errs.clear();
1661   cl::ResetAllOptionOccurrences();
1662 
1663   // Fails because `-ab` and `--ab` are treated the same and appear more than
1664   // once.  Also, `val1` is unexpected.
1665   EXPECT_FALSE(
1666       cl::ParseCommandLineOptions(4, args3, StringRef(), &OS)); OS.flush();
1667   outs()<< Errs << "\n";
1668   EXPECT_FALSE(Errs.empty()); Errs.clear();
1669   cl::ResetAllOptionOccurrences();
1670 
1671   //
1672   // The following tests treat `-` and `--` differently, with `-` for short, and
1673   // `--` for long options.
1674   //
1675 
1676   // Fails because `-ab` is treated as `-a -b`, so `-a` is seen twice, and
1677   // `val1` is unexpected.
1678   EXPECT_FALSE(cl::ParseCommandLineOptions(4, args1, StringRef(),
1679                                            &OS, nullptr, true)); OS.flush();
1680   EXPECT_FALSE(Errs.empty()); Errs.clear();
1681   cl::ResetAllOptionOccurrences();
1682 
1683   // Works because `-a` is treated differently than `--ab`.
1684   EXPECT_TRUE(cl::ParseCommandLineOptions(4, args2, StringRef(),
1685                                            &OS, nullptr, true)); OS.flush();
1686   EXPECT_TRUE(Errs.empty()); Errs.clear();
1687   cl::ResetAllOptionOccurrences();
1688 
1689   // Works because `-ab` is treated as `-a -b`, and `--ab` is a long option.
1690   EXPECT_TRUE(cl::ParseCommandLineOptions(4, args3, StringRef(),
1691                                            &OS, nullptr, true));
1692   EXPECT_TRUE(OptA);
1693   EXPECT_TRUE(OptBLong);
1694   EXPECT_STREQ("val1", OptAB.c_str());
1695   OS.flush();
1696   EXPECT_TRUE(Errs.empty()); Errs.clear();
1697   cl::ResetAllOptionOccurrences();
1698 }
1699 
1700 TEST(CommandLineTest, OptionErrorMessage) {
1701   // When there is an error, we expect some error message like:
1702   //   prog: for the -a option: [...]
1703   //
1704   // Test whether the "for the -a option"-part is correctly formatted.
1705   cl::ResetCommandLineParser();
1706 
1707   StackOption<bool> OptA("a", cl::desc("Some option"));
1708   StackOption<bool> OptLong("long", cl::desc("Some long option"));
1709 
1710   std::string Errs;
1711   raw_string_ostream OS(Errs);
1712 
1713   OptA.error("custom error", OS);
1714   OS.flush();
1715   EXPECT_FALSE(Errs.find("for the -a option:") == std::string::npos);
1716   Errs.clear();
1717 
1718   OptLong.error("custom error", OS);
1719   OS.flush();
1720   EXPECT_FALSE(Errs.find("for the --long option:") == std::string::npos);
1721   Errs.clear();
1722 
1723   cl::ResetAllOptionOccurrences();
1724 }
1725 
1726 TEST(CommandLineTest, OptionErrorMessageSuggest) {
1727   // When there is an error, and the edit-distance is not very large,
1728   // we expect some error message like:
1729   //   prog: did you mean '--option'?
1730   //
1731   // Test whether this message is well-formatted.
1732   cl::ResetCommandLineParser();
1733 
1734   StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1735 
1736   const char *args[] = {"prog", "--aluminum"};
1737 
1738   std::string Errs;
1739   raw_string_ostream OS(Errs);
1740 
1741   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1742   OS.flush();
1743   EXPECT_FALSE(Errs.find("prog: Did you mean '--aluminium'?\n") ==
1744                std::string::npos);
1745   Errs.clear();
1746 
1747   cl::ResetAllOptionOccurrences();
1748 }
1749 
1750 TEST(CommandLineTest, OptionErrorMessageSuggestNoHidden) {
1751   // We expect that 'really hidden' option do not show up in option
1752   // suggestions.
1753   cl::ResetCommandLineParser();
1754 
1755   StackOption<bool> OptLong("aluminium", cl::desc("Some long option"));
1756   StackOption<bool> OptLong2("aluminum", cl::desc("Bad option"),
1757                              cl::ReallyHidden);
1758 
1759   const char *args[] = {"prog", "--alumnum"};
1760 
1761   std::string Errs;
1762   raw_string_ostream OS(Errs);
1763 
1764   EXPECT_FALSE(cl::ParseCommandLineOptions(2, args, StringRef(), &OS));
1765   OS.flush();
1766   EXPECT_FALSE(Errs.find("prog: Did you mean '--aluminium'?\n") ==
1767                std::string::npos);
1768   Errs.clear();
1769 
1770   cl::ResetAllOptionOccurrences();
1771 }
1772 
1773 TEST(CommandLineTest, Callback) {
1774   cl::ResetCommandLineParser();
1775 
1776   StackOption<bool> OptA("a", cl::desc("option a"));
1777   StackOption<bool> OptB(
1778       "b", cl::desc("option b -- This option turns on option a"),
1779       cl::callback([&](const bool &) { OptA = true; }));
1780   StackOption<bool> OptC(
1781       "c", cl::desc("option c -- This option turns on options a and b"),
1782       cl::callback([&](const bool &) { OptB = true; }));
1783   StackOption<std::string, cl::list<std::string>> List(
1784       "list",
1785       cl::desc("option list -- This option turns on options a, b, and c when "
1786                "'foo' is included in list"),
1787       cl::CommaSeparated,
1788       cl::callback([&](const std::string &Str) {
1789         if (Str == "foo")
1790           OptC = true;
1791       }));
1792 
1793   const char *args1[] = {"prog", "-a"};
1794   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args1));
1795   EXPECT_TRUE(OptA);
1796   EXPECT_FALSE(OptB);
1797   EXPECT_FALSE(OptC);
1798   EXPECT_TRUE(List.size() == 0);
1799   cl::ResetAllOptionOccurrences();
1800 
1801   const char *args2[] = {"prog", "-b"};
1802   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args2));
1803   EXPECT_TRUE(OptA);
1804   EXPECT_TRUE(OptB);
1805   EXPECT_FALSE(OptC);
1806   EXPECT_TRUE(List.size() == 0);
1807   cl::ResetAllOptionOccurrences();
1808 
1809   const char *args3[] = {"prog", "-c"};
1810   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args3));
1811   EXPECT_TRUE(OptA);
1812   EXPECT_TRUE(OptB);
1813   EXPECT_TRUE(OptC);
1814   EXPECT_TRUE(List.size() == 0);
1815   cl::ResetAllOptionOccurrences();
1816 
1817   const char *args4[] = {"prog", "--list=foo,bar"};
1818   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args4));
1819   EXPECT_TRUE(OptA);
1820   EXPECT_TRUE(OptB);
1821   EXPECT_TRUE(OptC);
1822   EXPECT_TRUE(List.size() == 2);
1823   cl::ResetAllOptionOccurrences();
1824 
1825   const char *args5[] = {"prog", "--list=bar"};
1826   EXPECT_TRUE(cl::ParseCommandLineOptions(2, args5));
1827   EXPECT_FALSE(OptA);
1828   EXPECT_FALSE(OptB);
1829   EXPECT_FALSE(OptC);
1830   EXPECT_TRUE(List.size() == 1);
1831 
1832   cl::ResetAllOptionOccurrences();
1833 }
1834 
1835 enum Enum { Val1, Val2 };
1836 static cl::bits<Enum> ExampleBits(
1837     cl::desc("An example cl::bits to ensure it compiles"),
1838     cl::values(
1839       clEnumValN(Val1, "bits-val1", "The Val1 value"),
1840       clEnumValN(Val1, "bits-val2", "The Val2 value")));
1841 
1842 TEST(CommandLineTest, ConsumeAfterOnePositional) {
1843   cl::ResetCommandLineParser();
1844 
1845   // input [args]
1846   StackOption<std::string, cl::opt<std::string>> Input(cl::Positional,
1847                                                        cl::Required);
1848   StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
1849 
1850   const char *Args[] = {"prog", "input", "arg1", "arg2"};
1851 
1852   std::string Errs;
1853   raw_string_ostream OS(Errs);
1854   EXPECT_TRUE(cl::ParseCommandLineOptions(4, Args, StringRef(), &OS));
1855   OS.flush();
1856   EXPECT_EQ("input", Input);
1857   EXPECT_TRUE(ExtraArgs.size() == 2);
1858   EXPECT_TRUE(ExtraArgs[0] == "arg1");
1859   EXPECT_TRUE(ExtraArgs[1] == "arg2");
1860   EXPECT_TRUE(Errs.empty());
1861 }
1862 
1863 TEST(CommandLineTest, ConsumeAfterTwoPositionals) {
1864   cl::ResetCommandLineParser();
1865 
1866   // input1 input2 [args]
1867   StackOption<std::string, cl::opt<std::string>> Input1(cl::Positional,
1868                                                         cl::Required);
1869   StackOption<std::string, cl::opt<std::string>> Input2(cl::Positional,
1870                                                         cl::Required);
1871   StackOption<std::string, cl::list<std::string>> ExtraArgs(cl::ConsumeAfter);
1872 
1873   const char *Args[] = {"prog", "input1", "input2", "arg1", "arg2"};
1874 
1875   std::string Errs;
1876   raw_string_ostream OS(Errs);
1877   EXPECT_TRUE(cl::ParseCommandLineOptions(5, Args, StringRef(), &OS));
1878   OS.flush();
1879   EXPECT_EQ("input1", Input1);
1880   EXPECT_EQ("input2", Input2);
1881   EXPECT_TRUE(ExtraArgs.size() == 2);
1882   EXPECT_TRUE(ExtraArgs[0] == "arg1");
1883   EXPECT_TRUE(ExtraArgs[1] == "arg2");
1884   EXPECT_TRUE(Errs.empty());
1885 }
1886 
1887 } // anonymous namespace
1888