[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / clang-tools-extra / include-cleaner / lib / WalkAST.cpp
blobb7354fe300e0432d917e1ede407279516064052d
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 //===----------------------------------------------------------------------===//
9 #include "AnalysisInternal.h"
10 #include "clang/AST/RecursiveASTVisitor.h"
12 namespace clang {
13 namespace include_cleaner {
14 namespace {
15 using DeclCallback = llvm::function_ref<void(SourceLocation, NamedDecl &)>;
17 class ASTWalker : public RecursiveASTVisitor<ASTWalker> {
18 DeclCallback Callback;
20 void report(SourceLocation Loc, NamedDecl *ND) {
21 if (!ND || Loc.isInvalid())
22 return;
23 Callback(Loc, *cast<NamedDecl>(ND->getCanonicalDecl()));
26 public:
27 ASTWalker(DeclCallback Callback) : Callback(Callback) {}
29 bool VisitTagTypeLoc(TagTypeLoc TTL) {
30 report(TTL.getNameLoc(), TTL.getDecl());
31 return true;
34 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
35 report(DRE->getLocation(), DRE->getFoundDecl());
36 return true;
40 } // namespace
42 void walkAST(Decl &Root, DeclCallback Callback) {
43 ASTWalker(Callback).TraverseDecl(&Root);
46 } // namespace include_cleaner
47 } // namespace clang