xref: /llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp (revision 8d8c8981cac0e548f0fca1268d6e501431564f66)
1 //===- ExtractAPI/Serialization/SymbolGraphSerializer.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 /// \file
10 /// This file implements the SymbolGraphSerializer.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/ExtractAPI/Serialization/SymbolGraphSerializer.h"
15 #include "clang/Basic/SourceLocation.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/ExtractAPI/DeclarationFragments.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/STLFunctionalExtras.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/VersionTuple.h"
24 #include <optional>
25 #include <type_traits>
26 
27 using namespace clang;
28 using namespace clang::extractapi;
29 using namespace llvm;
30 using namespace llvm::json;
31 
32 namespace {
33 
34 /// Helper function to inject a JSON object \p Obj into another object \p Paren
35 /// at position \p Key.
36 void serializeObject(Object &Paren, StringRef Key, std::optional<Object> Obj) {
37   if (Obj)
38     Paren[Key] = std::move(*Obj);
39 }
40 
41 /// Helper function to inject a StringRef \p String into an object \p Paren at
42 /// position \p Key
43 void serializeString(Object &Paren, StringRef Key,
44                      std::optional<std::string> String) {
45   if (String)
46     Paren[Key] = std::move(*String);
47 }
48 
49 /// Helper function to inject a JSON array \p Array into object \p Paren at
50 /// position \p Key.
51 void serializeArray(Object &Paren, StringRef Key, std::optional<Array> Array) {
52   if (Array)
53     Paren[Key] = std::move(*Array);
54 }
55 
56 /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version
57 /// format.
58 ///
59 /// A semantic version object contains three numeric fields, representing the
60 /// \c major, \c minor, and \c patch parts of the version tuple.
61 /// For example version tuple 1.0.3 is serialized as:
62 /// \code
63 ///   {
64 ///     "major" : 1,
65 ///     "minor" : 0,
66 ///     "patch" : 3
67 ///   }
68 /// \endcode
69 ///
70 /// \returns \c std::nullopt if the version \p V is empty, or an \c Object
71 /// containing the semantic version representation of \p V.
72 std::optional<Object> serializeSemanticVersion(const VersionTuple &V) {
73   if (V.empty())
74     return std::nullopt;
75 
76   Object Version;
77   Version["major"] = V.getMajor();
78   Version["minor"] = V.getMinor().value_or(0);
79   Version["patch"] = V.getSubminor().value_or(0);
80   return Version;
81 }
82 
83 /// Serialize the OS information in the Symbol Graph platform property.
84 ///
85 /// The OS information in Symbol Graph contains the \c name of the OS, and an
86 /// optional \c minimumVersion semantic version field.
87 Object serializeOperatingSystem(const Triple &T) {
88   Object OS;
89   OS["name"] = T.getOSTypeName(T.getOS());
90   serializeObject(OS, "minimumVersion",
91                   serializeSemanticVersion(T.getMinimumSupportedOSVersion()));
92   return OS;
93 }
94 
95 /// Serialize the platform information in the Symbol Graph module section.
96 ///
97 /// The platform object describes a target platform triple in corresponding
98 /// three fields: \c architecture, \c vendor, and \c operatingSystem.
99 Object serializePlatform(const Triple &T) {
100   Object Platform;
101   Platform["architecture"] = T.getArchName();
102   Platform["vendor"] = T.getVendorName();
103   Platform["operatingSystem"] = serializeOperatingSystem(T);
104   return Platform;
105 }
106 
107 /// Serialize a source position.
108 Object serializeSourcePosition(const PresumedLoc &Loc) {
109   assert(Loc.isValid() && "invalid source position");
110 
111   Object SourcePosition;
112   SourcePosition["line"] = Loc.getLine();
113   SourcePosition["character"] = Loc.getColumn();
114 
115   return SourcePosition;
116 }
117 
118 /// Serialize a source location in file.
119 ///
120 /// \param Loc The presumed location to serialize.
121 /// \param IncludeFileURI If true, include the file path of \p Loc as a URI.
122 /// Defaults to false.
123 Object serializeSourceLocation(const PresumedLoc &Loc,
124                                bool IncludeFileURI = false) {
125   Object SourceLocation;
126   serializeObject(SourceLocation, "position", serializeSourcePosition(Loc));
127 
128   if (IncludeFileURI) {
129     std::string FileURI = "file://";
130     // Normalize file path to use forward slashes for the URI.
131     FileURI += sys::path::convert_to_slash(Loc.getFilename());
132     SourceLocation["uri"] = FileURI;
133   }
134 
135   return SourceLocation;
136 }
137 
138 /// Serialize a source range with begin and end locations.
139 Object serializeSourceRange(const PresumedLoc &BeginLoc,
140                             const PresumedLoc &EndLoc) {
141   Object SourceRange;
142   serializeObject(SourceRange, "start", serializeSourcePosition(BeginLoc));
143   serializeObject(SourceRange, "end", serializeSourcePosition(EndLoc));
144   return SourceRange;
145 }
146 
147 /// Serialize the availability attributes of a symbol.
148 ///
149 /// Availability information contains the introduced, deprecated, and obsoleted
150 /// versions of the symbol for a given domain (roughly corresponds to a
151 /// platform) as semantic versions, if not default.  Availability information
152 /// also contains flags to indicate if the symbol is unconditionally unavailable
153 /// or deprecated, i.e. \c __attribute__((unavailable)) and \c
154 /// __attribute__((deprecated)).
155 ///
156 /// \returns \c std::nullopt if the symbol has default availability attributes,
157 /// or an \c Array containing the formatted availability information.
158 std::optional<Array>
159 serializeAvailability(const AvailabilitySet &Availabilities) {
160   if (Availabilities.isDefault())
161     return std::nullopt;
162 
163   Array AvailabilityArray;
164 
165   if (Availabilities.isUnconditionallyDeprecated()) {
166     Object UnconditionallyDeprecated;
167     UnconditionallyDeprecated["domain"] = "*";
168     UnconditionallyDeprecated["isUnconditionallyDeprecated"] = true;
169     AvailabilityArray.emplace_back(std::move(UnconditionallyDeprecated));
170   }
171 
172   // Note unconditionally unavailable records are skipped.
173 
174   for (const auto &AvailInfo : Availabilities) {
175     Object Availability;
176     Availability["domain"] = AvailInfo.Domain;
177     if (AvailInfo.Unavailable)
178       Availability["isUnconditionallyUnavailable"] = true;
179     else {
180       serializeObject(Availability, "introducedVersion",
181                       serializeSemanticVersion(AvailInfo.Introduced));
182       serializeObject(Availability, "deprecatedVersion",
183                       serializeSemanticVersion(AvailInfo.Deprecated));
184       serializeObject(Availability, "obsoletedVersion",
185                       serializeSemanticVersion(AvailInfo.Obsoleted));
186     }
187     AvailabilityArray.emplace_back(std::move(Availability));
188   }
189 
190   return AvailabilityArray;
191 }
192 
193 /// Get the language name string for interface language references.
194 StringRef getLanguageName(Language Lang) {
195   switch (Lang) {
196   case Language::C:
197     return "c";
198   case Language::ObjC:
199     return "objective-c";
200   case Language::CXX:
201     return "c++";
202 
203   // Unsupported language currently
204   case Language::ObjCXX:
205   case Language::OpenCL:
206   case Language::OpenCLCXX:
207   case Language::CUDA:
208   case Language::RenderScript:
209   case Language::HIP:
210   case Language::HLSL:
211 
212   // Languages that the frontend cannot parse and compile
213   case Language::Unknown:
214   case Language::Asm:
215   case Language::LLVM_IR:
216     llvm_unreachable("Unsupported language kind");
217   }
218 
219   llvm_unreachable("Unhandled language kind");
220 }
221 
222 /// Serialize the identifier object as specified by the Symbol Graph format.
223 ///
224 /// The identifier property of a symbol contains the USR for precise and unique
225 /// references, and the interface language name.
226 Object serializeIdentifier(const APIRecord &Record, Language Lang) {
227   Object Identifier;
228   Identifier["precise"] = Record.USR;
229   Identifier["interfaceLanguage"] = getLanguageName(Lang);
230 
231   return Identifier;
232 }
233 
234 /// Serialize the documentation comments attached to a symbol, as specified by
235 /// the Symbol Graph format.
236 ///
237 /// The Symbol Graph \c docComment object contains an array of lines. Each line
238 /// represents one line of striped documentation comment, with source range
239 /// information.
240 /// e.g.
241 /// \code
242 ///   /// This is a documentation comment
243 ///       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'  First line.
244 ///   ///     with multiple lines.
245 ///       ^~~~~~~~~~~~~~~~~~~~~~~'         Second line.
246 /// \endcode
247 ///
248 /// \returns \c std::nullopt if \p Comment is empty, or an \c Object containing
249 /// the formatted lines.
250 std::optional<Object> serializeDocComment(const DocComment &Comment) {
251   if (Comment.empty())
252     return std::nullopt;
253 
254   Object DocComment;
255   Array LinesArray;
256   for (const auto &CommentLine : Comment) {
257     Object Line;
258     Line["text"] = CommentLine.Text;
259     serializeObject(Line, "range",
260                     serializeSourceRange(CommentLine.Begin, CommentLine.End));
261     LinesArray.emplace_back(std::move(Line));
262   }
263   serializeArray(DocComment, "lines", LinesArray);
264 
265   return DocComment;
266 }
267 
268 /// Serialize the declaration fragments of a symbol.
269 ///
270 /// The Symbol Graph declaration fragments is an array of tagged important
271 /// parts of a symbol's declaration. The fragments sequence can be joined to
272 /// form spans of declaration text, with attached information useful for
273 /// purposes like syntax-highlighting etc. For example:
274 /// \code
275 ///   const int pi; -> "declarationFragments" : [
276 ///                      {
277 ///                        "kind" : "keyword",
278 ///                        "spelling" : "const"
279 ///                      },
280 ///                      {
281 ///                        "kind" : "text",
282 ///                        "spelling" : " "
283 ///                      },
284 ///                      {
285 ///                        "kind" : "typeIdentifier",
286 ///                        "preciseIdentifier" : "c:I",
287 ///                        "spelling" : "int"
288 ///                      },
289 ///                      {
290 ///                        "kind" : "text",
291 ///                        "spelling" : " "
292 ///                      },
293 ///                      {
294 ///                        "kind" : "identifier",
295 ///                        "spelling" : "pi"
296 ///                      }
297 ///                    ]
298 /// \endcode
299 ///
300 /// \returns \c std::nullopt if \p DF is empty, or an \c Array containing the
301 /// formatted declaration fragments array.
302 std::optional<Array>
303 serializeDeclarationFragments(const DeclarationFragments &DF) {
304   if (DF.getFragments().empty())
305     return std::nullopt;
306 
307   Array Fragments;
308   for (const auto &F : DF.getFragments()) {
309     Object Fragment;
310     Fragment["spelling"] = F.Spelling;
311     Fragment["kind"] = DeclarationFragments::getFragmentKindString(F.Kind);
312     if (!F.PreciseIdentifier.empty())
313       Fragment["preciseIdentifier"] = F.PreciseIdentifier;
314     Fragments.emplace_back(std::move(Fragment));
315   }
316 
317   return Fragments;
318 }
319 
320 /// Serialize the \c names field of a symbol as specified by the Symbol Graph
321 /// format.
322 ///
323 /// The Symbol Graph names field contains multiple representations of a symbol
324 /// that can be used for different applications:
325 ///   - \c title : The simple declared name of the symbol;
326 ///   - \c subHeading : An array of declaration fragments that provides tags,
327 ///     and potentially more tokens (for example the \c +/- symbol for
328 ///     Objective-C methods). Can be used as sub-headings for documentation.
329 Object serializeNames(const APIRecord &Record) {
330   Object Names;
331   if (auto *CategoryRecord =
332           dyn_cast_or_null<const ObjCCategoryRecord>(&Record))
333     Names["title"] =
334         (CategoryRecord->Interface.Name + " (" + Record.Name + ")").str();
335   else
336     Names["title"] = Record.Name;
337 
338   serializeArray(Names, "subHeading",
339                  serializeDeclarationFragments(Record.SubHeading));
340   DeclarationFragments NavigatorFragments;
341   NavigatorFragments.append(Record.Name,
342                             DeclarationFragments::FragmentKind::Identifier,
343                             /*PreciseIdentifier*/ "");
344   serializeArray(Names, "navigator",
345                  serializeDeclarationFragments(NavigatorFragments));
346 
347   return Names;
348 }
349 
350 Object serializeSymbolKind(APIRecord::RecordKind RK, Language Lang) {
351   auto AddLangPrefix = [&Lang](StringRef S) -> std::string {
352     return (getLanguageName(Lang) + "." + S).str();
353   };
354 
355   Object Kind;
356   switch (RK) {
357   case APIRecord::RK_Unknown:
358     llvm_unreachable("Records should have an explicit kind");
359     break;
360   case APIRecord::RK_GlobalFunction:
361     Kind["identifier"] = AddLangPrefix("func");
362     Kind["displayName"] = "Function";
363     break;
364   case APIRecord::RK_GlobalVariableTemplate:
365     Kind["identifier"] = AddLangPrefix("var");
366     Kind["displayName"] = "Global Variable Template";
367     break;
368   case APIRecord::RK_GlobalVariableTemplateSpecialization:
369     Kind["identifier"] = AddLangPrefix("var");
370     Kind["displayName"] = "Global Variable Template Specialization";
371     break;
372   case APIRecord::RK_GlobalVariableTemplatePartialSpecialization:
373     Kind["identifier"] = AddLangPrefix("var");
374     Kind["displayName"] = "Global Variable Template Partial Specialization";
375     break;
376   case APIRecord::RK_GlobalVariable:
377     Kind["identifier"] = AddLangPrefix("var");
378     Kind["displayName"] = "Global Variable";
379     break;
380   case APIRecord::RK_EnumConstant:
381     Kind["identifier"] = AddLangPrefix("enum.case");
382     Kind["displayName"] = "Enumeration Case";
383     break;
384   case APIRecord::RK_Enum:
385     Kind["identifier"] = AddLangPrefix("enum");
386     Kind["displayName"] = "Enumeration";
387     break;
388   case APIRecord::RK_StructField:
389     Kind["identifier"] = AddLangPrefix("property");
390     Kind["displayName"] = "Instance Property";
391     break;
392   case APIRecord::RK_Struct:
393     Kind["identifier"] = AddLangPrefix("struct");
394     Kind["displayName"] = "Structure";
395     break;
396   case APIRecord::RK_CXXField:
397     Kind["identifier"] = AddLangPrefix("property");
398     Kind["displayName"] = "Instance Property";
399     break;
400   case APIRecord::RK_Union:
401     Kind["identifier"] = AddLangPrefix("union");
402     Kind["displayName"] = "Union";
403     break;
404   case APIRecord::RK_StaticField:
405     Kind["identifier"] = AddLangPrefix("type.property");
406     Kind["displayName"] = "Type Property";
407     break;
408   case APIRecord::RK_ClassTemplate:
409   case APIRecord::RK_ClassTemplateSpecialization:
410   case APIRecord::RK_ClassTemplatePartialSpecialization:
411   case APIRecord::RK_CXXClass:
412     Kind["identifier"] = AddLangPrefix("class");
413     Kind["displayName"] = "Class";
414     break;
415   case APIRecord::RK_Concept:
416     Kind["identifier"] = AddLangPrefix("concept");
417     Kind["displayName"] = "Concept";
418     break;
419   case APIRecord::RK_CXXStaticMethod:
420     Kind["identifier"] = AddLangPrefix("type.method");
421     Kind["displayName"] = "Static Method";
422     break;
423   case APIRecord::RK_CXXInstanceMethod:
424     Kind["identifier"] = AddLangPrefix("method");
425     Kind["displayName"] = "Instance Method";
426     break;
427   case APIRecord::RK_CXXConstructorMethod:
428     Kind["identifier"] = AddLangPrefix("method");
429     Kind["displayName"] = "Constructor";
430     break;
431   case APIRecord::RK_CXXDestructorMethod:
432     Kind["identifier"] = AddLangPrefix("method");
433     Kind["displayName"] = "Destructor";
434     break;
435   case APIRecord::RK_ObjCIvar:
436     Kind["identifier"] = AddLangPrefix("ivar");
437     Kind["displayName"] = "Instance Variable";
438     break;
439   case APIRecord::RK_ObjCInstanceMethod:
440     Kind["identifier"] = AddLangPrefix("method");
441     Kind["displayName"] = "Instance Method";
442     break;
443   case APIRecord::RK_ObjCClassMethod:
444     Kind["identifier"] = AddLangPrefix("type.method");
445     Kind["displayName"] = "Type Method";
446     break;
447   case APIRecord::RK_ObjCInstanceProperty:
448     Kind["identifier"] = AddLangPrefix("property");
449     Kind["displayName"] = "Instance Property";
450     break;
451   case APIRecord::RK_ObjCClassProperty:
452     Kind["identifier"] = AddLangPrefix("type.property");
453     Kind["displayName"] = "Type Property";
454     break;
455   case APIRecord::RK_ObjCInterface:
456     Kind["identifier"] = AddLangPrefix("class");
457     Kind["displayName"] = "Class";
458     break;
459   case APIRecord::RK_ObjCCategory:
460     Kind["identifier"] = AddLangPrefix("class.extension");
461     Kind["displayName"] = "Class Extension";
462     break;
463   case APIRecord::RK_ObjCCategoryModule:
464     Kind["identifier"] = AddLangPrefix("module.extension");
465     Kind["displayName"] = "Module Extension";
466     break;
467   case APIRecord::RK_ObjCProtocol:
468     Kind["identifier"] = AddLangPrefix("protocol");
469     Kind["displayName"] = "Protocol";
470     break;
471   case APIRecord::RK_MacroDefinition:
472     Kind["identifier"] = AddLangPrefix("macro");
473     Kind["displayName"] = "Macro";
474     break;
475   case APIRecord::RK_Typedef:
476     Kind["identifier"] = AddLangPrefix("typealias");
477     Kind["displayName"] = "Type Alias";
478     break;
479   }
480 
481   return Kind;
482 }
483 
484 /// Serialize the symbol kind information.
485 ///
486 /// The Symbol Graph symbol kind property contains a shorthand \c identifier
487 /// which is prefixed by the source language name, useful for tooling to parse
488 /// the kind, and a \c displayName for rendering human-readable names.
489 Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
490   return serializeSymbolKind(Record.getKind(), Lang);
491 }
492 
493 template <typename RecordTy>
494 std::optional<Object>
495 serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::true_type) {
496   const auto &FS = Record.Signature;
497   if (FS.empty())
498     return std::nullopt;
499 
500   Object Signature;
501   serializeArray(Signature, "returns",
502                  serializeDeclarationFragments(FS.getReturnType()));
503 
504   Array Parameters;
505   for (const auto &P : FS.getParameters()) {
506     Object Parameter;
507     Parameter["name"] = P.Name;
508     serializeArray(Parameter, "declarationFragments",
509                    serializeDeclarationFragments(P.Fragments));
510     Parameters.emplace_back(std::move(Parameter));
511   }
512 
513   if (!Parameters.empty())
514     Signature["parameters"] = std::move(Parameters);
515 
516   return Signature;
517 }
518 
519 template <typename RecordTy>
520 std::optional<Object>
521 serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::false_type) {
522   return std::nullopt;
523 }
524 
525 /// Serialize the function signature field, as specified by the
526 /// Symbol Graph format.
527 ///
528 /// The Symbol Graph function signature property contains two arrays.
529 ///   - The \c returns array is the declaration fragments of the return type;
530 ///   - The \c parameters array contains names and declaration fragments of the
531 ///     parameters.
532 ///
533 /// \returns \c std::nullopt if \p FS is empty, or an \c Object containing the
534 /// formatted function signature.
535 template <typename RecordTy>
536 void serializeFunctionSignatureMixin(Object &Paren, const RecordTy &Record) {
537   serializeObject(Paren, "functionSignature",
538                   serializeFunctionSignatureMixinImpl(
539                       Record, has_function_signature<RecordTy>()));
540 }
541 
542 template <typename RecordTy>
543 std::optional<std::string> serializeAccessMixinImpl(const RecordTy &Record,
544                                                     std::true_type) {
545   const auto &AccessControl = Record.Access;
546   std::string Access;
547   if (AccessControl.empty())
548     return std::nullopt;
549   Access = AccessControl.getAccess();
550   return Access;
551 }
552 
553 template <typename RecordTy>
554 std::optional<std::string> serializeAccessMixinImpl(const RecordTy &Record,
555                                                     std::false_type) {
556   return std::nullopt;
557 }
558 
559 template <typename RecordTy>
560 void serializeAccessMixin(Object &Paren, const RecordTy &Record) {
561   auto accessLevel = serializeAccessMixinImpl(Record, has_access<RecordTy>());
562   if (!accessLevel.has_value())
563     accessLevel = "public";
564   serializeString(Paren, "accessLevel", accessLevel);
565 }
566 
567 template <typename RecordTy>
568 std::optional<Object> serializeTemplateMixinImpl(const RecordTy &Record,
569                                                  std::true_type) {
570   const auto &Template = Record.Templ;
571   if (Template.empty())
572     return std::nullopt;
573 
574   Object Generics;
575   Array GenericParameters;
576   for (const auto Param : Template.getParameters()) {
577     Object Parameter;
578     Parameter["name"] = Param.Name;
579     Parameter["index"] = Param.Index;
580     Parameter["depth"] = Param.Depth;
581     GenericParameters.emplace_back(std::move(Parameter));
582   }
583   if (!GenericParameters.empty())
584     Generics["parameters"] = std::move(GenericParameters);
585 
586   Array GenericConstraints;
587   for (const auto Constr : Template.getConstraints()) {
588     Object Constraint;
589     Constraint["kind"] = Constr.Kind;
590     Constraint["lhs"] = Constr.LHS;
591     Constraint["rhs"] = Constr.RHS;
592     GenericConstraints.emplace_back(std::move(Constraint));
593   }
594 
595   if (!GenericConstraints.empty())
596     Generics["constraints"] = std::move(GenericConstraints);
597 
598   return Generics;
599 }
600 
601 template <typename RecordTy>
602 std::optional<Object> serializeTemplateMixinImpl(const RecordTy &Record,
603                                                  std::false_type) {
604   return std::nullopt;
605 }
606 
607 template <typename RecordTy>
608 void serializeTemplateMixin(Object &Paren, const RecordTy &Record) {
609   serializeObject(Paren, "swiftGenerics",
610                   serializeTemplateMixinImpl(Record, has_template<RecordTy>()));
611 }
612 
613 struct PathComponent {
614   StringRef USR;
615   StringRef Name;
616   APIRecord::RecordKind Kind;
617 
618   PathComponent(StringRef USR, StringRef Name, APIRecord::RecordKind Kind)
619       : USR(USR), Name(Name), Kind(Kind) {}
620 };
621 
622 template <typename RecordTy>
623 bool generatePathComponents(
624     const RecordTy &Record, const APISet &API,
625     function_ref<void(const PathComponent &)> ComponentTransformer) {
626   SmallVector<PathComponent, 4> ReverseComponenents;
627   ReverseComponenents.emplace_back(Record.USR, Record.Name, Record.getKind());
628   const auto *CurrentParent = &Record.ParentInformation;
629   bool FailedToFindParent = false;
630   while (CurrentParent && !CurrentParent->empty()) {
631     PathComponent CurrentParentComponent(CurrentParent->ParentUSR,
632                                          CurrentParent->ParentName,
633                                          CurrentParent->ParentKind);
634 
635     auto *ParentRecord = CurrentParent->ParentRecord;
636     // Slow path if we don't have a direct reference to the ParentRecord
637     if (!ParentRecord)
638       ParentRecord = API.findRecordForUSR(CurrentParent->ParentUSR);
639 
640     // If the parent is a category extended from internal module then we need to
641     // pretend this belongs to the associated interface.
642     if (auto *CategoryRecord =
643             dyn_cast_or_null<ObjCCategoryRecord>(ParentRecord)) {
644       if (!CategoryRecord->IsFromExternalModule) {
645         ParentRecord = API.findRecordForUSR(CategoryRecord->Interface.USR);
646         CurrentParentComponent = PathComponent(CategoryRecord->Interface.USR,
647                                                CategoryRecord->Interface.Name,
648                                                APIRecord::RK_ObjCInterface);
649       }
650     }
651 
652     // The parent record doesn't exist which means the symbol shouldn't be
653     // treated as part of the current product.
654     if (!ParentRecord) {
655       FailedToFindParent = true;
656       break;
657     }
658 
659     ReverseComponenents.push_back(std::move(CurrentParentComponent));
660     CurrentParent = &ParentRecord->ParentInformation;
661   }
662 
663   for (const auto &PC : reverse(ReverseComponenents))
664     ComponentTransformer(PC);
665 
666   return FailedToFindParent;
667 }
668 
669 Object serializeParentContext(const PathComponent &PC, Language Lang) {
670   Object ParentContextElem;
671   ParentContextElem["usr"] = PC.USR;
672   ParentContextElem["name"] = PC.Name;
673   ParentContextElem["kind"] = serializeSymbolKind(PC.Kind, Lang)["identifier"];
674   return ParentContextElem;
675 }
676 
677 template <typename RecordTy>
678 Array generateParentContexts(const RecordTy &Record, const APISet &API,
679                              Language Lang) {
680   Array ParentContexts;
681   generatePathComponents(
682       Record, API, [Lang, &ParentContexts](const PathComponent &PC) {
683         ParentContexts.push_back(serializeParentContext(PC, Lang));
684       });
685 
686   return ParentContexts;
687 }
688 } // namespace
689 
690 /// Defines the format version emitted by SymbolGraphSerializer.
691 const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
692 
693 Object SymbolGraphSerializer::serializeMetadata() const {
694   Object Metadata;
695   serializeObject(Metadata, "formatVersion",
696                   serializeSemanticVersion(FormatVersion));
697   Metadata["generator"] = clang::getClangFullVersion();
698   return Metadata;
699 }
700 
701 Object SymbolGraphSerializer::serializeModule() const {
702   Object Module;
703   // The user is expected to always pass `--product-name=` on the command line
704   // to populate this field.
705   Module["name"] = API.ProductName;
706   serializeObject(Module, "platform", serializePlatform(API.getTarget()));
707   return Module;
708 }
709 
710 bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const {
711   // Skip explicitly ignored symbols.
712   if (IgnoresList.shouldIgnore(Record.Name))
713     return true;
714 
715   // Skip unconditionally unavailable symbols
716   if (Record.Availabilities.isUnconditionallyUnavailable())
717     return true;
718 
719   // Filter out symbols prefixed with an underscored as they are understood to
720   // be symbols clients should not use.
721   if (Record.Name.startswith("_"))
722     return true;
723 
724   return false;
725 }
726 
727 template <typename RecordTy>
728 std::optional<Object>
729 SymbolGraphSerializer::serializeAPIRecord(const RecordTy &Record) const {
730   if (shouldSkip(Record))
731     return std::nullopt;
732 
733   Object Obj;
734   serializeObject(Obj, "identifier",
735                   serializeIdentifier(Record, API.getLanguage()));
736   serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage()));
737   serializeObject(Obj, "names", serializeNames(Record));
738   serializeObject(
739       Obj, "location",
740       serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true));
741   serializeArray(Obj, "availability",
742                  serializeAvailability(Record.Availabilities));
743   serializeObject(Obj, "docComment", serializeDocComment(Record.Comment));
744   serializeArray(Obj, "declarationFragments",
745                  serializeDeclarationFragments(Record.Declaration));
746   SmallVector<StringRef, 4> PathComponentsNames;
747   // If this returns true it indicates that we couldn't find a symbol in the
748   // hierarchy.
749   if (generatePathComponents(Record, API,
750                              [&PathComponentsNames](const PathComponent &PC) {
751                                PathComponentsNames.push_back(PC.Name);
752                              }))
753     return {};
754 
755   serializeArray(Obj, "pathComponents", Array(PathComponentsNames));
756 
757   serializeFunctionSignatureMixin(Obj, Record);
758   serializeAccessMixin(Obj, Record);
759   serializeTemplateMixin(Obj, Record);
760 
761   return Obj;
762 }
763 
764 template <typename MemberTy>
765 void SymbolGraphSerializer::serializeMembers(
766     const APIRecord &Record,
767     const SmallVector<std::unique_ptr<MemberTy>> &Members) {
768   // Members should not be serialized if we aren't recursing.
769   if (!ShouldRecurse)
770     return;
771   for (const auto &Member : Members) {
772     auto MemberRecord = serializeAPIRecord(*Member);
773     if (!MemberRecord)
774       continue;
775 
776     Symbols.emplace_back(std::move(*MemberRecord));
777     serializeRelationship(RelationshipKind::MemberOf, *Member, Record);
778   }
779 }
780 
781 StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) {
782   switch (Kind) {
783   case RelationshipKind::MemberOf:
784     return "memberOf";
785   case RelationshipKind::InheritsFrom:
786     return "inheritsFrom";
787   case RelationshipKind::ConformsTo:
788     return "conformsTo";
789   case RelationshipKind::ExtensionTo:
790     return "extensionTo";
791   }
792   llvm_unreachable("Unhandled relationship kind");
793 }
794 
795 StringRef SymbolGraphSerializer::getConstraintString(ConstraintKind Kind) {
796   switch (Kind) {
797   case ConstraintKind::Conformance:
798     return "conformance";
799   case ConstraintKind::ConditionalConformance:
800     return "conditionalConformance";
801   }
802   llvm_unreachable("Unhandled constraint kind");
803 }
804 
805 void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind,
806                                                   SymbolReference Source,
807                                                   SymbolReference Target) {
808   Object Relationship;
809   Relationship["source"] = Source.USR;
810   Relationship["target"] = Target.USR;
811   Relationship["targetFallback"] = Target.Name;
812   Relationship["kind"] = getRelationshipString(Kind);
813 
814   Relationships.emplace_back(std::move(Relationship));
815 }
816 
817 void SymbolGraphSerializer::visitGlobalFunctionRecord(
818     const GlobalFunctionRecord &Record) {
819   auto Obj = serializeAPIRecord(Record);
820   if (!Obj)
821     return;
822 
823   Symbols.emplace_back(std::move(*Obj));
824 }
825 
826 void SymbolGraphSerializer::visitGlobalVariableRecord(
827     const GlobalVariableRecord &Record) {
828   auto Obj = serializeAPIRecord(Record);
829   if (!Obj)
830     return;
831 
832   Symbols.emplace_back(std::move(*Obj));
833 }
834 
835 void SymbolGraphSerializer::visitEnumRecord(const EnumRecord &Record) {
836   auto Enum = serializeAPIRecord(Record);
837   if (!Enum)
838     return;
839 
840   Symbols.emplace_back(std::move(*Enum));
841   serializeMembers(Record, Record.Constants);
842 }
843 
844 void SymbolGraphSerializer::visitStructRecord(const StructRecord &Record) {
845   auto Struct = serializeAPIRecord(Record);
846   if (!Struct)
847     return;
848 
849   Symbols.emplace_back(std::move(*Struct));
850   serializeMembers(Record, Record.Fields);
851 }
852 
853 void SymbolGraphSerializer::visitStaticFieldRecord(
854     const StaticFieldRecord &Record) {
855   auto StaticField = serializeAPIRecord(Record);
856   if (!StaticField)
857     return;
858   Symbols.emplace_back(std::move(*StaticField));
859   serializeRelationship(RelationshipKind::MemberOf, Record, Record.Context);
860 }
861 
862 void SymbolGraphSerializer::visitCXXClassRecord(const CXXClassRecord &Record) {
863   auto Class = serializeAPIRecord(Record);
864   if (!Class)
865     return;
866 
867   Symbols.emplace_back(std::move(*Class));
868   serializeMembers(Record, Record.Fields);
869   serializeMembers(Record, Record.Methods);
870 
871   for (const auto Base : Record.Bases)
872     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
873 }
874 
875 void SymbolGraphSerializer::visitClassTemplateRecord(
876     const ClassTemplateRecord &Record) {
877   auto Class = serializeAPIRecord(Record);
878   if (!Class)
879     return;
880 
881   Symbols.emplace_back(std::move(*Class));
882   serializeMembers(Record, Record.Fields);
883   serializeMembers(Record, Record.Methods);
884 
885   for (const auto Base : Record.Bases)
886     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
887 }
888 
889 void SymbolGraphSerializer::visitClassTemplateSpecializationRecord(
890     const ClassTemplateSpecializationRecord &Record) {
891   auto Class = serializeAPIRecord(Record);
892   if (!Class)
893     return;
894 
895   Symbols.emplace_back(std::move(*Class));
896   serializeMembers(Record, Record.Fields);
897   serializeMembers(Record, Record.Methods);
898 
899   for (const auto Base : Record.Bases)
900     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
901 }
902 
903 void SymbolGraphSerializer::visitClassTemplatePartialSpecializationRecord(
904     const ClassTemplatePartialSpecializationRecord &Record) {
905   auto Class = serializeAPIRecord(Record);
906   if (!Class)
907     return;
908 
909   Symbols.emplace_back(std::move(*Class));
910   serializeMembers(Record, Record.Fields);
911   serializeMembers(Record, Record.Methods);
912 
913   for (const auto Base : Record.Bases)
914     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
915 }
916 
917 void SymbolGraphSerializer::visitConceptRecord(const ConceptRecord &Record) {
918   auto Concept = serializeAPIRecord(Record);
919   if (!Concept)
920     return;
921 
922   Symbols.emplace_back(std::move(*Concept));
923 }
924 
925 void SymbolGraphSerializer::visitGlobalVariableTemplateRecord(
926     const GlobalVariableTemplateRecord &Record) {
927   auto GlobalVariableTemplate = serializeAPIRecord(Record);
928   if (!GlobalVariableTemplate)
929     return;
930   Symbols.emplace_back(std::move(*GlobalVariableTemplate));
931 }
932 
933 void SymbolGraphSerializer::visitGlobalVariableTemplateSpecializationRecord(
934     const GlobalVariableTemplateSpecializationRecord &Record) {
935   auto GlobalVariableTemplateSpecialization = serializeAPIRecord(Record);
936   if (!GlobalVariableTemplateSpecialization)
937     return;
938   Symbols.emplace_back(std::move(*GlobalVariableTemplateSpecialization));
939 }
940 
941 void SymbolGraphSerializer::
942     visitGlobalVariableTemplatePartialSpecializationRecord(
943         const GlobalVariableTemplatePartialSpecializationRecord &Record) {
944   auto GlobalVariableTemplatePartialSpecialization = serializeAPIRecord(Record);
945   if (!GlobalVariableTemplatePartialSpecialization)
946     return;
947   Symbols.emplace_back(std::move(*GlobalVariableTemplatePartialSpecialization));
948 }
949 
950 void SymbolGraphSerializer::visitObjCContainerRecord(
951     const ObjCContainerRecord &Record) {
952   auto ObjCContainer = serializeAPIRecord(Record);
953   if (!ObjCContainer)
954     return;
955 
956   Symbols.emplace_back(std::move(*ObjCContainer));
957 
958   serializeMembers(Record, Record.Ivars);
959   serializeMembers(Record, Record.Methods);
960   serializeMembers(Record, Record.Properties);
961 
962   for (const auto &Protocol : Record.Protocols)
963     // Record that Record conforms to Protocol.
964     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
965 
966   if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record)) {
967     if (!ObjCInterface->SuperClass.empty())
968       // If Record is an Objective-C interface record and it has a super class,
969       // record that Record is inherited from SuperClass.
970       serializeRelationship(RelationshipKind::InheritsFrom, Record,
971                             ObjCInterface->SuperClass);
972 
973     // Members of categories extending an interface are serialized as members of
974     // the interface.
975     for (const auto *Category : ObjCInterface->Categories) {
976       serializeMembers(Record, Category->Ivars);
977       serializeMembers(Record, Category->Methods);
978       serializeMembers(Record, Category->Properties);
979 
980       // Surface the protocols of the category to the interface.
981       for (const auto &Protocol : Category->Protocols)
982         serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
983     }
984   }
985 }
986 
987 void SymbolGraphSerializer::visitObjCCategoryRecord(
988     const ObjCCategoryRecord &Record) {
989   if (!Record.IsFromExternalModule)
990     return;
991 
992   // Check if the current Category' parent has been visited before, if so skip.
993   if (!visitedCategories.contains(Record.Interface.Name)) {
994     visitedCategories.insert(Record.Interface.Name);
995     Object Obj;
996     serializeObject(Obj, "identifier",
997                     serializeIdentifier(Record, API.getLanguage()));
998     serializeObject(Obj, "kind",
999                     serializeSymbolKind(APIRecord::RK_ObjCCategoryModule,
1000                                         API.getLanguage()));
1001     Obj["accessLevel"] = "public";
1002     Symbols.emplace_back(std::move(Obj));
1003   }
1004 
1005   Object Relationship;
1006   Relationship["source"] = Record.USR;
1007   Relationship["target"] = Record.Interface.USR;
1008   Relationship["targetFallback"] = Record.Interface.Name;
1009   Relationship["kind"] = getRelationshipString(RelationshipKind::ExtensionTo);
1010   Relationships.emplace_back(std::move(Relationship));
1011 
1012   auto ObjCCategory = serializeAPIRecord(Record);
1013 
1014   if (!ObjCCategory)
1015     return;
1016 
1017   Symbols.emplace_back(std::move(*ObjCCategory));
1018   serializeMembers(Record, Record.Methods);
1019   serializeMembers(Record, Record.Properties);
1020 
1021   // Surface the protocols of the category to the interface.
1022   for (const auto &Protocol : Record.Protocols)
1023     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
1024 }
1025 
1026 void SymbolGraphSerializer::visitMacroDefinitionRecord(
1027     const MacroDefinitionRecord &Record) {
1028   auto Macro = serializeAPIRecord(Record);
1029 
1030   if (!Macro)
1031     return;
1032 
1033   Symbols.emplace_back(std::move(*Macro));
1034 }
1035 
1036 void SymbolGraphSerializer::serializeSingleRecord(const APIRecord *Record) {
1037   switch (Record->getKind()) {
1038   case APIRecord::RK_Unknown:
1039     llvm_unreachable("Records should have a known kind!");
1040   case APIRecord::RK_GlobalFunction:
1041     visitGlobalFunctionRecord(*cast<GlobalFunctionRecord>(Record));
1042     break;
1043   case APIRecord::RK_GlobalVariable:
1044     visitGlobalVariableRecord(*cast<GlobalVariableRecord>(Record));
1045     break;
1046   case APIRecord::RK_Enum:
1047     visitEnumRecord(*cast<EnumRecord>(Record));
1048     break;
1049   case APIRecord::RK_Struct:
1050     visitStructRecord(*cast<StructRecord>(Record));
1051     break;
1052   case APIRecord::RK_StaticField:
1053     visitStaticFieldRecord(*cast<StaticFieldRecord>(Record));
1054     break;
1055   case APIRecord::RK_CXXClass:
1056     visitCXXClassRecord(*cast<CXXClassRecord>(Record));
1057     break;
1058   case APIRecord::RK_ObjCInterface:
1059     visitObjCContainerRecord(*cast<ObjCInterfaceRecord>(Record));
1060     break;
1061   case APIRecord::RK_ObjCProtocol:
1062     visitObjCContainerRecord(*cast<ObjCProtocolRecord>(Record));
1063     break;
1064   case APIRecord::RK_ObjCCategory:
1065     visitObjCCategoryRecord(*cast<ObjCCategoryRecord>(Record));
1066     break;
1067   case APIRecord::RK_MacroDefinition:
1068     visitMacroDefinitionRecord(*cast<MacroDefinitionRecord>(Record));
1069     break;
1070   case APIRecord::RK_Typedef:
1071     visitTypedefRecord(*cast<TypedefRecord>(Record));
1072     break;
1073   default:
1074     if (auto Obj = serializeAPIRecord(*Record)) {
1075       Symbols.emplace_back(std::move(*Obj));
1076       auto &ParentInformation = Record->ParentInformation;
1077       if (!ParentInformation.empty())
1078         serializeRelationship(RelationshipKind::MemberOf, *Record,
1079                               *ParentInformation.ParentRecord);
1080     }
1081     break;
1082   }
1083 }
1084 
1085 void SymbolGraphSerializer::visitTypedefRecord(const TypedefRecord &Record) {
1086   // Typedefs of anonymous types have their entries unified with the underlying
1087   // type.
1088   bool ShouldDrop = Record.UnderlyingType.Name.empty();
1089   // enums declared with `NS_OPTION` have a named enum and a named typedef, with
1090   // the same name
1091   ShouldDrop |= (Record.UnderlyingType.Name == Record.Name);
1092   if (ShouldDrop)
1093     return;
1094 
1095   auto Typedef = serializeAPIRecord(Record);
1096   if (!Typedef)
1097     return;
1098 
1099   (*Typedef)["type"] = Record.UnderlyingType.USR;
1100 
1101   Symbols.emplace_back(std::move(*Typedef));
1102 }
1103 
1104 Object SymbolGraphSerializer::serialize() {
1105   traverseAPISet();
1106   return serializeCurrentGraph();
1107 }
1108 
1109 Object SymbolGraphSerializer::serializeCurrentGraph() {
1110   Object Root;
1111   serializeObject(Root, "metadata", serializeMetadata());
1112   serializeObject(Root, "module", serializeModule());
1113 
1114   Root["symbols"] = std::move(Symbols);
1115   Root["relationships"] = std::move(Relationships);
1116 
1117   return Root;
1118 }
1119 
1120 void SymbolGraphSerializer::serialize(raw_ostream &os) {
1121   Object root = serialize();
1122   if (Options.Compact)
1123     os << formatv("{0}", Value(std::move(root))) << "\n";
1124   else
1125     os << formatv("{0:2}", Value(std::move(root))) << "\n";
1126 }
1127 
1128 std::optional<Object>
1129 SymbolGraphSerializer::serializeSingleSymbolSGF(StringRef USR,
1130                                                 const APISet &API) {
1131   APIRecord *Record = API.findRecordForUSR(USR);
1132   if (!Record)
1133     return {};
1134 
1135   Object Root;
1136   APIIgnoresList EmptyIgnores;
1137   SymbolGraphSerializer Serializer(API, EmptyIgnores,
1138                                    /*Options.Compact*/ {true},
1139                                    /*ShouldRecurse*/ false);
1140   Serializer.serializeSingleRecord(Record);
1141   serializeObject(Root, "symbolGraph", Serializer.serializeCurrentGraph());
1142 
1143   Language Lang = API.getLanguage();
1144   serializeArray(Root, "parentContexts",
1145                  generateParentContexts(*Record, API, Lang));
1146 
1147   Array RelatedSymbols;
1148 
1149   for (const auto &Fragment : Record->Declaration.getFragments()) {
1150     // If we don't have a USR there isn't much we can do.
1151     if (Fragment.PreciseIdentifier.empty())
1152       continue;
1153 
1154     APIRecord *RelatedRecord = API.findRecordForUSR(Fragment.PreciseIdentifier);
1155 
1156     // If we can't find the record let's skip.
1157     if (!RelatedRecord)
1158       continue;
1159 
1160     Object RelatedSymbol;
1161     RelatedSymbol["usr"] = RelatedRecord->USR;
1162     RelatedSymbol["declarationLanguage"] = getLanguageName(Lang);
1163     // TODO: once we record this properly let's serialize it right.
1164     RelatedSymbol["accessLevel"] = "public";
1165     RelatedSymbol["filePath"] = RelatedRecord->Location.getFilename();
1166     RelatedSymbol["moduleName"] = API.ProductName;
1167     RelatedSymbol["isSystem"] = RelatedRecord->IsFromSystemHeader;
1168 
1169     serializeArray(RelatedSymbol, "parentContexts",
1170                    generateParentContexts(*RelatedRecord, API, Lang));
1171     RelatedSymbols.push_back(std::move(RelatedSymbol));
1172   }
1173 
1174   serializeArray(Root, "relatedSymbols", RelatedSymbols);
1175   return Root;
1176 }
1177