blob: 9ad825f8cf2b86dff3032c16af40d17a3ecdf999 [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
145class CXXMemberCallVisitor
146 : public ExpectedLocationVisitor<CXXMemberCallVisitor> {
147public:
148 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *Call) {
149 Match(Call->getMethodDecl()->getQualifiedNameAsString(),
150 Call->getLocStart());
151 return true;
152 }
153};
154
Richard Smitha313b2f2012-04-25 22:57:25 +0000155class NamedDeclVisitor
156 : public ExpectedLocationVisitor<NamedDeclVisitor> {
157public:
158 bool VisitNamedDecl(NamedDecl *Decl) {
159 std::string NameWithTemplateArgs;
160 Decl->getNameForDiagnostic(NameWithTemplateArgs,
161 Decl->getASTContext().getPrintingPolicy(),
162 true);
163 Match(NameWithTemplateArgs, Decl->getLocation());
164 return true;
165 }
166};
167
Richard Smithc8c22282012-05-02 00:30:48 +0000168class CXXOperatorCallExprTraverser
169 : public ExpectedLocationVisitor<CXXOperatorCallExprTraverser> {
170public:
171 // Use Traverse, not Visit, to check that data recursion optimization isn't
172 // bypassing the call of this function.
173 bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
174 Match(getOperatorSpelling(CE->getOperator()), CE->getExprLoc());
175 return ExpectedLocationVisitor<CXXOperatorCallExprTraverser>::
176 TraverseCXXOperatorCallExpr(CE);
177 }
178};
179
180class ParenExprVisitor : public ExpectedLocationVisitor<ParenExprVisitor> {
181public:
182 bool VisitParenExpr(ParenExpr *Parens) {
183 Match("", Parens->getExprLoc());
184 return true;
185 }
186};
187
Richard Smith6fada8e2012-05-30 23:55:51 +0000188class TemplateArgumentLocTraverser
189 : public ExpectedLocationVisitor<TemplateArgumentLocTraverser> {
190public:
191 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
192 std::string ArgStr;
193 llvm::raw_string_ostream Stream(ArgStr);
194 const TemplateArgument &Arg = ArgLoc.getArgument();
195
196 Arg.print(Context->getPrintingPolicy(), Stream);
197 Match(Stream.str(), ArgLoc.getLocation());
198 return ExpectedLocationVisitor<TemplateArgumentLocTraverser>::
199 TraverseTemplateArgumentLoc(ArgLoc);
200 }
201};
202
203class CXXBoolLiteralExprVisitor
204 : public ExpectedLocationVisitor<CXXBoolLiteralExprVisitor> {
205public:
206 bool VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *BE) {
207 if (BE->getValue())
208 Match("true", BE->getLocation());
209 else
210 Match("false", BE->getLocation());
211 return true;
212 }
213};
214
Manuel Klimekfad7f852012-04-19 08:48:53 +0000215TEST(RecursiveASTVisitor, VisitsBaseClassDeclarations) {
216 TypeLocVisitor Visitor;
217 Visitor.ExpectMatch("class X", 1, 30);
218 EXPECT_TRUE(Visitor.runOver("class X {}; class Y : public X {};"));
219}
220
Manuel Klimek9f99d062012-04-23 16:40:40 +0000221TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersOfForwardDeclaredClass) {
222 TypeLocVisitor Visitor;
223 Visitor.ExpectMatch("class X", 3, 18);
224 EXPECT_TRUE(Visitor.runOver(
225 "class Y;\n"
226 "class X {};\n"
227 "class Y : public X {};"));
228}
229
230TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersWithIncompleteInnerClass) {
231 TypeLocVisitor Visitor;
232 Visitor.ExpectMatch("class X", 2, 18);
233 EXPECT_TRUE(Visitor.runOver(
234 "class X {};\n"
235 "class Y : public X { class Z; };"));
236}
237
238TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersOfSelfReferentialType) {
239 TypeLocVisitor Visitor;
240 Visitor.ExpectMatch("X<class Y>", 2, 18);
241 EXPECT_TRUE(Visitor.runOver(
242 "template<typename T> class X {};\n"
243 "class Y : public X<Y> {};"));
244}
245
Manuel Klimekfad7f852012-04-19 08:48:53 +0000246TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArguments) {
247 DeclRefExprVisitor Visitor;
248 Visitor.ExpectMatch("x", 2, 3);
249 EXPECT_TRUE(Visitor.runOver(
250 "void x(); template <void (*T)()> class X {};\nX<x> y;"));
251}
252
253TEST(RecursiveASTVisitor, VisitsCallExpr) {
254 DeclRefExprVisitor Visitor;
255 Visitor.ExpectMatch("x", 1, 22);
256 EXPECT_TRUE(Visitor.runOver(
257 "void x(); void y() { x(); }"));
258}
259
260TEST(RecursiveASTVisitor, VisitsCallInTemplateInstantiation) {
261 CXXMemberCallVisitor Visitor;
262 Visitor.ExpectMatch("Y::x", 3, 3);
263 EXPECT_TRUE(Visitor.runOver(
264 "struct Y { void x(); };\n"
265 "template<typename T> void y(T t) {\n"
266 " t.x();\n"
267 "}\n"
268 "void foo() { y<Y>(Y()); }"));
269}
270
Richard Smith5482dc32012-04-24 20:39:49 +0000271TEST(RecursiveASTVisitor, VisitsCallInNestedFunctionTemplateInstantiation) {
Manuel Klimekfad7f852012-04-19 08:48:53 +0000272 CXXMemberCallVisitor Visitor;
273 Visitor.ExpectMatch("Y::x", 4, 5);
274 EXPECT_TRUE(Visitor.runOver(
275 "struct Y { void x(); };\n"
276 "template<typename T> struct Z {\n"
277 " template<typename U> static void f() {\n"
278 " T().x();\n"
279 " }\n"
280 "};\n"
281 "void foo() { Z<Y>::f<int>(); }"));
282}
Richard Smith5482dc32012-04-24 20:39:49 +0000283
284TEST(RecursiveASTVisitor, VisitsCallInNestedClassTemplateInstantiation) {
285 CXXMemberCallVisitor Visitor;
286 Visitor.ExpectMatch("A::x", 5, 7);
287 EXPECT_TRUE(Visitor.runOver(
288 "template <typename T1> struct X {\n"
289 " template <typename T2> struct Y {\n"
290 " void f() {\n"
291 " T2 y;\n"
292 " y.x();\n"
293 " }\n"
294 " };\n"
295 "};\n"
296 "struct A { void x(); };\n"
297 "int main() {\n"
298 " (new X<A>::Y<A>())->f();\n"
299 "}"));
300}
Manuel Klimekfad7f852012-04-19 08:48:53 +0000301
302/* FIXME: According to Richard Smith this is a bug in the AST.
303TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArgumentsInInstantiation) {
304 DeclRefExprVisitor Visitor;
305 Visitor.ExpectMatch("x", 3, 43);
306 EXPECT_TRUE(Visitor.runOver(
307 "template <typename T> void x();\n"
308 "template <void (*T)()> class X {};\n"
309 "template <typename T> class Y : public X< x<T> > {};\n"
310 "Y<int> y;"));
311}
312*/
313
Richard Smitha313b2f2012-04-25 22:57:25 +0000314TEST(RecursiveASTVisitor, VisitsCallInPartialTemplateSpecialization) {
315 CXXMemberCallVisitor Visitor;
316 Visitor.ExpectMatch("A::x", 6, 20);
317 EXPECT_TRUE(Visitor.runOver(
318 "template <typename T1> struct X {\n"
319 " template <typename T2, bool B> struct Y { void g(); };\n"
320 "};\n"
321 "template <typename T1> template <typename T2>\n"
322 "struct X<T1>::Y<T2, true> {\n"
323 " void f() { T2 y; y.x(); }\n"
324 "};\n"
325 "struct A { void x(); };\n"
326 "int main() {\n"
327 " (new X<A>::Y<A, true>())->f();\n"
328 "}\n"));
329}
330
Richard Smith06cd51a2012-05-09 23:51:36 +0000331TEST(RecursiveASTVisitor, VisitsExplicitTemplateSpecialization) {
332 CXXMemberCallVisitor Visitor;
333 Visitor.ExpectMatch("A::f", 4, 5);
334 EXPECT_TRUE(Visitor.runOver(
335 "struct A {\n"
336 " void f() const {}\n"
337 " template<class T> void g(const T& t) const {\n"
338 " t.f();\n"
339 " }\n"
340 "};\n"
341 "template void A::g(const A& a) const;\n"));
342}
343
Richard Smitha313b2f2012-04-25 22:57:25 +0000344TEST(RecursiveASTVisitor, VisitsPartialTemplateSpecialization) {
345 // From cfe-commits/Week-of-Mon-20100830/033998.html
Daniel Jaspere966bea2012-05-30 04:30:08 +0000346 // Contrary to the approach suggested in that email, we visit all
Richard Smitha313b2f2012-04-25 22:57:25 +0000347 // specializations when we visit the primary template. Visiting them when we
348 // visit the associated specialization is problematic for specializations of
349 // template members of class templates.
350 NamedDeclVisitor Visitor;
351 Visitor.ExpectMatch("A<bool>", 1, 26);
352 Visitor.ExpectMatch("A<char *>", 2, 26);
353 EXPECT_TRUE(Visitor.runOver(
354 "template <class T> class A {};\n"
355 "template <class T> class A<T*> {};\n"
356 "A<bool> ab;\n"
357 "A<char*> acp;\n"));
358}
359
360TEST(RecursiveASTVisitor, VisitsUndefinedClassTemplateSpecialization) {
361 NamedDeclVisitor Visitor;
362 Visitor.ExpectMatch("A<int>", 1, 29);
363 EXPECT_TRUE(Visitor.runOver(
364 "template<typename T> struct A;\n"
365 "A<int> *p;\n"));
366}
367
368TEST(RecursiveASTVisitor, VisitsNestedUndefinedClassTemplateSpecialization) {
369 NamedDeclVisitor Visitor;
370 Visitor.ExpectMatch("A<int>::B<char>", 2, 31);
371 EXPECT_TRUE(Visitor.runOver(
372 "template<typename T> struct A {\n"
373 " template<typename U> struct B;\n"
374 "};\n"
375 "A<int>::B<char> *p;\n"));
376}
377
378TEST(RecursiveASTVisitor, VisitsUndefinedFunctionTemplateSpecialization) {
379 NamedDeclVisitor Visitor;
380 Visitor.ExpectMatch("A<int>", 1, 26);
381 EXPECT_TRUE(Visitor.runOver(
382 "template<typename T> int A();\n"
383 "int k = A<int>();\n"));
384}
385
386TEST(RecursiveASTVisitor, VisitsNestedUndefinedFunctionTemplateSpecialization) {
387 NamedDeclVisitor Visitor;
388 Visitor.ExpectMatch("A<int>::B<char>", 2, 35);
389 EXPECT_TRUE(Visitor.runOver(
390 "template<typename T> struct A {\n"
391 " template<typename U> static int B();\n"
392 "};\n"
393 "int k = A<int>::B<char>();\n"));
394}
395
396TEST(RecursiveASTVisitor, NoRecursionInSelfFriend) {
397 // From cfe-commits/Week-of-Mon-20100830/033977.html
398 NamedDeclVisitor Visitor;
399 Visitor.ExpectMatch("vector_iterator<int>", 2, 7);
400 EXPECT_TRUE(Visitor.runOver(
401 "template<typename Container>\n"
402 "class vector_iterator {\n"
403 " template <typename C> friend class vector_iterator;\n"
404 "};\n"
405 "vector_iterator<int> it_int;\n"));
406}
407
Richard Smithc8c22282012-05-02 00:30:48 +0000408TEST(RecursiveASTVisitor, TraversesOverloadedOperator) {
409 CXXOperatorCallExprTraverser Visitor;
410 Visitor.ExpectMatch("()", 4, 9);
411 EXPECT_TRUE(Visitor.runOver(
412 "struct A {\n"
413 " int operator()();\n"
414 "} a;\n"
415 "int k = a();\n"));
416}
417
418TEST(RecursiveASTVisitor, VisitsParensDuringDataRecursion) {
419 ParenExprVisitor Visitor;
420 Visitor.ExpectMatch("", 1, 9);
421 EXPECT_TRUE(Visitor.runOver("int k = (4) + 9;\n"));
422}
423
Richard Smith6fada8e2012-05-30 23:55:51 +0000424TEST(RecursiveASTVisitor, VisitsClassTemplateNonTypeParmDefaultArgument) {
425 CXXBoolLiteralExprVisitor Visitor;
426 Visitor.ExpectMatch("true", 2, 19);
427 EXPECT_TRUE(Visitor.runOver(
428 "template<bool B> class X;\n"
429 "template<bool B = true> class Y;\n"
430 "template<bool B> class Y {};\n"));
431}
432
433TEST(RecursiveASTVisitor, VisitsClassTemplateTypeParmDefaultArgument) {
434 TypeLocVisitor Visitor;
435 Visitor.ExpectMatch("class X", 2, 23);
436 EXPECT_TRUE(Visitor.runOver(
437 "class X;\n"
438 "template<typename T = X> class Y;\n"
439 "template<typename T> class Y {};\n"));
440}
441
442TEST(RecursiveASTVisitor, VisitsClassTemplateTemplateParmDefaultArgument) {
443 TemplateArgumentLocTraverser Visitor;
444 Visitor.ExpectMatch("X", 2, 40);
445 EXPECT_TRUE(Visitor.runOver(
446 "template<typename T> class X;\n"
447 "template<template <typename> class T = X> class Y;\n"
448 "template<template <typename> class T> class Y {};\n"));
449}
450
Manuel Klimekfad7f852012-04-19 08:48:53 +0000451} // end namespace clang