xref: /llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp (revision 7ba37f4e46a5bbb1dc42f1ea1722296ea32034d5)
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_GlobalVariable:
365     Kind["identifier"] = AddLangPrefix("var");
366     Kind["displayName"] = "Global Variable";
367     break;
368   case APIRecord::RK_EnumConstant:
369     Kind["identifier"] = AddLangPrefix("enum.case");
370     Kind["displayName"] = "Enumeration Case";
371     break;
372   case APIRecord::RK_Enum:
373     Kind["identifier"] = AddLangPrefix("enum");
374     Kind["displayName"] = "Enumeration";
375     break;
376   case APIRecord::RK_StructField:
377     Kind["identifier"] = AddLangPrefix("property");
378     Kind["displayName"] = "Instance Property";
379     break;
380   case APIRecord::RK_Struct:
381     Kind["identifier"] = AddLangPrefix("struct");
382     Kind["displayName"] = "Structure";
383     break;
384   case APIRecord::RK_CXXField:
385     Kind["identifier"] = AddLangPrefix("property");
386     Kind["displayName"] = "Instance Property";
387     break;
388   case APIRecord::RK_Union:
389     Kind["identifier"] = AddLangPrefix("union");
390     Kind["displayName"] = "Union";
391     break;
392   case APIRecord::RK_StaticField:
393     Kind["identifier"] = AddLangPrefix("type.property");
394     Kind["displayName"] = "Type Property";
395     break;
396   case APIRecord::RK_ClassTemplate:
397   case APIRecord::RK_ClassTemplateSpecialization:
398   case APIRecord::RK_ClassTemplatePartialSpecialization:
399   case APIRecord::RK_CXXClass:
400     Kind["identifier"] = AddLangPrefix("class");
401     Kind["displayName"] = "Class";
402     break;
403   case APIRecord::RK_Concept:
404     Kind["identifier"] = AddLangPrefix("concept");
405     Kind["displayName"] = "Concept";
406     break;
407   case APIRecord::RK_CXXStaticMethod:
408     Kind["identifier"] = AddLangPrefix("type.method");
409     Kind["displayName"] = "Static Method";
410     break;
411   case APIRecord::RK_CXXInstanceMethod:
412     Kind["identifier"] = AddLangPrefix("method");
413     Kind["displayName"] = "Instance Method";
414     break;
415   case APIRecord::RK_CXXConstructorMethod:
416     Kind["identifier"] = AddLangPrefix("method");
417     Kind["displayName"] = "Constructor";
418     break;
419   case APIRecord::RK_CXXDestructorMethod:
420     Kind["identifier"] = AddLangPrefix("method");
421     Kind["displayName"] = "Destructor";
422     break;
423   case APIRecord::RK_ObjCIvar:
424     Kind["identifier"] = AddLangPrefix("ivar");
425     Kind["displayName"] = "Instance Variable";
426     break;
427   case APIRecord::RK_ObjCInstanceMethod:
428     Kind["identifier"] = AddLangPrefix("method");
429     Kind["displayName"] = "Instance Method";
430     break;
431   case APIRecord::RK_ObjCClassMethod:
432     Kind["identifier"] = AddLangPrefix("type.method");
433     Kind["displayName"] = "Type Method";
434     break;
435   case APIRecord::RK_ObjCInstanceProperty:
436     Kind["identifier"] = AddLangPrefix("property");
437     Kind["displayName"] = "Instance Property";
438     break;
439   case APIRecord::RK_ObjCClassProperty:
440     Kind["identifier"] = AddLangPrefix("type.property");
441     Kind["displayName"] = "Type Property";
442     break;
443   case APIRecord::RK_ObjCInterface:
444     Kind["identifier"] = AddLangPrefix("class");
445     Kind["displayName"] = "Class";
446     break;
447   case APIRecord::RK_ObjCCategory:
448     Kind["identifier"] = AddLangPrefix("class.extension");
449     Kind["displayName"] = "Class Extension";
450     break;
451   case APIRecord::RK_ObjCCategoryModule:
452     Kind["identifier"] = AddLangPrefix("module.extension");
453     Kind["displayName"] = "Module Extension";
454     break;
455   case APIRecord::RK_ObjCProtocol:
456     Kind["identifier"] = AddLangPrefix("protocol");
457     Kind["displayName"] = "Protocol";
458     break;
459   case APIRecord::RK_MacroDefinition:
460     Kind["identifier"] = AddLangPrefix("macro");
461     Kind["displayName"] = "Macro";
462     break;
463   case APIRecord::RK_Typedef:
464     Kind["identifier"] = AddLangPrefix("typealias");
465     Kind["displayName"] = "Type Alias";
466     break;
467   }
468 
469   return Kind;
470 }
471 
472 /// Serialize the symbol kind information.
473 ///
474 /// The Symbol Graph symbol kind property contains a shorthand \c identifier
475 /// which is prefixed by the source language name, useful for tooling to parse
476 /// the kind, and a \c displayName for rendering human-readable names.
477 Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
478   return serializeSymbolKind(Record.getKind(), Lang);
479 }
480 
481 template <typename RecordTy>
482 std::optional<Object>
483 serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::true_type) {
484   const auto &FS = Record.Signature;
485   if (FS.empty())
486     return std::nullopt;
487 
488   Object Signature;
489   serializeArray(Signature, "returns",
490                  serializeDeclarationFragments(FS.getReturnType()));
491 
492   Array Parameters;
493   for (const auto &P : FS.getParameters()) {
494     Object Parameter;
495     Parameter["name"] = P.Name;
496     serializeArray(Parameter, "declarationFragments",
497                    serializeDeclarationFragments(P.Fragments));
498     Parameters.emplace_back(std::move(Parameter));
499   }
500 
501   if (!Parameters.empty())
502     Signature["parameters"] = std::move(Parameters);
503 
504   return Signature;
505 }
506 
507 template <typename RecordTy>
508 std::optional<Object>
509 serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::false_type) {
510   return std::nullopt;
511 }
512 
513 /// Serialize the function signature field, as specified by the
514 /// Symbol Graph format.
515 ///
516 /// The Symbol Graph function signature property contains two arrays.
517 ///   - The \c returns array is the declaration fragments of the return type;
518 ///   - The \c parameters array contains names and declaration fragments of the
519 ///     parameters.
520 ///
521 /// \returns \c std::nullopt if \p FS is empty, or an \c Object containing the
522 /// formatted function signature.
523 template <typename RecordTy>
524 void serializeFunctionSignatureMixin(Object &Paren, const RecordTy &Record) {
525   serializeObject(Paren, "functionSignature",
526                   serializeFunctionSignatureMixinImpl(
527                       Record, has_function_signature<RecordTy>()));
528 }
529 
530 template <typename RecordTy>
531 std::optional<std::string> serializeAccessMixinImpl(const RecordTy &Record,
532                                                     std::true_type) {
533   const auto &AccessControl = Record.Access;
534   std::string Access;
535   if (AccessControl.empty())
536     return std::nullopt;
537   Access = AccessControl.getAccess();
538   return Access;
539 }
540 
541 template <typename RecordTy>
542 std::optional<std::string> serializeAccessMixinImpl(const RecordTy &Record,
543                                                     std::false_type) {
544   return std::nullopt;
545 }
546 
547 template <typename RecordTy>
548 void serializeAccessMixin(Object &Paren, const RecordTy &Record) {
549   auto accessLevel = serializeAccessMixinImpl(Record, has_access<RecordTy>());
550   if (!accessLevel.has_value())
551     accessLevel = "public";
552   serializeString(Paren, "accessLevel", accessLevel);
553 }
554 
555 template <typename RecordTy>
556 std::optional<Object> serializeTemplateMixinImpl(const RecordTy &Record,
557                                                  std::true_type) {
558   const auto &Template = Record.Templ;
559   if (Template.empty())
560     return std::nullopt;
561 
562   Object Generics;
563   Array GenericParameters;
564   for (const auto Param : Template.getParameters()) {
565     Object Parameter;
566     Parameter["name"] = Param.Name;
567     Parameter["index"] = Param.Index;
568     Parameter["depth"] = Param.Depth;
569     GenericParameters.emplace_back(std::move(Parameter));
570   }
571   if (!GenericParameters.empty())
572     Generics["parameters"] = std::move(GenericParameters);
573 
574   Array GenericConstraints;
575   for (const auto Constr : Template.getConstraints()) {
576     Object Constraint;
577     Constraint["kind"] = Constr.Kind;
578     Constraint["lhs"] = Constr.LHS;
579     Constraint["rhs"] = Constr.RHS;
580     GenericConstraints.emplace_back(std::move(Constraint));
581   }
582 
583   if (!GenericConstraints.empty())
584     Generics["constraints"] = std::move(GenericConstraints);
585 
586   return Generics;
587 }
588 
589 template <typename RecordTy>
590 std::optional<Object> serializeTemplateMixinImpl(const RecordTy &Record,
591                                                  std::false_type) {
592   return std::nullopt;
593 }
594 
595 template <typename RecordTy>
596 void serializeTemplateMixin(Object &Paren, const RecordTy &Record) {
597   serializeObject(Paren, "swiftGenerics",
598                   serializeTemplateMixinImpl(Record, has_template<RecordTy>()));
599 }
600 
601 struct PathComponent {
602   StringRef USR;
603   StringRef Name;
604   APIRecord::RecordKind Kind;
605 
606   PathComponent(StringRef USR, StringRef Name, APIRecord::RecordKind Kind)
607       : USR(USR), Name(Name), Kind(Kind) {}
608 };
609 
610 template <typename RecordTy>
611 bool generatePathComponents(
612     const RecordTy &Record, const APISet &API,
613     function_ref<void(const PathComponent &)> ComponentTransformer) {
614   SmallVector<PathComponent, 4> ReverseComponenents;
615   ReverseComponenents.emplace_back(Record.USR, Record.Name, Record.getKind());
616   const auto *CurrentParent = &Record.ParentInformation;
617   bool FailedToFindParent = false;
618   while (CurrentParent && !CurrentParent->empty()) {
619     PathComponent CurrentParentComponent(CurrentParent->ParentUSR,
620                                          CurrentParent->ParentName,
621                                          CurrentParent->ParentKind);
622 
623     auto *ParentRecord = CurrentParent->ParentRecord;
624     // Slow path if we don't have a direct reference to the ParentRecord
625     if (!ParentRecord)
626       ParentRecord = API.findRecordForUSR(CurrentParent->ParentUSR);
627 
628     // If the parent is a category extended from internal module then we need to
629     // pretend this belongs to the associated interface.
630     if (auto *CategoryRecord =
631             dyn_cast_or_null<ObjCCategoryRecord>(ParentRecord)) {
632       if (!CategoryRecord->IsFromExternalModule) {
633         ParentRecord = API.findRecordForUSR(CategoryRecord->Interface.USR);
634         CurrentParentComponent = PathComponent(CategoryRecord->Interface.USR,
635                                                CategoryRecord->Interface.Name,
636                                                APIRecord::RK_ObjCInterface);
637       }
638     }
639 
640     // The parent record doesn't exist which means the symbol shouldn't be
641     // treated as part of the current product.
642     if (!ParentRecord) {
643       FailedToFindParent = true;
644       break;
645     }
646 
647     ReverseComponenents.push_back(std::move(CurrentParentComponent));
648     CurrentParent = &ParentRecord->ParentInformation;
649   }
650 
651   for (const auto &PC : reverse(ReverseComponenents))
652     ComponentTransformer(PC);
653 
654   return FailedToFindParent;
655 }
656 
657 Object serializeParentContext(const PathComponent &PC, Language Lang) {
658   Object ParentContextElem;
659   ParentContextElem["usr"] = PC.USR;
660   ParentContextElem["name"] = PC.Name;
661   ParentContextElem["kind"] = serializeSymbolKind(PC.Kind, Lang)["identifier"];
662   return ParentContextElem;
663 }
664 
665 template <typename RecordTy>
666 Array generateParentContexts(const RecordTy &Record, const APISet &API,
667                              Language Lang) {
668   Array ParentContexts;
669   generatePathComponents(
670       Record, API, [Lang, &ParentContexts](const PathComponent &PC) {
671         ParentContexts.push_back(serializeParentContext(PC, Lang));
672       });
673 
674   return ParentContexts;
675 }
676 } // namespace
677 
678 /// Defines the format version emitted by SymbolGraphSerializer.
679 const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
680 
681 Object SymbolGraphSerializer::serializeMetadata() const {
682   Object Metadata;
683   serializeObject(Metadata, "formatVersion",
684                   serializeSemanticVersion(FormatVersion));
685   Metadata["generator"] = clang::getClangFullVersion();
686   return Metadata;
687 }
688 
689 Object SymbolGraphSerializer::serializeModule() const {
690   Object Module;
691   // The user is expected to always pass `--product-name=` on the command line
692   // to populate this field.
693   Module["name"] = API.ProductName;
694   serializeObject(Module, "platform", serializePlatform(API.getTarget()));
695   return Module;
696 }
697 
698 bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const {
699   // Skip explicitly ignored symbols.
700   if (IgnoresList.shouldIgnore(Record.Name))
701     return true;
702 
703   // Skip unconditionally unavailable symbols
704   if (Record.Availabilities.isUnconditionallyUnavailable())
705     return true;
706 
707   // Filter out symbols prefixed with an underscored as they are understood to
708   // be symbols clients should not use.
709   if (Record.Name.startswith("_"))
710     return true;
711 
712   return false;
713 }
714 
715 template <typename RecordTy>
716 std::optional<Object>
717 SymbolGraphSerializer::serializeAPIRecord(const RecordTy &Record) const {
718   if (shouldSkip(Record))
719     return std::nullopt;
720 
721   Object Obj;
722   serializeObject(Obj, "identifier",
723                   serializeIdentifier(Record, API.getLanguage()));
724   serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage()));
725   serializeObject(Obj, "names", serializeNames(Record));
726   serializeObject(
727       Obj, "location",
728       serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true));
729   serializeArray(Obj, "availability",
730                  serializeAvailability(Record.Availabilities));
731   serializeObject(Obj, "docComment", serializeDocComment(Record.Comment));
732   serializeArray(Obj, "declarationFragments",
733                  serializeDeclarationFragments(Record.Declaration));
734   SmallVector<StringRef, 4> PathComponentsNames;
735   // If this returns true it indicates that we couldn't find a symbol in the
736   // hierarchy.
737   if (generatePathComponents(Record, API,
738                              [&PathComponentsNames](const PathComponent &PC) {
739                                PathComponentsNames.push_back(PC.Name);
740                              }))
741     return {};
742 
743   serializeArray(Obj, "pathComponents", Array(PathComponentsNames));
744 
745   serializeFunctionSignatureMixin(Obj, Record);
746   serializeAccessMixin(Obj, Record);
747   serializeTemplateMixin(Obj, Record);
748 
749   return Obj;
750 }
751 
752 template <typename MemberTy>
753 void SymbolGraphSerializer::serializeMembers(
754     const APIRecord &Record,
755     const SmallVector<std::unique_ptr<MemberTy>> &Members) {
756   // Members should not be serialized if we aren't recursing.
757   if (!ShouldRecurse)
758     return;
759   for (const auto &Member : Members) {
760     auto MemberRecord = serializeAPIRecord(*Member);
761     if (!MemberRecord)
762       continue;
763 
764     Symbols.emplace_back(std::move(*MemberRecord));
765     serializeRelationship(RelationshipKind::MemberOf, *Member, Record);
766   }
767 }
768 
769 StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) {
770   switch (Kind) {
771   case RelationshipKind::MemberOf:
772     return "memberOf";
773   case RelationshipKind::InheritsFrom:
774     return "inheritsFrom";
775   case RelationshipKind::ConformsTo:
776     return "conformsTo";
777   case RelationshipKind::ExtensionTo:
778     return "extensionTo";
779   }
780   llvm_unreachable("Unhandled relationship kind");
781 }
782 
783 StringRef SymbolGraphSerializer::getConstraintString(ConstraintKind Kind) {
784   switch (Kind) {
785   case ConstraintKind::Conformance:
786     return "conformance";
787   case ConstraintKind::ConditionalConformance:
788     return "conditionalConformance";
789   }
790   llvm_unreachable("Unhandled constraint kind");
791 }
792 
793 void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind,
794                                                   SymbolReference Source,
795                                                   SymbolReference Target) {
796   Object Relationship;
797   Relationship["source"] = Source.USR;
798   Relationship["target"] = Target.USR;
799   Relationship["targetFallback"] = Target.Name;
800   Relationship["kind"] = getRelationshipString(Kind);
801 
802   Relationships.emplace_back(std::move(Relationship));
803 }
804 
805 void SymbolGraphSerializer::visitGlobalFunctionRecord(
806     const GlobalFunctionRecord &Record) {
807   auto Obj = serializeAPIRecord(Record);
808   if (!Obj)
809     return;
810 
811   Symbols.emplace_back(std::move(*Obj));
812 }
813 
814 void SymbolGraphSerializer::visitGlobalVariableRecord(
815     const GlobalVariableRecord &Record) {
816   auto Obj = serializeAPIRecord(Record);
817   if (!Obj)
818     return;
819 
820   Symbols.emplace_back(std::move(*Obj));
821 }
822 
823 void SymbolGraphSerializer::visitEnumRecord(const EnumRecord &Record) {
824   auto Enum = serializeAPIRecord(Record);
825   if (!Enum)
826     return;
827 
828   Symbols.emplace_back(std::move(*Enum));
829   serializeMembers(Record, Record.Constants);
830 }
831 
832 void SymbolGraphSerializer::visitStructRecord(const StructRecord &Record) {
833   auto Struct = serializeAPIRecord(Record);
834   if (!Struct)
835     return;
836 
837   Symbols.emplace_back(std::move(*Struct));
838   serializeMembers(Record, Record.Fields);
839 }
840 
841 void SymbolGraphSerializer::visitStaticFieldRecord(
842     const StaticFieldRecord &Record) {
843   auto StaticField = serializeAPIRecord(Record);
844   if (!StaticField)
845     return;
846   Symbols.emplace_back(std::move(*StaticField));
847   serializeRelationship(RelationshipKind::MemberOf, Record, Record.Context);
848 }
849 
850 void SymbolGraphSerializer::visitCXXClassRecord(const CXXClassRecord &Record) {
851   auto Class = serializeAPIRecord(Record);
852   if (!Class)
853     return;
854 
855   Symbols.emplace_back(std::move(*Class));
856   serializeMembers(Record, Record.Fields);
857   serializeMembers(Record, Record.Methods);
858 
859   for (const auto Base : Record.Bases)
860     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
861 }
862 
863 void SymbolGraphSerializer::visitClassTemplateRecord(
864     const ClassTemplateRecord &Record) {
865   auto Class = serializeAPIRecord(Record);
866   if (!Class)
867     return;
868 
869   Symbols.emplace_back(std::move(*Class));
870   serializeMembers(Record, Record.Fields);
871   serializeMembers(Record, Record.Methods);
872 
873   for (const auto Base : Record.Bases)
874     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
875 }
876 
877 void SymbolGraphSerializer::visitClassTemplateSpecializationRecord(
878     const ClassTemplateSpecializationRecord &Record) {
879   auto Class = serializeAPIRecord(Record);
880   if (!Class)
881     return;
882 
883   Symbols.emplace_back(std::move(*Class));
884   serializeMembers(Record, Record.Fields);
885   serializeMembers(Record, Record.Methods);
886 
887   for (const auto Base : Record.Bases)
888     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
889 }
890 
891 void SymbolGraphSerializer::visitClassTemplatePartialSpecializationRecord(
892     const ClassTemplatePartialSpecializationRecord &Record) {
893   auto Class = serializeAPIRecord(Record);
894   if (!Class)
895     return;
896 
897   Symbols.emplace_back(std::move(*Class));
898   serializeMembers(Record, Record.Fields);
899   serializeMembers(Record, Record.Methods);
900 
901   for (const auto Base : Record.Bases)
902     serializeRelationship(RelationshipKind::InheritsFrom, Record, Base);
903 }
904 
905 void SymbolGraphSerializer::visitConceptRecord(const ConceptRecord &Record) {
906   auto Concept = serializeAPIRecord(Record);
907   if (!Concept)
908     return;
909 
910   Symbols.emplace_back(std::move(*Concept));
911 }
912 
913 void SymbolGraphSerializer::visitObjCContainerRecord(
914     const ObjCContainerRecord &Record) {
915   auto ObjCContainer = serializeAPIRecord(Record);
916   if (!ObjCContainer)
917     return;
918 
919   Symbols.emplace_back(std::move(*ObjCContainer));
920 
921   serializeMembers(Record, Record.Ivars);
922   serializeMembers(Record, Record.Methods);
923   serializeMembers(Record, Record.Properties);
924 
925   for (const auto &Protocol : Record.Protocols)
926     // Record that Record conforms to Protocol.
927     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
928 
929   if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record)) {
930     if (!ObjCInterface->SuperClass.empty())
931       // If Record is an Objective-C interface record and it has a super class,
932       // record that Record is inherited from SuperClass.
933       serializeRelationship(RelationshipKind::InheritsFrom, Record,
934                             ObjCInterface->SuperClass);
935 
936     // Members of categories extending an interface are serialized as members of
937     // the interface.
938     for (const auto *Category : ObjCInterface->Categories) {
939       serializeMembers(Record, Category->Ivars);
940       serializeMembers(Record, Category->Methods);
941       serializeMembers(Record, Category->Properties);
942 
943       // Surface the protocols of the category to the interface.
944       for (const auto &Protocol : Category->Protocols)
945         serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
946     }
947   }
948 }
949 
950 void SymbolGraphSerializer::visitObjCCategoryRecord(
951     const ObjCCategoryRecord &Record) {
952   if (!Record.IsFromExternalModule)
953     return;
954 
955   // Check if the current Category' parent has been visited before, if so skip.
956   if (!visitedCategories.contains(Record.Interface.Name)) {
957     visitedCategories.insert(Record.Interface.Name);
958     Object Obj;
959     serializeObject(Obj, "identifier",
960                     serializeIdentifier(Record, API.getLanguage()));
961     serializeObject(Obj, "kind",
962                     serializeSymbolKind(APIRecord::RK_ObjCCategoryModule,
963                                         API.getLanguage()));
964     Obj["accessLevel"] = "public";
965     Symbols.emplace_back(std::move(Obj));
966   }
967 
968   Object Relationship;
969   Relationship["source"] = Record.USR;
970   Relationship["target"] = Record.Interface.USR;
971   Relationship["targetFallback"] = Record.Interface.Name;
972   Relationship["kind"] = getRelationshipString(RelationshipKind::ExtensionTo);
973   Relationships.emplace_back(std::move(Relationship));
974 
975   auto ObjCCategory = serializeAPIRecord(Record);
976 
977   if (!ObjCCategory)
978     return;
979 
980   Symbols.emplace_back(std::move(*ObjCCategory));
981   serializeMembers(Record, Record.Methods);
982   serializeMembers(Record, Record.Properties);
983 
984   // Surface the protocols of the category to the interface.
985   for (const auto &Protocol : Record.Protocols)
986     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
987 }
988 
989 void SymbolGraphSerializer::visitMacroDefinitionRecord(
990     const MacroDefinitionRecord &Record) {
991   auto Macro = serializeAPIRecord(Record);
992 
993   if (!Macro)
994     return;
995 
996   Symbols.emplace_back(std::move(*Macro));
997 }
998 
999 void SymbolGraphSerializer::serializeSingleRecord(const APIRecord *Record) {
1000   switch (Record->getKind()) {
1001   case APIRecord::RK_Unknown:
1002     llvm_unreachable("Records should have a known kind!");
1003   case APIRecord::RK_GlobalFunction:
1004     visitGlobalFunctionRecord(*cast<GlobalFunctionRecord>(Record));
1005     break;
1006   case APIRecord::RK_GlobalVariable:
1007     visitGlobalVariableRecord(*cast<GlobalVariableRecord>(Record));
1008     break;
1009   case APIRecord::RK_Enum:
1010     visitEnumRecord(*cast<EnumRecord>(Record));
1011     break;
1012   case APIRecord::RK_Struct:
1013     visitStructRecord(*cast<StructRecord>(Record));
1014     break;
1015   case APIRecord::RK_StaticField:
1016     visitStaticFieldRecord(*cast<StaticFieldRecord>(Record));
1017     break;
1018   case APIRecord::RK_CXXClass:
1019     visitCXXClassRecord(*cast<CXXClassRecord>(Record));
1020     break;
1021   case APIRecord::RK_ObjCInterface:
1022     visitObjCContainerRecord(*cast<ObjCInterfaceRecord>(Record));
1023     break;
1024   case APIRecord::RK_ObjCProtocol:
1025     visitObjCContainerRecord(*cast<ObjCProtocolRecord>(Record));
1026     break;
1027   case APIRecord::RK_ObjCCategory:
1028     visitObjCCategoryRecord(*cast<ObjCCategoryRecord>(Record));
1029     break;
1030   case APIRecord::RK_MacroDefinition:
1031     visitMacroDefinitionRecord(*cast<MacroDefinitionRecord>(Record));
1032     break;
1033   case APIRecord::RK_Typedef:
1034     visitTypedefRecord(*cast<TypedefRecord>(Record));
1035     break;
1036   default:
1037     if (auto Obj = serializeAPIRecord(*Record)) {
1038       Symbols.emplace_back(std::move(*Obj));
1039       auto &ParentInformation = Record->ParentInformation;
1040       if (!ParentInformation.empty())
1041         serializeRelationship(RelationshipKind::MemberOf, *Record,
1042                               *ParentInformation.ParentRecord);
1043     }
1044     break;
1045   }
1046 }
1047 
1048 void SymbolGraphSerializer::visitTypedefRecord(const TypedefRecord &Record) {
1049   // Typedefs of anonymous types have their entries unified with the underlying
1050   // type.
1051   bool ShouldDrop = Record.UnderlyingType.Name.empty();
1052   // enums declared with `NS_OPTION` have a named enum and a named typedef, with
1053   // the same name
1054   ShouldDrop |= (Record.UnderlyingType.Name == Record.Name);
1055   if (ShouldDrop)
1056     return;
1057 
1058   auto Typedef = serializeAPIRecord(Record);
1059   if (!Typedef)
1060     return;
1061 
1062   (*Typedef)["type"] = Record.UnderlyingType.USR;
1063 
1064   Symbols.emplace_back(std::move(*Typedef));
1065 }
1066 
1067 Object SymbolGraphSerializer::serialize() {
1068   traverseAPISet();
1069   return serializeCurrentGraph();
1070 }
1071 
1072 Object SymbolGraphSerializer::serializeCurrentGraph() {
1073   Object Root;
1074   serializeObject(Root, "metadata", serializeMetadata());
1075   serializeObject(Root, "module", serializeModule());
1076 
1077   Root["symbols"] = std::move(Symbols);
1078   Root["relationships"] = std::move(Relationships);
1079 
1080   return Root;
1081 }
1082 
1083 void SymbolGraphSerializer::serialize(raw_ostream &os) {
1084   Object root = serialize();
1085   if (Options.Compact)
1086     os << formatv("{0}", Value(std::move(root))) << "\n";
1087   else
1088     os << formatv("{0:2}", Value(std::move(root))) << "\n";
1089 }
1090 
1091 std::optional<Object>
1092 SymbolGraphSerializer::serializeSingleSymbolSGF(StringRef USR,
1093                                                 const APISet &API) {
1094   APIRecord *Record = API.findRecordForUSR(USR);
1095   if (!Record)
1096     return {};
1097 
1098   Object Root;
1099   APIIgnoresList EmptyIgnores;
1100   SymbolGraphSerializer Serializer(API, EmptyIgnores,
1101                                    /*Options.Compact*/ {true},
1102                                    /*ShouldRecurse*/ false);
1103   Serializer.serializeSingleRecord(Record);
1104   serializeObject(Root, "symbolGraph", Serializer.serializeCurrentGraph());
1105 
1106   Language Lang = API.getLanguage();
1107   serializeArray(Root, "parentContexts",
1108                  generateParentContexts(*Record, API, Lang));
1109 
1110   Array RelatedSymbols;
1111 
1112   for (const auto &Fragment : Record->Declaration.getFragments()) {
1113     // If we don't have a USR there isn't much we can do.
1114     if (Fragment.PreciseIdentifier.empty())
1115       continue;
1116 
1117     APIRecord *RelatedRecord = API.findRecordForUSR(Fragment.PreciseIdentifier);
1118 
1119     // If we can't find the record let's skip.
1120     if (!RelatedRecord)
1121       continue;
1122 
1123     Object RelatedSymbol;
1124     RelatedSymbol["usr"] = RelatedRecord->USR;
1125     RelatedSymbol["declarationLanguage"] = getLanguageName(Lang);
1126     // TODO: once we record this properly let's serialize it right.
1127     RelatedSymbol["accessLevel"] = "public";
1128     RelatedSymbol["filePath"] = RelatedRecord->Location.getFilename();
1129     RelatedSymbol["moduleName"] = API.ProductName;
1130     RelatedSymbol["isSystem"] = RelatedRecord->IsFromSystemHeader;
1131 
1132     serializeArray(RelatedSymbol, "parentContexts",
1133                    generateParentContexts(*RelatedRecord, API, Lang));
1134     RelatedSymbols.push_back(std::move(RelatedSymbol));
1135   }
1136 
1137   serializeArray(Root, "relatedSymbols", RelatedSymbols);
1138   return Root;
1139 }
1140