clang-tools 22.0.0git
Representation.cpp
Go to the documentation of this file.
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/ADT/StringMap.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/Path.h"
26
27namespace clang {
28namespace doc {
29
30CommentKind stringToCommentKind(llvm::StringRef KindStr) {
31 static const llvm::StringMap<CommentKind> KindMap = {
32 {"FullComment", CommentKind::CK_FullComment},
33 {"ParagraphComment", CommentKind::CK_ParagraphComment},
34 {"TextComment", CommentKind::CK_TextComment},
35 {"InlineCommandComment", CommentKind::CK_InlineCommandComment},
36 {"HTMLStartTagComment", CommentKind::CK_HTMLStartTagComment},
37 {"HTMLEndTagComment", CommentKind::CK_HTMLEndTagComment},
38 {"BlockCommandComment", CommentKind::CK_BlockCommandComment},
39 {"ParamCommandComment", CommentKind::CK_ParamCommandComment},
40 {"TParamCommandComment", CommentKind::CK_TParamCommandComment},
41 {"VerbatimBlockComment", CommentKind::CK_VerbatimBlockComment},
42 {"VerbatimBlockLineComment", CommentKind::CK_VerbatimBlockLineComment},
43 {"VerbatimLineComment", CommentKind::CK_VerbatimLineComment},
44 };
45
46 auto It = KindMap.find(KindStr);
47 if (It != KindMap.end()) {
48 return It->second;
49 }
51}
52
53llvm::StringRef commentKindToString(CommentKind Kind) {
54 switch (Kind) {
56 return "FullComment";
58 return "ParagraphComment";
60 return "TextComment";
62 return "InlineCommandComment";
64 return "HTMLStartTagComment";
66 return "HTMLEndTagComment";
68 return "BlockCommandComment";
70 return "ParamCommandComment";
72 return "TParamCommandComment";
74 return "VerbatimBlockComment";
76 return "VerbatimBlockLineComment";
78 return "VerbatimLineComment";
80 return "Unknown";
81 }
82 llvm_unreachable("Unhandled CommentKind");
83}
84
85const SymbolID EmptySID = SymbolID();
86
87template <typename T>
88static llvm::Expected<std::unique_ptr<Info>>
89reduce(std::vector<std::unique_ptr<Info>> &Values) {
90 if (Values.empty() || !Values[0])
91 return llvm::createStringError(llvm::inconvertibleErrorCode(),
92 "no value to reduce");
93 std::unique_ptr<Info> Merged = std::make_unique<T>(Values[0]->USR);
94 T *Tmp = static_cast<T *>(Merged.get());
95 for (auto &I : Values)
96 Tmp->merge(std::move(*static_cast<T *>(I.get())));
97 return std::move(Merged);
98}
99
100// Return the index of the matching child in the vector, or -1 if merge is not
101// necessary.
102template <typename T>
103static int getChildIndexIfExists(std::vector<T> &Children, T &ChildToMerge) {
104 for (unsigned long I = 0; I < Children.size(); I++) {
105 if (ChildToMerge.USR == Children[I].USR)
106 return I;
107 }
108 return -1;
109}
110
111template <typename T>
112static void reduceChildren(std::vector<T> &Children,
113 std::vector<T> &&ChildrenToMerge) {
114 for (auto &ChildToMerge : ChildrenToMerge) {
115 int MergeIdx = getChildIndexIfExists(Children, ChildToMerge);
116 if (MergeIdx == -1) {
117 Children.push_back(std::move(ChildToMerge));
118 continue;
119 }
120 Children[MergeIdx].merge(std::move(ChildToMerge));
121 }
122}
123
124// Dispatch function.
125llvm::Expected<std::unique_ptr<Info>>
126mergeInfos(std::vector<std::unique_ptr<Info>> &Values) {
127 if (Values.empty() || !Values[0])
128 return llvm::createStringError(llvm::inconvertibleErrorCode(),
129 "no info values to merge");
130
131 switch (Values[0]->IT) {
133 return reduce<NamespaceInfo>(Values);
135 return reduce<RecordInfo>(Values);
137 return reduce<EnumInfo>(Values);
139 return reduce<FunctionInfo>(Values);
141 return reduce<TypedefInfo>(Values);
143 return reduce<ConceptInfo>(Values);
145 return reduce<VarInfo>(Values);
147 return reduce<FriendInfo>(Values);
149 return llvm::createStringError(llvm::inconvertibleErrorCode(),
150 "unexpected info type");
151 }
152 llvm_unreachable("unhandled enumerator");
153}
154
155bool CommentInfo::operator==(const CommentInfo &Other) const {
156 auto FirstCI = std::tie(Kind, Text, Name, Direction, ParamName, CloseName,
158 auto SecondCI =
159 std::tie(Other.Kind, Other.Text, Other.Name, Other.Direction,
160 Other.ParamName, Other.CloseName, Other.SelfClosing,
161 Other.Explicit, Other.AttrKeys, Other.AttrValues, Other.Args);
162
163 if (FirstCI != SecondCI || Children.size() != Other.Children.size())
164 return false;
165
166 return std::equal(Children.begin(), Children.end(), Other.Children.begin(),
167 llvm::deref<std::equal_to<>>{});
168}
169
170bool CommentInfo::operator<(const CommentInfo &Other) const {
171 auto FirstCI = std::tie(Kind, Text, Name, Direction, ParamName, CloseName,
173 auto SecondCI =
174 std::tie(Other.Kind, Other.Text, Other.Name, Other.Direction,
175 Other.ParamName, Other.CloseName, Other.SelfClosing,
176 Other.Explicit, Other.AttrKeys, Other.AttrValues, Other.Args);
177
178 if (FirstCI < SecondCI)
179 return true;
180
181 if (FirstCI == SecondCI) {
182 return std::lexicographical_compare(
183 Children.begin(), Children.end(), Other.Children.begin(),
184 Other.Children.end(), llvm::deref<std::less<>>());
185 }
186
187 return false;
188}
189
190static llvm::SmallString<64>
191calculateRelativeFilePath(const InfoType &Type, const StringRef &Path,
192 const StringRef &Name, const StringRef &CurrentPath) {
193 llvm::SmallString<64> FilePath;
194
195 if (CurrentPath != Path) {
196 // iterate back to the top
197 for (llvm::sys::path::const_iterator I =
198 llvm::sys::path::begin(CurrentPath);
199 I != llvm::sys::path::end(CurrentPath); ++I)
200 llvm::sys::path::append(FilePath, "..");
201 llvm::sys::path::append(FilePath, Path);
202 }
203
204 // Namespace references have a Path to the parent namespace, but
205 // the file is actually in the subdirectory for the namespace.
206 if (Type == doc::InfoType::IT_namespace)
207 llvm::sys::path::append(FilePath, Name);
208
209 return llvm::sys::path::relative_path(FilePath);
210}
211
212llvm::SmallString<64>
213Reference::getRelativeFilePath(const StringRef &CurrentPath) const {
214 return calculateRelativeFilePath(RefType, Path, Name, CurrentPath);
215}
216
217llvm::SmallString<16> Reference::getFileBaseName() const {
219 return llvm::SmallString<16>("index");
220
221 return Name;
222}
223
224llvm::SmallString<64>
225Info::getRelativeFilePath(const StringRef &CurrentPath) const {
226 return calculateRelativeFilePath(IT, Path, extractName(), CurrentPath);
227}
228
229llvm::SmallString<16> Info::getFileBaseName() const {
231 return llvm::SmallString<16>("index");
232
233 return extractName();
234}
235
236bool Reference::mergeable(const Reference &Other) {
237 return RefType == Other.RefType && USR == Other.USR;
238}
239
241 assert(mergeable(Other));
242 if (Name.empty())
243 Name = Other.Name;
244 if (Path.empty())
245 Path = Other.Path;
246 if (DocumentationFileName.empty())
247 DocumentationFileName = Other.DocumentationFileName;
248}
249
251 return Ref.USR == Other.Ref.USR && Ref.Name == Other.Ref.Name;
252}
253
255 assert(mergeable(Other));
256 Ref.merge(std::move(Other.Ref));
257}
258
259void Info::mergeBase(Info &&Other) {
260 assert(mergeable(Other));
261 if (USR == EmptySID)
262 USR = Other.USR;
263 if (Name == "")
264 Name = Other.Name;
265 if (Path == "")
266 Path = Other.Path;
267 if (Namespace.empty())
268 Namespace = std::move(Other.Namespace);
269 // Unconditionally extend the description, since each decl may have a comment.
270 std::move(Other.Description.begin(), Other.Description.end(),
271 std::back_inserter(Description));
272 llvm::sort(Description);
273 auto Last = llvm::unique(Description);
274 Description.erase(Last, Description.end());
275}
276
277bool Info::mergeable(const Info &Other) {
278 return IT == Other.IT && USR == Other.USR;
279}
280
281void SymbolInfo::merge(SymbolInfo &&Other) {
282 assert(mergeable(Other));
283 if (!DefLoc)
284 DefLoc = std::move(Other.DefLoc);
285 // Unconditionally extend the list of locations, since we want all of them.
286 std::move(Other.Loc.begin(), Other.Loc.end(), std::back_inserter(Loc));
287 llvm::sort(Loc);
288 auto *Last = llvm::unique(Loc);
289 Loc.erase(Last, Loc.end());
290 mergeBase(std::move(Other));
291 if (MangledName.empty())
292 MangledName = std::move(Other.MangledName);
293}
294
297
299 assert(mergeable(Other));
300 // Reduce children if necessary.
301 reduceChildren(Children.Namespaces, std::move(Other.Children.Namespaces));
302 reduceChildren(Children.Records, std::move(Other.Children.Records));
303 reduceChildren(Children.Functions, std::move(Other.Children.Functions));
304 reduceChildren(Children.Enums, std::move(Other.Children.Enums));
305 reduceChildren(Children.Typedefs, std::move(Other.Children.Typedefs));
306 reduceChildren(Children.Concepts, std::move(Other.Children.Concepts));
307 reduceChildren(Children.Variables, std::move(Other.Children.Variables));
308 mergeBase(std::move(Other));
309}
310
313
315 assert(mergeable(Other));
316 if (!llvm::to_underlying(TagType))
317 TagType = Other.TagType;
318 IsTypeDef = IsTypeDef || Other.IsTypeDef;
319 if (Members.empty())
320 Members = std::move(Other.Members);
321 if (Bases.empty())
322 Bases = std::move(Other.Bases);
323 if (Parents.empty())
324 Parents = std::move(Other.Parents);
325 if (VirtualParents.empty())
326 VirtualParents = std::move(Other.VirtualParents);
327 if (Friends.empty())
328 Friends = std::move(Other.Friends);
329 // Reduce children if necessary.
330 reduceChildren(Children.Records, std::move(Other.Children.Records));
331 reduceChildren(Children.Functions, std::move(Other.Children.Functions));
332 reduceChildren(Children.Enums, std::move(Other.Children.Enums));
333 reduceChildren(Children.Typedefs, std::move(Other.Children.Typedefs));
334 SymbolInfo::merge(std::move(Other));
335 if (!Template)
336 Template = Other.Template;
337}
338
340 assert(mergeable(Other));
341 if (!Scoped)
342 Scoped = Other.Scoped;
343 if (Members.empty())
344 Members = std::move(Other.Members);
345 SymbolInfo::merge(std::move(Other));
346}
347
349 assert(mergeable(Other));
350 if (!IsMethod)
351 IsMethod = Other.IsMethod;
352 if (!Access)
353 Access = Other.Access;
354 if (ReturnType.Type.USR == EmptySID && ReturnType.Type.Name == "")
355 ReturnType = std::move(Other.ReturnType);
356 if (Parent.USR == EmptySID && Parent.Name == "")
357 Parent = std::move(Other.Parent);
358 if (Params.empty())
359 Params = std::move(Other.Params);
360 SymbolInfo::merge(std::move(Other));
361 if (!Template)
362 Template = Other.Template;
363}
364
366 assert(mergeable(Other));
367 if (!IsUsing)
368 IsUsing = Other.IsUsing;
369 if (Underlying.Type.Name == "")
370 Underlying = Other.Underlying;
371 SymbolInfo::merge(std::move(Other));
372}
373
375 assert(mergeable(Other));
376 if (!IsType)
377 IsType = Other.IsType;
378 if (ConstraintExpression.empty())
379 ConstraintExpression = std::move(Other.ConstraintExpression);
380 if (Template.Constraints.empty())
381 Template.Constraints = std::move(Other.Template.Constraints);
382 if (Template.Params.empty())
383 Template.Params = std::move(Other.Template.Params);
384 SymbolInfo::merge(std::move(Other));
385}
386
387void VarInfo::merge(VarInfo &&Other) {
388 assert(mergeable(Other));
389 if (!IsStatic)
390 IsStatic = Other.IsStatic;
391 if (Type.Type.USR == EmptySID && Type.Type.Name == "")
392 Type = std::move(Other.Type);
393 SymbolInfo::merge(std::move(Other));
394}
395
397
399 bool IsVirtual, AccessSpecifier Access,
400 bool IsParent)
403
404llvm::SmallString<16> Info::extractName() const {
405 if (!Name.empty())
406 return Name;
407
408 switch (IT) {
410 // Cover the case where the project contains a base namespace called
411 // 'GlobalNamespace' (i.e. a namespace at the same level as the global
412 // namespace, which would conflict with the hard-coded global namespace name
413 // below.)
414 if (Name == "GlobalNamespace" && Namespace.empty())
415 return llvm::SmallString<16>("@GlobalNamespace");
416 // The case of anonymous namespaces is taken care of in serialization,
417 // so here we can safely assume an unnamed namespace is the global
418 // one.
419 return llvm::SmallString<16>("GlobalNamespace");
421 return llvm::SmallString<16>("@nonymous_record_" +
422 toHex(llvm::toStringRef(USR)));
424 return llvm::SmallString<16>("@nonymous_enum_" +
425 toHex(llvm::toStringRef(USR)));
427 return llvm::SmallString<16>("@nonymous_typedef_" +
428 toHex(llvm::toStringRef(USR)));
430 return llvm::SmallString<16>("@nonymous_function_" +
431 toHex(llvm::toStringRef(USR)));
433 return llvm::SmallString<16>("@nonymous_concept_" +
434 toHex(llvm::toStringRef(USR)));
436 return llvm::SmallString<16>("@nonymous_variable_" +
437 toHex(llvm::toStringRef(USR)));
439 return llvm::SmallString<16>("@nonymous_friend_" +
440 toHex(llvm::toStringRef(USR)));
442 return llvm::SmallString<16>("@nonymous_" + toHex(llvm::toStringRef(USR)));
443 }
444 llvm_unreachable("Invalid InfoType.");
445 return llvm::SmallString<16>("");
446}
447
448// Order is based on the Name attribute: case insensitive order
449bool Index::operator<(const Index &Other) const {
450 // Loop through each character of both strings
451 for (unsigned I = 0; I < Name.size() && I < Other.Name.size(); ++I) {
452 // Compare them after converting both to lower case
453 int D = tolower(Name[I]) - tolower(Other.Name[I]);
454 if (D == 0)
455 continue;
456 return D < 0;
457 }
458 // If both strings have the size it means they would be equal if changed to
459 // lower case. In here, lower case will be smaller than upper case
460 // Example: string < stRing = true
461 // This is the opposite of how operator < handles strings
462 if (Name.size() == Other.Name.size())
463 return Name > Other.Name;
464 // If they are not the same size; the shorter string is smaller
465 return Name.size() < Other.Name.size();
466}
467
469 llvm::sort(Children);
470 for (auto &C : Children)
471 C.sort();
472}
473
474ClangDocContext::ClangDocContext(tooling::ExecutionContext *ECtx,
475 StringRef ProjectName, bool PublicOnly,
476 StringRef OutDirectory, StringRef SourceRoot,
477 StringRef RepositoryUrl,
478 StringRef RepositoryLinePrefix, StringRef Base,
479 std::vector<std::string> UserStylesheets,
480 clang::DiagnosticsEngine &Diags,
481 bool FTimeTrace)
485 llvm::SmallString<128> SourceRootDir(SourceRoot);
486 if (SourceRoot.empty())
487 // If no SourceRoot was provided the current path is used as the default
488 llvm::sys::fs::current_path(SourceRootDir);
489 this->SourceRoot = std::string(SourceRootDir);
490 if (!RepositoryUrl.empty()) {
491 this->RepositoryUrl = std::string(RepositoryUrl);
492 if (!RepositoryUrl.empty() && !RepositoryUrl.starts_with("http://") &&
493 !RepositoryUrl.starts_with("https://"))
494 this->RepositoryUrl->insert(0, "https://");
495
496 if (!RepositoryLinePrefix.empty())
497 this->RepositoryLinePrefix = std::string(RepositoryLinePrefix);
498 }
499}
500
502 llvm::sort(Namespaces);
503 llvm::sort(Records);
504 llvm::sort(Functions);
505 llvm::sort(Enums);
506 llvm::sort(Typedefs);
507 llvm::sort(Concepts);
508 llvm::sort(Variables);
509}
510} // namespace doc
511} // namespace clang
llvm::Expected< std::unique_ptr< Info > > mergeInfos(std::vector< std::unique_ptr< Info > > &Values)
static llvm::SmallString< 64 > calculateRelativeFilePath(const InfoType &Type, const StringRef &Path, const StringRef &Name, const StringRef &CurrentPath)
static void reduceChildren(std::vector< T > &Children, std::vector< T > &&ChildrenToMerge)
CommentKind stringToCommentKind(llvm::StringRef KindStr)
std::array< uint8_t, 20 > SymbolID
llvm::StringRef commentKindToString(CommentKind Kind)
static int getChildIndexIfExists(std::vector< T > &Children, T &ChildToMerge)
static llvm::Expected< std::unique_ptr< Info > > reduce(std::vector< std::unique_ptr< Info > > &Values)
static const SymbolID EmptySID
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::optional< std::string > RepositoryUrl
ClangDocContext(tooling::ExecutionContext *ECtx, StringRef ProjectName, bool PublicOnly, StringRef OutDirectory, StringRef SourceRoot, StringRef RepositoryUrl, StringRef RepositoryCodeLinePrefix, StringRef Base, std::vector< std::string > UserStylesheets, clang::DiagnosticsEngine &Diags, bool FTimeTrace=false)
std::vector< std::string > UserStylesheets
tooling::ExecutionContext * ECtx
clang::DiagnosticsEngine & Diags
std::optional< std::string > RepositoryLinePrefix
SmallString< 8 > Direction
std::vector< std::unique_ptr< CommentInfo > > Children
bool operator<(const CommentInfo &Other) const
llvm::SmallVector< SmallString< 16 >, 4 > AttrValues
SmallString< 16 > CloseName
bool operator==(const CommentInfo &Other) const
SmallString< 16 > Name
SmallString< 64 > Text
llvm::SmallVector< SmallString< 16 >, 4 > AttrKeys
llvm::SmallVector< SmallString< 16 >, 4 > Args
SmallString< 16 > ParamName
void merge(ConceptInfo &&I)
SmallString< 16 > ConstraintExpression
llvm::SmallVector< EnumValueInfo, 4 > Members
void merge(EnumInfo &&I)
void merge(FriendInfo &&Other)
bool mergeable(const FriendInfo &Other)
FunctionInfo(SymbolID USR=SymbolID())
llvm::SmallVector< FieldTypeInfo, 4 > Params
void merge(FunctionInfo &&I)
std::optional< TemplateInfo > Template
std::vector< Index > Children
bool operator<(const Index &Other) const
Info(InfoType IT=InfoType::IT_default, SymbolID USR=SymbolID(), StringRef Name=StringRef(), StringRef Path=StringRef())
bool mergeable(const Info &Other)
SmallString< 16 > Name
llvm::SmallString< 16 > getFileBaseName() const
Returns the basename that should be used for this Info.
std::vector< CommentInfo > Description
llvm::SmallString< 128 > Path
void mergeBase(Info &&I)
llvm::SmallString< 16 > extractName() const
llvm::SmallString< 64 > getRelativeFilePath(const StringRef &CurrentPath) const
Returns the file path for this Info relative to CurrentPath.
llvm::SmallVector< Reference, 4 > Namespace
NamespaceInfo(SymbolID USR=SymbolID(), StringRef Name=StringRef(), StringRef Path=StringRef())
void merge(NamespaceInfo &&I)
llvm::SmallVector< MemberTypeInfo, 4 > Members
RecordInfo(SymbolID USR=SymbolID(), StringRef Name=StringRef(), StringRef Path=StringRef())
std::optional< TemplateInfo > Template
std::vector< FriendInfo > Friends
llvm::SmallVector< Reference, 4 > VirtualParents
llvm::SmallVector< Reference, 4 > Parents
void merge(RecordInfo &&I)
std::vector< BaseRecordInfo > Bases
void merge(Reference &&I)
Reference(SymbolID USR=SymbolID(), StringRef Name=StringRef(), InfoType IT=InfoType::IT_default)
bool mergeable(const Reference &Other)
llvm::SmallString< 128 > Path
llvm::SmallString< 64 > getRelativeFilePath(const StringRef &CurrentPath) const
Returns the path for this Reference relative to CurrentPath.
llvm::SmallString< 16 > getFileBaseName() const
Returns the basename that should be used for this Reference.
SmallString< 16 > DocumentationFileName
SmallString< 16 > Name
std::vector< Reference > Records
std::vector< TypedefInfo > Typedefs
std::vector< FunctionInfo > Functions
std::vector< Reference > Namespaces
std::vector< VarInfo > Variables
std::vector< EnumInfo > Enums
std::vector< ConceptInfo > Concepts
SymbolInfo(InfoType IT, SymbolID USR=SymbolID(), StringRef Name=StringRef(), StringRef Path=StringRef())
llvm::SmallVector< Location, 2 > Loc
std::optional< Location > DefLoc
SmallString< 16 > MangledName
void merge(TypedefInfo &&I)
TypedefInfo(SymbolID USR=SymbolID())
void merge(VarInfo &&I)