• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- unittest/ASTMatchers/Dynamic/ParserTest.cpp - Parser unit 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 "../ASTMatchersTest.h"
10 #include "clang/ASTMatchers/Dynamic/Parser.h"
11 #include "clang/ASTMatchers/Dynamic/Registry.h"
12 #include "llvm/ADT/Optional.h"
13 #include "gtest/gtest.h"
14 #include <string>
15 #include <vector>
16 
17 namespace clang {
18 namespace ast_matchers {
19 namespace dynamic {
20 namespace {
21 
22 class MockSema : public Parser::Sema {
23 public:
~MockSema()24   ~MockSema() override {}
25 
expectMatcher(StringRef MatcherName)26   uint64_t expectMatcher(StringRef MatcherName) {
27     // Optimizations on the matcher framework make simple matchers like
28     // 'stmt()' to be all the same matcher.
29     // Use a more complex expression to prevent that.
30     ast_matchers::internal::Matcher<Stmt> M = stmt(stmt(), stmt());
31     ExpectedMatchers.insert(std::make_pair(std::string(MatcherName), M));
32     return M.getID().second;
33   }
34 
parse(StringRef Code)35   void parse(StringRef Code) {
36     Diagnostics Error;
37     VariantValue Value;
38     Parser::parseExpression(Code, this, &Value, &Error);
39     Values.push_back(Value);
40     Errors.push_back(Error.toStringFull());
41   }
42 
43   llvm::Optional<MatcherCtor>
lookupMatcherCtor(StringRef MatcherName)44   lookupMatcherCtor(StringRef MatcherName) override {
45     const ExpectedMatchersTy::value_type *Matcher =
46         &*ExpectedMatchers.find(std::string(MatcherName));
47     return reinterpret_cast<MatcherCtor>(Matcher);
48   }
49 
actOnMatcherExpression(MatcherCtor Ctor,SourceRange NameRange,StringRef BindID,ArrayRef<ParserValue> Args,Diagnostics * Error)50   VariantMatcher actOnMatcherExpression(MatcherCtor Ctor,
51                                         SourceRange NameRange,
52                                         StringRef BindID,
53                                         ArrayRef<ParserValue> Args,
54                                         Diagnostics *Error) override {
55     const ExpectedMatchersTy::value_type *Matcher =
56         reinterpret_cast<const ExpectedMatchersTy::value_type *>(Ctor);
57     MatcherInfo ToStore = {Matcher->first, NameRange, Args,
58                            std::string(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 
TEST(ParserTest,ParseBoolean)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 
TEST(ParserTest,ParseDouble)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 
TEST(ParserTest,ParseUnsigned)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 
TEST(ParserTest,ParseString)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 
matchesRange(SourceRange Range,unsigned StartLine,unsigned EndLine,unsigned StartColumn,unsigned EndColumn)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 
getSingleMatcher(const VariantValue & Value)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 
TEST(ParserTest,ParseMatcher)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 
TEST(ParserTest,ParseComment)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 
getTestNamedValues()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 
TEST(ParserTest,FullParserTest)209 TEST(ParserTest, FullParserTest) {
210   Diagnostics Error;
211 
212   StringRef Code =
213       "varDecl(hasInitializer(binaryOperator(hasLHS(integerLiteral()),"
214       "                                      hasOperatorName(\"+\"))))";
215   llvm::Optional<DynTypedMatcher> VarDecl(
216       Parser::parseMatcherExpression(Code, &Error));
217   EXPECT_EQ("", Error.toStringFull());
218   Matcher<Decl> M = VarDecl->unconditionalConvertTo<Decl>();
219   EXPECT_TRUE(matches("int x = 1 + false;", M));
220   EXPECT_FALSE(matches("int x = true + 1;", M));
221   EXPECT_FALSE(matches("int x = 1 - false;", M));
222   EXPECT_FALSE(matches("int x = true - 1;", M));
223 
224   Code = "implicitCastExpr(hasCastKind(\"CK_IntegralToBoolean\"))";
225   llvm::Optional<DynTypedMatcher> implicitIntBooleanCast(
226       Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error));
227   EXPECT_EQ("", Error.toStringFull());
228   Matcher<Stmt> MCastStmt =
229       traverse(TK_AsIs, implicitIntBooleanCast->unconditionalConvertTo<Stmt>());
230   EXPECT_TRUE(matches("bool X = 1;", MCastStmt));
231   EXPECT_FALSE(matches("bool X = true;", MCastStmt));
232 
233   Code = "functionDecl(hasParameter(1, hasName(\"x\")))";
234   llvm::Optional<DynTypedMatcher> HasParameter(
235       Parser::parseMatcherExpression(Code, &Error));
236   EXPECT_EQ("", Error.toStringFull());
237   M = HasParameter->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   // Test named values.
243   auto NamedValues = getTestNamedValues();
244 
245   Code = "functionDecl(hasParamA, hasParameter(1, hasName(nameX)))";
246   llvm::Optional<DynTypedMatcher> HasParameterWithNamedValues(
247       Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error));
248   EXPECT_EQ("", Error.toStringFull());
249   M = HasParameterWithNamedValues->unconditionalConvertTo<Decl>();
250 
251   EXPECT_TRUE(matches("void f(int a, int x);", M));
252   EXPECT_FALSE(matches("void f(int x, int a);", M));
253 
254   Code = "unaryExprOrTypeTraitExpr(ofKind(\"UETT_SizeOf\"))";
255   llvm::Optional<DynTypedMatcher> UnaryExprSizeOf(
256       Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error));
257   EXPECT_EQ("", Error.toStringFull());
258   Matcher<Stmt> MStmt = UnaryExprSizeOf->unconditionalConvertTo<Stmt>();
259   EXPECT_TRUE(matches("unsigned X = sizeof(int);", MStmt));
260   EXPECT_FALSE(matches("unsigned X = alignof(int);", MStmt));
261 
262   Code =
263       R"query(namedDecl(matchesName("^::[ABC]*$", "IgnoreCase | BasicRegex")))query";
264   llvm::Optional<DynTypedMatcher> MatchesName(
265       Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error));
266   EXPECT_EQ("", Error.toStringFull());
267   M = MatchesName->unconditionalConvertTo<Decl>();
268   EXPECT_TRUE(matches("unsigned AAACCBB;", M));
269   EXPECT_TRUE(matches("unsigned aaaccbb;", M));
270 
271   Code = "hasInitializer(\n    binaryOperator(hasLHS(\"A\")))";
272   EXPECT_TRUE(!Parser::parseMatcherExpression(Code, &Error).hasValue());
273   EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
274             "2:5: Error parsing argument 1 for matcher binaryOperator.\n"
275             "2:20: Error building matcher hasLHS.\n"
276             "2:27: Incorrect type for arg 1. "
277             "(Expected = Matcher<Expr>) != (Actual = String)",
278             Error.toStringFull());
279 }
280 
TEST(ParserTest,VariadicMatchTest)281 TEST(ParserTest, VariadicMatchTest) {
282   Diagnostics Error;
283 
284   StringRef Code =
285       "stmt(objcMessageExpr(hasAnySelector(\"methodA\", \"methodB:\")))";
286   llvm::Optional<DynTypedMatcher> OM(
287       Parser::parseMatcherExpression(Code, &Error));
288   EXPECT_EQ("", Error.toStringFull());
289   auto M = OM->unconditionalConvertTo<Stmt>();
290   EXPECT_TRUE(matchesObjC("@interface I @end "
291                           "void foo(I* i) { [i methodA]; }", M));
292 }
293 
ParseWithError(StringRef Code)294 std::string ParseWithError(StringRef Code) {
295   Diagnostics Error;
296   VariantValue Value;
297   Parser::parseExpression(Code, &Value, &Error);
298   return Error.toStringFull();
299 }
300 
ParseMatcherWithError(StringRef Code)301 std::string ParseMatcherWithError(StringRef Code) {
302   Diagnostics Error;
303   Parser::parseMatcherExpression(Code, &Error);
304   return Error.toStringFull();
305 }
306 
TEST(ParserTest,Errors)307 TEST(ParserTest, Errors) {
308   EXPECT_EQ(
309       "1:5: Error parsing matcher. Found token <123> while looking for '('.",
310       ParseWithError("Foo 123"));
311   EXPECT_EQ(
312       "1:1: Matcher not found: Foo\n"
313       "1:9: Error parsing matcher. Found token <123> while looking for ','.",
314       ParseWithError("Foo(\"A\" 123)"));
315   EXPECT_EQ(
316       "1:1: Error parsing argument 1 for matcher stmt.\n"
317       "1:6: Value not found: someValue",
318       ParseWithError("stmt(someValue)"));
319   EXPECT_EQ(
320       "1:1: Matcher not found: Foo\n"
321       "1:4: Error parsing matcher. Found end-of-code while looking for ')'.",
322       ParseWithError("Foo("));
323   EXPECT_EQ("1:1: End of code found while looking for token.",
324             ParseWithError(""));
325   EXPECT_EQ("Input value is not a matcher expression.",
326             ParseMatcherWithError("\"A\""));
327   EXPECT_EQ("1:1: Matcher not found: Foo\n"
328             "1:1: Error parsing argument 1 for matcher Foo.\n"
329             "1:5: Invalid token <(> found when looking for a value.",
330             ParseWithError("Foo(("));
331   EXPECT_EQ("1:7: Expected end of code.", ParseWithError("expr()a"));
332   EXPECT_EQ("1:11: Malformed bind() expression.",
333             ParseWithError("isArrow().biind"));
334   EXPECT_EQ("1:15: Malformed bind() expression.",
335             ParseWithError("isArrow().bind"));
336   EXPECT_EQ("1:16: Malformed bind() expression.",
337             ParseWithError("isArrow().bind(foo"));
338   EXPECT_EQ("1:21: Malformed bind() expression.",
339             ParseWithError("isArrow().bind(\"foo\""));
340   EXPECT_EQ("1:1: Error building matcher isArrow.\n"
341             "1:1: Matcher does not support binding.",
342             ParseWithError("isArrow().bind(\"foo\")"));
343   EXPECT_EQ("Input value has unresolved overloaded type: "
344             "Matcher<DoStmt|ForStmt|WhileStmt|CXXForRangeStmt|FunctionDecl>",
345             ParseMatcherWithError("hasBody(stmt())"));
346   EXPECT_EQ(
347       "1:1: Error parsing argument 1 for matcher decl.\n"
348       "1:6: Error building matcher hasAttr.\n"
349       "1:14: Unknown value 'attr::Fnal' for arg 1; did you mean 'attr::Final'",
350       ParseMatcherWithError(R"query(decl(hasAttr("attr::Fnal")))query"));
351   EXPECT_EQ("1:1: Error parsing argument 1 for matcher decl.\n"
352             "1:6: Error building matcher hasAttr.\n"
353             "1:14: Unknown value 'Final' for arg 1; did you mean 'attr::Final'",
354             ParseMatcherWithError(R"query(decl(hasAttr("Final")))query"));
355   EXPECT_EQ("1:1: Error parsing argument 1 for matcher decl.\n"
356             "1:6: Error building matcher hasAttr.\n"
357             "1:14: Value not found: unrelated",
358             ParseMatcherWithError(R"query(decl(hasAttr("unrelated")))query"));
359   EXPECT_EQ(
360       "1:1: Error parsing argument 1 for matcher namedDecl.\n"
361       "1:11: Error building matcher matchesName.\n"
362       "1:33: Unknown value 'Ignorecase' for arg 2; did you mean 'IgnoreCase'",
363       ParseMatcherWithError(
364           R"query(namedDecl(matchesName("[ABC]*", "Ignorecase")))query"));
365   EXPECT_EQ(
366       "1:1: Error parsing argument 1 for matcher namedDecl.\n"
367       "1:11: Error building matcher matchesName.\n"
368       "1:33: Value not found: IgnoreCase & BasicRegex",
369       ParseMatcherWithError(
370           R"query(namedDecl(matchesName("[ABC]*", "IgnoreCase & BasicRegex")))query"));
371   EXPECT_EQ(
372       "1:1: Error parsing argument 1 for matcher namedDecl.\n"
373       "1:11: Error building matcher matchesName.\n"
374       "1:33: Unknown value 'IgnoreCase | Basicregex' for arg 2; did you mean "
375       "'IgnoreCase | BasicRegex'",
376       ParseMatcherWithError(
377           R"query(namedDecl(matchesName("[ABC]*", "IgnoreCase | Basicregex")))query"));
378 }
379 
TEST(ParserTest,OverloadErrors)380 TEST(ParserTest, OverloadErrors) {
381   EXPECT_EQ("1:1: Error building matcher callee.\n"
382             "1:8: Candidate 1: Incorrect type for arg 1. "
383             "(Expected = Matcher<Stmt>) != (Actual = String)\n"
384             "1:8: Candidate 2: Incorrect type for arg 1. "
385             "(Expected = Matcher<Decl>) != (Actual = String)",
386             ParseWithError("callee(\"A\")"));
387 }
388 
TEST(ParserTest,ParseMultiline)389 TEST(ParserTest, ParseMultiline) {
390   StringRef Code;
391 
392   llvm::Optional<DynTypedMatcher> M;
393   {
394     Code = R"matcher(varDecl(
395   hasName("foo")
396   )
397 )matcher";
398     Diagnostics Error;
399     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
400   }
401 
402   {
403     Code = R"matcher(varDecl(
404   # Internal comment
405   hasName("foo") # Internal comment
406 # Internal comment
407   )
408 )matcher";
409     Diagnostics Error;
410     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
411   }
412 
413   {
414     Code = R"matcher(decl().bind(
415   "paramName")
416 )matcher";
417     Diagnostics Error;
418     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
419   }
420 
421   {
422     Code = R"matcher(decl().bind(
423   "paramName"
424   )
425 )matcher";
426     Diagnostics Error;
427     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
428   }
429 
430   {
431     Code = R"matcher(decl(decl()
432 , decl()))matcher";
433     Diagnostics Error;
434     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
435   }
436 
437   {
438     Code = R"matcher(decl(decl(),
439 decl()))matcher";
440     Diagnostics Error;
441     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
442   }
443 
444   {
445     Code = "namedDecl(hasName(\"n\"\n))";
446     Diagnostics Error;
447     EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue());
448   }
449 
450   {
451     Diagnostics Error;
452 
453     auto NamedValues = getTestNamedValues();
454 
455     Code = R"matcher(hasParamA.bind
456   ("paramName")
457 )matcher";
458     M = Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error);
459     EXPECT_FALSE(M.hasValue());
460     EXPECT_EQ("1:15: Malformed bind() expression.", Error.toStringFull());
461   }
462 
463   {
464     Diagnostics Error;
465 
466     auto NamedValues = getTestNamedValues();
467 
468     Code = R"matcher(hasParamA.
469   bind("paramName")
470 )matcher";
471     M = Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error);
472     EXPECT_FALSE(M.hasValue());
473     EXPECT_EQ("1:11: Malformed bind() expression.", Error.toStringFull());
474   }
475 
476   {
477     Diagnostics Error;
478 
479     Code = R"matcher(varDecl
480 ()
481 )matcher";
482     M = Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error);
483     EXPECT_FALSE(M.hasValue());
484     EXPECT_EQ("1:8: Error parsing matcher. Found token "
485               "<NewLine> while looking for '('.",
486               Error.toStringFull());
487   }
488 
489   // Correct line/column numbers
490   {
491     Diagnostics Error;
492 
493     Code = R"matcher(varDecl(
494   doesNotExist()
495   )
496 )matcher";
497     M = Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error);
498     EXPECT_FALSE(M.hasValue());
499     StringRef Expected = R"error(1:1: Error parsing argument 1 for matcher varDecl.
500 2:3: Matcher not found: doesNotExist)error";
501     EXPECT_EQ(Expected, Error.toStringFull());
502   }
503 }
504 
TEST(ParserTest,CompletionRegistry)505 TEST(ParserTest, CompletionRegistry) {
506   StringRef Code = "while";
507   std::vector<MatcherCompletion> Comps = Parser::completeExpression(Code, 5);
508   ASSERT_EQ(1u, Comps.size());
509   EXPECT_EQ("Stmt(", Comps[0].TypedText);
510   EXPECT_EQ("Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)",
511             Comps[0].MatcherDecl);
512 
513   Code = "whileStmt().";
514   Comps = Parser::completeExpression(Code, 12);
515   ASSERT_EQ(1u, Comps.size());
516   EXPECT_EQ("bind(\"", Comps[0].TypedText);
517   EXPECT_EQ("bind", Comps[0].MatcherDecl);
518 }
519 
TEST(ParserTest,CompletionNamedValues)520 TEST(ParserTest, CompletionNamedValues) {
521   // Can complete non-matcher types.
522   auto NamedValues = getTestNamedValues();
523   StringRef Code = "functionDecl(hasName(";
524   std::vector<MatcherCompletion> Comps =
525       Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
526   ASSERT_EQ(1u, Comps.size());
527   EXPECT_EQ("nameX", Comps[0].TypedText);
528   EXPECT_EQ("String nameX", Comps[0].MatcherDecl);
529 
530   // Can complete if there are names in the expression.
531   Code = "cxxMethodDecl(hasName(nameX), ";
532   Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
533   EXPECT_LT(0u, Comps.size());
534 
535   // Can complete names and registry together.
536   Code = "functionDecl(hasP";
537   Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
538   ASSERT_EQ(3u, Comps.size());
539 
540   EXPECT_EQ("arameter(", Comps[0].TypedText);
541   EXPECT_EQ(
542       "Matcher<FunctionDecl> hasParameter(unsigned, Matcher<ParmVarDecl>)",
543       Comps[0].MatcherDecl);
544 
545   EXPECT_EQ("aramA", Comps[1].TypedText);
546   EXPECT_EQ("Matcher<Decl> hasParamA", Comps[1].MatcherDecl);
547 
548   EXPECT_EQ("arent(", Comps[2].TypedText);
549   EXPECT_EQ(
550       "Matcher<Decl> "
551       "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)",
552       Comps[2].MatcherDecl);
553 }
554 
TEST(ParserTest,ParseBindOnLet)555 TEST(ParserTest, ParseBindOnLet) {
556 
557   auto NamedValues = getTestNamedValues();
558 
559   Diagnostics Error;
560 
561   {
562     StringRef Code = "hasParamA.bind(\"parmABinding\")";
563     llvm::Optional<DynTypedMatcher> TopLevelLetBinding(
564         Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error));
565     EXPECT_EQ("", Error.toStringFull());
566     auto M = TopLevelLetBinding->unconditionalConvertTo<Decl>();
567 
568     EXPECT_TRUE(matchAndVerifyResultTrue(
569         "void foo(int a);", M,
570         std::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
571     EXPECT_TRUE(matchAndVerifyResultFalse(
572         "void foo(int b);", M,
573         std::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
574   }
575 
576   {
577     StringRef Code = "functionDecl(hasParamA.bind(\"parmABinding\"))";
578     llvm::Optional<DynTypedMatcher> NestedLetBinding(
579         Parser::parseMatcherExpression(Code, nullptr, &NamedValues, &Error));
580     EXPECT_EQ("", Error.toStringFull());
581     auto M = NestedLetBinding->unconditionalConvertTo<Decl>();
582 
583     EXPECT_TRUE(matchAndVerifyResultTrue(
584         "void foo(int a);", M,
585         std::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
586     EXPECT_TRUE(matchAndVerifyResultFalse(
587         "void foo(int b);", M,
588         std::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("parmABinding")));
589   }
590 }
591 
592 }  // end anonymous namespace
593 }  // end namespace dynamic
594 }  // end namespace ast_matchers
595 }  // end namespace clang
596