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;
404*178aad9bSZixu Wang   case APIRecord::RK_ObjCCategory:
405*178aad9bSZixu Wang     // We don't serialize out standalone Objective-C category symbols yet.
406*178aad9bSZixu Wang     llvm_unreachable("Serializing standalone Objective-C category symbols is "
407*178aad9bSZixu Wang                      "not supported.");
408*178aad9bSZixu Wang     break;
409d1d34bafSZixu Wang   case APIRecord::RK_ObjCProtocol:
410d1d34bafSZixu Wang     Kind["identifier"] = AddLangPrefix("protocol");
411d1d34bafSZixu Wang     Kind["displayName"] = "Protocol";
412d1d34bafSZixu Wang     break;
413529a0570SDaniel Grumberg   case APIRecord::RK_MacroDefinition:
414529a0570SDaniel Grumberg     Kind["identifier"] = AddLangPrefix("macro");
415529a0570SDaniel Grumberg     Kind["displayName"] = "Macro";
4169fc45ca0SDaniel Grumberg     break;
4179fc45ca0SDaniel Grumberg   case APIRecord::RK_Typedef:
4189fc45ca0SDaniel Grumberg     Kind["identifier"] = AddLangPrefix("typealias");
4199fc45ca0SDaniel Grumberg     Kind["displayName"] = "Type Alias";
4209fc45ca0SDaniel Grumberg     break;
42171b4c226SZixu Wang   }
42289f6b26fSZixu Wang 
42389f6b26fSZixu Wang   return Kind;
42489f6b26fSZixu Wang }
42589f6b26fSZixu Wang 
42689f6b26fSZixu Wang } // namespace
42789f6b26fSZixu Wang 
42889f6b26fSZixu Wang void SymbolGraphSerializer::anchor() {}
42989f6b26fSZixu Wang 
43089f6b26fSZixu Wang /// Defines the format version emitted by SymbolGraphSerializer.
43189f6b26fSZixu Wang const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
43289f6b26fSZixu Wang 
43389f6b26fSZixu Wang Object SymbolGraphSerializer::serializeMetadata() const {
43489f6b26fSZixu Wang   Object Metadata;
43589f6b26fSZixu Wang   serializeObject(Metadata, "formatVersion",
43689f6b26fSZixu Wang                   serializeSemanticVersion(FormatVersion));
43789f6b26fSZixu Wang   Metadata["generator"] = clang::getClangFullVersion();
43889f6b26fSZixu Wang   return Metadata;
43989f6b26fSZixu Wang }
44089f6b26fSZixu Wang 
44189f6b26fSZixu Wang Object SymbolGraphSerializer::serializeModule() const {
44289f6b26fSZixu Wang   Object Module;
4435ef2ec7eSDaniel Grumberg   // The user is expected to always pass `--product-name=` on the command line
4445ef2ec7eSDaniel Grumberg   // to populate this field.
4455ef2ec7eSDaniel Grumberg   Module["name"] = ProductName;
44689f6b26fSZixu Wang   serializeObject(Module, "platform", serializePlatform(API.getTarget()));
44789f6b26fSZixu Wang   return Module;
44889f6b26fSZixu Wang }
44989f6b26fSZixu Wang 
45089f6b26fSZixu Wang bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const {
45189f6b26fSZixu Wang   // Skip unconditionally unavailable symbols
45289f6b26fSZixu Wang   if (Record.Availability.isUnconditionallyUnavailable())
45389f6b26fSZixu Wang     return true;
45489f6b26fSZixu Wang 
45589f6b26fSZixu Wang   return false;
45689f6b26fSZixu Wang }
45789f6b26fSZixu Wang 
45889f6b26fSZixu Wang Optional<Object>
45989f6b26fSZixu Wang SymbolGraphSerializer::serializeAPIRecord(const APIRecord &Record) const {
46089f6b26fSZixu Wang   if (shouldSkip(Record))
46189f6b26fSZixu Wang     return None;
46289f6b26fSZixu Wang 
46389f6b26fSZixu Wang   Object Obj;
46489f6b26fSZixu Wang   serializeObject(Obj, "identifier",
46515bf0e56SZixu Wang                   serializeIdentifier(Record, API.getLanguage()));
46615bf0e56SZixu Wang   serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage()));
46789f6b26fSZixu Wang   serializeObject(Obj, "names", serializeNames(Record));
46889f6b26fSZixu Wang   serializeObject(
46989f6b26fSZixu Wang       Obj, "location",
47028d79314SDaniel Grumberg       serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true));
47189f6b26fSZixu Wang   serializeObject(Obj, "availbility",
47289f6b26fSZixu Wang                   serializeAvailability(Record.Availability));
47389f6b26fSZixu Wang   serializeObject(Obj, "docComment", serializeDocComment(Record.Comment));
47489f6b26fSZixu Wang   serializeArray(Obj, "declarationFragments",
47589f6b26fSZixu Wang                  serializeDeclarationFragments(Record.Declaration));
47628d79314SDaniel Grumberg   // TODO: Once we keep track of symbol access information serialize it
47728d79314SDaniel Grumberg   // correctly here.
47828d79314SDaniel Grumberg   Obj["accessLevel"] = "public";
47928d79314SDaniel Grumberg   serializeArray(Obj, "pathComponents", Array(PathComponents));
48089f6b26fSZixu Wang 
48189f6b26fSZixu Wang   return Obj;
48289f6b26fSZixu Wang }
48389f6b26fSZixu Wang 
484*178aad9bSZixu Wang template <typename MemberTy>
485*178aad9bSZixu Wang void SymbolGraphSerializer::serializeMembers(
486*178aad9bSZixu Wang     const APIRecord &Record,
487*178aad9bSZixu Wang     const SmallVector<std::unique_ptr<MemberTy>> &Members) {
488*178aad9bSZixu Wang   for (const auto &Member : Members) {
489*178aad9bSZixu Wang     auto MemberPathComponentGuard = makePathComponentGuard(Member->Name);
490*178aad9bSZixu Wang     auto MemberRecord = serializeAPIRecord(*Member);
491*178aad9bSZixu Wang     if (!MemberRecord)
492*178aad9bSZixu Wang       continue;
493*178aad9bSZixu Wang 
494*178aad9bSZixu Wang     Symbols.emplace_back(std::move(*MemberRecord));
495*178aad9bSZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Member, Record);
496*178aad9bSZixu Wang   }
497*178aad9bSZixu Wang }
498*178aad9bSZixu Wang 
49971b4c226SZixu Wang StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) {
50071b4c226SZixu Wang   switch (Kind) {
50171b4c226SZixu Wang   case RelationshipKind::MemberOf:
50271b4c226SZixu Wang     return "memberOf";
5039b36e126SZixu Wang   case RelationshipKind::InheritsFrom:
5049b36e126SZixu Wang     return "inheritsFrom";
5059b36e126SZixu Wang   case RelationshipKind::ConformsTo:
5069b36e126SZixu Wang     return "conformsTo";
50771b4c226SZixu Wang   }
50871b4c226SZixu Wang   llvm_unreachable("Unhandled relationship kind");
50971b4c226SZixu Wang }
51071b4c226SZixu Wang 
51171b4c226SZixu Wang void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind,
5129b36e126SZixu Wang                                                   SymbolReference Source,
5139b36e126SZixu Wang                                                   SymbolReference Target) {
51471b4c226SZixu Wang   Object Relationship;
51571b4c226SZixu Wang   Relationship["source"] = Source.USR;
51671b4c226SZixu Wang   Relationship["target"] = Target.USR;
51771b4c226SZixu Wang   Relationship["kind"] = getRelationshipString(Kind);
51871b4c226SZixu Wang 
51971b4c226SZixu Wang   Relationships.emplace_back(std::move(Relationship));
52071b4c226SZixu Wang }
52171b4c226SZixu Wang 
52289f6b26fSZixu Wang void SymbolGraphSerializer::serializeGlobalRecord(const GlobalRecord &Record) {
52328d79314SDaniel Grumberg   auto GlobalPathComponentGuard = makePathComponentGuard(Record.Name);
52428d79314SDaniel Grumberg 
52589f6b26fSZixu Wang   auto Obj = serializeAPIRecord(Record);
52689f6b26fSZixu Wang   if (!Obj)
52789f6b26fSZixu Wang     return;
52889f6b26fSZixu Wang 
52989f6b26fSZixu Wang   if (Record.GlobalKind == GVKind::Function)
53028d79314SDaniel Grumberg     serializeObject(*Obj, "functionSignature",
53189f6b26fSZixu Wang                     serializeFunctionSignature(Record.Signature));
53289f6b26fSZixu Wang 
53389f6b26fSZixu Wang   Symbols.emplace_back(std::move(*Obj));
53489f6b26fSZixu Wang }
53589f6b26fSZixu Wang 
53671b4c226SZixu Wang void SymbolGraphSerializer::serializeEnumRecord(const EnumRecord &Record) {
53728d79314SDaniel Grumberg   auto EnumPathComponentGuard = makePathComponentGuard(Record.Name);
53871b4c226SZixu Wang   auto Enum = serializeAPIRecord(Record);
53971b4c226SZixu Wang   if (!Enum)
54071b4c226SZixu Wang     return;
54171b4c226SZixu Wang 
54271b4c226SZixu Wang   Symbols.emplace_back(std::move(*Enum));
543*178aad9bSZixu Wang   serializeMembers(Record, Record.Constants);
54471b4c226SZixu Wang }
54571b4c226SZixu Wang 
5465bb5704cSZixu Wang void SymbolGraphSerializer::serializeStructRecord(const StructRecord &Record) {
54728d79314SDaniel Grumberg   auto StructPathComponentGuard = makePathComponentGuard(Record.Name);
5485bb5704cSZixu Wang   auto Struct = serializeAPIRecord(Record);
5495bb5704cSZixu Wang   if (!Struct)
5505bb5704cSZixu Wang     return;
5515bb5704cSZixu Wang 
5525bb5704cSZixu Wang   Symbols.emplace_back(std::move(*Struct));
553*178aad9bSZixu Wang   serializeMembers(Record, Record.Fields);
5545bb5704cSZixu Wang }
5555bb5704cSZixu Wang 
5569b36e126SZixu Wang void SymbolGraphSerializer::serializeObjCContainerRecord(
5579b36e126SZixu Wang     const ObjCContainerRecord &Record) {
55828d79314SDaniel Grumberg   auto ObjCContainerPathComponentGuard = makePathComponentGuard(Record.Name);
5599b36e126SZixu Wang   auto ObjCContainer = serializeAPIRecord(Record);
5609b36e126SZixu Wang   if (!ObjCContainer)
5619b36e126SZixu Wang     return;
5629b36e126SZixu Wang 
5639b36e126SZixu Wang   Symbols.emplace_back(std::move(*ObjCContainer));
5649b36e126SZixu Wang 
565*178aad9bSZixu Wang   serializeMembers(Record, Record.Ivars);
566*178aad9bSZixu Wang   serializeMembers(Record, Record.Methods);
567*178aad9bSZixu Wang   serializeMembers(Record, Record.Properties);
5689b36e126SZixu Wang 
5699b36e126SZixu Wang   for (const auto &Protocol : Record.Protocols)
5709b36e126SZixu Wang     // Record that Record conforms to Protocol.
5719b36e126SZixu Wang     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
5729b36e126SZixu Wang 
573*178aad9bSZixu Wang   if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record)) {
5749b36e126SZixu Wang     if (!ObjCInterface->SuperClass.empty())
5759b36e126SZixu Wang       // If Record is an Objective-C interface record and it has a super class,
5769b36e126SZixu Wang       // record that Record is inherited from SuperClass.
5779b36e126SZixu Wang       serializeRelationship(RelationshipKind::InheritsFrom, Record,
5789b36e126SZixu Wang                             ObjCInterface->SuperClass);
579*178aad9bSZixu Wang 
580*178aad9bSZixu Wang     // Members of categories extending an interface are serialized as members of
581*178aad9bSZixu Wang     // the interface.
582*178aad9bSZixu Wang     for (const auto *Category : ObjCInterface->Categories) {
583*178aad9bSZixu Wang       serializeMembers(Record, Category->Ivars);
584*178aad9bSZixu Wang       serializeMembers(Record, Category->Methods);
585*178aad9bSZixu Wang       serializeMembers(Record, Category->Properties);
586*178aad9bSZixu Wang 
587*178aad9bSZixu Wang       // Surface the protocols of the the category to the interface.
588*178aad9bSZixu Wang       for (const auto &Protocol : Category->Protocols)
589*178aad9bSZixu Wang         serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
590*178aad9bSZixu Wang     }
591*178aad9bSZixu Wang   }
5929b36e126SZixu Wang }
5939b36e126SZixu Wang 
594529a0570SDaniel Grumberg void SymbolGraphSerializer::serializeMacroDefinitionRecord(
595529a0570SDaniel Grumberg     const MacroDefinitionRecord &Record) {
59628d79314SDaniel Grumberg   auto MacroPathComponentGuard = makePathComponentGuard(Record.Name);
597529a0570SDaniel Grumberg   auto Macro = serializeAPIRecord(Record);
59828d79314SDaniel Grumberg 
599529a0570SDaniel Grumberg   if (!Macro)
600529a0570SDaniel Grumberg     return;
601529a0570SDaniel Grumberg 
602529a0570SDaniel Grumberg   Symbols.emplace_back(std::move(*Macro));
603529a0570SDaniel Grumberg }
604529a0570SDaniel Grumberg 
6059fc45ca0SDaniel Grumberg void SymbolGraphSerializer::serializeTypedefRecord(
6069fc45ca0SDaniel Grumberg     const TypedefRecord &Record) {
6079fc45ca0SDaniel Grumberg   // Typedefs of anonymous types have their entries unified with the underlying
6089fc45ca0SDaniel Grumberg   // type.
6099fc45ca0SDaniel Grumberg   bool ShouldDrop = Record.UnderlyingType.Name.empty();
6109fc45ca0SDaniel Grumberg   // enums declared with `NS_OPTION` have a named enum and a named typedef, with
6119fc45ca0SDaniel Grumberg   // the same name
6129fc45ca0SDaniel Grumberg   ShouldDrop |= (Record.UnderlyingType.Name == Record.Name);
6139fc45ca0SDaniel Grumberg   if (ShouldDrop)
6149fc45ca0SDaniel Grumberg     return;
6159fc45ca0SDaniel Grumberg 
6169fc45ca0SDaniel Grumberg   auto TypedefPathComponentGuard = makePathComponentGuard(Record.Name);
6179fc45ca0SDaniel Grumberg   auto Typedef = serializeAPIRecord(Record);
6189fc45ca0SDaniel Grumberg   if (!Typedef)
6199fc45ca0SDaniel Grumberg     return;
6209fc45ca0SDaniel Grumberg 
6219fc45ca0SDaniel Grumberg   (*Typedef)["type"] = Record.UnderlyingType.USR;
6229fc45ca0SDaniel Grumberg 
6239fc45ca0SDaniel Grumberg   Symbols.emplace_back(std::move(*Typedef));
6249fc45ca0SDaniel Grumberg }
6259fc45ca0SDaniel Grumberg 
62628d79314SDaniel Grumberg SymbolGraphSerializer::PathComponentGuard
62728d79314SDaniel Grumberg SymbolGraphSerializer::makePathComponentGuard(StringRef Component) {
62828d79314SDaniel Grumberg   return PathComponentGuard(PathComponents, Component);
62928d79314SDaniel Grumberg }
63028d79314SDaniel Grumberg 
63189f6b26fSZixu Wang Object SymbolGraphSerializer::serialize() {
63289f6b26fSZixu Wang   Object Root;
63389f6b26fSZixu Wang   serializeObject(Root, "metadata", serializeMetadata());
63489f6b26fSZixu Wang   serializeObject(Root, "module", serializeModule());
63589f6b26fSZixu Wang 
63689f6b26fSZixu Wang   // Serialize global records in the API set.
63789f6b26fSZixu Wang   for (const auto &Global : API.getGlobals())
63889f6b26fSZixu Wang     serializeGlobalRecord(*Global.second);
63989f6b26fSZixu Wang 
64071b4c226SZixu Wang   // Serialize enum records in the API set.
64171b4c226SZixu Wang   for (const auto &Enum : API.getEnums())
64271b4c226SZixu Wang     serializeEnumRecord(*Enum.second);
64371b4c226SZixu Wang 
6445bb5704cSZixu Wang   // Serialize struct records in the API set.
6455bb5704cSZixu Wang   for (const auto &Struct : API.getStructs())
6465bb5704cSZixu Wang     serializeStructRecord(*Struct.second);
6475bb5704cSZixu Wang 
6489b36e126SZixu Wang   // Serialize Objective-C interface records in the API set.
6499b36e126SZixu Wang   for (const auto &ObjCInterface : API.getObjCInterfaces())
6509b36e126SZixu Wang     serializeObjCContainerRecord(*ObjCInterface.second);
6519b36e126SZixu Wang 
652d1d34bafSZixu Wang   // Serialize Objective-C protocol records in the API set.
653d1d34bafSZixu Wang   for (const auto &ObjCProtocol : API.getObjCProtocols())
654d1d34bafSZixu Wang     serializeObjCContainerRecord(*ObjCProtocol.second);
655d1d34bafSZixu Wang 
656529a0570SDaniel Grumberg   for (const auto &Macro : API.getMacros())
657529a0570SDaniel Grumberg     serializeMacroDefinitionRecord(*Macro.second);
658529a0570SDaniel Grumberg 
6599fc45ca0SDaniel Grumberg   for (const auto &Typedef : API.getTypedefs())
6609fc45ca0SDaniel Grumberg     serializeTypedefRecord(*Typedef.second);
6619fc45ca0SDaniel Grumberg 
66289f6b26fSZixu Wang   Root["symbols"] = std::move(Symbols);
66328d79314SDaniel Grumberg   Root["relationships"] = std::move(Relationships);
66489f6b26fSZixu Wang 
66589f6b26fSZixu Wang   return Root;
66689f6b26fSZixu Wang }
66789f6b26fSZixu Wang 
66889f6b26fSZixu Wang void SymbolGraphSerializer::serialize(raw_ostream &os) {
66989f6b26fSZixu Wang   Object root = serialize();
67089f6b26fSZixu Wang   if (Options.Compact)
67189f6b26fSZixu Wang     os << formatv("{0}", Value(std::move(root))) << "\n";
67289f6b26fSZixu Wang   else
67389f6b26fSZixu Wang     os << formatv("{0:2}", Value(std::move(root))) << "\n";
67489f6b26fSZixu Wang }
675