1 | //===- unittest/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp -------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "TestVisitor.h" |
10 | |
11 | using namespace clang; |
12 | |
13 | namespace { |
14 | |
15 | class Visitor : public ExpectedLocationVisitor<Visitor, clang::TestVisitor> { |
16 | public: |
17 | Visitor(ASTContext *Context) { this->Context = Context; } |
18 | |
19 | bool VisitTranslationUnitDecl(TranslationUnitDecl *D) { |
20 | auto &SM = D->getParentASTContext().getSourceManager(); |
21 | Match(Name: "TU" , Location: SM.getLocForStartOfFile(SM.getMainFileID())); |
22 | return true; |
23 | } |
24 | |
25 | bool VisitNamedDecl(NamedDecl *D) { |
26 | if (!D->isImplicit()) |
27 | Match(Name: D->getName(), Location: D->getLocation()); |
28 | return true; |
29 | } |
30 | }; |
31 | |
32 | TEST(RecursiveASTVisitor, RespectsTraversalScope) { |
33 | auto AST = tooling::buildASTFromCode( |
34 | Code: R"cpp( |
35 | struct foo { |
36 | struct bar { |
37 | struct baz {}; |
38 | }; |
39 | }; |
40 | )cpp" , |
41 | FileName: "foo.cpp" , PCHContainerOps: std::make_shared<PCHContainerOperations>()); |
42 | auto &Ctx = AST->getASTContext(); |
43 | auto &TU = *Ctx.getTranslationUnitDecl(); |
44 | auto &Foo = *TU.lookup(&Ctx.Idents.get(Name: "foo" )).front(); |
45 | auto &Bar = *cast<DeclContext>(Foo).lookup(&Ctx.Idents.get(Name: "bar" )).front(); |
46 | |
47 | Ctx.setTraversalScope({&Bar}); |
48 | |
49 | Visitor V(&Ctx); |
50 | V.ExpectMatch(Match: "TU" , Line: 1, Column: 1); |
51 | V.DisallowMatch(Match: "foo" , Line: 2, Column: 8); |
52 | V.ExpectMatch(Match: "bar" , Line: 3, Column: 10); |
53 | V.ExpectMatch(Match: "baz" , Line: 4, Column: 12); |
54 | V.TraverseAST(AST&: Ctx); |
55 | } |
56 | |
57 | } // end anonymous namespace |
58 | |