189f6b26fSZixu Wang //===- ExtractAPI/Serialization/SymbolGraphSerializer.cpp -------*- C++ -*-===//
289f6b26fSZixu Wang //
389f6b26fSZixu Wang // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
489f6b26fSZixu Wang // See https://llvm.org/LICENSE.txt for license information.
589f6b26fSZixu Wang // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
689f6b26fSZixu Wang //
789f6b26fSZixu Wang //===----------------------------------------------------------------------===//
889f6b26fSZixu Wang ///
989f6b26fSZixu Wang /// \file
1089f6b26fSZixu Wang /// This file implements the SymbolGraphSerializer.
1189f6b26fSZixu Wang ///
1289f6b26fSZixu Wang //===----------------------------------------------------------------------===//
1389f6b26fSZixu Wang 
1489f6b26fSZixu Wang #include "clang/ExtractAPI/Serialization/SymbolGraphSerializer.h"
1589f6b26fSZixu Wang #include "clang/Basic/Version.h"
1689f6b26fSZixu Wang #include "clang/ExtractAPI/API.h"
1789f6b26fSZixu Wang #include "llvm/Support/JSON.h"
1889f6b26fSZixu Wang #include "llvm/Support/Path.h"
1989f6b26fSZixu Wang #include "llvm/Support/VersionTuple.h"
2089f6b26fSZixu Wang 
2189f6b26fSZixu Wang using namespace clang;
2289f6b26fSZixu Wang using namespace clang::extractapi;
2389f6b26fSZixu Wang using namespace llvm;
2489f6b26fSZixu Wang using namespace llvm::json;
2589f6b26fSZixu Wang 
2689f6b26fSZixu Wang namespace {
2789f6b26fSZixu Wang 
2889f6b26fSZixu Wang /// Helper function to inject a JSON object \p Obj into another object \p Paren
2989f6b26fSZixu Wang /// at position \p Key.
3089f6b26fSZixu Wang void serializeObject(Object &Paren, StringRef Key, Optional<Object> Obj) {
3189f6b26fSZixu Wang   if (Obj)
3289f6b26fSZixu Wang     Paren[Key] = std::move(Obj.getValue());
3389f6b26fSZixu Wang }
3489f6b26fSZixu Wang 
3589f6b26fSZixu Wang /// Helper function to inject a JSON array \p Array into object \p Paren at
3689f6b26fSZixu Wang /// position \p Key.
3789f6b26fSZixu Wang void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) {
3889f6b26fSZixu Wang   if (Array)
3989f6b26fSZixu Wang     Paren[Key] = std::move(Array.getValue());
4089f6b26fSZixu Wang }
4189f6b26fSZixu Wang 
4289f6b26fSZixu Wang /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version
4389f6b26fSZixu Wang /// format.
4489f6b26fSZixu Wang ///
4589f6b26fSZixu Wang /// A semantic version object contains three numeric fields, representing the
4689f6b26fSZixu Wang /// \c major, \c minor, and \c patch parts of the version tuple.
4789f6b26fSZixu Wang /// For example version tuple 1.0.3 is serialized as:
4889f6b26fSZixu Wang /// \code
4989f6b26fSZixu Wang ///   {
5089f6b26fSZixu Wang ///     "major" : 1,
5189f6b26fSZixu Wang ///     "minor" : 0,
5289f6b26fSZixu Wang ///     "patch" : 3
5389f6b26fSZixu Wang ///   }
5489f6b26fSZixu Wang /// \endcode
5589f6b26fSZixu Wang ///
5689f6b26fSZixu Wang /// \returns \c None if the version \p V is empty, or an \c Object containing
5789f6b26fSZixu Wang /// the semantic version representation of \p V.
5889f6b26fSZixu Wang Optional<Object> serializeSemanticVersion(const VersionTuple &V) {
5989f6b26fSZixu Wang   if (V.empty())
6089f6b26fSZixu Wang     return None;
6189f6b26fSZixu Wang 
6289f6b26fSZixu Wang   Object Version;
6389f6b26fSZixu Wang   Version["major"] = V.getMajor();
6489f6b26fSZixu Wang   Version["minor"] = V.getMinor().getValueOr(0);
6589f6b26fSZixu Wang   Version["patch"] = V.getSubminor().getValueOr(0);
6689f6b26fSZixu Wang   return Version;
6789f6b26fSZixu Wang }
6889f6b26fSZixu Wang 
6989f6b26fSZixu Wang /// Serialize the OS information in the Symbol Graph platform property.
7089f6b26fSZixu Wang ///
7189f6b26fSZixu Wang /// The OS information in Symbol Graph contains the \c name of the OS, and an
7289f6b26fSZixu Wang /// optional \c minimumVersion semantic version field.
7389f6b26fSZixu Wang Object serializeOperatingSystem(const Triple &T) {
7489f6b26fSZixu Wang   Object OS;
7589f6b26fSZixu Wang   OS["name"] = T.getOSTypeName(T.getOS());
7689f6b26fSZixu Wang   serializeObject(OS, "minimumVersion",
7789f6b26fSZixu Wang                   serializeSemanticVersion(T.getMinimumSupportedOSVersion()));
7889f6b26fSZixu Wang   return OS;
7989f6b26fSZixu Wang }
8089f6b26fSZixu Wang 
8189f6b26fSZixu Wang /// Serialize the platform information in the Symbol Graph module section.
8289f6b26fSZixu Wang ///
8389f6b26fSZixu Wang /// The platform object describes a target platform triple in corresponding
8489f6b26fSZixu Wang /// three fields: \c architecture, \c vendor, and \c operatingSystem.
8589f6b26fSZixu Wang Object serializePlatform(const Triple &T) {
8689f6b26fSZixu Wang   Object Platform;
8789f6b26fSZixu Wang   Platform["architecture"] = T.getArchName();
8889f6b26fSZixu Wang   Platform["vendor"] = T.getVendorName();
8989f6b26fSZixu Wang   Platform["operatingSystem"] = serializeOperatingSystem(T);
9089f6b26fSZixu Wang   return Platform;
9189f6b26fSZixu Wang }
9289f6b26fSZixu Wang 
9328d79314SDaniel Grumberg /// Serialize a source position.
9428d79314SDaniel Grumberg Object serializeSourcePosition(const PresumedLoc &Loc) {
9589f6b26fSZixu Wang   assert(Loc.isValid() && "invalid source position");
9689f6b26fSZixu Wang 
9789f6b26fSZixu Wang   Object SourcePosition;
9889f6b26fSZixu Wang   SourcePosition["line"] = Loc.getLine();
9989f6b26fSZixu Wang   SourcePosition["character"] = Loc.getColumn();
10089f6b26fSZixu Wang 
10128d79314SDaniel Grumberg   return SourcePosition;
10228d79314SDaniel Grumberg }
10328d79314SDaniel Grumberg 
10428d79314SDaniel Grumberg /// Serialize a source location in file.
10528d79314SDaniel Grumberg ///
10628d79314SDaniel Grumberg /// \param Loc The presumed location to serialize.
10728d79314SDaniel Grumberg /// \param IncludeFileURI If true, include the file path of \p Loc as a URI.
10828d79314SDaniel Grumberg /// Defaults to false.
10928d79314SDaniel Grumberg Object serializeSourceLocation(const PresumedLoc &Loc,
11028d79314SDaniel Grumberg                                bool IncludeFileURI = false) {
11128d79314SDaniel Grumberg   Object SourceLocation;
11228d79314SDaniel Grumberg   serializeObject(SourceLocation, "position", serializeSourcePosition(Loc));
11328d79314SDaniel Grumberg 
11489f6b26fSZixu Wang   if (IncludeFileURI) {
11589f6b26fSZixu Wang     std::string FileURI = "file://";
11689f6b26fSZixu Wang     // Normalize file path to use forward slashes for the URI.
11789f6b26fSZixu Wang     FileURI += sys::path::convert_to_slash(Loc.getFilename());
11828d79314SDaniel Grumberg     SourceLocation["uri"] = FileURI;
11989f6b26fSZixu Wang   }
12089f6b26fSZixu Wang 
12128d79314SDaniel Grumberg   return SourceLocation;
12289f6b26fSZixu Wang }
12389f6b26fSZixu Wang 
12489f6b26fSZixu Wang /// Serialize a source range with begin and end locations.
12589f6b26fSZixu Wang Object serializeSourceRange(const PresumedLoc &BeginLoc,
12689f6b26fSZixu Wang                             const PresumedLoc &EndLoc) {
12789f6b26fSZixu Wang   Object SourceRange;
12889f6b26fSZixu Wang   serializeObject(SourceRange, "start", serializeSourcePosition(BeginLoc));
12989f6b26fSZixu Wang   serializeObject(SourceRange, "end", serializeSourcePosition(EndLoc));
13089f6b26fSZixu Wang   return SourceRange;
13189f6b26fSZixu Wang }
13289f6b26fSZixu Wang 
13389f6b26fSZixu Wang /// Serialize the availability attributes of a symbol.
13489f6b26fSZixu Wang ///
13589f6b26fSZixu Wang /// Availability information contains the introduced, deprecated, and obsoleted
13689f6b26fSZixu Wang /// versions of the symbol as semantic versions, if not default.
13789f6b26fSZixu Wang /// Availability information also contains flags to indicate if the symbol is
13889f6b26fSZixu Wang /// unconditionally unavailable or deprecated,
13989f6b26fSZixu Wang /// i.e. \c __attribute__((unavailable)) and \c __attribute__((deprecated)).
14089f6b26fSZixu Wang ///
14189f6b26fSZixu Wang /// \returns \c None if the symbol has default availability attributes, or
14289f6b26fSZixu Wang /// an \c Object containing the formatted availability information.
14389f6b26fSZixu Wang Optional<Object> serializeAvailability(const AvailabilityInfo &Avail) {
14489f6b26fSZixu Wang   if (Avail.isDefault())
14589f6b26fSZixu Wang     return None;
14689f6b26fSZixu Wang 
14789f6b26fSZixu Wang   Object Availbility;
14889f6b26fSZixu Wang   serializeObject(Availbility, "introducedVersion",
14989f6b26fSZixu Wang                   serializeSemanticVersion(Avail.Introduced));
15089f6b26fSZixu Wang   serializeObject(Availbility, "deprecatedVersion",
15189f6b26fSZixu Wang                   serializeSemanticVersion(Avail.Deprecated));
15289f6b26fSZixu Wang   serializeObject(Availbility, "obsoletedVersion",
15389f6b26fSZixu Wang                   serializeSemanticVersion(Avail.Obsoleted));
15489f6b26fSZixu Wang   if (Avail.isUnavailable())
15589f6b26fSZixu Wang     Availbility["isUnconditionallyUnavailable"] = true;
15689f6b26fSZixu Wang   if (Avail.isUnconditionallyDeprecated())
15789f6b26fSZixu Wang     Availbility["isUnconditionallyDeprecated"] = true;
15889f6b26fSZixu Wang 
15989f6b26fSZixu Wang   return Availbility;
16089f6b26fSZixu Wang }
16189f6b26fSZixu Wang 
16215bf0e56SZixu Wang /// Get the language name string for interface language references.
16315bf0e56SZixu Wang StringRef getLanguageName(Language Lang) {
16415bf0e56SZixu Wang   switch (Lang) {
16589f6b26fSZixu Wang   case Language::C:
16689f6b26fSZixu Wang     return "c";
16789f6b26fSZixu Wang   case Language::ObjC:
168b62d4021SZixu Wang     return "objective-c";
16989f6b26fSZixu Wang 
17089f6b26fSZixu Wang   // Unsupported language currently
17189f6b26fSZixu Wang   case Language::CXX:
17289f6b26fSZixu Wang   case Language::ObjCXX:
17389f6b26fSZixu Wang   case Language::OpenCL:
17489f6b26fSZixu Wang   case Language::OpenCLCXX:
17589f6b26fSZixu Wang   case Language::CUDA:
17689f6b26fSZixu Wang   case Language::RenderScript:
17789f6b26fSZixu Wang   case Language::HIP:
178d394f9f8SChris Bieneman   case Language::HLSL:
17989f6b26fSZixu Wang 
18089f6b26fSZixu Wang   // Languages that the frontend cannot parse and compile
18189f6b26fSZixu Wang   case Language::Unknown:
18289f6b26fSZixu Wang   case Language::Asm:
18389f6b26fSZixu Wang   case Language::LLVM_IR:
18489f6b26fSZixu Wang     llvm_unreachable("Unsupported language kind");
18589f6b26fSZixu Wang   }
18689f6b26fSZixu Wang 
18789f6b26fSZixu Wang   llvm_unreachable("Unhandled language kind");
18889f6b26fSZixu Wang }
18989f6b26fSZixu Wang 
19089f6b26fSZixu Wang /// Serialize the identifier object as specified by the Symbol Graph format.
19189f6b26fSZixu Wang ///
19289f6b26fSZixu Wang /// The identifier property of a symbol contains the USR for precise and unique
19389f6b26fSZixu Wang /// references, and the interface language name.
19415bf0e56SZixu Wang Object serializeIdentifier(const APIRecord &Record, Language Lang) {
19589f6b26fSZixu Wang   Object Identifier;
19689f6b26fSZixu Wang   Identifier["precise"] = Record.USR;
19715bf0e56SZixu Wang   Identifier["interfaceLanguage"] = getLanguageName(Lang);
19889f6b26fSZixu Wang 
19989f6b26fSZixu Wang   return Identifier;
20089f6b26fSZixu Wang }
20189f6b26fSZixu Wang 
20289f6b26fSZixu Wang /// Serialize the documentation comments attached to a symbol, as specified by
20389f6b26fSZixu Wang /// the Symbol Graph format.
20489f6b26fSZixu Wang ///
20589f6b26fSZixu Wang /// The Symbol Graph \c docComment object contains an array of lines. Each line
20689f6b26fSZixu Wang /// represents one line of striped documentation comment, with source range
20789f6b26fSZixu Wang /// information.
20889f6b26fSZixu Wang /// e.g.
20989f6b26fSZixu Wang /// \code
21089f6b26fSZixu Wang ///   /// This is a documentation comment
21189f6b26fSZixu Wang ///       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'  First line.
21289f6b26fSZixu Wang ///   ///     with multiple lines.
21389f6b26fSZixu Wang ///       ^~~~~~~~~~~~~~~~~~~~~~~'         Second line.
21489f6b26fSZixu Wang /// \endcode
21589f6b26fSZixu Wang ///
21689f6b26fSZixu Wang /// \returns \c None if \p Comment is empty, or an \c Object containing the
21789f6b26fSZixu Wang /// formatted lines.
21889f6b26fSZixu Wang Optional<Object> serializeDocComment(const DocComment &Comment) {
21989f6b26fSZixu Wang   if (Comment.empty())
22089f6b26fSZixu Wang     return None;
22189f6b26fSZixu Wang 
22289f6b26fSZixu Wang   Object DocComment;
22389f6b26fSZixu Wang   Array LinesArray;
22489f6b26fSZixu Wang   for (const auto &CommentLine : Comment) {
22589f6b26fSZixu Wang     Object Line;
22689f6b26fSZixu Wang     Line["text"] = CommentLine.Text;
22789f6b26fSZixu Wang     serializeObject(Line, "range",
22889f6b26fSZixu Wang                     serializeSourceRange(CommentLine.Begin, CommentLine.End));
22989f6b26fSZixu Wang     LinesArray.emplace_back(std::move(Line));
23089f6b26fSZixu Wang   }
23189f6b26fSZixu Wang   serializeArray(DocComment, "lines", LinesArray);
23289f6b26fSZixu Wang 
23389f6b26fSZixu Wang   return DocComment;
23489f6b26fSZixu Wang }
23589f6b26fSZixu Wang 
23689f6b26fSZixu Wang /// Serialize the declaration fragments of a symbol.
23789f6b26fSZixu Wang ///
23889f6b26fSZixu Wang /// The Symbol Graph declaration fragments is an array of tagged important
23989f6b26fSZixu Wang /// parts of a symbol's declaration. The fragments sequence can be joined to
24089f6b26fSZixu Wang /// form spans of declaration text, with attached information useful for
24189f6b26fSZixu Wang /// purposes like syntax-highlighting etc. For example:
24289f6b26fSZixu Wang /// \code
24389f6b26fSZixu Wang ///   const int pi; -> "declarationFragments" : [
24489f6b26fSZixu Wang ///                      {
24589f6b26fSZixu Wang ///                        "kind" : "keyword",
24689f6b26fSZixu Wang ///                        "spelling" : "const"
24789f6b26fSZixu Wang ///                      },
24889f6b26fSZixu Wang ///                      {
24989f6b26fSZixu Wang ///                        "kind" : "text",
25089f6b26fSZixu Wang ///                        "spelling" : " "
25189f6b26fSZixu Wang ///                      },
25289f6b26fSZixu Wang ///                      {
25389f6b26fSZixu Wang ///                        "kind" : "typeIdentifier",
25489f6b26fSZixu Wang ///                        "preciseIdentifier" : "c:I",
25589f6b26fSZixu Wang ///                        "spelling" : "int"
25689f6b26fSZixu Wang ///                      },
25789f6b26fSZixu Wang ///                      {
25889f6b26fSZixu Wang ///                        "kind" : "text",
25989f6b26fSZixu Wang ///                        "spelling" : " "
26089f6b26fSZixu Wang ///                      },
26189f6b26fSZixu Wang ///                      {
26289f6b26fSZixu Wang ///                        "kind" : "identifier",
26389f6b26fSZixu Wang ///                        "spelling" : "pi"
26489f6b26fSZixu Wang ///                      }
26589f6b26fSZixu Wang ///                    ]
26689f6b26fSZixu Wang /// \endcode
26789f6b26fSZixu Wang ///
26889f6b26fSZixu Wang /// \returns \c None if \p DF is empty, or an \c Array containing the formatted
26989f6b26fSZixu Wang /// declaration fragments array.
27089f6b26fSZixu Wang Optional<Array> serializeDeclarationFragments(const DeclarationFragments &DF) {
27189f6b26fSZixu Wang   if (DF.getFragments().empty())
27289f6b26fSZixu Wang     return None;
27389f6b26fSZixu Wang 
27489f6b26fSZixu Wang   Array Fragments;
27589f6b26fSZixu Wang   for (const auto &F : DF.getFragments()) {
27689f6b26fSZixu Wang     Object Fragment;
27789f6b26fSZixu Wang     Fragment["spelling"] = F.Spelling;
27889f6b26fSZixu Wang     Fragment["kind"] = DeclarationFragments::getFragmentKindString(F.Kind);
27989f6b26fSZixu Wang     if (!F.PreciseIdentifier.empty())
28089f6b26fSZixu Wang       Fragment["preciseIdentifier"] = F.PreciseIdentifier;
28189f6b26fSZixu Wang     Fragments.emplace_back(std::move(Fragment));
28289f6b26fSZixu Wang   }
28389f6b26fSZixu Wang 
28489f6b26fSZixu Wang   return Fragments;
28589f6b26fSZixu Wang }
28689f6b26fSZixu Wang 
28789f6b26fSZixu Wang /// Serialize the function signature field of a function, as specified by the
28889f6b26fSZixu Wang /// Symbol Graph format.
28989f6b26fSZixu Wang ///
29089f6b26fSZixu Wang /// The Symbol Graph function signature property contains two arrays.
29189f6b26fSZixu Wang ///   - The \c returns array is the declaration fragments of the return type;
29289f6b26fSZixu Wang ///   - The \c parameters array contains names and declaration fragments of the
29389f6b26fSZixu Wang ///     parameters.
29489f6b26fSZixu Wang ///
29589f6b26fSZixu Wang /// \returns \c None if \p FS is empty, or an \c Object containing the
29689f6b26fSZixu Wang /// formatted function signature.
29789f6b26fSZixu Wang Optional<Object> serializeFunctionSignature(const FunctionSignature &FS) {
29889f6b26fSZixu Wang   if (FS.empty())
29989f6b26fSZixu Wang     return None;
30089f6b26fSZixu Wang 
30189f6b26fSZixu Wang   Object Signature;
30289f6b26fSZixu Wang   serializeArray(Signature, "returns",
30389f6b26fSZixu Wang                  serializeDeclarationFragments(FS.getReturnType()));
30489f6b26fSZixu Wang 
30589f6b26fSZixu Wang   Array Parameters;
30689f6b26fSZixu Wang   for (const auto &P : FS.getParameters()) {
30789f6b26fSZixu Wang     Object Parameter;
30889f6b26fSZixu Wang     Parameter["name"] = P.Name;
30989f6b26fSZixu Wang     serializeArray(Parameter, "declarationFragments",
31089f6b26fSZixu Wang                    serializeDeclarationFragments(P.Fragments));
31189f6b26fSZixu Wang     Parameters.emplace_back(std::move(Parameter));
31289f6b26fSZixu Wang   }
31389f6b26fSZixu Wang 
31489f6b26fSZixu Wang   if (!Parameters.empty())
31589f6b26fSZixu Wang     Signature["parameters"] = std::move(Parameters);
31689f6b26fSZixu Wang 
31789f6b26fSZixu Wang   return Signature;
31889f6b26fSZixu Wang }
31989f6b26fSZixu Wang 
32089f6b26fSZixu Wang /// Serialize the \c names field of a symbol as specified by the Symbol Graph
32189f6b26fSZixu Wang /// format.
32289f6b26fSZixu Wang ///
32389f6b26fSZixu Wang /// The Symbol Graph names field contains multiple representations of a symbol
32489f6b26fSZixu Wang /// that can be used for different applications:
32589f6b26fSZixu Wang ///   - \c title : The simple declared name of the symbol;
32689f6b26fSZixu Wang ///   - \c subHeading : An array of declaration fragments that provides tags,
32789f6b26fSZixu Wang ///     and potentially more tokens (for example the \c +/- symbol for
32889f6b26fSZixu Wang ///     Objective-C methods). Can be used as sub-headings for documentation.
32989f6b26fSZixu Wang Object serializeNames(const APIRecord &Record) {
33089f6b26fSZixu Wang   Object Names;
33189f6b26fSZixu Wang   Names["title"] = Record.Name;
33289f6b26fSZixu Wang   serializeArray(Names, "subHeading",
33389f6b26fSZixu Wang                  serializeDeclarationFragments(Record.SubHeading));
33489f6b26fSZixu Wang 
33589f6b26fSZixu Wang   return Names;
33689f6b26fSZixu Wang }
33789f6b26fSZixu Wang 
33889f6b26fSZixu Wang /// Serialize the symbol kind information.
33989f6b26fSZixu Wang ///
34089f6b26fSZixu Wang /// The Symbol Graph symbol kind property contains a shorthand \c identifier
34189f6b26fSZixu Wang /// which is prefixed by the source language name, useful for tooling to parse
34289f6b26fSZixu Wang /// the kind, and a \c displayName for rendering human-readable names.
34315bf0e56SZixu Wang Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
34415bf0e56SZixu Wang   auto AddLangPrefix = [&Lang](StringRef S) -> std::string {
34515bf0e56SZixu Wang     return (getLanguageName(Lang) + "." + S).str();
34671b4c226SZixu Wang   };
34771b4c226SZixu Wang 
34889f6b26fSZixu Wang   Object Kind;
34989f6b26fSZixu Wang   switch (Record.getKind()) {
35071b4c226SZixu Wang   case APIRecord::RK_Global: {
35189f6b26fSZixu Wang     auto *GR = dyn_cast<GlobalRecord>(&Record);
35289f6b26fSZixu Wang     switch (GR->GlobalKind) {
35389f6b26fSZixu Wang     case GVKind::Function:
35471b4c226SZixu Wang       Kind["identifier"] = AddLangPrefix("func");
35589f6b26fSZixu Wang       Kind["displayName"] = "Function";
35689f6b26fSZixu Wang       break;
35789f6b26fSZixu Wang     case GVKind::Variable:
35871b4c226SZixu Wang       Kind["identifier"] = AddLangPrefix("var");
35989f6b26fSZixu Wang       Kind["displayName"] = "Global Variable";
36089f6b26fSZixu Wang       break;
36189f6b26fSZixu Wang     case GVKind::Unknown:
36289f6b26fSZixu Wang       // Unknown global kind
36389f6b26fSZixu Wang       break;
36489f6b26fSZixu Wang     }
36589f6b26fSZixu Wang     break;
36689f6b26fSZixu Wang   }
36771b4c226SZixu Wang   case APIRecord::RK_EnumConstant:
36871b4c226SZixu Wang     Kind["identifier"] = AddLangPrefix("enum.case");
36971b4c226SZixu Wang     Kind["displayName"] = "Enumeration Case";
37071b4c226SZixu Wang     break;
37171b4c226SZixu Wang   case APIRecord::RK_Enum:
37271b4c226SZixu Wang     Kind["identifier"] = AddLangPrefix("enum");
37371b4c226SZixu Wang     Kind["displayName"] = "Enumeration";
37471b4c226SZixu Wang     break;
3755bb5704cSZixu Wang   case APIRecord::RK_StructField:
3765bb5704cSZixu Wang     Kind["identifier"] = AddLangPrefix("property");
3775bb5704cSZixu Wang     Kind["displayName"] = "Instance Property";
3785bb5704cSZixu Wang     break;
3795bb5704cSZixu Wang   case APIRecord::RK_Struct:
3805bb5704cSZixu Wang     Kind["identifier"] = AddLangPrefix("struct");
3815bb5704cSZixu Wang     Kind["displayName"] = "Structure";
3825bb5704cSZixu Wang     break;
3839b36e126SZixu Wang   case APIRecord::RK_ObjCIvar:
3849b36e126SZixu Wang     Kind["identifier"] = AddLangPrefix("ivar");
3859b36e126SZixu Wang     Kind["displayName"] = "Instance Variable";
3869b36e126SZixu Wang     break;
3879b36e126SZixu Wang   case APIRecord::RK_ObjCMethod:
3889b36e126SZixu Wang     if (dyn_cast<ObjCMethodRecord>(&Record)->IsInstanceMethod) {
3899b36e126SZixu Wang       Kind["identifier"] = AddLangPrefix("method");
3909b36e126SZixu Wang       Kind["displayName"] = "Instance Method";
3919b36e126SZixu Wang     } else {
3929b36e126SZixu Wang       Kind["identifier"] = AddLangPrefix("type.method");
3939b36e126SZixu Wang       Kind["displayName"] = "Type Method";
3949b36e126SZixu Wang     }
3959b36e126SZixu Wang     break;
3969b36e126SZixu Wang   case APIRecord::RK_ObjCProperty:
3979b36e126SZixu Wang     Kind["identifier"] = AddLangPrefix("property");
3989b36e126SZixu Wang     Kind["displayName"] = "Instance Property";
3999b36e126SZixu Wang     break;
4009b36e126SZixu Wang   case APIRecord::RK_ObjCInterface:
4019b36e126SZixu Wang     Kind["identifier"] = AddLangPrefix("class");
4029b36e126SZixu Wang     Kind["displayName"] = "Class";
4039b36e126SZixu Wang     break;
404d1d34bafSZixu Wang   case APIRecord::RK_ObjCProtocol:
405d1d34bafSZixu Wang     Kind["identifier"] = AddLangPrefix("protocol");
406d1d34bafSZixu Wang     Kind["displayName"] = "Protocol";
407d1d34bafSZixu Wang     break;
408529a0570SDaniel Grumberg   case APIRecord::RK_MacroDefinition:
409529a0570SDaniel Grumberg     Kind["identifier"] = AddLangPrefix("macro");
410529a0570SDaniel Grumberg     Kind["displayName"] = "Macro";
411*9fc45ca0SDaniel Grumberg     break;
412*9fc45ca0SDaniel Grumberg   case APIRecord::RK_Typedef:
413*9fc45ca0SDaniel Grumberg     Kind["identifier"] = AddLangPrefix("typealias");
414*9fc45ca0SDaniel Grumberg     Kind["displayName"] = "Type Alias";
415*9fc45ca0SDaniel Grumberg     break;
41671b4c226SZixu Wang   }
41789f6b26fSZixu Wang 
41889f6b26fSZixu Wang   return Kind;
41989f6b26fSZixu Wang }
42089f6b26fSZixu Wang 
42189f6b26fSZixu Wang } // namespace
42289f6b26fSZixu Wang 
42389f6b26fSZixu Wang void SymbolGraphSerializer::anchor() {}
42489f6b26fSZixu Wang 
42589f6b26fSZixu Wang /// Defines the format version emitted by SymbolGraphSerializer.
42689f6b26fSZixu Wang const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
42789f6b26fSZixu Wang 
42889f6b26fSZixu Wang Object SymbolGraphSerializer::serializeMetadata() const {
42989f6b26fSZixu Wang   Object Metadata;
43089f6b26fSZixu Wang   serializeObject(Metadata, "formatVersion",
43189f6b26fSZixu Wang                   serializeSemanticVersion(FormatVersion));
43289f6b26fSZixu Wang   Metadata["generator"] = clang::getClangFullVersion();
43389f6b26fSZixu Wang   return Metadata;
43489f6b26fSZixu Wang }
43589f6b26fSZixu Wang 
43689f6b26fSZixu Wang Object SymbolGraphSerializer::serializeModule() const {
43789f6b26fSZixu Wang   Object Module;
4385ef2ec7eSDaniel Grumberg   // The user is expected to always pass `--product-name=` on the command line
4395ef2ec7eSDaniel Grumberg   // to populate this field.
4405ef2ec7eSDaniel Grumberg   Module["name"] = ProductName;
44189f6b26fSZixu Wang   serializeObject(Module, "platform", serializePlatform(API.getTarget()));
44289f6b26fSZixu Wang   return Module;
44389f6b26fSZixu Wang }
44489f6b26fSZixu Wang 
44589f6b26fSZixu Wang bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const {
44689f6b26fSZixu Wang   // Skip unconditionally unavailable symbols
44789f6b26fSZixu Wang   if (Record.Availability.isUnconditionallyUnavailable())
44889f6b26fSZixu Wang     return true;
44989f6b26fSZixu Wang 
45089f6b26fSZixu Wang   return false;
45189f6b26fSZixu Wang }
45289f6b26fSZixu Wang 
45389f6b26fSZixu Wang Optional<Object>
45489f6b26fSZixu Wang SymbolGraphSerializer::serializeAPIRecord(const APIRecord &Record) const {
45589f6b26fSZixu Wang   if (shouldSkip(Record))
45689f6b26fSZixu Wang     return None;
45789f6b26fSZixu Wang 
45889f6b26fSZixu Wang   Object Obj;
45989f6b26fSZixu Wang   serializeObject(Obj, "identifier",
46015bf0e56SZixu Wang                   serializeIdentifier(Record, API.getLanguage()));
46115bf0e56SZixu Wang   serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage()));
46289f6b26fSZixu Wang   serializeObject(Obj, "names", serializeNames(Record));
46389f6b26fSZixu Wang   serializeObject(
46489f6b26fSZixu Wang       Obj, "location",
46528d79314SDaniel Grumberg       serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true));
46689f6b26fSZixu Wang   serializeObject(Obj, "availbility",
46789f6b26fSZixu Wang                   serializeAvailability(Record.Availability));
46889f6b26fSZixu Wang   serializeObject(Obj, "docComment", serializeDocComment(Record.Comment));
46989f6b26fSZixu Wang   serializeArray(Obj, "declarationFragments",
47089f6b26fSZixu Wang                  serializeDeclarationFragments(Record.Declaration));
47128d79314SDaniel Grumberg   // TODO: Once we keep track of symbol access information serialize it
47228d79314SDaniel Grumberg   // correctly here.
47328d79314SDaniel Grumberg   Obj["accessLevel"] = "public";
47428d79314SDaniel Grumberg   serializeArray(Obj, "pathComponents", Array(PathComponents));
47589f6b26fSZixu Wang 
47689f6b26fSZixu Wang   return Obj;
47789f6b26fSZixu Wang }
47889f6b26fSZixu Wang 
47971b4c226SZixu Wang StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) {
48071b4c226SZixu Wang   switch (Kind) {
48171b4c226SZixu Wang   case RelationshipKind::MemberOf:
48271b4c226SZixu Wang     return "memberOf";
4839b36e126SZixu Wang   case RelationshipKind::InheritsFrom:
4849b36e126SZixu Wang     return "inheritsFrom";
4859b36e126SZixu Wang   case RelationshipKind::ConformsTo:
4869b36e126SZixu Wang     return "conformsTo";
48771b4c226SZixu Wang   }
48871b4c226SZixu Wang   llvm_unreachable("Unhandled relationship kind");
48971b4c226SZixu Wang }
49071b4c226SZixu Wang 
49171b4c226SZixu Wang void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind,
4929b36e126SZixu Wang                                                   SymbolReference Source,
4939b36e126SZixu Wang                                                   SymbolReference Target) {
49471b4c226SZixu Wang   Object Relationship;
49571b4c226SZixu Wang   Relationship["source"] = Source.USR;
49671b4c226SZixu Wang   Relationship["target"] = Target.USR;
49771b4c226SZixu Wang   Relationship["kind"] = getRelationshipString(Kind);
49871b4c226SZixu Wang 
49971b4c226SZixu Wang   Relationships.emplace_back(std::move(Relationship));
50071b4c226SZixu Wang }
50171b4c226SZixu Wang 
50289f6b26fSZixu Wang void SymbolGraphSerializer::serializeGlobalRecord(const GlobalRecord &Record) {
50328d79314SDaniel Grumberg   auto GlobalPathComponentGuard = makePathComponentGuard(Record.Name);
50428d79314SDaniel Grumberg 
50589f6b26fSZixu Wang   auto Obj = serializeAPIRecord(Record);
50689f6b26fSZixu Wang   if (!Obj)
50789f6b26fSZixu Wang     return;
50889f6b26fSZixu Wang 
50989f6b26fSZixu Wang   if (Record.GlobalKind == GVKind::Function)
51028d79314SDaniel Grumberg     serializeObject(*Obj, "functionSignature",
51189f6b26fSZixu Wang                     serializeFunctionSignature(Record.Signature));
51289f6b26fSZixu Wang 
51389f6b26fSZixu Wang   Symbols.emplace_back(std::move(*Obj));
51489f6b26fSZixu Wang }
51589f6b26fSZixu Wang 
51671b4c226SZixu Wang void SymbolGraphSerializer::serializeEnumRecord(const EnumRecord &Record) {
51728d79314SDaniel Grumberg   auto EnumPathComponentGuard = makePathComponentGuard(Record.Name);
51871b4c226SZixu Wang   auto Enum = serializeAPIRecord(Record);
51971b4c226SZixu Wang   if (!Enum)
52071b4c226SZixu Wang     return;
52171b4c226SZixu Wang 
52271b4c226SZixu Wang   Symbols.emplace_back(std::move(*Enum));
52371b4c226SZixu Wang 
52471b4c226SZixu Wang   for (const auto &Constant : Record.Constants) {
52528d79314SDaniel Grumberg     auto EnumConstantPathComponentGuard =
52628d79314SDaniel Grumberg         makePathComponentGuard(Constant->Name);
52771b4c226SZixu Wang     auto EnumConstant = serializeAPIRecord(*Constant);
52828d79314SDaniel Grumberg 
52971b4c226SZixu Wang     if (!EnumConstant)
53071b4c226SZixu Wang       continue;
53171b4c226SZixu Wang 
53271b4c226SZixu Wang     Symbols.emplace_back(std::move(*EnumConstant));
53371b4c226SZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Constant, Record);
53471b4c226SZixu Wang   }
53571b4c226SZixu Wang }
53671b4c226SZixu Wang 
5375bb5704cSZixu Wang void SymbolGraphSerializer::serializeStructRecord(const StructRecord &Record) {
53828d79314SDaniel Grumberg   auto StructPathComponentGuard = makePathComponentGuard(Record.Name);
5395bb5704cSZixu Wang   auto Struct = serializeAPIRecord(Record);
5405bb5704cSZixu Wang   if (!Struct)
5415bb5704cSZixu Wang     return;
5425bb5704cSZixu Wang 
5435bb5704cSZixu Wang   Symbols.emplace_back(std::move(*Struct));
5445bb5704cSZixu Wang 
5455bb5704cSZixu Wang   for (const auto &Field : Record.Fields) {
54628d79314SDaniel Grumberg     auto StructFieldPathComponentGuard = makePathComponentGuard(Field->Name);
5475bb5704cSZixu Wang     auto StructField = serializeAPIRecord(*Field);
54828d79314SDaniel Grumberg 
5495bb5704cSZixu Wang     if (!StructField)
5505bb5704cSZixu Wang       continue;
5515bb5704cSZixu Wang 
5525bb5704cSZixu Wang     Symbols.emplace_back(std::move(*StructField));
5535bb5704cSZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Field, Record);
5545bb5704cSZixu Wang   }
5555bb5704cSZixu Wang }
5565bb5704cSZixu Wang 
5579b36e126SZixu Wang void SymbolGraphSerializer::serializeObjCContainerRecord(
5589b36e126SZixu Wang     const ObjCContainerRecord &Record) {
55928d79314SDaniel Grumberg   auto ObjCContainerPathComponentGuard = makePathComponentGuard(Record.Name);
5609b36e126SZixu Wang   auto ObjCContainer = serializeAPIRecord(Record);
5619b36e126SZixu Wang   if (!ObjCContainer)
5629b36e126SZixu Wang     return;
5639b36e126SZixu Wang 
5649b36e126SZixu Wang   Symbols.emplace_back(std::move(*ObjCContainer));
5659b36e126SZixu Wang 
5669b36e126SZixu Wang   // Record instance variables and that the instance variables are members of
5679b36e126SZixu Wang   // the container.
5689b36e126SZixu Wang   for (const auto &Ivar : Record.Ivars) {
56928d79314SDaniel Grumberg     auto IvarPathComponentGuard = makePathComponentGuard(Ivar->Name);
5709b36e126SZixu Wang     auto ObjCIvar = serializeAPIRecord(*Ivar);
57128d79314SDaniel Grumberg 
5729b36e126SZixu Wang     if (!ObjCIvar)
5739b36e126SZixu Wang       continue;
5749b36e126SZixu Wang 
5759b36e126SZixu Wang     Symbols.emplace_back(std::move(*ObjCIvar));
5769b36e126SZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Ivar, Record);
5779b36e126SZixu Wang   }
5789b36e126SZixu Wang 
5799b36e126SZixu Wang   // Record methods and that the methods are members of the container.
5809b36e126SZixu Wang   for (const auto &Method : Record.Methods) {
58128d79314SDaniel Grumberg     auto MethodPathComponentGuard = makePathComponentGuard(Method->Name);
5829b36e126SZixu Wang     auto ObjCMethod = serializeAPIRecord(*Method);
58328d79314SDaniel Grumberg 
5849b36e126SZixu Wang     if (!ObjCMethod)
5859b36e126SZixu Wang       continue;
5869b36e126SZixu Wang 
5879b36e126SZixu Wang     Symbols.emplace_back(std::move(*ObjCMethod));
5889b36e126SZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Method, Record);
5899b36e126SZixu Wang   }
5909b36e126SZixu Wang 
5919b36e126SZixu Wang   // Record properties and that the properties are members of the container.
5929b36e126SZixu Wang   for (const auto &Property : Record.Properties) {
59328d79314SDaniel Grumberg     auto PropertyPathComponentGuard = makePathComponentGuard(Property->Name);
5949b36e126SZixu Wang     auto ObjCProperty = serializeAPIRecord(*Property);
59528d79314SDaniel Grumberg 
5969b36e126SZixu Wang     if (!ObjCProperty)
5979b36e126SZixu Wang       continue;
5989b36e126SZixu Wang 
5999b36e126SZixu Wang     Symbols.emplace_back(std::move(*ObjCProperty));
6009b36e126SZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Property, Record);
6019b36e126SZixu Wang   }
6029b36e126SZixu Wang 
6039b36e126SZixu Wang   for (const auto &Protocol : Record.Protocols)
6049b36e126SZixu Wang     // Record that Record conforms to Protocol.
6059b36e126SZixu Wang     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
6069b36e126SZixu Wang 
6079b36e126SZixu Wang   if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record))
6089b36e126SZixu Wang     if (!ObjCInterface->SuperClass.empty())
6099b36e126SZixu Wang       // If Record is an Objective-C interface record and it has a super class,
6109b36e126SZixu Wang       // record that Record is inherited from SuperClass.
6119b36e126SZixu Wang       serializeRelationship(RelationshipKind::InheritsFrom, Record,
6129b36e126SZixu Wang                             ObjCInterface->SuperClass);
6139b36e126SZixu Wang }
6149b36e126SZixu Wang 
615529a0570SDaniel Grumberg void SymbolGraphSerializer::serializeMacroDefinitionRecord(
616529a0570SDaniel Grumberg     const MacroDefinitionRecord &Record) {
61728d79314SDaniel Grumberg   auto MacroPathComponentGuard = makePathComponentGuard(Record.Name);
618529a0570SDaniel Grumberg   auto Macro = serializeAPIRecord(Record);
61928d79314SDaniel Grumberg 
620529a0570SDaniel Grumberg   if (!Macro)
621529a0570SDaniel Grumberg     return;
622529a0570SDaniel Grumberg 
623529a0570SDaniel Grumberg   Symbols.emplace_back(std::move(*Macro));
624529a0570SDaniel Grumberg }
625529a0570SDaniel Grumberg 
626*9fc45ca0SDaniel Grumberg void SymbolGraphSerializer::serializeTypedefRecord(
627*9fc45ca0SDaniel Grumberg     const TypedefRecord &Record) {
628*9fc45ca0SDaniel Grumberg   // Typedefs of anonymous types have their entries unified with the underlying
629*9fc45ca0SDaniel Grumberg   // type.
630*9fc45ca0SDaniel Grumberg   bool ShouldDrop = Record.UnderlyingType.Name.empty();
631*9fc45ca0SDaniel Grumberg   // enums declared with `NS_OPTION` have a named enum and a named typedef, with
632*9fc45ca0SDaniel Grumberg   // the same name
633*9fc45ca0SDaniel Grumberg   ShouldDrop |= (Record.UnderlyingType.Name == Record.Name);
634*9fc45ca0SDaniel Grumberg   if (ShouldDrop)
635*9fc45ca0SDaniel Grumberg     return;
636*9fc45ca0SDaniel Grumberg 
637*9fc45ca0SDaniel Grumberg   auto TypedefPathComponentGuard = makePathComponentGuard(Record.Name);
638*9fc45ca0SDaniel Grumberg   auto Typedef = serializeAPIRecord(Record);
639*9fc45ca0SDaniel Grumberg   if (!Typedef)
640*9fc45ca0SDaniel Grumberg     return;
641*9fc45ca0SDaniel Grumberg 
642*9fc45ca0SDaniel Grumberg   (*Typedef)["type"] = Record.UnderlyingType.USR;
643*9fc45ca0SDaniel Grumberg 
644*9fc45ca0SDaniel Grumberg   Symbols.emplace_back(std::move(*Typedef));
645*9fc45ca0SDaniel Grumberg }
646*9fc45ca0SDaniel Grumberg 
64728d79314SDaniel Grumberg SymbolGraphSerializer::PathComponentGuard
64828d79314SDaniel Grumberg SymbolGraphSerializer::makePathComponentGuard(StringRef Component) {
64928d79314SDaniel Grumberg   return PathComponentGuard(PathComponents, Component);
65028d79314SDaniel Grumberg }
65128d79314SDaniel Grumberg 
65289f6b26fSZixu Wang Object SymbolGraphSerializer::serialize() {
65389f6b26fSZixu Wang   Object Root;
65489f6b26fSZixu Wang   serializeObject(Root, "metadata", serializeMetadata());
65589f6b26fSZixu Wang   serializeObject(Root, "module", serializeModule());
65689f6b26fSZixu Wang 
65789f6b26fSZixu Wang   // Serialize global records in the API set.
65889f6b26fSZixu Wang   for (const auto &Global : API.getGlobals())
65989f6b26fSZixu Wang     serializeGlobalRecord(*Global.second);
66089f6b26fSZixu Wang 
66171b4c226SZixu Wang   // Serialize enum records in the API set.
66271b4c226SZixu Wang   for (const auto &Enum : API.getEnums())
66371b4c226SZixu Wang     serializeEnumRecord(*Enum.second);
66471b4c226SZixu Wang 
6655bb5704cSZixu Wang   // Serialize struct records in the API set.
6665bb5704cSZixu Wang   for (const auto &Struct : API.getStructs())
6675bb5704cSZixu Wang     serializeStructRecord(*Struct.second);
6685bb5704cSZixu Wang 
6699b36e126SZixu Wang   // Serialize Objective-C interface records in the API set.
6709b36e126SZixu Wang   for (const auto &ObjCInterface : API.getObjCInterfaces())
6719b36e126SZixu Wang     serializeObjCContainerRecord(*ObjCInterface.second);
6729b36e126SZixu Wang 
673d1d34bafSZixu Wang   // Serialize Objective-C protocol records in the API set.
674d1d34bafSZixu Wang   for (const auto &ObjCProtocol : API.getObjCProtocols())
675d1d34bafSZixu Wang     serializeObjCContainerRecord(*ObjCProtocol.second);
676d1d34bafSZixu Wang 
677529a0570SDaniel Grumberg   for (const auto &Macro : API.getMacros())
678529a0570SDaniel Grumberg     serializeMacroDefinitionRecord(*Macro.second);
679529a0570SDaniel Grumberg 
680*9fc45ca0SDaniel Grumberg   for (const auto &Typedef : API.getTypedefs())
681*9fc45ca0SDaniel Grumberg     serializeTypedefRecord(*Typedef.second);
682*9fc45ca0SDaniel Grumberg 
68389f6b26fSZixu Wang   Root["symbols"] = std::move(Symbols);
68428d79314SDaniel Grumberg   Root["relationships"] = std::move(Relationships);
68589f6b26fSZixu Wang 
68689f6b26fSZixu Wang   return Root;
68789f6b26fSZixu Wang }
68889f6b26fSZixu Wang 
68989f6b26fSZixu Wang void SymbolGraphSerializer::serialize(raw_ostream &os) {
69089f6b26fSZixu Wang   Object root = serialize();
69189f6b26fSZixu Wang   if (Options.Compact)
69289f6b26fSZixu Wang     os << formatv("{0}", Value(std::move(root))) << "\n";
69389f6b26fSZixu Wang   else
69489f6b26fSZixu Wang     os << formatv("{0:2}", Value(std::move(root))) << "\n";
69589f6b26fSZixu Wang }
696