Debian Codegraph @

llvm-project/clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp

raw
1 //===--- LocateSymbol.cpp - Find locations providing a symbol -------------===//
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/Decl.h"
11 #include "clang/AST/DeclBase.h"
12 #include "clang/AST/DeclCXX.h"
13 #include "clang/AST/DeclTemplate.h"
14 #include "clang/Tooling/Inclusions/StandardLibrary.h"
15 #include "llvm/Support/Casting.h"
16 #include <utility>
17 #include <vector>
18
19 namespace clang::include_cleaner {
20 namespace {
21
22 template <typename T> Hints completeIfDefinition(T *D) {
23 return D->isThisDeclarationADefinition() ? Hints::CompleteSymbol
24 : Hints::None;
25 }
26
27 Hints declHints(const Decl *D) {
28 // Definition is only needed for classes and templates for completeness.
29 if (auto *TD = llvm::dyn_cast<TagDecl>(D))
30 return completeIfDefinition(TD);
31 else if (auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(D))
32 return completeIfDefinition(CTD);
33 else if (auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
34 return completeIfDefinition(FTD);
35 // Any other declaration is assumed usable.
36 return Hints::CompleteSymbol;
37 }
38
39 std::vector<Hinted<SymbolLocation>> locateDecl(const Decl &D) {
40 std::vector<Hinted<SymbolLocation>> Result;
41 // FIXME: Should we also provide physical locations?
42 if (auto SS = tooling::stdlib::Recognizer()(&D))
43 return {{*SS, Hints::CompleteSymbol}};
44 // FIXME: Signal foreign decls, e.g. a forward declaration not owned by a
45 // library. Some useful signals could be derived by checking the DeclContext.
46 // Most incidental forward decls look like:
47 // namespace clang {
48 // class SourceManager; // likely an incidental forward decl.
49 // namespace my_own_ns {}
50 // }
51 for (auto *Redecl : D.redecls())
52 Result.push_back({Redecl->getLocation(), declHints(Redecl)});
53 return Result;
54 }
55
56 } // namespace
57
58 std::vector<Hinted<SymbolLocation>> locateSymbol(const Symbol &S) {
59 switch (S.kind()) {
60 case Symbol::Declaration:
61 return locateDecl(S.declaration());
62 case Symbol::Macro:
63 return {{S.macro().Definition, Hints::CompleteSymbol}};
64 }
65 llvm_unreachable("Unknown Symbol::Kind enum");
66 }
67
68 } // namespace clang::include_cleaner