ParserTest.cpp revision ef7eb024397a6a9d1455b31bc7b10288a817ac3b
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 <string>
11#include <vector>
12
13#include "../ASTMatchersTest.h"
14#include "clang/ASTMatchers/Dynamic/Parser.h"
15#include "clang/ASTMatchers/Dynamic/Registry.h"
16#include "gtest/gtest.h"
17#include "llvm/ADT/StringMap.h"
18
19namespace clang {
20namespace ast_matchers {
21namespace dynamic {
22namespace {
23
24class DummyDynTypedMatcher : public DynTypedMatcher {
25public:
26  DummyDynTypedMatcher(uint64_t ID) : ID(ID) {}
27  DummyDynTypedMatcher(uint64_t ID, StringRef BoundID)
28      : ID(ID), BoundID(BoundID) {}
29
30  typedef ast_matchers::internal::ASTMatchFinder ASTMatchFinder;
31  typedef ast_matchers::internal::BoundNodesTreeBuilder BoundNodesTreeBuilder;
32  virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
33                       ASTMatchFinder *Finder,
34                       BoundNodesTreeBuilder *Builder) const {
35    return false;
36  }
37
38  /// \brief Makes a copy of this matcher object.
39  virtual DynTypedMatcher *clone() const {
40    return new DummyDynTypedMatcher(*this);
41  }
42
43  /// \brief Returns a unique ID for the matcher.
44  virtual uint64_t getID() const { return ID; }
45
46  virtual DynTypedMatcher* tryBind(StringRef BoundID) const {
47    return new DummyDynTypedMatcher(ID, BoundID);
48  }
49
50  StringRef boundID() const { return BoundID; }
51
52  virtual ast_type_traits::ASTNodeKind getSupportedKind() const {
53    return ast_type_traits::ASTNodeKind();
54  }
55
56private:
57  uint64_t ID;
58  std::string BoundID;
59};
60
61class MockSema : public Parser::Sema {
62public:
63  virtual ~MockSema() {}
64
65  uint64_t expectMatcher(StringRef MatcherName) {
66    uint64_t ID = ExpectedMatchers.size() + 1;
67    ExpectedMatchers[MatcherName] = ID;
68    return ID;
69  }
70
71  void parse(StringRef Code) {
72    Diagnostics Error;
73    VariantValue Value;
74    Parser::parseExpression(Code, this, &Value, &Error);
75    Values.push_back(Value);
76    Errors.push_back(Error.ToStringFull());
77  }
78
79  MatcherList actOnMatcherExpression(StringRef MatcherName,
80                                     const SourceRange &NameRange,
81                                     StringRef BindID,
82                                     ArrayRef<ParserValue> Args,
83                                     Diagnostics *Error) {
84    MatcherInfo ToStore = { MatcherName, NameRange, Args, BindID };
85    Matchers.push_back(ToStore);
86    DummyDynTypedMatcher Matcher(ExpectedMatchers[MatcherName]);
87    OwningPtr<DynTypedMatcher> Out(Matcher.tryBind(BindID));
88    return *Out;
89  }
90
91  struct MatcherInfo {
92    StringRef MatcherName;
93    SourceRange NameRange;
94    std::vector<ParserValue> Args;
95    std::string BoundID;
96  };
97
98  std::vector<std::string> Errors;
99  std::vector<VariantValue> Values;
100  std::vector<MatcherInfo> Matchers;
101  llvm::StringMap<uint64_t> ExpectedMatchers;
102};
103
104TEST(ParserTest, ParseUnsigned) {
105  MockSema Sema;
106  Sema.parse("0");
107  Sema.parse("123");
108  Sema.parse("0x1f");
109  Sema.parse("12345678901");
110  Sema.parse("1a1");
111  EXPECT_EQ(5U, Sema.Values.size());
112  EXPECT_EQ(0U, Sema.Values[0].getUnsigned());
113  EXPECT_EQ(123U, Sema.Values[1].getUnsigned());
114  EXPECT_EQ(31U, Sema.Values[2].getUnsigned());
115  EXPECT_EQ("1:1: Error parsing unsigned token: <12345678901>", Sema.Errors[3]);
116  EXPECT_EQ("1:1: Error parsing unsigned token: <1a1>", Sema.Errors[4]);
117}
118
119TEST(ParserTest, ParseString) {
120  MockSema Sema;
121  Sema.parse("\"Foo\"");
122  Sema.parse("\"\"");
123  Sema.parse("\"Baz");
124  EXPECT_EQ(3ULL, Sema.Values.size());
125  EXPECT_EQ("Foo", Sema.Values[0].getString());
126  EXPECT_EQ("", Sema.Values[1].getString());
127  EXPECT_EQ("1:1: Error parsing string token: <\"Baz>", Sema.Errors[2]);
128}
129
130bool matchesRange(const SourceRange &Range, unsigned StartLine,
131                  unsigned EndLine, unsigned StartColumn, unsigned EndColumn) {
132  EXPECT_EQ(StartLine, Range.Start.Line);
133  EXPECT_EQ(EndLine, Range.End.Line);
134  EXPECT_EQ(StartColumn, Range.Start.Column);
135  EXPECT_EQ(EndColumn, Range.End.Column);
136  return Range.Start.Line == StartLine && Range.End.Line == EndLine &&
137         Range.Start.Column == StartColumn && Range.End.Column == EndColumn;
138}
139
140TEST(ParserTest, ParseMatcher) {
141  MockSema Sema;
142  const uint64_t ExpectedFoo = Sema.expectMatcher("Foo");
143  const uint64_t ExpectedBar = Sema.expectMatcher("Bar");
144  const uint64_t ExpectedBaz = Sema.expectMatcher("Baz");
145  Sema.parse(" Foo ( Bar ( 17), Baz( \n \"B A,Z\") ) .bind( \"Yo!\") ");
146  for (size_t i = 0, e = Sema.Errors.size(); i != e; ++i) {
147    EXPECT_EQ("", Sema.Errors[i]);
148  }
149
150  EXPECT_EQ(1ULL, Sema.Values.size());
151  EXPECT_EQ(ExpectedFoo, Sema.Values[0].getMatchers().matchers()[0]->getID());
152  EXPECT_EQ("Yo!", static_cast<const DummyDynTypedMatcher *>(
153                       Sema.Values[0].getMatchers().matchers()[0])->boundID());
154
155  EXPECT_EQ(3ULL, Sema.Matchers.size());
156  const MockSema::MatcherInfo Bar = Sema.Matchers[0];
157  EXPECT_EQ("Bar", Bar.MatcherName);
158  EXPECT_TRUE(matchesRange(Bar.NameRange, 1, 1, 8, 17));
159  EXPECT_EQ(1ULL, Bar.Args.size());
160  EXPECT_EQ(17U, Bar.Args[0].Value.getUnsigned());
161
162  const MockSema::MatcherInfo Baz = Sema.Matchers[1];
163  EXPECT_EQ("Baz", Baz.MatcherName);
164  EXPECT_TRUE(matchesRange(Baz.NameRange, 1, 2, 19, 10));
165  EXPECT_EQ(1ULL, Baz.Args.size());
166  EXPECT_EQ("B A,Z", Baz.Args[0].Value.getString());
167
168  const MockSema::MatcherInfo Foo = Sema.Matchers[2];
169  EXPECT_EQ("Foo", Foo.MatcherName);
170  EXPECT_TRUE(matchesRange(Foo.NameRange, 1, 2, 2, 12));
171  EXPECT_EQ(2ULL, Foo.Args.size());
172  EXPECT_EQ(ExpectedBar,
173            Foo.Args[0].Value.getMatchers().matchers()[0]->getID());
174  EXPECT_EQ(ExpectedBaz,
175            Foo.Args[1].Value.getMatchers().matchers()[0]->getID());
176  EXPECT_EQ("Yo!", Foo.BoundID);
177}
178
179using ast_matchers::internal::Matcher;
180
181TEST(ParserTest, FullParserTest) {
182  OwningPtr<DynTypedMatcher> VarDecl(Parser::parseMatcherExpression(
183      "varDecl(hasInitializer(binaryOperator(hasLHS(integerLiteral()),"
184      "                                      hasOperatorName(\"+\"))))",
185      NULL));
186  Matcher<Decl> M = Matcher<Decl>::constructFrom(*VarDecl);
187  EXPECT_TRUE(matches("int x = 1 + false;", M));
188  EXPECT_FALSE(matches("int x = true + 1;", M));
189  EXPECT_FALSE(matches("int x = 1 - false;", M));
190  EXPECT_FALSE(matches("int x = true - 1;", M));
191
192  OwningPtr<DynTypedMatcher> HasParameter(Parser::parseMatcherExpression(
193      "functionDecl(hasParameter(1, hasName(\"x\")))", NULL));
194  M = Matcher<Decl>::constructFrom(*HasParameter);
195
196  EXPECT_TRUE(matches("void f(int a, int x);", M));
197  EXPECT_FALSE(matches("void f(int x, int a);", M));
198
199  Diagnostics Error;
200  EXPECT_TRUE(Parser::parseMatcherExpression(
201      "hasInitializer(\n    binaryOperator(hasLHS(\"A\")))", &Error) == NULL);
202  EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
203            "2:5: Error parsing argument 1 for matcher binaryOperator.\n"
204            "2:20: Error building matcher hasLHS.\n"
205            "2:27: Incorrect type for arg 1. "
206            "(Expected = Matcher<Expr>) != (Actual = String)",
207            Error.ToStringFull());
208}
209
210std::string ParseWithError(StringRef Code) {
211  Diagnostics Error;
212  VariantValue Value;
213  Parser::parseExpression(Code, &Value, &Error);
214  return Error.ToStringFull();
215}
216
217std::string ParseMatcherWithError(StringRef Code) {
218  Diagnostics Error;
219  Parser::parseMatcherExpression(Code, &Error);
220  return Error.ToStringFull();
221}
222
223TEST(ParserTest, Errors) {
224  EXPECT_EQ(
225      "1:5: Error parsing matcher. Found token <123> while looking for '('.",
226      ParseWithError("Foo 123"));
227  EXPECT_EQ(
228      "1:9: Error parsing matcher. Found token <123> while looking for ','.",
229      ParseWithError("Foo(\"A\" 123)"));
230  EXPECT_EQ(
231      "1:4: Error parsing matcher. Found end-of-code while looking for ')'.",
232      ParseWithError("Foo("));
233  EXPECT_EQ("1:1: End of code found while looking for token.",
234            ParseWithError(""));
235  EXPECT_EQ("Input value is not a matcher expression.",
236            ParseMatcherWithError("\"A\""));
237  EXPECT_EQ("1:1: Error parsing argument 1 for matcher Foo.\n"
238            "1:5: Invalid token <(> found when looking for a value.",
239            ParseWithError("Foo(("));
240  EXPECT_EQ("1:7: Expected end of code.", ParseWithError("expr()a"));
241  EXPECT_EQ("1:11: Malformed bind() expression.",
242            ParseWithError("isArrow().biind"));
243  EXPECT_EQ("1:15: Malformed bind() expression.",
244            ParseWithError("isArrow().bind"));
245  EXPECT_EQ("1:16: Malformed bind() expression.",
246            ParseWithError("isArrow().bind(foo"));
247  EXPECT_EQ("1:21: Malformed bind() expression.",
248            ParseWithError("isArrow().bind(\"foo\""));
249  EXPECT_EQ("1:1: Error building matcher isArrow.\n"
250            "1:1: Matcher does not support binding.",
251            ParseWithError("isArrow().bind(\"foo\")"));
252  EXPECT_EQ("Input value has unresolved overloaded type: "
253            "Matcher<DoStmt|ForStmt|WhileStmt>",
254            ParseMatcherWithError("hasBody(stmt())"));
255}
256
257}  // end anonymous namespace
258}  // end namespace dynamic
259}  // end namespace ast_matchers
260}  // end namespace clang
261