[Support] Promote cl::StringSaver to a separate utility
[oota-llvm.git] / unittests / Support / CommandLineTest.cpp
1 //===- llvm/unittest/Support/CommandLineTest.cpp - CommandLine tests ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/Config/config.h"
12 #include "llvm/Support/CommandLine.h"
13 #include "gtest/gtest.h"
14 #include <stdlib.h>
15 #include <string>
16
17 using namespace llvm;
18
19 namespace {
20
21 class TempEnvVar {
22  public:
23   TempEnvVar(const char *name, const char *value)
24       : name(name) {
25     const char *old_value = getenv(name);
26     EXPECT_EQ(nullptr, old_value) << old_value;
27 #if HAVE_SETENV
28     setenv(name, value, true);
29 #else
30 #   define SKIP_ENVIRONMENT_TESTS
31 #endif
32   }
33
34   ~TempEnvVar() {
35 #if HAVE_SETENV
36     // Assume setenv and unsetenv come together.
37     unsetenv(name);
38 #endif
39   }
40
41  private:
42   const char *const name;
43 };
44
45 template <typename T>
46 class StackOption : public cl::opt<T> {
47   typedef cl::opt<T> Base;
48 public:
49   // One option...
50   template<class M0t>
51   explicit StackOption(const M0t &M0) : Base(M0) {}
52
53   // Two options...
54   template<class M0t, class M1t>
55   StackOption(const M0t &M0, const M1t &M1) : Base(M0, M1) {}
56
57   // Three options...
58   template<class M0t, class M1t, class M2t>
59   StackOption(const M0t &M0, const M1t &M1, const M2t &M2) : Base(M0, M1, M2) {}
60
61   // Four options...
62   template<class M0t, class M1t, class M2t, class M3t>
63   StackOption(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
64     : Base(M0, M1, M2, M3) {}
65
66   ~StackOption() {
67     this->removeArgument();
68   }
69 };
70
71
72 cl::OptionCategory TestCategory("Test Options", "Description");
73 cl::opt<int> TestOption("test-option", cl::desc("old description"));
74 TEST(CommandLineTest, ModifyExisitingOption) {
75   const char Description[] = "New description";
76   const char ArgString[] = "new-test-option";
77   const char ValueString[] = "Integer";
78
79   StringMap<cl::Option*> Map;
80   cl::getRegisteredOptions(Map);
81
82   ASSERT_TRUE(Map.count("test-option") == 1) <<
83     "Could not find option in map.";
84
85   cl::Option *Retrieved = Map["test-option"];
86   ASSERT_EQ(&TestOption, Retrieved) << "Retrieved wrong option.";
87
88   ASSERT_EQ(&cl::GeneralCategory,Retrieved->Category) <<
89     "Incorrect default option category.";
90
91   Retrieved->setCategory(TestCategory);
92   ASSERT_EQ(&TestCategory,Retrieved->Category) <<
93     "Failed to modify option's option category.";
94
95   Retrieved->setDescription(Description);
96   ASSERT_STREQ(Retrieved->HelpStr, Description) <<
97     "Changing option description failed.";
98
99   Retrieved->setArgStr(ArgString);
100   ASSERT_STREQ(ArgString, Retrieved->ArgStr) <<
101     "Failed to modify option's Argument string.";
102
103   Retrieved->setValueStr(ValueString);
104   ASSERT_STREQ(Retrieved->ValueStr, ValueString) <<
105     "Failed to modify option's Value string.";
106
107   Retrieved->setHiddenFlag(cl::Hidden);
108   ASSERT_EQ(cl::Hidden, TestOption.getOptionHiddenFlag()) <<
109     "Failed to modify option's hidden flag.";
110 }
111 #ifndef SKIP_ENVIRONMENT_TESTS
112
113 const char test_env_var[] = "LLVM_TEST_COMMAND_LINE_FLAGS";
114
115 cl::opt<std::string> EnvironmentTestOption("env-test-opt");
116 TEST(CommandLineTest, ParseEnvironment) {
117   TempEnvVar TEV(test_env_var, "-env-test-opt=hello");
118   EXPECT_EQ("", EnvironmentTestOption);
119   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
120   EXPECT_EQ("hello", EnvironmentTestOption);
121 }
122
123 // This test used to make valgrind complain
124 // ("Conditional jump or move depends on uninitialised value(s)")
125 //
126 // Warning: Do not run any tests after this one that try to gain access to
127 // registered command line options because this will likely result in a
128 // SEGFAULT. This can occur because the cl::opt in the test below is declared
129 // on the stack which will be destroyed after the test completes but the
130 // command line system will still hold a pointer to a deallocated cl::Option.
131 TEST(CommandLineTest, ParseEnvironmentToLocalVar) {
132   // Put cl::opt on stack to check for proper initialization of fields.
133   StackOption<std::string> EnvironmentTestOptionLocal("env-test-opt-local");
134   TempEnvVar TEV(test_env_var, "-env-test-opt-local=hello-local");
135   EXPECT_EQ("", EnvironmentTestOptionLocal);
136   cl::ParseEnvironmentOptions("CommandLineTest", test_env_var);
137   EXPECT_EQ("hello-local", EnvironmentTestOptionLocal);
138 }
139
140 #endif  // SKIP_ENVIRONMENT_TESTS
141
142 TEST(CommandLineTest, UseOptionCategory) {
143   StackOption<int> TestOption2("test-option", cl::cat(TestCategory));
144
145   ASSERT_EQ(&TestCategory,TestOption2.Category) << "Failed to assign Option "
146                                                   "Category.";
147 }
148
149 typedef void ParserFunction(StringRef Source, StringSaver &Saver,
150                             SmallVectorImpl<const char *> &NewArgv);
151
152
153 void testCommandLineTokenizer(ParserFunction *parse, const char *Input,
154                               const char *const Output[], size_t OutputSize) {
155   SmallVector<const char *, 0> Actual;
156   StringSaver Saver;
157   parse(Input, Saver, Actual);
158   EXPECT_EQ(OutputSize, Actual.size());
159   for (unsigned I = 0, E = Actual.size(); I != E; ++I) {
160     if (I < OutputSize)
161       EXPECT_STREQ(Output[I], Actual[I]);
162   }
163 }
164
165 TEST(CommandLineTest, TokenizeGNUCommandLine) {
166   const char *Input = "foo\\ bar \"foo bar\" \'foo bar\' 'foo\\\\bar' "
167                       "foo\"bar\"baz C:\\src\\foo.cpp \"C:\\src\\foo.cpp\"";
168   const char *const Output[] = { "foo bar", "foo bar", "foo bar", "foo\\bar",
169                                  "foobarbaz", "C:\\src\\foo.cpp",
170                                  "C:\\src\\foo.cpp" };
171   testCommandLineTokenizer(cl::TokenizeGNUCommandLine, Input, Output,
172                            array_lengthof(Output));
173 }
174
175 TEST(CommandLineTest, TokenizeWindowsCommandLine) {
176   const char *Input = "a\\b c\\\\d e\\\\\"f g\" h\\\"i j\\\\\\\"k \"lmn\" o pqr "
177                       "\"st \\\"u\" \\v";
178   const char *const Output[] = { "a\\b", "c\\\\d", "e\\f g", "h\"i", "j\\\"k",
179                                  "lmn", "o", "pqr", "st \"u", "\\v" };
180   testCommandLineTokenizer(cl::TokenizeWindowsCommandLine, Input, Output,
181                            array_lengthof(Output));
182 }
183
184 TEST(CommandLineTest, AliasesWithArguments) {
185   static const size_t ARGC = 3;
186   const char *const Inputs[][ARGC] = {
187     { "-tool", "-actual=x", "-extra" },
188     { "-tool", "-actual", "x" },
189     { "-tool", "-alias=x", "-extra" },
190     { "-tool", "-alias", "x" }
191   };
192
193   for (size_t i = 0, e = array_lengthof(Inputs); i < e; ++i) {
194     StackOption<std::string> Actual("actual");
195     StackOption<bool> Extra("extra");
196     StackOption<std::string> Input(cl::Positional);
197
198     cl::alias Alias("alias", llvm::cl::aliasopt(Actual));
199
200     cl::ParseCommandLineOptions(ARGC, Inputs[i]);
201     EXPECT_EQ("x", Actual);
202     EXPECT_EQ(0, Input.getNumOccurrences());
203
204     Alias.removeArgument();
205   }
206 }
207
208 void testAliasRequired(int argc, const char *const *argv) {
209   StackOption<std::string> Option("option", cl::Required);
210   cl::alias Alias("o", llvm::cl::aliasopt(Option));
211
212   cl::ParseCommandLineOptions(argc, argv);
213   EXPECT_EQ("x", Option);
214   EXPECT_EQ(1, Option.getNumOccurrences());
215
216   Alias.removeArgument();
217 }
218
219 TEST(CommandLineTest, AliasRequired) {
220   const char *opts1[] = { "-tool", "-option=x" };
221   const char *opts2[] = { "-tool", "-o", "x" };
222   testAliasRequired(array_lengthof(opts1), opts1);
223   testAliasRequired(array_lengthof(opts2), opts2);
224 }
225
226
227 }  // anonymous namespace