• 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 (but not 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 { Lang_C, Lang_CXX };
43 
44   /// \brief Runs the current AST visitor over the given code.
45   bool runOver(StringRef Code, Language L = Lang_CXX) {
46     std::vector<std::string> Args;
47     switch (L) {
48       case Lang_C: Args.push_back("-std=c99"); break;
49       case Lang_CXX: Args.push_back("-std=c++98"); break;
50     }
51     return tooling::runToolOnCodeWithArgs(CreateTestAction(), Code, Args);
52   }
53 
shouldVisitTemplateInstantiations()54   bool shouldVisitTemplateInstantiations() const {
55     return true;
56   }
57 
58 protected:
CreateTestAction()59   virtual ASTFrontendAction* CreateTestAction() {
60     return new TestAction(this);
61   }
62 
63   class FindConsumer : public ASTConsumer {
64   public:
FindConsumer(TestVisitor * Visitor)65     FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
66 
HandleTranslationUnit(clang::ASTContext & Context)67     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
68       Visitor->Context = &Context;
69       Visitor->TraverseDecl(Context.getTranslationUnitDecl());
70     }
71 
72   private:
73     TestVisitor *Visitor;
74   };
75 
76   class TestAction : public ASTFrontendAction {
77   public:
TestAction(TestVisitor * Visitor)78     TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
79 
CreateASTConsumer(CompilerInstance &,llvm::StringRef dummy)80     virtual clang::ASTConsumer* CreateASTConsumer(
81         CompilerInstance&, llvm::StringRef dummy) {
82       /// TestConsumer will be deleted by the framework calling us.
83       return new FindConsumer(Visitor);
84     }
85 
86   protected:
87     TestVisitor *Visitor;
88   };
89 
90   ASTContext *Context;
91 };
92 
93 /// \brief A RecursiveASTVisitor to check that certain matches are (or are
94 /// not) observed during visitation.
95 ///
96 /// This is a RecursiveASTVisitor for testing the RecursiveASTVisitor itself,
97 /// and allows simple creation of test visitors running matches on only a small
98 /// subset of the Visit* methods.
99 template <typename T, template <typename> class Visitor = TestVisitor>
100 class ExpectedLocationVisitor : public Visitor<T> {
101 public:
102   /// \brief Expect 'Match' *not* to occur at the given 'Line' and 'Column'.
103   ///
104   /// Any number of matches can be disallowed.
DisallowMatch(Twine Match,unsigned Line,unsigned Column)105   void DisallowMatch(Twine Match, unsigned Line, unsigned Column) {
106     DisallowedMatches.push_back(MatchCandidate(Match, Line, Column));
107   }
108 
109   /// \brief Expect 'Match' to occur at the given 'Line' and 'Column'.
110   ///
111   /// Any number of expected matches can be set by calling this repeatedly.
112   /// Each is expected to be matched exactly once.
ExpectMatch(Twine Match,unsigned Line,unsigned Column)113   void ExpectMatch(Twine Match, unsigned Line, unsigned Column) {
114     ExpectedMatches.push_back(ExpectedMatch(Match, Line, Column));
115   }
116 
117   /// \brief Checks that all expected matches have been found.
~ExpectedLocationVisitor()118   virtual ~ExpectedLocationVisitor() {
119     for (typename std::vector<ExpectedMatch>::const_iterator
120              It = ExpectedMatches.begin(), End = ExpectedMatches.end();
121          It != End; ++It) {
122       It->ExpectFound();
123     }
124   }
125 
126 protected:
127   /// \brief Checks an actual match against expected and disallowed matches.
128   ///
129   /// Implementations are required to call this with appropriate values
130   /// for 'Name' during visitation.
Match(StringRef Name,SourceLocation Location)131   void Match(StringRef Name, SourceLocation Location) {
132     const FullSourceLoc FullLocation = this->Context->getFullLoc(Location);
133 
134     for (typename std::vector<MatchCandidate>::const_iterator
135              It = DisallowedMatches.begin(), End = DisallowedMatches.end();
136          It != End; ++It) {
137       EXPECT_FALSE(It->Matches(Name, FullLocation))
138           << "Matched disallowed " << *It;
139     }
140 
141     for (typename std::vector<ExpectedMatch>::iterator
142              It = ExpectedMatches.begin(), End = ExpectedMatches.end();
143          It != End; ++It) {
144       It->UpdateFor(Name, FullLocation, this->Context->getSourceManager());
145     }
146   }
147 
148  private:
149   struct MatchCandidate {
150     std::string ExpectedName;
151     unsigned LineNumber;
152     unsigned ColumnNumber;
153 
MatchCandidateMatchCandidate154     MatchCandidate(Twine Name, unsigned LineNumber, unsigned ColumnNumber)
155       : ExpectedName(Name.str()), LineNumber(LineNumber),
156         ColumnNumber(ColumnNumber) {
157     }
158 
MatchesMatchCandidate159     bool Matches(StringRef Name, FullSourceLoc const &Location) const {
160       return MatchesName(Name) && MatchesLocation(Location);
161     }
162 
PartiallyMatchesMatchCandidate163     bool PartiallyMatches(StringRef Name, FullSourceLoc const &Location) const {
164       return MatchesName(Name) || MatchesLocation(Location);
165     }
166 
MatchesNameMatchCandidate167     bool MatchesName(StringRef Name) const {
168       return Name == ExpectedName;
169     }
170 
MatchesLocationMatchCandidate171     bool MatchesLocation(FullSourceLoc const &Location) const {
172       return Location.isValid() &&
173           Location.getSpellingLineNumber() == LineNumber &&
174           Location.getSpellingColumnNumber() == ColumnNumber;
175     }
176 
177     friend std::ostream &operator<<(std::ostream &Stream,
178                                     MatchCandidate const &Match) {
179       return Stream << Match.ExpectedName
180                     << " at " << Match.LineNumber << ":" << Match.ColumnNumber;
181     }
182   };
183 
184   struct ExpectedMatch {
ExpectedMatchExpectedMatch185     ExpectedMatch(Twine Name, unsigned LineNumber, unsigned ColumnNumber)
186       : Candidate(Name, LineNumber, ColumnNumber), Found(false) {}
187 
UpdateForExpectedMatch188     void UpdateFor(StringRef Name, FullSourceLoc Location, SourceManager &SM) {
189       if (Candidate.Matches(Name, Location)) {
190         EXPECT_TRUE(!Found);
191         Found = true;
192       } else if (!Found && Candidate.PartiallyMatches(Name, Location)) {
193         llvm::raw_string_ostream Stream(PartialMatches);
194         Stream << ", partial match: \"" << Name << "\" at ";
195         Location.print(Stream, SM);
196       }
197     }
198 
ExpectFoundExpectedMatch199     void ExpectFound() const {
200       EXPECT_TRUE(Found)
201           << "Expected \"" << Candidate.ExpectedName
202           << "\" at " << Candidate.LineNumber
203           << ":" << Candidate.ColumnNumber << PartialMatches;
204     }
205 
206     MatchCandidate Candidate;
207     std::string PartialMatches;
208     bool Found;
209   };
210 
211   std::vector<MatchCandidate> DisallowedMatches;
212   std::vector<ExpectedMatch> ExpectedMatches;
213 };
214 }
215 
216 #endif /* LLVM_CLANG_TEST_VISITOR_H */
217