ParserTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. #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 "llvm/ADT/StringMap.h"
  14. #include "gtest/gtest.h"
  15. #include <string>
  16. #include <vector>
  17. namespace clang {
  18. namespace ast_matchers {
  19. namespace dynamic {
  20. namespace {
  21. class MockSema : public Parser::Sema {
  22. public:
  23. ~MockSema() override {}
  24. uint64_t expectMatcher(StringRef MatcherName) {
  25. // Optimizations on the matcher framework make simple matchers like
  26. // 'stmt()' to be all the same matcher.
  27. // Use a more complex expression to prevent that.
  28. ast_matchers::internal::Matcher<Stmt> M = stmt(stmt(), stmt());
  29. ExpectedMatchers.insert(std::make_pair(MatcherName, M));
  30. return M.getID().second;
  31. }
  32. void parse(StringRef Code) {
  33. Diagnostics Error;
  34. VariantValue Value;
  35. Parser::parseExpression(Code, this, &Value, &Error);
  36. Values.push_back(Value);
  37. Errors.push_back(Error.toStringFull());
  38. }
  39. llvm::Optional<MatcherCtor>
  40. lookupMatcherCtor(StringRef MatcherName) override {
  41. const ExpectedMatchersTy::value_type *Matcher =
  42. &*ExpectedMatchers.find(MatcherName);
  43. return reinterpret_cast<MatcherCtor>(Matcher);
  44. }
  45. VariantMatcher actOnMatcherExpression(MatcherCtor Ctor,
  46. const SourceRange &NameRange,
  47. StringRef BindID,
  48. ArrayRef<ParserValue> Args,
  49. Diagnostics *Error) override {
  50. const ExpectedMatchersTy::value_type *Matcher =
  51. reinterpret_cast<const ExpectedMatchersTy::value_type *>(Ctor);
  52. MatcherInfo ToStore = { Matcher->first, NameRange, Args, BindID };
  53. Matchers.push_back(ToStore);
  54. return VariantMatcher::SingleMatcher(Matcher->second);
  55. }
  56. struct MatcherInfo {
  57. StringRef MatcherName;
  58. SourceRange NameRange;
  59. std::vector<ParserValue> Args;
  60. std::string BoundID;
  61. };
  62. std::vector<std::string> Errors;
  63. std::vector<VariantValue> Values;
  64. std::vector<MatcherInfo> Matchers;
  65. typedef std::map<std::string, ast_matchers::internal::Matcher<Stmt> >
  66. ExpectedMatchersTy;
  67. ExpectedMatchersTy ExpectedMatchers;
  68. };
  69. TEST(ParserTest, ParseUnsigned) {
  70. MockSema Sema;
  71. Sema.parse("0");
  72. Sema.parse("123");
  73. Sema.parse("0x1f");
  74. Sema.parse("12345678901");
  75. Sema.parse("1a1");
  76. EXPECT_EQ(5U, Sema.Values.size());
  77. EXPECT_EQ(0U, Sema.Values[0].getUnsigned());
  78. EXPECT_EQ(123U, Sema.Values[1].getUnsigned());
  79. EXPECT_EQ(31U, Sema.Values[2].getUnsigned());
  80. EXPECT_EQ("1:1: Error parsing unsigned token: <12345678901>", Sema.Errors[3]);
  81. EXPECT_EQ("1:1: Error parsing unsigned token: <1a1>", Sema.Errors[4]);
  82. }
  83. TEST(ParserTest, ParseString) {
  84. MockSema Sema;
  85. Sema.parse("\"Foo\"");
  86. Sema.parse("\"\"");
  87. Sema.parse("\"Baz");
  88. EXPECT_EQ(3ULL, Sema.Values.size());
  89. EXPECT_EQ("Foo", Sema.Values[0].getString());
  90. EXPECT_EQ("", Sema.Values[1].getString());
  91. EXPECT_EQ("1:1: Error parsing string token: <\"Baz>", Sema.Errors[2]);
  92. }
  93. bool matchesRange(const SourceRange &Range, unsigned StartLine,
  94. unsigned EndLine, unsigned StartColumn, unsigned EndColumn) {
  95. EXPECT_EQ(StartLine, Range.Start.Line);
  96. EXPECT_EQ(EndLine, Range.End.Line);
  97. EXPECT_EQ(StartColumn, Range.Start.Column);
  98. EXPECT_EQ(EndColumn, Range.End.Column);
  99. return Range.Start.Line == StartLine && Range.End.Line == EndLine &&
  100. Range.Start.Column == StartColumn && Range.End.Column == EndColumn;
  101. }
  102. llvm::Optional<DynTypedMatcher> getSingleMatcher(const VariantValue &Value) {
  103. llvm::Optional<DynTypedMatcher> Result =
  104. Value.getMatcher().getSingleMatcher();
  105. EXPECT_TRUE(Result.hasValue());
  106. return Result;
  107. }
  108. TEST(ParserTest, ParseMatcher) {
  109. MockSema Sema;
  110. const uint64_t ExpectedFoo = Sema.expectMatcher("Foo");
  111. const uint64_t ExpectedBar = Sema.expectMatcher("Bar");
  112. const uint64_t ExpectedBaz = Sema.expectMatcher("Baz");
  113. Sema.parse(" Foo ( Bar ( 17), Baz( \n \"B A,Z\") ) .bind( \"Yo!\") ");
  114. for (size_t i = 0, e = Sema.Errors.size(); i != e; ++i) {
  115. EXPECT_EQ("", Sema.Errors[i]);
  116. }
  117. EXPECT_NE(ExpectedFoo, ExpectedBar);
  118. EXPECT_NE(ExpectedFoo, ExpectedBaz);
  119. EXPECT_NE(ExpectedBar, ExpectedBaz);
  120. EXPECT_EQ(1ULL, Sema.Values.size());
  121. EXPECT_EQ(ExpectedFoo, getSingleMatcher(Sema.Values[0])->getID().second);
  122. EXPECT_EQ(3ULL, Sema.Matchers.size());
  123. const MockSema::MatcherInfo Bar = Sema.Matchers[0];
  124. EXPECT_EQ("Bar", Bar.MatcherName);
  125. EXPECT_TRUE(matchesRange(Bar.NameRange, 1, 1, 8, 17));
  126. EXPECT_EQ(1ULL, Bar.Args.size());
  127. EXPECT_EQ(17U, Bar.Args[0].Value.getUnsigned());
  128. const MockSema::MatcherInfo Baz = Sema.Matchers[1];
  129. EXPECT_EQ("Baz", Baz.MatcherName);
  130. EXPECT_TRUE(matchesRange(Baz.NameRange, 1, 2, 19, 10));
  131. EXPECT_EQ(1ULL, Baz.Args.size());
  132. EXPECT_EQ("B A,Z", Baz.Args[0].Value.getString());
  133. const MockSema::MatcherInfo Foo = Sema.Matchers[2];
  134. EXPECT_EQ("Foo", Foo.MatcherName);
  135. EXPECT_TRUE(matchesRange(Foo.NameRange, 1, 2, 2, 12));
  136. EXPECT_EQ(2ULL, Foo.Args.size());
  137. EXPECT_EQ(ExpectedBar, getSingleMatcher(Foo.Args[0].Value)->getID().second);
  138. EXPECT_EQ(ExpectedBaz, getSingleMatcher(Foo.Args[1].Value)->getID().second);
  139. EXPECT_EQ("Yo!", Foo.BoundID);
  140. }
  141. using ast_matchers::internal::Matcher;
  142. Parser::NamedValueMap getTestNamedValues() {
  143. Parser::NamedValueMap Values;
  144. Values["nameX"] = std::string("x");
  145. Values["hasParamA"] =
  146. VariantMatcher::SingleMatcher(hasParameter(0, hasName("a")));
  147. return Values;
  148. }
  149. TEST(ParserTest, FullParserTest) {
  150. Diagnostics Error;
  151. llvm::Optional<DynTypedMatcher> VarDecl(Parser::parseMatcherExpression(
  152. "varDecl(hasInitializer(binaryOperator(hasLHS(integerLiteral()),"
  153. " hasOperatorName(\"+\"))))",
  154. &Error));
  155. EXPECT_EQ("", Error.toStringFull());
  156. Matcher<Decl> M = VarDecl->unconditionalConvertTo<Decl>();
  157. EXPECT_TRUE(matches("int x = 1 + false;", M));
  158. EXPECT_FALSE(matches("int x = true + 1;", M));
  159. EXPECT_FALSE(matches("int x = 1 - false;", M));
  160. EXPECT_FALSE(matches("int x = true - 1;", M));
  161. llvm::Optional<DynTypedMatcher> HasParameter(Parser::parseMatcherExpression(
  162. "functionDecl(hasParameter(1, hasName(\"x\")))", &Error));
  163. EXPECT_EQ("", Error.toStringFull());
  164. M = HasParameter->unconditionalConvertTo<Decl>();
  165. EXPECT_TRUE(matches("void f(int a, int x);", M));
  166. EXPECT_FALSE(matches("void f(int x, int a);", M));
  167. // Test named values.
  168. auto NamedValues = getTestNamedValues();
  169. llvm::Optional<DynTypedMatcher> HasParameterWithNamedValues(
  170. Parser::parseMatcherExpression(
  171. "functionDecl(hasParamA, hasParameter(1, hasName(nameX)))",
  172. nullptr, &NamedValues, &Error));
  173. EXPECT_EQ("", Error.toStringFull());
  174. M = HasParameterWithNamedValues->unconditionalConvertTo<Decl>();
  175. EXPECT_TRUE(matches("void f(int a, int x);", M));
  176. EXPECT_FALSE(matches("void f(int x, int a);", M));
  177. EXPECT_TRUE(!Parser::parseMatcherExpression(
  178. "hasInitializer(\n binaryOperator(hasLHS(\"A\")))",
  179. &Error).hasValue());
  180. EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
  181. "2:5: Error parsing argument 1 for matcher binaryOperator.\n"
  182. "2:20: Error building matcher hasLHS.\n"
  183. "2:27: Incorrect type for arg 1. "
  184. "(Expected = Matcher<Expr>) != (Actual = String)",
  185. Error.toStringFull());
  186. }
  187. std::string ParseWithError(StringRef Code) {
  188. Diagnostics Error;
  189. VariantValue Value;
  190. Parser::parseExpression(Code, &Value, &Error);
  191. return Error.toStringFull();
  192. }
  193. std::string ParseMatcherWithError(StringRef Code) {
  194. Diagnostics Error;
  195. Parser::parseMatcherExpression(Code, &Error);
  196. return Error.toStringFull();
  197. }
  198. TEST(ParserTest, Errors) {
  199. EXPECT_EQ(
  200. "1:5: Error parsing matcher. Found token <123> while looking for '('.",
  201. ParseWithError("Foo 123"));
  202. EXPECT_EQ(
  203. "1:1: Matcher not found: Foo\n"
  204. "1:9: Error parsing matcher. Found token <123> while looking for ','.",
  205. ParseWithError("Foo(\"A\" 123)"));
  206. EXPECT_EQ(
  207. "1:1: Error parsing argument 1 for matcher stmt.\n"
  208. "1:6: Value not found: someValue",
  209. ParseWithError("stmt(someValue)"));
  210. EXPECT_EQ(
  211. "1:1: Matcher not found: Foo\n"
  212. "1:4: Error parsing matcher. Found end-of-code while looking for ')'.",
  213. ParseWithError("Foo("));
  214. EXPECT_EQ("1:1: End of code found while looking for token.",
  215. ParseWithError(""));
  216. EXPECT_EQ("Input value is not a matcher expression.",
  217. ParseMatcherWithError("\"A\""));
  218. EXPECT_EQ("1:1: Matcher not found: Foo\n"
  219. "1:1: Error parsing argument 1 for matcher Foo.\n"
  220. "1:5: Invalid token <(> found when looking for a value.",
  221. ParseWithError("Foo(("));
  222. EXPECT_EQ("1:7: Expected end of code.", ParseWithError("expr()a"));
  223. EXPECT_EQ("1:11: Malformed bind() expression.",
  224. ParseWithError("isArrow().biind"));
  225. EXPECT_EQ("1:15: Malformed bind() expression.",
  226. ParseWithError("isArrow().bind"));
  227. EXPECT_EQ("1:16: Malformed bind() expression.",
  228. ParseWithError("isArrow().bind(foo"));
  229. EXPECT_EQ("1:21: Malformed bind() expression.",
  230. ParseWithError("isArrow().bind(\"foo\""));
  231. EXPECT_EQ("1:1: Error building matcher isArrow.\n"
  232. "1:1: Matcher does not support binding.",
  233. ParseWithError("isArrow().bind(\"foo\")"));
  234. EXPECT_EQ("Input value has unresolved overloaded type: "
  235. "Matcher<DoStmt|ForStmt|WhileStmt|CXXForRangeStmt>",
  236. ParseMatcherWithError("hasBody(stmt())"));
  237. }
  238. TEST(ParserTest, OverloadErrors) {
  239. EXPECT_EQ("1:1: Error building matcher callee.\n"
  240. "1:8: Candidate 1: Incorrect type for arg 1. "
  241. "(Expected = Matcher<Stmt>) != (Actual = String)\n"
  242. "1:8: Candidate 2: Incorrect type for arg 1. "
  243. "(Expected = Matcher<Decl>) != (Actual = String)",
  244. ParseWithError("callee(\"A\")"));
  245. }
  246. TEST(ParserTest, CompletionRegistry) {
  247. std::vector<MatcherCompletion> Comps =
  248. Parser::completeExpression("while", 5);
  249. ASSERT_EQ(1u, Comps.size());
  250. EXPECT_EQ("Stmt(", Comps[0].TypedText);
  251. EXPECT_EQ("Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)",
  252. Comps[0].MatcherDecl);
  253. Comps = Parser::completeExpression("whileStmt().", 12);
  254. ASSERT_EQ(1u, Comps.size());
  255. EXPECT_EQ("bind(\"", Comps[0].TypedText);
  256. EXPECT_EQ("bind", Comps[0].MatcherDecl);
  257. }
  258. TEST(ParserTest, CompletionNamedValues) {
  259. // Can complete non-matcher types.
  260. auto NamedValues = getTestNamedValues();
  261. StringRef Code = "functionDecl(hasName(";
  262. std::vector<MatcherCompletion> Comps =
  263. Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
  264. ASSERT_EQ(1u, Comps.size());
  265. EXPECT_EQ("nameX", Comps[0].TypedText);
  266. EXPECT_EQ("String nameX", Comps[0].MatcherDecl);
  267. // Can complete if there are names in the expression.
  268. Code = "methodDecl(hasName(nameX), ";
  269. Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
  270. EXPECT_LT(0u, Comps.size());
  271. // Can complete names and registry together.
  272. Code = "methodDecl(hasP";
  273. Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
  274. ASSERT_EQ(3u, Comps.size());
  275. EXPECT_EQ("aramA", Comps[0].TypedText);
  276. EXPECT_EQ("Matcher<FunctionDecl> hasParamA", Comps[0].MatcherDecl);
  277. EXPECT_EQ("arameter(", Comps[1].TypedText);
  278. EXPECT_EQ(
  279. "Matcher<FunctionDecl> hasParameter(unsigned, Matcher<ParmVarDecl>)",
  280. Comps[1].MatcherDecl);
  281. EXPECT_EQ("arent(", Comps[2].TypedText);
  282. EXPECT_EQ("Matcher<Decl> hasParent(Matcher<Decl|Stmt>)",
  283. Comps[2].MatcherDecl);
  284. }
  285. } // end anonymous namespace
  286. } // end namespace dynamic
  287. } // end namespace ast_matchers
  288. } // end namespace clang