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