• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- TestVisitor.h ------------------------------------------*- C++ -*-===//
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 /// \file
11 /// \brief Defines utility templates for RecursiveASTVisitor related tests.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_TEST_VISITOR_H
16 #define LLVM_CLANG_TEST_VISITOR_H
17 
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/RecursiveASTVisitor.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/FrontendAction.h"
23 #include "clang/Tooling/Tooling.h"
24 #include "gtest/gtest.h"
25 #include <vector>
26 
27 namespace clang {
28 
29 /// \brief Base class for simple RecursiveASTVisitor based tests.
30 ///
31 /// This is a drop-in replacement for RecursiveASTVisitor itself, with the
32 /// additional capability of running it over a snippet of code.
33 ///
34 /// Visits template instantiations and implicit code by default.
35 template <typename T>
36 class TestVisitor : public RecursiveASTVisitor<T> {
37 public:
TestVisitor()38   TestVisitor() { }
39 
~TestVisitor()40   virtual ~TestVisitor() { }
41 
42   enum Language {
43     Lang_C,
44     Lang_CXX98,
45     Lang_CXX11,
46     Lang_OBJC,
47     Lang_OBJCXX11,
48     Lang_CXX = Lang_CXX98
49   };
50 
51   /// \brief Runs the current AST visitor over the given code.
52   bool runOver(StringRef Code, Language L = Lang_CXX) {
53     std::vector<std::string> Args;
54     switch (L) {
55       case Lang_C: Args.push_back("-std=c99"); break;
56       case Lang_CXX98: Args.push_back("-std=c++98"); break;
57       case Lang_CXX11: Args.push_back("-std=c++11"); break;
58       case Lang_OBJC: Args.push_back("-ObjC"); break;
59       case Lang_OBJCXX11:
60         Args.push_back("-ObjC++");
61         Args.push_back("-std=c++11");
62         Args.push_back("-fblocks");
63         break;
64     }
65     return tooling::runToolOnCodeWithArgs(CreateTestAction(), Code, Args);
66   }
67 
shouldVisitTemplateInstantiations()68   bool shouldVisitTemplateInstantiations() const {
69     return true;
70   }
71 
shouldVisitImplicitCode()72   bool shouldVisitImplicitCode() const {
73     return true;
74   }
75 
76 protected:
CreateTestAction()77   virtual ASTFrontendAction* CreateTestAction() {
78     return new TestAction(this);
79   }
80 
81   class FindConsumer : public ASTConsumer {
82   public:
FindConsumer(TestVisitor * Visitor)83     FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
84 
HandleTranslationUnit(clang::ASTContext & Context)85     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
86       Visitor->Context = &Context;
87       Visitor->TraverseDecl(Context.getTranslationUnitDecl());
88     }
89 
90   private:
91     TestVisitor *Visitor;
92   };
93 
94   class TestAction : public ASTFrontendAction {
95   public:
TestAction(TestVisitor * Visitor)96     TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
97 
CreateASTConsumer(CompilerInstance &,llvm::StringRef dummy)98     virtual clang::ASTConsumer* CreateASTConsumer(
99         CompilerInstance&, llvm::StringRef dummy) {
100       /// TestConsumer will be deleted by the framework calling us.
101       return new FindConsumer(Visitor);
102     }
103 
104   protected:
105     TestVisitor *Visitor;
106   };
107 
108   ASTContext *Context;
109 };
110 
111 /// \brief A RecursiveASTVisitor to check that certain matches are (or are
112 /// not) observed during visitation.
113 ///
114 /// This is a RecursiveASTVisitor for testing the RecursiveASTVisitor itself,
115 /// and allows simple creation of test visitors running matches on only a small
116 /// subset of the Visit* methods.
117 template <typename T, template <typename> class Visitor = TestVisitor>
118 class ExpectedLocationVisitor : public Visitor<T> {
119 public:
120   /// \brief Expect 'Match' *not* to occur at the given 'Line' and 'Column'.
121   ///
122   /// Any number of matches can be disallowed.
DisallowMatch(Twine Match,unsigned Line,unsigned Column)123   void DisallowMatch(Twine Match, unsigned Line, unsigned Column) {
124     DisallowedMatches.push_back(MatchCandidate(Match, Line, Column));
125   }
126 
127   /// \brief Expect 'Match' to occur at the given 'Line' and 'Column'.
128   ///
129   /// Any number of expected matches can be set by calling this repeatedly.
130   /// Each is expected to be matched exactly once.
ExpectMatch(Twine Match,unsigned Line,unsigned Column)131   void ExpectMatch(Twine Match, unsigned Line, unsigned Column) {
132     ExpectedMatches.push_back(ExpectedMatch(Match, Line, Column));
133   }
134 
135   /// \brief Checks that all expected matches have been found.
~ExpectedLocationVisitor()136   virtual ~ExpectedLocationVisitor() {
137     for (typename std::vector<ExpectedMatch>::const_iterator
138              It = ExpectedMatches.begin(), End = ExpectedMatches.end();
139          It != End; ++It) {
140       It->ExpectFound();
141     }
142   }
143 
144 protected:
145   /// \brief Checks an actual match against expected and disallowed matches.
146   ///
147   /// Implementations are required to call this with appropriate values
148   /// for 'Name' during visitation.
Match(StringRef Name,SourceLocation Location)149   void Match(StringRef Name, SourceLocation Location) {
150     const FullSourceLoc FullLocation = this->Context->getFullLoc(Location);
151 
152     for (typename std::vector<MatchCandidate>::const_iterator
153              It = DisallowedMatches.begin(), End = DisallowedMatches.end();
154          It != End; ++It) {
155       EXPECT_FALSE(It->Matches(Name, FullLocation))
156           << "Matched disallowed " << *It;
157     }
158 
159     for (typename std::vector<ExpectedMatch>::iterator
160              It = ExpectedMatches.begin(), End = ExpectedMatches.end();
161          It != End; ++It) {
162       It->UpdateFor(Name, FullLocation, this->Context->getSourceManager());
163     }
164   }
165 
166  private:
167   struct MatchCandidate {
168     std::string ExpectedName;
169     unsigned LineNumber;
170     unsigned ColumnNumber;
171 
MatchCandidateMatchCandidate172     MatchCandidate(Twine Name, unsigned LineNumber, unsigned ColumnNumber)
173       : ExpectedName(Name.str()), LineNumber(LineNumber),
174         ColumnNumber(ColumnNumber) {
175     }
176 
MatchesMatchCandidate177     bool Matches(StringRef Name, FullSourceLoc const &Location) const {
178       return MatchesName(Name) && MatchesLocation(Location);
179     }
180 
PartiallyMatchesMatchCandidate181     bool PartiallyMatches(StringRef Name, FullSourceLoc const &Location) const {
182       return MatchesName(Name) || MatchesLocation(Location);
183     }
184 
MatchesNameMatchCandidate185     bool MatchesName(StringRef Name) const {
186       return Name == ExpectedName;
187     }
188 
MatchesLocationMatchCandidate189     bool MatchesLocation(FullSourceLoc const &Location) const {
190       return Location.isValid() &&
191           Location.getSpellingLineNumber() == LineNumber &&
192           Location.getSpellingColumnNumber() == ColumnNumber;
193     }
194 
195     friend std::ostream &operator<<(std::ostream &Stream,
196                                     MatchCandidate const &Match) {
197       return Stream << Match.ExpectedName
198                     << " at " << Match.LineNumber << ":" << Match.ColumnNumber;
199     }
200   };
201 
202   struct ExpectedMatch {
ExpectedMatchExpectedMatch203     ExpectedMatch(Twine Name, unsigned LineNumber, unsigned ColumnNumber)
204       : Candidate(Name, LineNumber, ColumnNumber), Found(false) {}
205 
UpdateForExpectedMatch206     void UpdateFor(StringRef Name, FullSourceLoc Location, SourceManager &SM) {
207       if (Candidate.Matches(Name, Location)) {
208         EXPECT_TRUE(!Found);
209         Found = true;
210       } else if (!Found && Candidate.PartiallyMatches(Name, Location)) {
211         llvm::raw_string_ostream Stream(PartialMatches);
212         Stream << ", partial match: \"" << Name << "\" at ";
213         Location.print(Stream, SM);
214       }
215     }
216 
ExpectFoundExpectedMatch217     void ExpectFound() const {
218       EXPECT_TRUE(Found)
219           << "Expected \"" << Candidate.ExpectedName
220           << "\" at " << Candidate.LineNumber
221           << ":" << Candidate.ColumnNumber << PartialMatches;
222     }
223 
224     MatchCandidate Candidate;
225     std::string PartialMatches;
226     bool Found;
227   };
228 
229   std::vector<MatchCandidate> DisallowedMatches;
230   std::vector<ExpectedMatch> ExpectedMatches;
231 };
232 }
233 
234 #endif /* LLVM_CLANG_TEST_VISITOR_H */
235