1 //===- ASTSrcLocProcessor.cpp --------------------------------*- C++ -*----===//
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 "ASTSrcLocProcessor.h"
10 
11 #include "clang/Frontend/CompilerInstance.h"
12 #include "llvm/Support/JSON.h"
13 
14 using namespace clang::tooling;
15 using namespace llvm;
16 using namespace clang::ast_matchers;
17 
18 ASTSrcLocProcessor::ASTSrcLocProcessor(StringRef JsonPath)
19     : JsonPath(JsonPath) {
20 
21   MatchFinder::MatchFinderOptions FinderOptions;
22 
23   Finder = std::make_unique<MatchFinder>(std::move(FinderOptions));
24   Finder->addMatcher(
25       cxxRecordDecl(
26           isDefinition(),
27           isSameOrDerivedFrom(
28               // TODO: Extend this with other clades
29               namedDecl(hasName("clang::Stmt")).bind("nodeClade")),
30           optionally(isDerivedFrom(cxxRecordDecl().bind("derivedFrom"))))
31           .bind("className"),
32       this);
33 }
34 
35 std::unique_ptr<clang::ASTConsumer>
36 ASTSrcLocProcessor::createASTConsumer(clang::CompilerInstance &Compiler,
37                                       StringRef File) {
38   return Finder->newASTConsumer();
39 }
40 
41 llvm::json::Object toJSON(llvm::StringMap<std::vector<StringRef>> const &Obj) {
42   using llvm::json::toJSON;
43 
44   llvm::json::Object JsonObj;
45   for (const auto &Item : Obj) {
46     JsonObj[Item.first()] = Item.second;
47   }
48   return JsonObj;
49 }
50 
51 llvm::json::Object toJSON(llvm::StringMap<StringRef> const &Obj) {
52   using llvm::json::toJSON;
53 
54   llvm::json::Object JsonObj;
55   for (const auto &Item : Obj) {
56     JsonObj[Item.first()] = Item.second;
57   }
58   return JsonObj;
59 }
60 
61 llvm::json::Object toJSON(ClassData const &Obj) {
62   llvm::json::Object JsonObj;
63 
64   if (!Obj.ASTClassLocations.empty())
65     JsonObj["sourceLocations"] = Obj.ASTClassLocations;
66   if (!Obj.ASTClassRanges.empty())
67     JsonObj["sourceRanges"] = Obj.ASTClassRanges;
68   return JsonObj;
69 }
70 
71 llvm::json::Object toJSON(llvm::StringMap<ClassData> const &Obj) {
72   using llvm::json::toJSON;
73 
74   llvm::json::Object JsonObj;
75   for (const auto &Item : Obj) {
76     if (!Item.second.isEmpty())
77       JsonObj[Item.first()] = ::toJSON(Item.second);
78   }
79   return JsonObj;
80 }
81 
82 void WriteJSON(std::string JsonPath,
83                llvm::StringMap<StringRef> const &ClassInheritance,
84                llvm::StringMap<std::vector<StringRef>> const &ClassesInClade,
85                llvm::StringMap<ClassData> const &ClassEntries) {
86   llvm::json::Object JsonObj;
87 
88   using llvm::json::toJSON;
89 
90   JsonObj["classInheritance"] = ::toJSON(ClassInheritance);
91   JsonObj["classesInClade"] = ::toJSON(ClassesInClade);
92   JsonObj["classEntries"] = ::toJSON(ClassEntries);
93 
94   std::error_code EC;
95   llvm::raw_fd_ostream JsonOut(JsonPath, EC, llvm::sys::fs::F_Text);
96   if (EC)
97     return;
98 
99   llvm::json::Value JsonVal(std::move(JsonObj));
100   JsonOut << formatv("{0:2}", JsonVal);
101 }
102 
103 void ASTSrcLocProcessor::generate() {
104   WriteJSON(JsonPath, ClassInheritance, ClassesInClade, ClassEntries);
105 }
106 
107 std::vector<std::string>
108 CaptureMethods(std::string TypeString, const clang::CXXRecordDecl *ASTClass,
109                const MatchFinder::MatchResult &Result) {
110 
111   auto publicAccessor = [](auto... InnerMatcher) {
112     return cxxMethodDecl(isPublic(), parameterCountIs(0), isConst(),
113                          InnerMatcher...);
114   };
115 
116   auto BoundNodesVec =
117       match(findAll(publicAccessor(ofClass(equalsNode(ASTClass)),
118                                    returns(asString(TypeString)))
119                         .bind("classMethod")),
120             *ASTClass, *Result.Context);
121 
122   std::vector<std::string> Methods;
123   for (const auto &BN : BoundNodesVec) {
124     if (const auto *Node = BN.getNodeAs<clang::NamedDecl>("classMethod")) {
125       // Only record the getBeginLoc etc on Stmt etc, because it will call
126       // more-derived implementations pseudo-virtually.
127       if ((ASTClass->getName() != "Stmt" && ASTClass->getName() != "Decl") &&
128           (Node->getName() == "getBeginLoc" || Node->getName() == "getEndLoc" ||
129            Node->getName() == "getSourceRange")) {
130         continue;
131       }
132       // Only record the getExprLoc on Expr, because it will call
133       // more-derived implementations pseudo-virtually.
134       if (ASTClass->getName() != "Expr" && Node->getName() == "getExprLoc") {
135         continue;
136       }
137       Methods.push_back(Node->getName().str());
138     }
139   }
140   return Methods;
141 }
142 
143 void ASTSrcLocProcessor::run(const MatchFinder::MatchResult &Result) {
144 
145   if (const auto *ASTClass =
146           Result.Nodes.getNodeAs<clang::CXXRecordDecl>("className")) {
147 
148     StringRef ClassName = ASTClass->getName();
149 
150     ClassData CD;
151 
152     const auto *NodeClade =
153         Result.Nodes.getNodeAs<clang::CXXRecordDecl>("nodeClade");
154     StringRef CladeName = NodeClade->getName();
155 
156     if (const auto *DerivedFrom =
157             Result.Nodes.getNodeAs<clang::CXXRecordDecl>("derivedFrom"))
158       ClassInheritance[ClassName] = DerivedFrom->getName();
159 
160     CD.ASTClassLocations =
161         CaptureMethods("class clang::SourceLocation", ASTClass, Result);
162     CD.ASTClassRanges =
163         CaptureMethods("class clang::SourceRange", ASTClass, Result);
164 
165     if (!CD.isEmpty()) {
166       ClassEntries[ClassName] = CD;
167       ClassesInClade[CladeName].push_back(ClassName);
168     }
169   }
170 }
171