1 //===--- WalkAST.cpp - Find declaration references in the AST -------------===//
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 "AnalysisInternal.h"
10 #include "clang/AST/RecursiveASTVisitor.h"
11 
12 namespace clang {
13 namespace include_cleaner {
14 namespace {
15 using DeclCallback = llvm::function_ref<void(SourceLocation, NamedDecl &)>;
16 
17 class ASTWalker : public RecursiveASTVisitor<ASTWalker> {
18   DeclCallback Callback;
19 
report(SourceLocation Loc,NamedDecl * ND)20   void report(SourceLocation Loc, NamedDecl *ND) {
21     if (!ND || Loc.isInvalid())
22       return;
23     Callback(Loc, *cast<NamedDecl>(ND->getCanonicalDecl()));
24   }
25 
26 public:
ASTWalker(DeclCallback Callback)27   ASTWalker(DeclCallback Callback) : Callback(Callback) {}
28 
VisitTagTypeLoc(TagTypeLoc TTL)29   bool VisitTagTypeLoc(TagTypeLoc TTL) {
30     report(TTL.getNameLoc(), TTL.getDecl());
31     return true;
32   }
33 
VisitDeclRefExpr(DeclRefExpr * DRE)34   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
35     report(DRE->getLocation(), DRE->getFoundDecl());
36     return true;
37   }
38 };
39 
40 } // namespace
41 
walkAST(Decl & Root,DeclCallback Callback)42 void walkAST(Decl &Root, DeclCallback Callback) {
43   ASTWalker(Callback).TraverseDecl(&Root);
44 }
45 
46 } // namespace include_cleaner
47 } // namespace clang
48