Debian Codegraph @

llvm-project/clang-tools-extra/clang-doc/Representation.cpp

raw
1 ///===-- Representation.cpp - ClangDoc Representation -----------*- 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 // This file defines the merging of different types of infos. The data in the
10 // calling Info is preserved during a merge unless that field is empty or
11 // default. In that case, the data from the parameter Info is used to replace
12 // the empty or default data.
13 //
14 // For most fields, the first decl seen provides the data. Exceptions to this
15 // include the location and description fields, which are collections of data on
16 // all decls related to a given definition. All other fields are ignored in new
17 // decls unless the first seen decl didn't, for whatever reason, incorporate
18 // data on that field (e.g. a forward declared class wouldn't have information
19 // on members on the forward declaration, but would have the class name).
20 //
21 //===----------------------------------------------------------------------===//
22 #include "Representation.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/Path.h"
25
26 namespace clang {
27 namespace doc {
28
29 namespace {
30
31 const SymbolID EmptySID = SymbolID();
32
33 template <typename T>
34 llvm::Expected<std::unique_ptr<Info>>
35 reduce(std::vector<std::unique_ptr<Info>> &Values) {
36 if (Values.empty() || !Values[0])
37 return llvm::createStringError(llvm::inconvertibleErrorCode(),
38 "no value to reduce");
39 std::unique_ptr<Info> Merged = std::make_unique<T>(Values[0]->USR);
40 T *Tmp = static_cast<T *>(Merged.get());
41 for (auto &I : Values)
42 Tmp->merge(std::move(*static_cast<T *>(I.get())));
43 return std::move(Merged);
44 }
45
46 // Return the index of the matching child in the vector, or -1 if merge is not
47 // necessary.
48 template <typename T>
49 int getChildIndexIfExists(std::vector<T> &Children, T &ChildToMerge) {
50 for (unsigned long I = 0; I < Children.size(); I++) {
51 if (ChildToMerge.USR == Children[I].USR)
52 return I;
53 }
54 return -1;
55 }
56
57 void reduceChildren(std::vector<Reference> &Children,
58 std::vector<Reference> &&ChildrenToMerge) {
59 for (auto &ChildToMerge : ChildrenToMerge) {
60 int mergeIdx = getChildIndexIfExists(Children, ChildToMerge);
61 if (mergeIdx == -1) {
62 Children.push_back(std::move(ChildToMerge));
63 continue;
64 }
65 Children[mergeIdx].merge(std::move(ChildToMerge));
66 }
67 }
68
69 void reduceChildren(std::vector<FunctionInfo> &Children,
70 std::vector<FunctionInfo> &&ChildrenToMerge) {
71 for (auto &ChildToMerge : ChildrenToMerge) {
72 int mergeIdx = getChildIndexIfExists(Children, ChildToMerge);
73 if (mergeIdx == -1) {
74 Children.push_back(std::move(ChildToMerge));
75 continue;
76 }
77 Children[mergeIdx].merge(std::move(ChildToMerge));
78 }
79 }
80
81 void reduceChildren(std::vector<EnumInfo> &Children,
82 std::vector<EnumInfo> &&ChildrenToMerge) {
83 for (auto &ChildToMerge : ChildrenToMerge) {
84 int mergeIdx = getChildIndexIfExists(Children, ChildToMerge);
85 if (mergeIdx == -1) {
86 Children.push_back(std::move(ChildToMerge));
87 continue;
88 }
89 Children[mergeIdx].merge(std::move(ChildToMerge));
90 }
91 }
92
93 void reduceChildren(std::vector<TypedefInfo> &Children,
94 std::vector<TypedefInfo> &&ChildrenToMerge) {
95 for (auto &ChildToMerge : ChildrenToMerge) {
96 int mergeIdx = getChildIndexIfExists(Children, ChildToMerge);
97 if (mergeIdx == -1) {
98 Children.push_back(std::move(ChildToMerge));
99 continue;
100 }
101 Children[mergeIdx].merge(std::move(ChildToMerge));
102 }
103 }
104
105 } // namespace
106
107 // Dispatch function.
108 llvm::Expected<std::unique_ptr<Info>>
109 mergeInfos(std::vector<std::unique_ptr<Info>> &Values) {
110 if (Values.empty() || !Values[0])
111 return llvm::createStringError(llvm::inconvertibleErrorCode(),
112 "no info values to merge");
113
114 switch (Values[0]->IT) {
115 case InfoType::IT_namespace:
116 return reduce<NamespaceInfo>(Values);
117 case InfoType::IT_record:
118 return reduce<RecordInfo>(Values);
119 case InfoType::IT_enum:
120 return reduce<EnumInfo>(Values);
121 case InfoType::IT_function:
122 return reduce<FunctionInfo>(Values);
123 case InfoType::IT_typedef:
124 return reduce<TypedefInfo>(Values);
125 default:
126 return llvm::createStringError(llvm::inconvertibleErrorCode(),
127 "unexpected info type");
128 }
129 }
130
131 bool CommentInfo::operator==(const CommentInfo &Other) const {
132 auto FirstCI = std::tie(Kind, Text, Name, Direction, ParamName, CloseName,
133 SelfClosing, Explicit, AttrKeys, AttrValues, Args);
134 auto SecondCI =
135 std::tie(Other.Kind, Other.Text, Other.Name, Other.Direction,
136 Other.ParamName, Other.CloseName, Other.SelfClosing,
137 Other.Explicit, Other.AttrKeys, Other.AttrValues, Other.Args);
138
139 if (FirstCI != SecondCI || Children.size() != Other.Children.size())
140 return false;
141
142 return std::equal(Children.begin(), Children.end(), Other.Children.begin(),
143 llvm::deref<std::equal_to<>>{});
144 }
145
146 bool CommentInfo::operator<(const CommentInfo &Other) const {
147 auto FirstCI = std::tie(Kind, Text, Name, Direction, ParamName, CloseName,
148 SelfClosing, Explicit, AttrKeys, AttrValues, Args);
149 auto SecondCI =
150 std::tie(Other.Kind, Other.Text, Other.Name, Other.Direction,
151 Other.ParamName, Other.CloseName, Other.SelfClosing,
152 Other.Explicit, Other.AttrKeys, Other.AttrValues, Other.Args);
153
154 if (FirstCI < SecondCI)
155 return true;
156
157 if (FirstCI == SecondCI) {
158 return std::lexicographical_compare(
159 Children.begin(), Children.end(), Other.Children.begin(),
160 Other.Children.end(), llvm::deref<std::less<>>());
161 }
162
163 return false;
164 }
165
166 static llvm::SmallString<64>
167 calculateRelativeFilePath(const InfoType &Type, const StringRef &Path,
168 const StringRef &Name, const StringRef &CurrentPath) {
169 llvm::SmallString<64> FilePath;
170
171 if (CurrentPath != Path) {
172 // iterate back to the top
173 for (llvm::sys::path::const_iterator I =
174 llvm::sys::path::begin(CurrentPath);
175 I != llvm::sys::path::end(CurrentPath); ++I)
176 llvm::sys::path::append(FilePath, "..");
177 llvm::sys::path::append(FilePath, Path);
178 }
179
180 // Namespace references have a Path to the parent namespace, but
181 // the file is actually in the subdirectory for the namespace.
182 if (Type == doc::InfoType::IT_namespace)
183 llvm::sys::path::append(FilePath, Name);
184
185 return llvm::sys::path::relative_path(FilePath);
186 }
187
188 llvm::SmallString<64>
189 Reference::getRelativeFilePath(const StringRef &CurrentPath) const {
190 return calculateRelativeFilePath(RefType, Path, Name, CurrentPath);
191 }
192
193 llvm::SmallString<16> Reference::getFileBaseName() const {
194 if (RefType == InfoType::IT_namespace)
195 return llvm::SmallString<16>("index");
196
197 return Name;
198 }
199
200 llvm::SmallString<64>
201 Info::getRelativeFilePath(const StringRef &CurrentPath) const {
202 return calculateRelativeFilePath(IT, Path, extractName(), CurrentPath);
203 }
204
205 llvm::SmallString<16> Info::getFileBaseName() const {
206 if (IT == InfoType::IT_namespace)
207 return llvm::SmallString<16>("index");
208
209 return extractName();
210 }
211
212 bool Reference::mergeable(const Reference &Other) {
213 return RefType == Other.RefType && USR == Other.USR;
214 }
215
216 void Reference::merge(Reference &&Other) {
217 assert(mergeable(Other));
218 if (Name.empty())
219 Name = Other.Name;
220 if (Path.empty())
221 Path = Other.Path;
222 }
223
224 void Info::mergeBase(Info &&Other) {
225 assert(mergeable(Other));
226 if (USR == EmptySID)
227 USR = Other.USR;
228 if (Name == "")
229 Name = Other.Name;
230 if (Path == "")
231 Path = Other.Path;
232 if (Namespace.empty())
233 Namespace = std::move(Other.Namespace);
234 // Unconditionally extend the description, since each decl may have a comment.
235 std::move(Other.Description.begin(), Other.Description.end(),
236 std::back_inserter(Description));
237 llvm::sort(Description);
238 auto Last = std::unique(Description.begin(), Description.end());
239 Description.erase(Last, Description.end());
240 }
241
242 bool Info::mergeable(const Info &Other) {
243 return IT == Other.IT && USR == Other.USR;
244 }
245
246 void SymbolInfo::merge(SymbolInfo &&Other) {
247 assert(mergeable(Other));
248 if (!DefLoc)
249 DefLoc = std::move(Other.DefLoc);
250 // Unconditionally extend the list of locations, since we want all of them.
251 std::move(Other.Loc.begin(), Other.Loc.end(), std::back_inserter(Loc));
252 llvm::sort(Loc);
253 auto Last = std::unique(Loc.begin(), Loc.end());
254 Loc.erase(Last, Loc.end());
255 mergeBase(std::move(Other));
256 }
257
258 NamespaceInfo::NamespaceInfo(SymbolID USR, StringRef Name, StringRef Path)
259 : Info(InfoType::IT_namespace, USR, Name, Path) {}
260
261 void NamespaceInfo::merge(NamespaceInfo &&Other) {
262 assert(mergeable(Other));
263 // Reduce children if necessary.
264 reduceChildren(Children.Namespaces, std::move(Other.Children.Namespaces));
265 reduceChildren(Children.Records, std::move(Other.Children.Records));
266 reduceChildren(Children.Functions, std::move(Other.Children.Functions));
267 reduceChildren(Children.Enums, std::move(Other.Children.Enums));
268 reduceChildren(Children.Typedefs, std::move(Other.Children.Typedefs));
269 mergeBase(std::move(Other));
270 }
271
272 RecordInfo::RecordInfo(SymbolID USR, StringRef Name, StringRef Path)
273 : SymbolInfo(InfoType::IT_record, USR, Name, Path) {}
274
275 void RecordInfo::merge(RecordInfo &&Other) {
276 assert(mergeable(Other));
277 if (!TagType)
278 TagType = Other.TagType;
279 IsTypeDef = IsTypeDef || Other.IsTypeDef;
280 if (Members.empty())
281 Members = std::move(Other.Members);
282 if (Bases.empty())
283 Bases = std::move(Other.Bases);
284 if (Parents.empty())
285 Parents = std::move(Other.Parents);
286 if (VirtualParents.empty())
287 VirtualParents = std::move(Other.VirtualParents);
288 // Reduce children if necessary.
289 reduceChildren(Children.Records, std::move(Other.Children.Records));
290 reduceChildren(Children.Functions, std::move(Other.Children.Functions));
291 reduceChildren(Children.Enums, std::move(Other.Children.Enums));
292 reduceChildren(Children.Typedefs, std::move(Other.Children.Typedefs));
293 SymbolInfo::merge(std::move(Other));
294 if (!Template)
295 Template = Other.Template;
296 }
297
298 void EnumInfo::merge(EnumInfo &&Other) {
299 assert(mergeable(Other));
300 if (!Scoped)
301 Scoped = Other.Scoped;
302 if (Members.empty())
303 Members = std::move(Other.Members);
304 SymbolInfo::merge(std::move(Other));
305 }
306
307 void FunctionInfo::merge(FunctionInfo &&Other) {
308 assert(mergeable(Other));
309 if (!IsMethod)
310 IsMethod = Other.IsMethod;
311 if (!Access)
312 Access = Other.Access;
313 if (ReturnType.Type.USR == EmptySID && ReturnType.Type.Name == "")
314 ReturnType = std::move(Other.ReturnType);
315 if (Parent.USR == EmptySID && Parent.Name == "")
316 Parent = std::move(Other.Parent);
317 if (Params.empty())
318 Params = std::move(Other.Params);
319 SymbolInfo::merge(std::move(Other));
320 if (!Template)
321 Template = Other.Template;
322 }
323
324 void TypedefInfo::merge(TypedefInfo &&Other) {
325 assert(mergeable(Other));
326 if (!IsUsing)
327 IsUsing = Other.IsUsing;
328 if (Underlying.Type.Name == "")
329 Underlying = Other.Underlying;
330 SymbolInfo::merge(std::move(Other));
331 }
332
333 BaseRecordInfo::BaseRecordInfo() : RecordInfo() {}
334
335 BaseRecordInfo::BaseRecordInfo(SymbolID USR, StringRef Name, StringRef Path,
336 bool IsVirtual, AccessSpecifier Access,
337 bool IsParent)
338 : RecordInfo(USR, Name, Path), IsVirtual(IsVirtual), Access(Access),
339 IsParent(IsParent) {}
340
341 llvm::SmallString<16> Info::extractName() const {
342 if (!Name.empty())
343 return Name;
344
345 switch (IT) {
346 case InfoType::IT_namespace:
347 // Cover the case where the project contains a base namespace called
348 // 'GlobalNamespace' (i.e. a namespace at the same level as the global
349 // namespace, which would conflict with the hard-coded global namespace name
350 // below.)
351 if (Name == "GlobalNamespace" && Namespace.empty())
352 return llvm::SmallString<16>("@GlobalNamespace");
353 // The case of anonymous namespaces is taken care of in serialization,
354 // so here we can safely assume an unnamed namespace is the global
355 // one.
356 return llvm::SmallString<16>("GlobalNamespace");
357 case InfoType::IT_record:
358 return llvm::SmallString<16>("@nonymous_record_" +
359 toHex(llvm::toStringRef(USR)));
360 case InfoType::IT_enum:
361 return llvm::SmallString<16>("@nonymous_enum_" +
362 toHex(llvm::toStringRef(USR)));
363 case InfoType::IT_typedef:
364 return llvm::SmallString<16>("@nonymous_typedef_" +
365 toHex(llvm::toStringRef(USR)));
366 case InfoType::IT_function:
367 return llvm::SmallString<16>("@nonymous_function_" +
368 toHex(llvm::toStringRef(USR)));
369 case InfoType::IT_default:
370 return llvm::SmallString<16>("@nonymous_" + toHex(llvm::toStringRef(USR)));
371 }
372 llvm_unreachable("Invalid InfoType.");
373 return llvm::SmallString<16>("");
374 }
375
376 // Order is based on the Name attribute: case insensitive order
377 bool Index::operator<(const Index &Other) const {
378 // Loop through each character of both strings
379 for (unsigned I = 0; I < Name.size() && I < Other.Name.size(); ++I) {
380 // Compare them after converting both to lower case
381 int D = tolower(Name[I]) - tolower(Other.Name[I]);
382 if (D == 0)
383 continue;
384 return D < 0;
385 }
386 // If both strings have the size it means they would be equal if changed to
387 // lower case. In here, lower case will be smaller than upper case
388 // Example: string < stRing = true
389 // This is the opposite of how operator < handles strings
390 if (Name.size() == Other.Name.size())
391 return Name > Other.Name;
392 // If they are not the same size; the shorter string is smaller
393 return Name.size() < Other.Name.size();
394 }
395
396 void Index::sort() {
397 llvm::sort(Children);
398 for (auto &C : Children)
399 C.sort();
400 }
401
402 ClangDocContext::ClangDocContext(tooling::ExecutionContext *ECtx,
403 StringRef ProjectName, bool PublicOnly,
404 StringRef OutDirectory, StringRef SourceRoot,
405 StringRef RepositoryUrl,
406 std::vector<std::string> UserStylesheets,
407 std::vector<std::string> JsScripts)
408 : ECtx(ECtx), ProjectName(ProjectName), PublicOnly(PublicOnly),
409 OutDirectory(OutDirectory), UserStylesheets(UserStylesheets),
410 JsScripts(JsScripts) {
411 llvm::SmallString<128> SourceRootDir(SourceRoot);
412 if (SourceRoot.empty())
413 // If no SourceRoot was provided the current path is used as the default
414 llvm::sys::fs::current_path(SourceRootDir);
415 this->SourceRoot = std::string(SourceRootDir.str());
416 if (!RepositoryUrl.empty()) {
417 this->RepositoryUrl = std::string(RepositoryUrl);
418 if (!RepositoryUrl.empty() && RepositoryUrl.find("http://") != 0 &&
419 RepositoryUrl.find("https://") != 0)
420 this->RepositoryUrl->insert(0, "https://");
421 }
422 }
423
424 } // namespace doc
425 } // namespace clang