blob: 9ef86b552cfc3c9273be36a60909a1c40b0b6f14 [file] [log] [blame]
David Blaikiee0026312012-04-26 20:39:46 +00001//===- unittest/Tooling/RecursiveASTVisitorTest.cpp -----------------------===//
Manuel Klimekfad7f852012-04-19 08:48:53 +00002//
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 "clang/AST/ASTConsumer.h"
11#include "clang/AST/RecursiveASTVisitor.h"
12#include "clang/Frontend/FrontendAction.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Tooling/Tooling.h"
15#include "gtest/gtest.h"
16
17namespace clang {
18
19/// \brief Base class for sipmle RecursiveASTVisitor based tests.
20///
21/// This is a drop-in replacement for RecursiveASTVisitor itself, with the
22/// additional capability of running it over a snippet of code.
23///
24/// Visits template instantiations by default.
25///
26/// FIXME: Put into a common location.
27template <typename T>
28class TestVisitor : public clang::RecursiveASTVisitor<T> {
29public:
30 /// \brief Runs the current AST visitor over the given code.
31 bool runOver(StringRef Code) {
32 return tooling::runToolOnCode(new TestAction(this), Code);
33 }
34
35 bool shouldVisitTemplateInstantiations() const {
36 return true;
37 }
38
39protected:
40 clang::ASTContext *Context;
Manuel Klimekfad7f852012-04-19 08:48:53 +000041
42private:
43 class FindConsumer : public clang::ASTConsumer {
44 public:
45 FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
46
47 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
48 Visitor->TraverseDecl(Context.getTranslationUnitDecl());
49 }
50
51 private:
52 TestVisitor *Visitor;
53 };
54
55 class TestAction : public clang::ASTFrontendAction {
56 public:
57 TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
58
59 virtual clang::ASTConsumer* CreateASTConsumer(
60 clang::CompilerInstance& compiler, llvm::StringRef dummy) {
Manuel Klimekfad7f852012-04-19 08:48:53 +000061 Visitor->Context = &compiler.getASTContext();
62 /// TestConsumer will be deleted by the framework calling us.
63 return new FindConsumer(Visitor);
64 }
65
66 private:
67 TestVisitor *Visitor;
68 };
69};
70
71/// \brief A RecursiveASTVisitor for testing the RecursiveASTVisitor itself.
72///
73/// Allows simple creation of test visitors running matches on only a small
74/// subset of the Visit* methods.
75template <typename T>
76class ExpectedLocationVisitor : public TestVisitor<T> {
77public:
78 ExpectedLocationVisitor()
79 : ExpectedLine(0), ExpectedColumn(0), Found(false) {}
80
81 ~ExpectedLocationVisitor() {
82 EXPECT_TRUE(Found)
83 << "Expected \"" << ExpectedMatch << "\" at " << ExpectedLine
84 << ":" << ExpectedColumn << PartialMatches;
85 }
86
87 /// \brief Expect 'Match' to occur at the given 'Line' and 'Column'.
88 void ExpectMatch(Twine Match, unsigned Line, unsigned Column) {
89 ExpectedMatch = Match.str();
90 ExpectedLine = Line;
91 ExpectedColumn = Column;
92 }
93
94protected:
95 /// \brief Convenience method to simplify writing test visitors.
96 ///
97 /// Sets 'Found' to true if 'Name' and 'Location' match the expected
98 /// values. If only a partial match is found, record the information
99 /// to produce nice error output when a test fails.
100 ///
101 /// Implementations are required to call this with appropriate values
102 /// for 'Name' during visitation.
103 void Match(StringRef Name, SourceLocation Location) {
104 FullSourceLoc FullLocation = this->Context->getFullLoc(Location);
105 if (Name == ExpectedMatch &&
106 FullLocation.isValid() &&
107 FullLocation.getSpellingLineNumber() == ExpectedLine &&
108 FullLocation.getSpellingColumnNumber() == ExpectedColumn) {
Manuel Klimek9f99d062012-04-23 16:40:40 +0000109 EXPECT_TRUE(!Found);
Manuel Klimekfad7f852012-04-19 08:48:53 +0000110 Found = true;
111 } else if (Name == ExpectedMatch ||
112 (FullLocation.isValid() &&
113 FullLocation.getSpellingLineNumber() == ExpectedLine &&
114 FullLocation.getSpellingColumnNumber() == ExpectedColumn)) {
115 // If we did not match, record information about partial matches.
116 llvm::raw_string_ostream Stream(PartialMatches);
117 Stream << ", partial match: \"" << Name << "\" at ";
Manuel Klimekdab28942012-04-20 14:07:01 +0000118 Location.print(Stream, this->Context->getSourceManager());
Manuel Klimekfad7f852012-04-19 08:48:53 +0000119 }
120 }
121
122 std::string ExpectedMatch;
123 unsigned ExpectedLine;
124 unsigned ExpectedColumn;
125 std::string PartialMatches;
126 bool Found;
127};
128
129class TypeLocVisitor : public ExpectedLocationVisitor<TypeLocVisitor> {
130public:
131 bool VisitTypeLoc(TypeLoc TypeLocation) {
132 Match(TypeLocation.getType().getAsString(), TypeLocation.getBeginLoc());
133 return true;
134 }
135};
136
137class DeclRefExprVisitor : public ExpectedLocationVisitor<DeclRefExprVisitor> {
138public:
139 bool VisitDeclRefExpr(DeclRefExpr *Reference) {
140 Match(Reference->getNameInfo().getAsString(), Reference->getLocation());
141 return true;
142 }
143};
144
Daniel Jasper52ec0c02012-06-13 07:12:33 +0000145class VarDeclVisitor : public ExpectedLocationVisitor<VarDeclVisitor> {
146public:
147 bool VisitVarDecl(VarDecl *Variable) {
148 Match(Variable->getNameAsString(), Variable->getLocStart());
149 return true;
150 }
151};
152
Manuel Klimekfad7f852012-04-19 08:48:53 +0000153class CXXMemberCallVisitor
154 : public ExpectedLocationVisitor<CXXMemberCallVisitor> {
155public:
156 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *Call) {
157 Match(Call->getMethodDecl()->getQualifiedNameAsString(),
158 Call->getLocStart());
159 return true;
160 }
161};
162
Richard Smitha313b2f2012-04-25 22:57:25 +0000163class NamedDeclVisitor
164 : public ExpectedLocationVisitor<NamedDeclVisitor> {
165public:
166 bool VisitNamedDecl(NamedDecl *Decl) {
167 std::string NameWithTemplateArgs;
168 Decl->getNameForDiagnostic(NameWithTemplateArgs,
169 Decl->getASTContext().getPrintingPolicy(),
170 true);
171 Match(NameWithTemplateArgs, Decl->getLocation());
172 return true;
173 }
174};
175
Richard Smithc8c22282012-05-02 00:30:48 +0000176class CXXOperatorCallExprTraverser
177 : public ExpectedLocationVisitor<CXXOperatorCallExprTraverser> {
178public:
179 // Use Traverse, not Visit, to check that data recursion optimization isn't
180 // bypassing the call of this function.
181 bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
182 Match(getOperatorSpelling(CE->getOperator()), CE->getExprLoc());
183 return ExpectedLocationVisitor<CXXOperatorCallExprTraverser>::
184 TraverseCXXOperatorCallExpr(CE);
185 }
186};
187
188class ParenExprVisitor : public ExpectedLocationVisitor<ParenExprVisitor> {
189public:
190 bool VisitParenExpr(ParenExpr *Parens) {
191 Match("", Parens->getExprLoc());
192 return true;
193 }
194};
195
Richard Smith6fada8e2012-05-30 23:55:51 +0000196class TemplateArgumentLocTraverser
197 : public ExpectedLocationVisitor<TemplateArgumentLocTraverser> {
198public:
199 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
200 std::string ArgStr;
201 llvm::raw_string_ostream Stream(ArgStr);
202 const TemplateArgument &Arg = ArgLoc.getArgument();
203
204 Arg.print(Context->getPrintingPolicy(), Stream);
205 Match(Stream.str(), ArgLoc.getLocation());
206 return ExpectedLocationVisitor<TemplateArgumentLocTraverser>::
207 TraverseTemplateArgumentLoc(ArgLoc);
208 }
209};
210
211class CXXBoolLiteralExprVisitor
212 : public ExpectedLocationVisitor<CXXBoolLiteralExprVisitor> {
213public:
214 bool VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *BE) {
215 if (BE->getValue())
216 Match("true", BE->getLocation());
217 else
218 Match("false", BE->getLocation());
219 return true;
220 }
221};
222
Manuel Klimekfad7f852012-04-19 08:48:53 +0000223TEST(RecursiveASTVisitor, VisitsBaseClassDeclarations) {
224 TypeLocVisitor Visitor;
225 Visitor.ExpectMatch("class X", 1, 30);
226 EXPECT_TRUE(Visitor.runOver("class X {}; class Y : public X {};"));
227}
228
Manuel Klimek9f99d062012-04-23 16:40:40 +0000229TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersOfForwardDeclaredClass) {
230 TypeLocVisitor Visitor;
231 Visitor.ExpectMatch("class X", 3, 18);
232 EXPECT_TRUE(Visitor.runOver(
233 "class Y;\n"
234 "class X {};\n"
235 "class Y : public X {};"));
236}
237
238TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersWithIncompleteInnerClass) {
239 TypeLocVisitor Visitor;
240 Visitor.ExpectMatch("class X", 2, 18);
241 EXPECT_TRUE(Visitor.runOver(
242 "class X {};\n"
243 "class Y : public X { class Z; };"));
244}
245
246TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersOfSelfReferentialType) {
247 TypeLocVisitor Visitor;
248 Visitor.ExpectMatch("X<class Y>", 2, 18);
249 EXPECT_TRUE(Visitor.runOver(
250 "template<typename T> class X {};\n"
251 "class Y : public X<Y> {};"));
252}
253
Manuel Klimekfad7f852012-04-19 08:48:53 +0000254TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArguments) {
255 DeclRefExprVisitor Visitor;
256 Visitor.ExpectMatch("x", 2, 3);
257 EXPECT_TRUE(Visitor.runOver(
258 "void x(); template <void (*T)()> class X {};\nX<x> y;"));
259}
260
Daniel Jasper52ec0c02012-06-13 07:12:33 +0000261TEST(RecursiveASTVisitor, VisitsCXXForRangeStmtRange) {
262 DeclRefExprVisitor Visitor;
263 Visitor.ExpectMatch("x", 2, 25);
Daniel Jasper1071ba92012-06-21 08:50:04 +0000264 Visitor.ExpectMatch("x", 2, 30);
Daniel Jasper52ec0c02012-06-13 07:12:33 +0000265 EXPECT_TRUE(Visitor.runOver(
266 "int x[5];\n"
Daniel Jasper1071ba92012-06-21 08:50:04 +0000267 "void f() { for (int i : x) { x[0] = 1; } }"));
Daniel Jasper52ec0c02012-06-13 07:12:33 +0000268}
269
270TEST(RecursiveASTVisitor, VisitsCXXForRangeStmtLoopVariable) {
271 VarDeclVisitor Visitor;
272 Visitor.ExpectMatch("i", 2, 17);
273 EXPECT_TRUE(Visitor.runOver(
274 "int x[5];\n"
275 "void f() { for (int i : x) {} }"));
276}
277
Manuel Klimekfad7f852012-04-19 08:48:53 +0000278TEST(RecursiveASTVisitor, VisitsCallExpr) {
279 DeclRefExprVisitor Visitor;
280 Visitor.ExpectMatch("x", 1, 22);
281 EXPECT_TRUE(Visitor.runOver(
282 "void x(); void y() { x(); }"));
283}
284
285TEST(RecursiveASTVisitor, VisitsCallInTemplateInstantiation) {
286 CXXMemberCallVisitor Visitor;
287 Visitor.ExpectMatch("Y::x", 3, 3);
288 EXPECT_TRUE(Visitor.runOver(
289 "struct Y { void x(); };\n"
290 "template<typename T> void y(T t) {\n"
291 " t.x();\n"
292 "}\n"
293 "void foo() { y<Y>(Y()); }"));
294}
295
Richard Smith5482dc32012-04-24 20:39:49 +0000296TEST(RecursiveASTVisitor, VisitsCallInNestedFunctionTemplateInstantiation) {
Manuel Klimekfad7f852012-04-19 08:48:53 +0000297 CXXMemberCallVisitor Visitor;
298 Visitor.ExpectMatch("Y::x", 4, 5);
299 EXPECT_TRUE(Visitor.runOver(
300 "struct Y { void x(); };\n"
301 "template<typename T> struct Z {\n"
302 " template<typename U> static void f() {\n"
303 " T().x();\n"
304 " }\n"
305 "};\n"
306 "void foo() { Z<Y>::f<int>(); }"));
307}
Richard Smith5482dc32012-04-24 20:39:49 +0000308
309TEST(RecursiveASTVisitor, VisitsCallInNestedClassTemplateInstantiation) {
310 CXXMemberCallVisitor Visitor;
311 Visitor.ExpectMatch("A::x", 5, 7);
312 EXPECT_TRUE(Visitor.runOver(
313 "template <typename T1> struct X {\n"
314 " template <typename T2> struct Y {\n"
315 " void f() {\n"
316 " T2 y;\n"
317 " y.x();\n"
318 " }\n"
319 " };\n"
320 "};\n"
321 "struct A { void x(); };\n"
322 "int main() {\n"
323 " (new X<A>::Y<A>())->f();\n"
324 "}"));
325}
Manuel Klimekfad7f852012-04-19 08:48:53 +0000326
327/* FIXME: According to Richard Smith this is a bug in the AST.
328TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArgumentsInInstantiation) {
329 DeclRefExprVisitor Visitor;
330 Visitor.ExpectMatch("x", 3, 43);
331 EXPECT_TRUE(Visitor.runOver(
332 "template <typename T> void x();\n"
333 "template <void (*T)()> class X {};\n"
334 "template <typename T> class Y : public X< x<T> > {};\n"
335 "Y<int> y;"));
336}
337*/
338
Richard Smitha313b2f2012-04-25 22:57:25 +0000339TEST(RecursiveASTVisitor, VisitsCallInPartialTemplateSpecialization) {
340 CXXMemberCallVisitor Visitor;
341 Visitor.ExpectMatch("A::x", 6, 20);
342 EXPECT_TRUE(Visitor.runOver(
343 "template <typename T1> struct X {\n"
344 " template <typename T2, bool B> struct Y { void g(); };\n"
345 "};\n"
346 "template <typename T1> template <typename T2>\n"
347 "struct X<T1>::Y<T2, true> {\n"
348 " void f() { T2 y; y.x(); }\n"
349 "};\n"
350 "struct A { void x(); };\n"
351 "int main() {\n"
352 " (new X<A>::Y<A, true>())->f();\n"
353 "}\n"));
354}
355
Richard Smith06cd51a2012-05-09 23:51:36 +0000356TEST(RecursiveASTVisitor, VisitsExplicitTemplateSpecialization) {
357 CXXMemberCallVisitor Visitor;
358 Visitor.ExpectMatch("A::f", 4, 5);
359 EXPECT_TRUE(Visitor.runOver(
360 "struct A {\n"
361 " void f() const {}\n"
362 " template<class T> void g(const T& t) const {\n"
363 " t.f();\n"
364 " }\n"
365 "};\n"
366 "template void A::g(const A& a) const;\n"));
367}
368
Richard Smitha313b2f2012-04-25 22:57:25 +0000369TEST(RecursiveASTVisitor, VisitsPartialTemplateSpecialization) {
370 // From cfe-commits/Week-of-Mon-20100830/033998.html
Daniel Jaspere966bea2012-05-30 04:30:08 +0000371 // Contrary to the approach suggested in that email, we visit all
Richard Smitha313b2f2012-04-25 22:57:25 +0000372 // specializations when we visit the primary template. Visiting them when we
373 // visit the associated specialization is problematic for specializations of
374 // template members of class templates.
375 NamedDeclVisitor Visitor;
376 Visitor.ExpectMatch("A<bool>", 1, 26);
377 Visitor.ExpectMatch("A<char *>", 2, 26);
378 EXPECT_TRUE(Visitor.runOver(
379 "template <class T> class A {};\n"
380 "template <class T> class A<T*> {};\n"
381 "A<bool> ab;\n"
382 "A<char*> acp;\n"));
383}
384
385TEST(RecursiveASTVisitor, VisitsUndefinedClassTemplateSpecialization) {
386 NamedDeclVisitor Visitor;
387 Visitor.ExpectMatch("A<int>", 1, 29);
388 EXPECT_TRUE(Visitor.runOver(
389 "template<typename T> struct A;\n"
390 "A<int> *p;\n"));
391}
392
393TEST(RecursiveASTVisitor, VisitsNestedUndefinedClassTemplateSpecialization) {
394 NamedDeclVisitor Visitor;
395 Visitor.ExpectMatch("A<int>::B<char>", 2, 31);
396 EXPECT_TRUE(Visitor.runOver(
397 "template<typename T> struct A {\n"
398 " template<typename U> struct B;\n"
399 "};\n"
400 "A<int>::B<char> *p;\n"));
401}
402
403TEST(RecursiveASTVisitor, VisitsUndefinedFunctionTemplateSpecialization) {
404 NamedDeclVisitor Visitor;
405 Visitor.ExpectMatch("A<int>", 1, 26);
406 EXPECT_TRUE(Visitor.runOver(
407 "template<typename T> int A();\n"
408 "int k = A<int>();\n"));
409}
410
411TEST(RecursiveASTVisitor, VisitsNestedUndefinedFunctionTemplateSpecialization) {
412 NamedDeclVisitor Visitor;
413 Visitor.ExpectMatch("A<int>::B<char>", 2, 35);
414 EXPECT_TRUE(Visitor.runOver(
415 "template<typename T> struct A {\n"
416 " template<typename U> static int B();\n"
417 "};\n"
418 "int k = A<int>::B<char>();\n"));
419}
420
421TEST(RecursiveASTVisitor, NoRecursionInSelfFriend) {
422 // From cfe-commits/Week-of-Mon-20100830/033977.html
423 NamedDeclVisitor Visitor;
424 Visitor.ExpectMatch("vector_iterator<int>", 2, 7);
425 EXPECT_TRUE(Visitor.runOver(
426 "template<typename Container>\n"
427 "class vector_iterator {\n"
428 " template <typename C> friend class vector_iterator;\n"
429 "};\n"
430 "vector_iterator<int> it_int;\n"));
431}
432
Richard Smithc8c22282012-05-02 00:30:48 +0000433TEST(RecursiveASTVisitor, TraversesOverloadedOperator) {
434 CXXOperatorCallExprTraverser Visitor;
435 Visitor.ExpectMatch("()", 4, 9);
436 EXPECT_TRUE(Visitor.runOver(
437 "struct A {\n"
438 " int operator()();\n"
439 "} a;\n"
440 "int k = a();\n"));
441}
442
443TEST(RecursiveASTVisitor, VisitsParensDuringDataRecursion) {
444 ParenExprVisitor Visitor;
445 Visitor.ExpectMatch("", 1, 9);
446 EXPECT_TRUE(Visitor.runOver("int k = (4) + 9;\n"));
447}
448
Richard Smith6fada8e2012-05-30 23:55:51 +0000449TEST(RecursiveASTVisitor, VisitsClassTemplateNonTypeParmDefaultArgument) {
450 CXXBoolLiteralExprVisitor Visitor;
451 Visitor.ExpectMatch("true", 2, 19);
452 EXPECT_TRUE(Visitor.runOver(
453 "template<bool B> class X;\n"
454 "template<bool B = true> class Y;\n"
455 "template<bool B> class Y {};\n"));
456}
457
458TEST(RecursiveASTVisitor, VisitsClassTemplateTypeParmDefaultArgument) {
459 TypeLocVisitor Visitor;
460 Visitor.ExpectMatch("class X", 2, 23);
461 EXPECT_TRUE(Visitor.runOver(
462 "class X;\n"
463 "template<typename T = X> class Y;\n"
464 "template<typename T> class Y {};\n"));
465}
466
467TEST(RecursiveASTVisitor, VisitsClassTemplateTemplateParmDefaultArgument) {
468 TemplateArgumentLocTraverser Visitor;
469 Visitor.ExpectMatch("X", 2, 40);
470 EXPECT_TRUE(Visitor.runOver(
471 "template<typename T> class X;\n"
472 "template<template <typename> class T = X> class Y;\n"
473 "template<template <typename> class T> class Y {};\n"));
474}
475
Richard Smithc28a3352012-06-05 16:18:26 +0000476// A visitor that visits implicit declarations and matches constructors.
477class ImplicitCtorVisitor
478 : public ExpectedLocationVisitor<ImplicitCtorVisitor> {
479public:
Daniel Jasper52ec0c02012-06-13 07:12:33 +0000480 bool shouldVisitImplicitCode() const { return true; }
Richard Smithc28a3352012-06-05 16:18:26 +0000481
482 bool VisitCXXConstructorDecl(CXXConstructorDecl* Ctor) {
483 if (Ctor->isImplicit()) { // Was not written in source code
484 if (const CXXRecordDecl* Class = Ctor->getParent()) {
485 Match(Class->getName(), Ctor->getLocation());
486 }
487 }
488 return true;
489 }
490};
491
492TEST(RecursiveASTVisitor, VisitsImplicitCopyConstructors) {
493 ImplicitCtorVisitor Visitor;
494 Visitor.ExpectMatch("Simple", 2, 8);
495 // Note: Clang lazily instantiates implicit declarations, so we need
496 // to use them in order to force them to appear in the AST.
497 EXPECT_TRUE(Visitor.runOver(
498 "struct WithCtor { WithCtor(); }; \n"
499 "struct Simple { Simple(); WithCtor w; }; \n"
500 "int main() { Simple s; Simple t(s); }\n"));
501}
502
Manuel Klimekfad7f852012-04-19 08:48:53 +0000503} // end namespace clang