1 //===- unittest/ASTMatchers/Dynamic/ParserTest.cpp - Parser unit 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 "../ASTMatchersTest.h"
11 #include "clang/ASTMatchers/Dynamic/Parser.h"
12 #include "clang/ASTMatchers/Dynamic/Registry.h"
13 #include "llvm/ADT/Optional.h"
14 #include "gtest/gtest.h"
15 #include <string>
16 #include <vector>
17 
18 namespace clang {
19 namespace ast_matchers {
20 namespace dynamic {
21 namespace {
22 
23 class MockSema : public Parser::Sema {
24 public:
25   ~MockSema() override {}
26 
27   uint64_t expectMatcher(StringRef MatcherName) {
28     // Optimizations on the matcher framework make simple matchers like
29     // 'stmt()' to be all the same matcher.
30     // Use a more complex expression to prevent that.
31     ast_matchers::internal::Matcher<Stmt> M = stmt(stmt(), stmt());
32     ExpectedMatchers.insert(std::make_pair(MatcherName, M));
33     return M.getID().second;
34   }
35 
36   void parse(StringRef Code) {
37     Diagnostics Error;
38     VariantValue Value;
39     Parser::parseExpression(Code, this, &Value, &Error);
40     Values.push_back(Value);
41     Errors.push_back(Error.toStringFull());
42   }
43 
44   llvm::Optional<MatcherCtor>
45   lookupMatcherCtor(StringRef MatcherName) override {
46     const ExpectedMatchersTy::value_type *Matcher =
47         &*ExpectedMatchers.find(MatcherName);
48     return reinterpret_cast<MatcherCtor>(Matcher);
49   }
50 
51   VariantMatcher actOnMatcherExpression(MatcherCtor Ctor,
52                                         SourceRange NameRange,
53                                         StringRef BindID,
54                                         ArrayRef<ParserValue> Args,
55                                         Diagnostics *Error) override {
56     const ExpectedMatchersTy::value_type *Matcher =
57         reinterpret_cast<const ExpectedMatchersTy::value_type *>(Ctor);
58     MatcherInfo ToStore = { Matcher->first, NameRange, Args, BindID };
59     Matchers.push_back(ToStore);
60     return VariantMatcher::SingleMatcher(Matcher->second);
61   }
62 
63   struct MatcherInfo {
64     StringRef MatcherName;
65     SourceRange NameRange;
66     std::vector<ParserValue> Args;
67     std::string BoundID;
68   };
69 
70   std::vector<std::string> Errors;
71   std::vector<VariantValue> Values;
72   std::vector<MatcherInfo> Matchers;
73   typedef std::map<std::string, ast_matchers::internal::Matcher<Stmt> >
74   ExpectedMatchersTy;
75   ExpectedMatchersTy ExpectedMatchers;
76 };
77 
78 TEST(ParserTest, ParseBoolean) {
79   MockSema Sema;
80   Sema.parse("true");
81   Sema.parse("false");
82   EXPECT_EQ(2U, Sema.Values.size());
83   EXPECT_TRUE(Sema.Values[0].getBoolean());
84   EXPECT_FALSE(Sema.Values[1].getBoolean());
85 }
86 
87 TEST(ParserTest, ParseDouble) {
88   MockSema Sema;
89   Sema.parse("1.0");
90   Sema.parse("2.0f");
91   Sema.parse("34.56e-78");
92   Sema.parse("4.E+6");
93   Sema.parse("1");
94   EXPECT_EQ(5U, Sema.Values.size());
95   EXPECT_EQ(1.0, Sema.Values[0].getDouble());
96   EXPECT_EQ("1:1: Error parsing numeric literal: <2.0f>", Sema.Errors[1]);
97   EXPECT_EQ(34.56e-78, Sema.Values[2].getDouble());
98   EXPECT_EQ(4e+6, Sema.Values[3].getDouble());
99   EXPECT_FALSE(Sema.Values[4].isDouble());
100 }
101 
102 TEST(ParserTest, ParseUnsigned) {
103   MockSema Sema;
104   Sema.parse("0");
105   Sema.parse("123");
106   Sema.parse("0x1f");
107   Sema.parse("12345678901");
108   Sema.parse("1a1");
109   EXPECT_EQ(5U, Sema.Values.size());
110   EXPECT_EQ(0U, Sema.Values[0].getUnsigned());
111   EXPECT_EQ(123U, Sema.Values[1].getUnsigned());
112   EXPECT_EQ(31U, Sema.Values[2].getUnsigned());
113   EXPECT_EQ("1:1: Error parsing numeric literal: <12345678901>", Sema.Errors[3]);
114   EXPECT_EQ("1:1: Error parsing numeric literal: <1a1>", Sema.Errors[4]);
115 }
116 
117 TEST(ParserTest, ParseString) {
118   MockSema Sema;
119   Sema.parse("\"Foo\"");
120   Sema.parse("\"\"");
121   Sema.parse("\"Baz");
122   EXPECT_EQ(3ULL, Sema.Values.size());
123   EXPECT_EQ("Foo", Sema.Values[0].getString());
124   EXPECT_EQ("", Sema.Values[1].getString());
125   EXPECT_EQ("1:1: Error parsing string token: <\"Baz>", Sema.Errors[2]);
126 }
127 
128 bool matchesRange(SourceRange Range, unsigned StartLine,
129                   unsigned EndLine, unsigned StartColumn, unsigned EndColumn) {
130   EXPECT_EQ(StartLine, Range.Start.Line);
131   EXPECT_EQ(EndLine, Range.End.Line);
132   EXPECT_EQ(StartColumn, Range.Start.Column);
133   EXPECT_EQ(EndColumn, Range.End.Column);
134   return Range.Start.Line == StartLine && Range.End.Line == EndLine &&
135          Range.Start.Column == StartColumn && Range.End.Column == EndColumn;
136 }
137 
138 llvm::Optional<DynTypedMatcher> getSingleMatcher(const VariantValue &Value) {
139   llvm::Optional<DynTypedMatcher> Result =
140       Value.getMatcher().getSingleMatcher();
141   EXPECT_TRUE(Result.hasValue());
142   return Result;
143 }
144 
145 TEST(ParserTest, ParseMatcher) {
146   MockSema Sema;
147   const uint64_t ExpectedFoo = Sema.expectMatcher("Foo");
148   const uint64_t ExpectedBar = Sema.expectMatcher("Bar");
149   const uint64_t ExpectedBaz = Sema.expectMatcher("Baz");
150   Sema.parse(" Foo ( Bar ( 17), Baz( \n \"B A,Z\") ) .bind( \"Yo!\") ");
151   for (const auto &E : Sema.Errors) {
152     EXPECT_EQ("", E);
153   }
154 
155   EXPECT_NE(ExpectedFoo, ExpectedBar);
156   EXPECT_NE(ExpectedFoo, ExpectedBaz);
157   EXPECT_NE(ExpectedBar, ExpectedBaz);
158 
159   EXPECT_EQ(1ULL, Sema.Values.size());
160   EXPECT_EQ(ExpectedFoo, getSingleMatcher(Sema.Values[0])->getID().second);
161 
162   EXPECT_EQ(3ULL, Sema.Matchers.size());
163   const MockSema::MatcherInfo Bar = Sema.Matchers[0];
164   EXPECT_EQ("Bar", Bar.MatcherName);
165   EXPECT_TRUE(matchesRange(Bar.NameRange, 1, 1, 8, 17));
166   EXPECT_EQ(1ULL, Bar.Args.size());
167   EXPECT_EQ(17U, Bar.Args[0].Value.getUnsigned());
168 
169   const MockSema::MatcherInfo Baz = Sema.Matchers[1];
170   EXPECT_EQ("Baz", Baz.MatcherName);
171   EXPECT_TRUE(matchesRange(Baz.NameRange, 1, 2, 19, 10));
172   EXPECT_EQ(1ULL, Baz.Args.size());
173   EXPECT_EQ("B A,Z", Baz.Args[0].Value.getString());
174 
175   const MockSema::MatcherInfo Foo = Sema.Matchers[2];
176   EXPECT_EQ("Foo", Foo.MatcherName);
177   EXPECT_TRUE(matchesRange(Foo.NameRange, 1, 2, 2, 12));
178   EXPECT_EQ(2ULL, Foo.Args.size());
179   EXPECT_EQ(ExpectedBar, getSingleMatcher(Foo.Args[0].Value)->getID().second);
180   EXPECT_EQ(ExpectedBaz, getSingleMatcher(Foo.Args[1].Value)->getID().second);
181   EXPECT_EQ("Yo!", Foo.BoundID);
182 }
183 
184 TEST(ParserTest, ParseComment) {
185   MockSema Sema;
186   Sema.expectMatcher("Foo");
187   Sema.parse(" Foo() # Bar() ");
188   for (const auto &E : Sema.Errors) {
189     EXPECT_EQ("", E);
190   }
191 
192   EXPECT_EQ(1ULL, Sema.Matchers.size());
193 
194   Sema.parse("Foo(#) ");
195 
196   EXPECT_EQ("1:4: Error parsing matcher. Found end-of-code while looking for ')'.", Sema.Errors[1]);
197 }
198 
199 using ast_matchers::internal::Matcher;
200 
201 Parser::NamedValueMap getTestNamedValues() {
202   Parser::NamedValueMap Values;
203   Values["nameX"] = llvm::StringRef("x");
204   Values["hasParamA"] = VariantMatcher::SingleMatcher(
205       functionDecl(hasParameter(0, hasName("a"))));
206   return Values;
207 }
208 
209 TEST(ParserTest, FullParserTest) {
210   Diagnostics Error;
211   llvm::Optional<DynTypedMatcher> VarDecl(Parser::parseMatcherExpression(
212       "varDecl(hasInitializer(binaryOperator(hasLHS(integerLiteral()),"
213       "                                      hasOperatorName(\"+\"))))",
214       &Error));
215   EXPECT_EQ("", Error.toStringFull());
216   Matcher<Decl> M = VarDecl->unconditionalConvertTo<Decl>();
217   EXPECT_TRUE(matches("int x = 1 + false;", M));
218   EXPECT_FALSE(matches("int x = true + 1;", M));
219   EXPECT_FALSE(matches("int x = 1 - false;", M));
220   EXPECT_FALSE(matches("int x = true - 1;", M));
221 
222   llvm::Optional<DynTypedMatcher> HasParameter(Parser::parseMatcherExpression(
223       "functionDecl(hasParameter(1, hasName(\"x\")))", &Error));
224   EXPECT_EQ("", Error.toStringFull());
225   M = HasParameter->unconditionalConvertTo<Decl>();
226 
227   EXPECT_TRUE(matches("void f(int a, int x);", M));
228   EXPECT_FALSE(matches("void f(int x, int a);", M));
229 
230   // Test named values.
231   auto NamedValues = getTestNamedValues();
232   llvm::Optional<DynTypedMatcher> HasParameterWithNamedValues(
233       Parser::parseMatcherExpression(
234           "functionDecl(hasParamA, hasParameter(1, hasName(nameX)))",
235           nullptr, &NamedValues, &Error));
236   EXPECT_EQ("", Error.toStringFull());
237   M = HasParameterWithNamedValues->unconditionalConvertTo<Decl>();
238 
239   EXPECT_TRUE(matches("void f(int a, int x);", M));
240   EXPECT_FALSE(matches("void f(int x, int a);", M));
241 
242 
243   EXPECT_TRUE(!Parser::parseMatcherExpression(
244                    "hasInitializer(\n    binaryOperator(hasLHS(\"A\")))",
245                    &Error).hasValue());
246   EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
247             "2:5: Error parsing argument 1 for matcher binaryOperator.\n"
248             "2:20: Error building matcher hasLHS.\n"
249             "2:27: Incorrect type for arg 1. "
250             "(Expected = Matcher<Expr>) != (Actual = String)",
251             Error.toStringFull());
252 }
253 
254 TEST(ParserTest, VariadicMatchTest) {
255   Diagnostics Error;
256   llvm::Optional<DynTypedMatcher> OM(Parser::parseMatcherExpression(
257       "stmt(objcMessageExpr(hasAnySelector(\"methodA\", \"methodB:\")))",
258       &Error));
259   EXPECT_EQ("", Error.toStringFull());
260   auto M = OM->unconditionalConvertTo<Stmt>();
261   EXPECT_TRUE(matchesObjC("@interface I @end "
262                           "void foo(I* i) { [i methodA]; }", M));
263 }
264 
265 std::string ParseWithError(StringRef Code) {
266   Diagnostics Error;
267   VariantValue Value;
268   Parser::parseExpression(Code, &Value, &Error);
269   return Error.toStringFull();
270 }
271 
272 std::string ParseMatcherWithError(StringRef Code) {
273   Diagnostics Error;
274   Parser::parseMatcherExpression(Code, &Error);
275   return Error.toStringFull();
276 }
277 
278 TEST(ParserTest, Errors) {
279   EXPECT_EQ(
280       "1:5: Error parsing matcher. Found token <123> while looking for '('.",
281       ParseWithError("Foo 123"));
282   EXPECT_EQ(
283       "1:1: Matcher not found: Foo\n"
284       "1:9: Error parsing matcher. Found token <123> while looking for ','.",
285       ParseWithError("Foo(\"A\" 123)"));
286   EXPECT_EQ(
287       "1:1: Error parsing argument 1 for matcher stmt.\n"
288       "1:6: Value not found: someValue",
289       ParseWithError("stmt(someValue)"));
290   EXPECT_EQ(
291       "1:1: Matcher not found: Foo\n"
292       "1:4: Error parsing matcher. Found end-of-code while looking for ')'.",
293       ParseWithError("Foo("));
294   EXPECT_EQ("1:1: End of code found while looking for token.",
295             ParseWithError(""));
296   EXPECT_EQ("Input value is not a matcher expression.",
297             ParseMatcherWithError("\"A\""));
298   EXPECT_EQ("1:1: Matcher not found: Foo\n"
299             "1:1: Error parsing argument 1 for matcher Foo.\n"
300             "1:5: Invalid token <(> found when looking for a value.",
301             ParseWithError("Foo(("));
302   EXPECT_EQ("1:7: Expected end of code.", ParseWithError("expr()a"));
303   EXPECT_EQ("1:11: Malformed bind() expression.",
304             ParseWithError("isArrow().biind"));
305   EXPECT_EQ("1:15: Malformed bind() expression.",
306             ParseWithError("isArrow().bind"));
307   EXPECT_EQ("1:16: Malformed bind() expression.",
308             ParseWithError("isArrow().bind(foo"));
309   EXPECT_EQ("1:21: Malformed bind() expression.",
310             ParseWithError("isArrow().bind(\"foo\""));
311   EXPECT_EQ("1:1: Error building matcher isArrow.\n"
312             "1:1: Matcher does not support binding.",
313             ParseWithError("isArrow().bind(\"foo\")"));
314   EXPECT_EQ("Input value has unresolved overloaded type: "
315             "Matcher<DoStmt|ForStmt|WhileStmt|CXXForRangeStmt|FunctionDecl>",
316             ParseMatcherWithError("hasBody(stmt())"));
317 }
318 
319 TEST(ParserTest, OverloadErrors) {
320   EXPECT_EQ("1:1: Error building matcher callee.\n"
321             "1:8: Candidate 1: Incorrect type for arg 1. "
322             "(Expected = Matcher<Stmt>) != (Actual = String)\n"
323             "1:8: Candidate 2: Incorrect type for arg 1. "
324             "(Expected = Matcher<Decl>) != (Actual = String)",
325             ParseWithError("callee(\"A\")"));
326 }
327 
328 TEST(ParserTest, CompletionRegistry) {
329   std::vector<MatcherCompletion> Comps =
330       Parser::completeExpression("while", 5);
331   ASSERT_EQ(1u, Comps.size());
332   EXPECT_EQ("Stmt(", Comps[0].TypedText);
333   EXPECT_EQ("Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)",
334             Comps[0].MatcherDecl);
335 
336   Comps = Parser::completeExpression("whileStmt().", 12);
337   ASSERT_EQ(1u, Comps.size());
338   EXPECT_EQ("bind(\"", Comps[0].TypedText);
339   EXPECT_EQ("bind", Comps[0].MatcherDecl);
340 }
341 
342 TEST(ParserTest, CompletionNamedValues) {
343   // Can complete non-matcher types.
344   auto NamedValues = getTestNamedValues();
345   StringRef Code = "functionDecl(hasName(";
346   std::vector<MatcherCompletion> Comps =
347       Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
348   ASSERT_EQ(1u, Comps.size());
349   EXPECT_EQ("nameX", Comps[0].TypedText);
350   EXPECT_EQ("String nameX", Comps[0].MatcherDecl);
351 
352   // Can complete if there are names in the expression.
353   Code = "cxxMethodDecl(hasName(nameX), ";
354   Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
355   EXPECT_LT(0u, Comps.size());
356 
357   // Can complete names and registry together.
358   Code = "functionDecl(hasP";
359   Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
360   ASSERT_EQ(3u, Comps.size());
361 
362   EXPECT_EQ("arameter(", Comps[0].TypedText);
363   EXPECT_EQ(
364       "Matcher<FunctionDecl> hasParameter(unsigned, Matcher<ParmVarDecl>)",
365       Comps[0].MatcherDecl);
366 
367   EXPECT_EQ("aramA", Comps[1].TypedText);
368   EXPECT_EQ("Matcher<Decl> hasParamA", Comps[1].MatcherDecl);
369 
370   EXPECT_EQ("arent(", Comps[2].TypedText);
371   EXPECT_EQ(
372       "Matcher<Decl> "
373       "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)",
374       Comps[2].MatcherDecl);
375 }
376 
377 TEST(ParserTest, ParseBindOnLet) {
378 
379   auto NamedValues = getTestNamedValues();
380 
381   Diagnostics Error;
382 
383   {
384     llvm::Optional<DynTypedMatcher> TopLevelLetBinding(
385         Parser::parseMatcherExpression("hasParamA.bind(\"parmABinding\")",
386                                        nullptr, &NamedValues, &Error));
387     EXPECT_EQ("", Error.toStringFull());
388     auto M = TopLevelLetBinding->unconditionalConvertTo<Decl>();
389 
390     EXPECT_TRUE(matchAndVerifyResultTrue(
391         "void foo(int a);", M,
392         llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
393     EXPECT_TRUE(matchAndVerifyResultFalse(
394         "void foo(int b);", M,
395         llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
396   }
397 
398   {
399     llvm::Optional<DynTypedMatcher> NestedLetBinding(
400         Parser::parseMatcherExpression(
401             "functionDecl(hasParamA.bind(\"parmABinding\"))", nullptr,
402             &NamedValues, &Error));
403     EXPECT_EQ("", Error.toStringFull());
404     auto M = NestedLetBinding->unconditionalConvertTo<Decl>();
405 
406     EXPECT_TRUE(matchAndVerifyResultTrue(
407         "void foo(int a);", M,
408         llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
409     EXPECT_TRUE(matchAndVerifyResultFalse(
410         "void foo(int b);", M,
411         llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
412   }
413 }
414 
415 }  // end anonymous namespace
416 }  // end namespace dynamic
417 }  // end namespace ast_matchers
418 }  // end namespace clang
419