xref: /llvm-project/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp (revision 178aad9b946e3c5abe9df162e5c482fb4acae99c)
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/Version.h"
16 #include "clang/ExtractAPI/API.h"
17 #include "llvm/Support/JSON.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/VersionTuple.h"
20 
21 using namespace clang;
22 using namespace clang::extractapi;
23 using namespace llvm;
24 using namespace llvm::json;
25 
26 namespace {
27 
28 /// Helper function to inject a JSON object \p Obj into another object \p Paren
29 /// at position \p Key.
30 void serializeObject(Object &Paren, StringRef Key, Optional<Object> Obj) {
31   if (Obj)
32     Paren[Key] = std::move(Obj.getValue());
33 }
34 
35 /// Helper function to inject a JSON array \p Array into object \p Paren at
36 /// position \p Key.
37 void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) {
38   if (Array)
39     Paren[Key] = std::move(Array.getValue());
40 }
41 
42 /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version
43 /// format.
44 ///
45 /// A semantic version object contains three numeric fields, representing the
46 /// \c major, \c minor, and \c patch parts of the version tuple.
47 /// For example version tuple 1.0.3 is serialized as:
48 /// \code
49 ///   {
50 ///     "major" : 1,
51 ///     "minor" : 0,
52 ///     "patch" : 3
53 ///   }
54 /// \endcode
55 ///
56 /// \returns \c None if the version \p V is empty, or an \c Object containing
57 /// the semantic version representation of \p V.
58 Optional<Object> serializeSemanticVersion(const VersionTuple &V) {
59   if (V.empty())
60     return None;
61 
62   Object Version;
63   Version["major"] = V.getMajor();
64   Version["minor"] = V.getMinor().getValueOr(0);
65   Version["patch"] = V.getSubminor().getValueOr(0);
66   return Version;
67 }
68 
69 /// Serialize the OS information in the Symbol Graph platform property.
70 ///
71 /// The OS information in Symbol Graph contains the \c name of the OS, and an
72 /// optional \c minimumVersion semantic version field.
73 Object serializeOperatingSystem(const Triple &T) {
74   Object OS;
75   OS["name"] = T.getOSTypeName(T.getOS());
76   serializeObject(OS, "minimumVersion",
77                   serializeSemanticVersion(T.getMinimumSupportedOSVersion()));
78   return OS;
79 }
80 
81 /// Serialize the platform information in the Symbol Graph module section.
82 ///
83 /// The platform object describes a target platform triple in corresponding
84 /// three fields: \c architecture, \c vendor, and \c operatingSystem.
85 Object serializePlatform(const Triple &T) {
86   Object Platform;
87   Platform["architecture"] = T.getArchName();
88   Platform["vendor"] = T.getVendorName();
89   Platform["operatingSystem"] = serializeOperatingSystem(T);
90   return Platform;
91 }
92 
93 /// Serialize a source position.
94 Object serializeSourcePosition(const PresumedLoc &Loc) {
95   assert(Loc.isValid() && "invalid source position");
96 
97   Object SourcePosition;
98   SourcePosition["line"] = Loc.getLine();
99   SourcePosition["character"] = Loc.getColumn();
100 
101   return SourcePosition;
102 }
103 
104 /// Serialize a source location in file.
105 ///
106 /// \param Loc The presumed location to serialize.
107 /// \param IncludeFileURI If true, include the file path of \p Loc as a URI.
108 /// Defaults to false.
109 Object serializeSourceLocation(const PresumedLoc &Loc,
110                                bool IncludeFileURI = false) {
111   Object SourceLocation;
112   serializeObject(SourceLocation, "position", serializeSourcePosition(Loc));
113 
114   if (IncludeFileURI) {
115     std::string FileURI = "file://";
116     // Normalize file path to use forward slashes for the URI.
117     FileURI += sys::path::convert_to_slash(Loc.getFilename());
118     SourceLocation["uri"] = FileURI;
119   }
120 
121   return SourceLocation;
122 }
123 
124 /// Serialize a source range with begin and end locations.
125 Object serializeSourceRange(const PresumedLoc &BeginLoc,
126                             const PresumedLoc &EndLoc) {
127   Object SourceRange;
128   serializeObject(SourceRange, "start", serializeSourcePosition(BeginLoc));
129   serializeObject(SourceRange, "end", serializeSourcePosition(EndLoc));
130   return SourceRange;
131 }
132 
133 /// Serialize the availability attributes of a symbol.
134 ///
135 /// Availability information contains the introduced, deprecated, and obsoleted
136 /// versions of the symbol as semantic versions, if not default.
137 /// Availability information also contains flags to indicate if the symbol is
138 /// unconditionally unavailable or deprecated,
139 /// i.e. \c __attribute__((unavailable)) and \c __attribute__((deprecated)).
140 ///
141 /// \returns \c None if the symbol has default availability attributes, or
142 /// an \c Object containing the formatted availability information.
143 Optional<Object> serializeAvailability(const AvailabilityInfo &Avail) {
144   if (Avail.isDefault())
145     return None;
146 
147   Object Availbility;
148   serializeObject(Availbility, "introducedVersion",
149                   serializeSemanticVersion(Avail.Introduced));
150   serializeObject(Availbility, "deprecatedVersion",
151                   serializeSemanticVersion(Avail.Deprecated));
152   serializeObject(Availbility, "obsoletedVersion",
153                   serializeSemanticVersion(Avail.Obsoleted));
154   if (Avail.isUnavailable())
155     Availbility["isUnconditionallyUnavailable"] = true;
156   if (Avail.isUnconditionallyDeprecated())
157     Availbility["isUnconditionallyDeprecated"] = true;
158 
159   return Availbility;
160 }
161 
162 /// Get the language name string for interface language references.
163 StringRef getLanguageName(Language Lang) {
164   switch (Lang) {
165   case Language::C:
166     return "c";
167   case Language::ObjC:
168     return "objective-c";
169 
170   // Unsupported language currently
171   case Language::CXX:
172   case Language::ObjCXX:
173   case Language::OpenCL:
174   case Language::OpenCLCXX:
175   case Language::CUDA:
176   case Language::RenderScript:
177   case Language::HIP:
178   case Language::HLSL:
179 
180   // Languages that the frontend cannot parse and compile
181   case Language::Unknown:
182   case Language::Asm:
183   case Language::LLVM_IR:
184     llvm_unreachable("Unsupported language kind");
185   }
186 
187   llvm_unreachable("Unhandled language kind");
188 }
189 
190 /// Serialize the identifier object as specified by the Symbol Graph format.
191 ///
192 /// The identifier property of a symbol contains the USR for precise and unique
193 /// references, and the interface language name.
194 Object serializeIdentifier(const APIRecord &Record, Language Lang) {
195   Object Identifier;
196   Identifier["precise"] = Record.USR;
197   Identifier["interfaceLanguage"] = getLanguageName(Lang);
198 
199   return Identifier;
200 }
201 
202 /// Serialize the documentation comments attached to a symbol, as specified by
203 /// the Symbol Graph format.
204 ///
205 /// The Symbol Graph \c docComment object contains an array of lines. Each line
206 /// represents one line of striped documentation comment, with source range
207 /// information.
208 /// e.g.
209 /// \code
210 ///   /// This is a documentation comment
211 ///       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'  First line.
212 ///   ///     with multiple lines.
213 ///       ^~~~~~~~~~~~~~~~~~~~~~~'         Second line.
214 /// \endcode
215 ///
216 /// \returns \c None if \p Comment is empty, or an \c Object containing the
217 /// formatted lines.
218 Optional<Object> serializeDocComment(const DocComment &Comment) {
219   if (Comment.empty())
220     return None;
221 
222   Object DocComment;
223   Array LinesArray;
224   for (const auto &CommentLine : Comment) {
225     Object Line;
226     Line["text"] = CommentLine.Text;
227     serializeObject(Line, "range",
228                     serializeSourceRange(CommentLine.Begin, CommentLine.End));
229     LinesArray.emplace_back(std::move(Line));
230   }
231   serializeArray(DocComment, "lines", LinesArray);
232 
233   return DocComment;
234 }
235 
236 /// Serialize the declaration fragments of a symbol.
237 ///
238 /// The Symbol Graph declaration fragments is an array of tagged important
239 /// parts of a symbol's declaration. The fragments sequence can be joined to
240 /// form spans of declaration text, with attached information useful for
241 /// purposes like syntax-highlighting etc. For example:
242 /// \code
243 ///   const int pi; -> "declarationFragments" : [
244 ///                      {
245 ///                        "kind" : "keyword",
246 ///                        "spelling" : "const"
247 ///                      },
248 ///                      {
249 ///                        "kind" : "text",
250 ///                        "spelling" : " "
251 ///                      },
252 ///                      {
253 ///                        "kind" : "typeIdentifier",
254 ///                        "preciseIdentifier" : "c:I",
255 ///                        "spelling" : "int"
256 ///                      },
257 ///                      {
258 ///                        "kind" : "text",
259 ///                        "spelling" : " "
260 ///                      },
261 ///                      {
262 ///                        "kind" : "identifier",
263 ///                        "spelling" : "pi"
264 ///                      }
265 ///                    ]
266 /// \endcode
267 ///
268 /// \returns \c None if \p DF is empty, or an \c Array containing the formatted
269 /// declaration fragments array.
270 Optional<Array> serializeDeclarationFragments(const DeclarationFragments &DF) {
271   if (DF.getFragments().empty())
272     return None;
273 
274   Array Fragments;
275   for (const auto &F : DF.getFragments()) {
276     Object Fragment;
277     Fragment["spelling"] = F.Spelling;
278     Fragment["kind"] = DeclarationFragments::getFragmentKindString(F.Kind);
279     if (!F.PreciseIdentifier.empty())
280       Fragment["preciseIdentifier"] = F.PreciseIdentifier;
281     Fragments.emplace_back(std::move(Fragment));
282   }
283 
284   return Fragments;
285 }
286 
287 /// Serialize the function signature field of a function, as specified by the
288 /// Symbol Graph format.
289 ///
290 /// The Symbol Graph function signature property contains two arrays.
291 ///   - The \c returns array is the declaration fragments of the return type;
292 ///   - The \c parameters array contains names and declaration fragments of the
293 ///     parameters.
294 ///
295 /// \returns \c None if \p FS is empty, or an \c Object containing the
296 /// formatted function signature.
297 Optional<Object> serializeFunctionSignature(const FunctionSignature &FS) {
298   if (FS.empty())
299     return None;
300 
301   Object Signature;
302   serializeArray(Signature, "returns",
303                  serializeDeclarationFragments(FS.getReturnType()));
304 
305   Array Parameters;
306   for (const auto &P : FS.getParameters()) {
307     Object Parameter;
308     Parameter["name"] = P.Name;
309     serializeArray(Parameter, "declarationFragments",
310                    serializeDeclarationFragments(P.Fragments));
311     Parameters.emplace_back(std::move(Parameter));
312   }
313 
314   if (!Parameters.empty())
315     Signature["parameters"] = std::move(Parameters);
316 
317   return Signature;
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   Names["title"] = Record.Name;
332   serializeArray(Names, "subHeading",
333                  serializeDeclarationFragments(Record.SubHeading));
334 
335   return Names;
336 }
337 
338 /// Serialize the symbol kind information.
339 ///
340 /// The Symbol Graph symbol kind property contains a shorthand \c identifier
341 /// which is prefixed by the source language name, useful for tooling to parse
342 /// the kind, and a \c displayName for rendering human-readable names.
343 Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
344   auto AddLangPrefix = [&Lang](StringRef S) -> std::string {
345     return (getLanguageName(Lang) + "." + S).str();
346   };
347 
348   Object Kind;
349   switch (Record.getKind()) {
350   case APIRecord::RK_Global: {
351     auto *GR = dyn_cast<GlobalRecord>(&Record);
352     switch (GR->GlobalKind) {
353     case GVKind::Function:
354       Kind["identifier"] = AddLangPrefix("func");
355       Kind["displayName"] = "Function";
356       break;
357     case GVKind::Variable:
358       Kind["identifier"] = AddLangPrefix("var");
359       Kind["displayName"] = "Global Variable";
360       break;
361     case GVKind::Unknown:
362       // Unknown global kind
363       break;
364     }
365     break;
366   }
367   case APIRecord::RK_EnumConstant:
368     Kind["identifier"] = AddLangPrefix("enum.case");
369     Kind["displayName"] = "Enumeration Case";
370     break;
371   case APIRecord::RK_Enum:
372     Kind["identifier"] = AddLangPrefix("enum");
373     Kind["displayName"] = "Enumeration";
374     break;
375   case APIRecord::RK_StructField:
376     Kind["identifier"] = AddLangPrefix("property");
377     Kind["displayName"] = "Instance Property";
378     break;
379   case APIRecord::RK_Struct:
380     Kind["identifier"] = AddLangPrefix("struct");
381     Kind["displayName"] = "Structure";
382     break;
383   case APIRecord::RK_ObjCIvar:
384     Kind["identifier"] = AddLangPrefix("ivar");
385     Kind["displayName"] = "Instance Variable";
386     break;
387   case APIRecord::RK_ObjCMethod:
388     if (dyn_cast<ObjCMethodRecord>(&Record)->IsInstanceMethod) {
389       Kind["identifier"] = AddLangPrefix("method");
390       Kind["displayName"] = "Instance Method";
391     } else {
392       Kind["identifier"] = AddLangPrefix("type.method");
393       Kind["displayName"] = "Type Method";
394     }
395     break;
396   case APIRecord::RK_ObjCProperty:
397     Kind["identifier"] = AddLangPrefix("property");
398     Kind["displayName"] = "Instance Property";
399     break;
400   case APIRecord::RK_ObjCInterface:
401     Kind["identifier"] = AddLangPrefix("class");
402     Kind["displayName"] = "Class";
403     break;
404   case APIRecord::RK_ObjCCategory:
405     // We don't serialize out standalone Objective-C category symbols yet.
406     llvm_unreachable("Serializing standalone Objective-C category symbols is "
407                      "not supported.");
408     break;
409   case APIRecord::RK_ObjCProtocol:
410     Kind["identifier"] = AddLangPrefix("protocol");
411     Kind["displayName"] = "Protocol";
412     break;
413   case APIRecord::RK_MacroDefinition:
414     Kind["identifier"] = AddLangPrefix("macro");
415     Kind["displayName"] = "Macro";
416     break;
417   case APIRecord::RK_Typedef:
418     Kind["identifier"] = AddLangPrefix("typealias");
419     Kind["displayName"] = "Type Alias";
420     break;
421   }
422 
423   return Kind;
424 }
425 
426 } // namespace
427 
428 void SymbolGraphSerializer::anchor() {}
429 
430 /// Defines the format version emitted by SymbolGraphSerializer.
431 const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
432 
433 Object SymbolGraphSerializer::serializeMetadata() const {
434   Object Metadata;
435   serializeObject(Metadata, "formatVersion",
436                   serializeSemanticVersion(FormatVersion));
437   Metadata["generator"] = clang::getClangFullVersion();
438   return Metadata;
439 }
440 
441 Object SymbolGraphSerializer::serializeModule() const {
442   Object Module;
443   // The user is expected to always pass `--product-name=` on the command line
444   // to populate this field.
445   Module["name"] = ProductName;
446   serializeObject(Module, "platform", serializePlatform(API.getTarget()));
447   return Module;
448 }
449 
450 bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const {
451   // Skip unconditionally unavailable symbols
452   if (Record.Availability.isUnconditionallyUnavailable())
453     return true;
454 
455   return false;
456 }
457 
458 Optional<Object>
459 SymbolGraphSerializer::serializeAPIRecord(const APIRecord &Record) const {
460   if (shouldSkip(Record))
461     return None;
462 
463   Object Obj;
464   serializeObject(Obj, "identifier",
465                   serializeIdentifier(Record, API.getLanguage()));
466   serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage()));
467   serializeObject(Obj, "names", serializeNames(Record));
468   serializeObject(
469       Obj, "location",
470       serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true));
471   serializeObject(Obj, "availbility",
472                   serializeAvailability(Record.Availability));
473   serializeObject(Obj, "docComment", serializeDocComment(Record.Comment));
474   serializeArray(Obj, "declarationFragments",
475                  serializeDeclarationFragments(Record.Declaration));
476   // TODO: Once we keep track of symbol access information serialize it
477   // correctly here.
478   Obj["accessLevel"] = "public";
479   serializeArray(Obj, "pathComponents", Array(PathComponents));
480 
481   return Obj;
482 }
483 
484 template <typename MemberTy>
485 void SymbolGraphSerializer::serializeMembers(
486     const APIRecord &Record,
487     const SmallVector<std::unique_ptr<MemberTy>> &Members) {
488   for (const auto &Member : Members) {
489     auto MemberPathComponentGuard = makePathComponentGuard(Member->Name);
490     auto MemberRecord = serializeAPIRecord(*Member);
491     if (!MemberRecord)
492       continue;
493 
494     Symbols.emplace_back(std::move(*MemberRecord));
495     serializeRelationship(RelationshipKind::MemberOf, *Member, Record);
496   }
497 }
498 
499 StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) {
500   switch (Kind) {
501   case RelationshipKind::MemberOf:
502     return "memberOf";
503   case RelationshipKind::InheritsFrom:
504     return "inheritsFrom";
505   case RelationshipKind::ConformsTo:
506     return "conformsTo";
507   }
508   llvm_unreachable("Unhandled relationship kind");
509 }
510 
511 void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind,
512                                                   SymbolReference Source,
513                                                   SymbolReference Target) {
514   Object Relationship;
515   Relationship["source"] = Source.USR;
516   Relationship["target"] = Target.USR;
517   Relationship["kind"] = getRelationshipString(Kind);
518 
519   Relationships.emplace_back(std::move(Relationship));
520 }
521 
522 void SymbolGraphSerializer::serializeGlobalRecord(const GlobalRecord &Record) {
523   auto GlobalPathComponentGuard = makePathComponentGuard(Record.Name);
524 
525   auto Obj = serializeAPIRecord(Record);
526   if (!Obj)
527     return;
528 
529   if (Record.GlobalKind == GVKind::Function)
530     serializeObject(*Obj, "functionSignature",
531                     serializeFunctionSignature(Record.Signature));
532 
533   Symbols.emplace_back(std::move(*Obj));
534 }
535 
536 void SymbolGraphSerializer::serializeEnumRecord(const EnumRecord &Record) {
537   auto EnumPathComponentGuard = makePathComponentGuard(Record.Name);
538   auto Enum = serializeAPIRecord(Record);
539   if (!Enum)
540     return;
541 
542   Symbols.emplace_back(std::move(*Enum));
543   serializeMembers(Record, Record.Constants);
544 }
545 
546 void SymbolGraphSerializer::serializeStructRecord(const StructRecord &Record) {
547   auto StructPathComponentGuard = makePathComponentGuard(Record.Name);
548   auto Struct = serializeAPIRecord(Record);
549   if (!Struct)
550     return;
551 
552   Symbols.emplace_back(std::move(*Struct));
553   serializeMembers(Record, Record.Fields);
554 }
555 
556 void SymbolGraphSerializer::serializeObjCContainerRecord(
557     const ObjCContainerRecord &Record) {
558   auto ObjCContainerPathComponentGuard = makePathComponentGuard(Record.Name);
559   auto ObjCContainer = serializeAPIRecord(Record);
560   if (!ObjCContainer)
561     return;
562 
563   Symbols.emplace_back(std::move(*ObjCContainer));
564 
565   serializeMembers(Record, Record.Ivars);
566   serializeMembers(Record, Record.Methods);
567   serializeMembers(Record, Record.Properties);
568 
569   for (const auto &Protocol : Record.Protocols)
570     // Record that Record conforms to Protocol.
571     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
572 
573   if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record)) {
574     if (!ObjCInterface->SuperClass.empty())
575       // If Record is an Objective-C interface record and it has a super class,
576       // record that Record is inherited from SuperClass.
577       serializeRelationship(RelationshipKind::InheritsFrom, Record,
578                             ObjCInterface->SuperClass);
579 
580     // Members of categories extending an interface are serialized as members of
581     // the interface.
582     for (const auto *Category : ObjCInterface->Categories) {
583       serializeMembers(Record, Category->Ivars);
584       serializeMembers(Record, Category->Methods);
585       serializeMembers(Record, Category->Properties);
586 
587       // Surface the protocols of the the category to the interface.
588       for (const auto &Protocol : Category->Protocols)
589         serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
590     }
591   }
592 }
593 
594 void SymbolGraphSerializer::serializeMacroDefinitionRecord(
595     const MacroDefinitionRecord &Record) {
596   auto MacroPathComponentGuard = makePathComponentGuard(Record.Name);
597   auto Macro = serializeAPIRecord(Record);
598 
599   if (!Macro)
600     return;
601 
602   Symbols.emplace_back(std::move(*Macro));
603 }
604 
605 void SymbolGraphSerializer::serializeTypedefRecord(
606     const TypedefRecord &Record) {
607   // Typedefs of anonymous types have their entries unified with the underlying
608   // type.
609   bool ShouldDrop = Record.UnderlyingType.Name.empty();
610   // enums declared with `NS_OPTION` have a named enum and a named typedef, with
611   // the same name
612   ShouldDrop |= (Record.UnderlyingType.Name == Record.Name);
613   if (ShouldDrop)
614     return;
615 
616   auto TypedefPathComponentGuard = makePathComponentGuard(Record.Name);
617   auto Typedef = serializeAPIRecord(Record);
618   if (!Typedef)
619     return;
620 
621   (*Typedef)["type"] = Record.UnderlyingType.USR;
622 
623   Symbols.emplace_back(std::move(*Typedef));
624 }
625 
626 SymbolGraphSerializer::PathComponentGuard
627 SymbolGraphSerializer::makePathComponentGuard(StringRef Component) {
628   return PathComponentGuard(PathComponents, Component);
629 }
630 
631 Object SymbolGraphSerializer::serialize() {
632   Object Root;
633   serializeObject(Root, "metadata", serializeMetadata());
634   serializeObject(Root, "module", serializeModule());
635 
636   // Serialize global records in the API set.
637   for (const auto &Global : API.getGlobals())
638     serializeGlobalRecord(*Global.second);
639 
640   // Serialize enum records in the API set.
641   for (const auto &Enum : API.getEnums())
642     serializeEnumRecord(*Enum.second);
643 
644   // Serialize struct records in the API set.
645   for (const auto &Struct : API.getStructs())
646     serializeStructRecord(*Struct.second);
647 
648   // Serialize Objective-C interface records in the API set.
649   for (const auto &ObjCInterface : API.getObjCInterfaces())
650     serializeObjCContainerRecord(*ObjCInterface.second);
651 
652   // Serialize Objective-C protocol records in the API set.
653   for (const auto &ObjCProtocol : API.getObjCProtocols())
654     serializeObjCContainerRecord(*ObjCProtocol.second);
655 
656   for (const auto &Macro : API.getMacros())
657     serializeMacroDefinitionRecord(*Macro.second);
658 
659   for (const auto &Typedef : API.getTypedefs())
660     serializeTypedefRecord(*Typedef.second);
661 
662   Root["symbols"] = std::move(Symbols);
663   Root["relationships"] = std::move(Relationships);
664 
665   return Root;
666 }
667 
668 void SymbolGraphSerializer::serialize(raw_ostream &os) {
669   Object root = serialize();
670   if (Options.Compact)
671     os << formatv("{0}", Value(std::move(root))) << "\n";
672   else
673     os << formatv("{0:2}", Value(std::move(root))) << "\n";
674 }
675