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"
17*80ae3665SDaniel Grumberg #include "clang/ExtractAPI/DeclarationFragments.h"
1889f6b26fSZixu Wang #include "llvm/Support/JSON.h"
1989f6b26fSZixu Wang #include "llvm/Support/Path.h"
2089f6b26fSZixu Wang #include "llvm/Support/VersionTuple.h"
2189f6b26fSZixu Wang 
2289f6b26fSZixu Wang using namespace clang;
2389f6b26fSZixu Wang using namespace clang::extractapi;
2489f6b26fSZixu Wang using namespace llvm;
2589f6b26fSZixu Wang using namespace llvm::json;
2689f6b26fSZixu Wang 
2789f6b26fSZixu Wang namespace {
2889f6b26fSZixu Wang 
2989f6b26fSZixu Wang /// Helper function to inject a JSON object \p Obj into another object \p Paren
3089f6b26fSZixu Wang /// at position \p Key.
3189f6b26fSZixu Wang void serializeObject(Object &Paren, StringRef Key, Optional<Object> Obj) {
3289f6b26fSZixu Wang   if (Obj)
3389f6b26fSZixu Wang     Paren[Key] = std::move(Obj.getValue());
3489f6b26fSZixu Wang }
3589f6b26fSZixu Wang 
3689f6b26fSZixu Wang /// Helper function to inject a JSON array \p Array into object \p Paren at
3789f6b26fSZixu Wang /// position \p Key.
3889f6b26fSZixu Wang void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) {
3989f6b26fSZixu Wang   if (Array)
4089f6b26fSZixu Wang     Paren[Key] = std::move(Array.getValue());
4189f6b26fSZixu Wang }
4289f6b26fSZixu Wang 
4389f6b26fSZixu Wang /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version
4489f6b26fSZixu Wang /// format.
4589f6b26fSZixu Wang ///
4689f6b26fSZixu Wang /// A semantic version object contains three numeric fields, representing the
4789f6b26fSZixu Wang /// \c major, \c minor, and \c patch parts of the version tuple.
4889f6b26fSZixu Wang /// For example version tuple 1.0.3 is serialized as:
4989f6b26fSZixu Wang /// \code
5089f6b26fSZixu Wang ///   {
5189f6b26fSZixu Wang ///     "major" : 1,
5289f6b26fSZixu Wang ///     "minor" : 0,
5389f6b26fSZixu Wang ///     "patch" : 3
5489f6b26fSZixu Wang ///   }
5589f6b26fSZixu Wang /// \endcode
5689f6b26fSZixu Wang ///
5789f6b26fSZixu Wang /// \returns \c None if the version \p V is empty, or an \c Object containing
5889f6b26fSZixu Wang /// the semantic version representation of \p V.
5989f6b26fSZixu Wang Optional<Object> serializeSemanticVersion(const VersionTuple &V) {
6089f6b26fSZixu Wang   if (V.empty())
6189f6b26fSZixu Wang     return None;
6289f6b26fSZixu Wang 
6389f6b26fSZixu Wang   Object Version;
6489f6b26fSZixu Wang   Version["major"] = V.getMajor();
6589f6b26fSZixu Wang   Version["minor"] = V.getMinor().getValueOr(0);
6689f6b26fSZixu Wang   Version["patch"] = V.getSubminor().getValueOr(0);
6789f6b26fSZixu Wang   return Version;
6889f6b26fSZixu Wang }
6989f6b26fSZixu Wang 
7089f6b26fSZixu Wang /// Serialize the OS information in the Symbol Graph platform property.
7189f6b26fSZixu Wang ///
7289f6b26fSZixu Wang /// The OS information in Symbol Graph contains the \c name of the OS, and an
7389f6b26fSZixu Wang /// optional \c minimumVersion semantic version field.
7489f6b26fSZixu Wang Object serializeOperatingSystem(const Triple &T) {
7589f6b26fSZixu Wang   Object OS;
7689f6b26fSZixu Wang   OS["name"] = T.getOSTypeName(T.getOS());
7789f6b26fSZixu Wang   serializeObject(OS, "minimumVersion",
7889f6b26fSZixu Wang                   serializeSemanticVersion(T.getMinimumSupportedOSVersion()));
7989f6b26fSZixu Wang   return OS;
8089f6b26fSZixu Wang }
8189f6b26fSZixu Wang 
8289f6b26fSZixu Wang /// Serialize the platform information in the Symbol Graph module section.
8389f6b26fSZixu Wang ///
8489f6b26fSZixu Wang /// The platform object describes a target platform triple in corresponding
8589f6b26fSZixu Wang /// three fields: \c architecture, \c vendor, and \c operatingSystem.
8689f6b26fSZixu Wang Object serializePlatform(const Triple &T) {
8789f6b26fSZixu Wang   Object Platform;
8889f6b26fSZixu Wang   Platform["architecture"] = T.getArchName();
8989f6b26fSZixu Wang   Platform["vendor"] = T.getVendorName();
9089f6b26fSZixu Wang   Platform["operatingSystem"] = serializeOperatingSystem(T);
9189f6b26fSZixu Wang   return Platform;
9289f6b26fSZixu Wang }
9389f6b26fSZixu Wang 
9428d79314SDaniel Grumberg /// Serialize a source position.
9528d79314SDaniel Grumberg Object serializeSourcePosition(const PresumedLoc &Loc) {
9689f6b26fSZixu Wang   assert(Loc.isValid() && "invalid source position");
9789f6b26fSZixu Wang 
9889f6b26fSZixu Wang   Object SourcePosition;
9989f6b26fSZixu Wang   SourcePosition["line"] = Loc.getLine();
10089f6b26fSZixu Wang   SourcePosition["character"] = Loc.getColumn();
10189f6b26fSZixu Wang 
10228d79314SDaniel Grumberg   return SourcePosition;
10328d79314SDaniel Grumberg }
10428d79314SDaniel Grumberg 
10528d79314SDaniel Grumberg /// Serialize a source location in file.
10628d79314SDaniel Grumberg ///
10728d79314SDaniel Grumberg /// \param Loc The presumed location to serialize.
10828d79314SDaniel Grumberg /// \param IncludeFileURI If true, include the file path of \p Loc as a URI.
10928d79314SDaniel Grumberg /// Defaults to false.
11028d79314SDaniel Grumberg Object serializeSourceLocation(const PresumedLoc &Loc,
11128d79314SDaniel Grumberg                                bool IncludeFileURI = false) {
11228d79314SDaniel Grumberg   Object SourceLocation;
11328d79314SDaniel Grumberg   serializeObject(SourceLocation, "position", serializeSourcePosition(Loc));
11428d79314SDaniel Grumberg 
11589f6b26fSZixu Wang   if (IncludeFileURI) {
11689f6b26fSZixu Wang     std::string FileURI = "file://";
11789f6b26fSZixu Wang     // Normalize file path to use forward slashes for the URI.
11889f6b26fSZixu Wang     FileURI += sys::path::convert_to_slash(Loc.getFilename());
11928d79314SDaniel Grumberg     SourceLocation["uri"] = FileURI;
12089f6b26fSZixu Wang   }
12189f6b26fSZixu Wang 
12228d79314SDaniel Grumberg   return SourceLocation;
12389f6b26fSZixu Wang }
12489f6b26fSZixu Wang 
12589f6b26fSZixu Wang /// Serialize a source range with begin and end locations.
12689f6b26fSZixu Wang Object serializeSourceRange(const PresumedLoc &BeginLoc,
12789f6b26fSZixu Wang                             const PresumedLoc &EndLoc) {
12889f6b26fSZixu Wang   Object SourceRange;
12989f6b26fSZixu Wang   serializeObject(SourceRange, "start", serializeSourcePosition(BeginLoc));
13089f6b26fSZixu Wang   serializeObject(SourceRange, "end", serializeSourcePosition(EndLoc));
13189f6b26fSZixu Wang   return SourceRange;
13289f6b26fSZixu Wang }
13389f6b26fSZixu Wang 
13489f6b26fSZixu Wang /// Serialize the availability attributes of a symbol.
13589f6b26fSZixu Wang ///
13689f6b26fSZixu Wang /// Availability information contains the introduced, deprecated, and obsoleted
13789f6b26fSZixu Wang /// versions of the symbol as semantic versions, if not default.
13889f6b26fSZixu Wang /// Availability information also contains flags to indicate if the symbol is
13989f6b26fSZixu Wang /// unconditionally unavailable or deprecated,
14089f6b26fSZixu Wang /// i.e. \c __attribute__((unavailable)) and \c __attribute__((deprecated)).
14189f6b26fSZixu Wang ///
14289f6b26fSZixu Wang /// \returns \c None if the symbol has default availability attributes, or
14389f6b26fSZixu Wang /// an \c Object containing the formatted availability information.
14489f6b26fSZixu Wang Optional<Object> serializeAvailability(const AvailabilityInfo &Avail) {
14589f6b26fSZixu Wang   if (Avail.isDefault())
14689f6b26fSZixu Wang     return None;
14789f6b26fSZixu Wang 
14889f6b26fSZixu Wang   Object Availbility;
14989f6b26fSZixu Wang   serializeObject(Availbility, "introducedVersion",
15089f6b26fSZixu Wang                   serializeSemanticVersion(Avail.Introduced));
15189f6b26fSZixu Wang   serializeObject(Availbility, "deprecatedVersion",
15289f6b26fSZixu Wang                   serializeSemanticVersion(Avail.Deprecated));
15389f6b26fSZixu Wang   serializeObject(Availbility, "obsoletedVersion",
15489f6b26fSZixu Wang                   serializeSemanticVersion(Avail.Obsoleted));
15589f6b26fSZixu Wang   if (Avail.isUnavailable())
15689f6b26fSZixu Wang     Availbility["isUnconditionallyUnavailable"] = true;
15789f6b26fSZixu Wang   if (Avail.isUnconditionallyDeprecated())
15889f6b26fSZixu Wang     Availbility["isUnconditionallyDeprecated"] = true;
15989f6b26fSZixu Wang 
16089f6b26fSZixu Wang   return Availbility;
16189f6b26fSZixu Wang }
16289f6b26fSZixu Wang 
16315bf0e56SZixu Wang /// Get the language name string for interface language references.
16415bf0e56SZixu Wang StringRef getLanguageName(Language Lang) {
16515bf0e56SZixu Wang   switch (Lang) {
16689f6b26fSZixu Wang   case Language::C:
16789f6b26fSZixu Wang     return "c";
16889f6b26fSZixu Wang   case Language::ObjC:
169b62d4021SZixu Wang     return "objective-c";
17089f6b26fSZixu Wang 
17189f6b26fSZixu Wang   // Unsupported language currently
17289f6b26fSZixu Wang   case Language::CXX:
17389f6b26fSZixu Wang   case Language::ObjCXX:
17489f6b26fSZixu Wang   case Language::OpenCL:
17589f6b26fSZixu Wang   case Language::OpenCLCXX:
17689f6b26fSZixu Wang   case Language::CUDA:
17789f6b26fSZixu Wang   case Language::RenderScript:
17889f6b26fSZixu Wang   case Language::HIP:
179d394f9f8SChris Bieneman   case Language::HLSL:
18089f6b26fSZixu Wang 
18189f6b26fSZixu Wang   // Languages that the frontend cannot parse and compile
18289f6b26fSZixu Wang   case Language::Unknown:
18389f6b26fSZixu Wang   case Language::Asm:
18489f6b26fSZixu Wang   case Language::LLVM_IR:
18589f6b26fSZixu Wang     llvm_unreachable("Unsupported language kind");
18689f6b26fSZixu Wang   }
18789f6b26fSZixu Wang 
18889f6b26fSZixu Wang   llvm_unreachable("Unhandled language kind");
18989f6b26fSZixu Wang }
19089f6b26fSZixu Wang 
19189f6b26fSZixu Wang /// Serialize the identifier object as specified by the Symbol Graph format.
19289f6b26fSZixu Wang ///
19389f6b26fSZixu Wang /// The identifier property of a symbol contains the USR for precise and unique
19489f6b26fSZixu Wang /// references, and the interface language name.
19515bf0e56SZixu Wang Object serializeIdentifier(const APIRecord &Record, Language Lang) {
19689f6b26fSZixu Wang   Object Identifier;
19789f6b26fSZixu Wang   Identifier["precise"] = Record.USR;
19815bf0e56SZixu Wang   Identifier["interfaceLanguage"] = getLanguageName(Lang);
19989f6b26fSZixu Wang 
20089f6b26fSZixu Wang   return Identifier;
20189f6b26fSZixu Wang }
20289f6b26fSZixu Wang 
20389f6b26fSZixu Wang /// Serialize the documentation comments attached to a symbol, as specified by
20489f6b26fSZixu Wang /// the Symbol Graph format.
20589f6b26fSZixu Wang ///
20689f6b26fSZixu Wang /// The Symbol Graph \c docComment object contains an array of lines. Each line
20789f6b26fSZixu Wang /// represents one line of striped documentation comment, with source range
20889f6b26fSZixu Wang /// information.
20989f6b26fSZixu Wang /// e.g.
21089f6b26fSZixu Wang /// \code
21189f6b26fSZixu Wang ///   /// This is a documentation comment
21289f6b26fSZixu Wang ///       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'  First line.
21389f6b26fSZixu Wang ///   ///     with multiple lines.
21489f6b26fSZixu Wang ///       ^~~~~~~~~~~~~~~~~~~~~~~'         Second line.
21589f6b26fSZixu Wang /// \endcode
21689f6b26fSZixu Wang ///
21789f6b26fSZixu Wang /// \returns \c None if \p Comment is empty, or an \c Object containing the
21889f6b26fSZixu Wang /// formatted lines.
21989f6b26fSZixu Wang Optional<Object> serializeDocComment(const DocComment &Comment) {
22089f6b26fSZixu Wang   if (Comment.empty())
22189f6b26fSZixu Wang     return None;
22289f6b26fSZixu Wang 
22389f6b26fSZixu Wang   Object DocComment;
22489f6b26fSZixu Wang   Array LinesArray;
22589f6b26fSZixu Wang   for (const auto &CommentLine : Comment) {
22689f6b26fSZixu Wang     Object Line;
22789f6b26fSZixu Wang     Line["text"] = CommentLine.Text;
22889f6b26fSZixu Wang     serializeObject(Line, "range",
22989f6b26fSZixu Wang                     serializeSourceRange(CommentLine.Begin, CommentLine.End));
23089f6b26fSZixu Wang     LinesArray.emplace_back(std::move(Line));
23189f6b26fSZixu Wang   }
23289f6b26fSZixu Wang   serializeArray(DocComment, "lines", LinesArray);
23389f6b26fSZixu Wang 
23489f6b26fSZixu Wang   return DocComment;
23589f6b26fSZixu Wang }
23689f6b26fSZixu Wang 
23789f6b26fSZixu Wang /// Serialize the declaration fragments of a symbol.
23889f6b26fSZixu Wang ///
23989f6b26fSZixu Wang /// The Symbol Graph declaration fragments is an array of tagged important
24089f6b26fSZixu Wang /// parts of a symbol's declaration. The fragments sequence can be joined to
24189f6b26fSZixu Wang /// form spans of declaration text, with attached information useful for
24289f6b26fSZixu Wang /// purposes like syntax-highlighting etc. For example:
24389f6b26fSZixu Wang /// \code
24489f6b26fSZixu Wang ///   const int pi; -> "declarationFragments" : [
24589f6b26fSZixu Wang ///                      {
24689f6b26fSZixu Wang ///                        "kind" : "keyword",
24789f6b26fSZixu Wang ///                        "spelling" : "const"
24889f6b26fSZixu Wang ///                      },
24989f6b26fSZixu Wang ///                      {
25089f6b26fSZixu Wang ///                        "kind" : "text",
25189f6b26fSZixu Wang ///                        "spelling" : " "
25289f6b26fSZixu Wang ///                      },
25389f6b26fSZixu Wang ///                      {
25489f6b26fSZixu Wang ///                        "kind" : "typeIdentifier",
25589f6b26fSZixu Wang ///                        "preciseIdentifier" : "c:I",
25689f6b26fSZixu Wang ///                        "spelling" : "int"
25789f6b26fSZixu Wang ///                      },
25889f6b26fSZixu Wang ///                      {
25989f6b26fSZixu Wang ///                        "kind" : "text",
26089f6b26fSZixu Wang ///                        "spelling" : " "
26189f6b26fSZixu Wang ///                      },
26289f6b26fSZixu Wang ///                      {
26389f6b26fSZixu Wang ///                        "kind" : "identifier",
26489f6b26fSZixu Wang ///                        "spelling" : "pi"
26589f6b26fSZixu Wang ///                      }
26689f6b26fSZixu Wang ///                    ]
26789f6b26fSZixu Wang /// \endcode
26889f6b26fSZixu Wang ///
26989f6b26fSZixu Wang /// \returns \c None if \p DF is empty, or an \c Array containing the formatted
27089f6b26fSZixu Wang /// declaration fragments array.
27189f6b26fSZixu Wang Optional<Array> serializeDeclarationFragments(const DeclarationFragments &DF) {
27289f6b26fSZixu Wang   if (DF.getFragments().empty())
27389f6b26fSZixu Wang     return None;
27489f6b26fSZixu Wang 
27589f6b26fSZixu Wang   Array Fragments;
27689f6b26fSZixu Wang   for (const auto &F : DF.getFragments()) {
27789f6b26fSZixu Wang     Object Fragment;
27889f6b26fSZixu Wang     Fragment["spelling"] = F.Spelling;
27989f6b26fSZixu Wang     Fragment["kind"] = DeclarationFragments::getFragmentKindString(F.Kind);
28089f6b26fSZixu Wang     if (!F.PreciseIdentifier.empty())
28189f6b26fSZixu Wang       Fragment["preciseIdentifier"] = F.PreciseIdentifier;
28289f6b26fSZixu Wang     Fragments.emplace_back(std::move(Fragment));
28389f6b26fSZixu Wang   }
28489f6b26fSZixu Wang 
28589f6b26fSZixu Wang   return Fragments;
28689f6b26fSZixu Wang }
28789f6b26fSZixu Wang 
28889f6b26fSZixu Wang /// Serialize the function signature field of a function, as specified by the
28989f6b26fSZixu Wang /// Symbol Graph format.
29089f6b26fSZixu Wang ///
29189f6b26fSZixu Wang /// The Symbol Graph function signature property contains two arrays.
29289f6b26fSZixu Wang ///   - The \c returns array is the declaration fragments of the return type;
29389f6b26fSZixu Wang ///   - The \c parameters array contains names and declaration fragments of the
29489f6b26fSZixu Wang ///     parameters.
29589f6b26fSZixu Wang ///
29689f6b26fSZixu Wang /// \returns \c None if \p FS is empty, or an \c Object containing the
29789f6b26fSZixu Wang /// formatted function signature.
29889f6b26fSZixu Wang Optional<Object> serializeFunctionSignature(const FunctionSignature &FS) {
29989f6b26fSZixu Wang   if (FS.empty())
30089f6b26fSZixu Wang     return None;
30189f6b26fSZixu Wang 
30289f6b26fSZixu Wang   Object Signature;
30389f6b26fSZixu Wang   serializeArray(Signature, "returns",
30489f6b26fSZixu Wang                  serializeDeclarationFragments(FS.getReturnType()));
30589f6b26fSZixu Wang 
30689f6b26fSZixu Wang   Array Parameters;
30789f6b26fSZixu Wang   for (const auto &P : FS.getParameters()) {
30889f6b26fSZixu Wang     Object Parameter;
30989f6b26fSZixu Wang     Parameter["name"] = P.Name;
31089f6b26fSZixu Wang     serializeArray(Parameter, "declarationFragments",
31189f6b26fSZixu Wang                    serializeDeclarationFragments(P.Fragments));
31289f6b26fSZixu Wang     Parameters.emplace_back(std::move(Parameter));
31389f6b26fSZixu Wang   }
31489f6b26fSZixu Wang 
31589f6b26fSZixu Wang   if (!Parameters.empty())
31689f6b26fSZixu Wang     Signature["parameters"] = std::move(Parameters);
31789f6b26fSZixu Wang 
31889f6b26fSZixu Wang   return Signature;
31989f6b26fSZixu Wang }
32089f6b26fSZixu Wang 
32189f6b26fSZixu Wang /// Serialize the \c names field of a symbol as specified by the Symbol Graph
32289f6b26fSZixu Wang /// format.
32389f6b26fSZixu Wang ///
32489f6b26fSZixu Wang /// The Symbol Graph names field contains multiple representations of a symbol
32589f6b26fSZixu Wang /// that can be used for different applications:
32689f6b26fSZixu Wang ///   - \c title : The simple declared name of the symbol;
32789f6b26fSZixu Wang ///   - \c subHeading : An array of declaration fragments that provides tags,
32889f6b26fSZixu Wang ///     and potentially more tokens (for example the \c +/- symbol for
32989f6b26fSZixu Wang ///     Objective-C methods). Can be used as sub-headings for documentation.
33089f6b26fSZixu Wang Object serializeNames(const APIRecord &Record) {
33189f6b26fSZixu Wang   Object Names;
33289f6b26fSZixu Wang   Names["title"] = Record.Name;
33389f6b26fSZixu Wang   serializeArray(Names, "subHeading",
33489f6b26fSZixu Wang                  serializeDeclarationFragments(Record.SubHeading));
335*80ae3665SDaniel Grumberg   DeclarationFragments NavigatorFragments;
336*80ae3665SDaniel Grumberg   NavigatorFragments.append(Record.Name,
337*80ae3665SDaniel Grumberg                             DeclarationFragments::FragmentKind::Identifier,
338*80ae3665SDaniel Grumberg                             /*PreciseIdentifier*/ "");
339*80ae3665SDaniel Grumberg   serializeArray(Names, "navigator",
340*80ae3665SDaniel Grumberg                  serializeDeclarationFragments(NavigatorFragments));
34189f6b26fSZixu Wang 
34289f6b26fSZixu Wang   return Names;
34389f6b26fSZixu Wang }
34489f6b26fSZixu Wang 
34589f6b26fSZixu Wang /// Serialize the symbol kind information.
34689f6b26fSZixu Wang ///
34789f6b26fSZixu Wang /// The Symbol Graph symbol kind property contains a shorthand \c identifier
34889f6b26fSZixu Wang /// which is prefixed by the source language name, useful for tooling to parse
34989f6b26fSZixu Wang /// the kind, and a \c displayName for rendering human-readable names.
35015bf0e56SZixu Wang Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
35115bf0e56SZixu Wang   auto AddLangPrefix = [&Lang](StringRef S) -> std::string {
35215bf0e56SZixu Wang     return (getLanguageName(Lang) + "." + S).str();
35371b4c226SZixu Wang   };
35471b4c226SZixu Wang 
35589f6b26fSZixu Wang   Object Kind;
35689f6b26fSZixu Wang   switch (Record.getKind()) {
35771b4c226SZixu Wang   case APIRecord::RK_Global: {
35889f6b26fSZixu Wang     auto *GR = dyn_cast<GlobalRecord>(&Record);
35989f6b26fSZixu Wang     switch (GR->GlobalKind) {
36089f6b26fSZixu Wang     case GVKind::Function:
36171b4c226SZixu Wang       Kind["identifier"] = AddLangPrefix("func");
36289f6b26fSZixu Wang       Kind["displayName"] = "Function";
36389f6b26fSZixu Wang       break;
36489f6b26fSZixu Wang     case GVKind::Variable:
36571b4c226SZixu Wang       Kind["identifier"] = AddLangPrefix("var");
36689f6b26fSZixu Wang       Kind["displayName"] = "Global Variable";
36789f6b26fSZixu Wang       break;
36889f6b26fSZixu Wang     case GVKind::Unknown:
36989f6b26fSZixu Wang       // Unknown global kind
37089f6b26fSZixu Wang       break;
37189f6b26fSZixu Wang     }
37289f6b26fSZixu Wang     break;
37389f6b26fSZixu Wang   }
37471b4c226SZixu Wang   case APIRecord::RK_EnumConstant:
37571b4c226SZixu Wang     Kind["identifier"] = AddLangPrefix("enum.case");
37671b4c226SZixu Wang     Kind["displayName"] = "Enumeration Case";
37771b4c226SZixu Wang     break;
37871b4c226SZixu Wang   case APIRecord::RK_Enum:
37971b4c226SZixu Wang     Kind["identifier"] = AddLangPrefix("enum");
38071b4c226SZixu Wang     Kind["displayName"] = "Enumeration";
38171b4c226SZixu Wang     break;
3825bb5704cSZixu Wang   case APIRecord::RK_StructField:
3835bb5704cSZixu Wang     Kind["identifier"] = AddLangPrefix("property");
3845bb5704cSZixu Wang     Kind["displayName"] = "Instance Property";
3855bb5704cSZixu Wang     break;
3865bb5704cSZixu Wang   case APIRecord::RK_Struct:
3875bb5704cSZixu Wang     Kind["identifier"] = AddLangPrefix("struct");
3885bb5704cSZixu Wang     Kind["displayName"] = "Structure";
3895bb5704cSZixu Wang     break;
3909b36e126SZixu Wang   case APIRecord::RK_ObjCIvar:
3919b36e126SZixu Wang     Kind["identifier"] = AddLangPrefix("ivar");
3929b36e126SZixu Wang     Kind["displayName"] = "Instance Variable";
3939b36e126SZixu Wang     break;
3949b36e126SZixu Wang   case APIRecord::RK_ObjCMethod:
3959b36e126SZixu Wang     if (dyn_cast<ObjCMethodRecord>(&Record)->IsInstanceMethod) {
3969b36e126SZixu Wang       Kind["identifier"] = AddLangPrefix("method");
3979b36e126SZixu Wang       Kind["displayName"] = "Instance Method";
3989b36e126SZixu Wang     } else {
3999b36e126SZixu Wang       Kind["identifier"] = AddLangPrefix("type.method");
4009b36e126SZixu Wang       Kind["displayName"] = "Type Method";
4019b36e126SZixu Wang     }
4029b36e126SZixu Wang     break;
4039b36e126SZixu Wang   case APIRecord::RK_ObjCProperty:
4049b36e126SZixu Wang     Kind["identifier"] = AddLangPrefix("property");
4059b36e126SZixu Wang     Kind["displayName"] = "Instance Property";
4069b36e126SZixu Wang     break;
4079b36e126SZixu Wang   case APIRecord::RK_ObjCInterface:
4089b36e126SZixu Wang     Kind["identifier"] = AddLangPrefix("class");
4099b36e126SZixu Wang     Kind["displayName"] = "Class";
4109b36e126SZixu Wang     break;
411178aad9bSZixu Wang   case APIRecord::RK_ObjCCategory:
412178aad9bSZixu Wang     // We don't serialize out standalone Objective-C category symbols yet.
413178aad9bSZixu Wang     llvm_unreachable("Serializing standalone Objective-C category symbols is "
414178aad9bSZixu Wang                      "not supported.");
415178aad9bSZixu Wang     break;
416d1d34bafSZixu Wang   case APIRecord::RK_ObjCProtocol:
417d1d34bafSZixu Wang     Kind["identifier"] = AddLangPrefix("protocol");
418d1d34bafSZixu Wang     Kind["displayName"] = "Protocol";
419d1d34bafSZixu Wang     break;
420529a0570SDaniel Grumberg   case APIRecord::RK_MacroDefinition:
421529a0570SDaniel Grumberg     Kind["identifier"] = AddLangPrefix("macro");
422529a0570SDaniel Grumberg     Kind["displayName"] = "Macro";
4239fc45ca0SDaniel Grumberg     break;
4249fc45ca0SDaniel Grumberg   case APIRecord::RK_Typedef:
4259fc45ca0SDaniel Grumberg     Kind["identifier"] = AddLangPrefix("typealias");
4269fc45ca0SDaniel Grumberg     Kind["displayName"] = "Type Alias";
4279fc45ca0SDaniel Grumberg     break;
42871b4c226SZixu Wang   }
42989f6b26fSZixu Wang 
43089f6b26fSZixu Wang   return Kind;
43189f6b26fSZixu Wang }
43289f6b26fSZixu Wang 
43389f6b26fSZixu Wang } // namespace
43489f6b26fSZixu Wang 
43589f6b26fSZixu Wang void SymbolGraphSerializer::anchor() {}
43689f6b26fSZixu Wang 
43789f6b26fSZixu Wang /// Defines the format version emitted by SymbolGraphSerializer.
43889f6b26fSZixu Wang const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3};
43989f6b26fSZixu Wang 
44089f6b26fSZixu Wang Object SymbolGraphSerializer::serializeMetadata() const {
44189f6b26fSZixu Wang   Object Metadata;
44289f6b26fSZixu Wang   serializeObject(Metadata, "formatVersion",
44389f6b26fSZixu Wang                   serializeSemanticVersion(FormatVersion));
44489f6b26fSZixu Wang   Metadata["generator"] = clang::getClangFullVersion();
44589f6b26fSZixu Wang   return Metadata;
44689f6b26fSZixu Wang }
44789f6b26fSZixu Wang 
44889f6b26fSZixu Wang Object SymbolGraphSerializer::serializeModule() const {
44989f6b26fSZixu Wang   Object Module;
4505ef2ec7eSDaniel Grumberg   // The user is expected to always pass `--product-name=` on the command line
4515ef2ec7eSDaniel Grumberg   // to populate this field.
4525ef2ec7eSDaniel Grumberg   Module["name"] = ProductName;
45389f6b26fSZixu Wang   serializeObject(Module, "platform", serializePlatform(API.getTarget()));
45489f6b26fSZixu Wang   return Module;
45589f6b26fSZixu Wang }
45689f6b26fSZixu Wang 
45789f6b26fSZixu Wang bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const {
45889f6b26fSZixu Wang   // Skip unconditionally unavailable symbols
45989f6b26fSZixu Wang   if (Record.Availability.isUnconditionallyUnavailable())
46089f6b26fSZixu Wang     return true;
46189f6b26fSZixu Wang 
46289f6b26fSZixu Wang   return false;
46389f6b26fSZixu Wang }
46489f6b26fSZixu Wang 
46589f6b26fSZixu Wang Optional<Object>
46689f6b26fSZixu Wang SymbolGraphSerializer::serializeAPIRecord(const APIRecord &Record) const {
46789f6b26fSZixu Wang   if (shouldSkip(Record))
46889f6b26fSZixu Wang     return None;
46989f6b26fSZixu Wang 
47089f6b26fSZixu Wang   Object Obj;
47189f6b26fSZixu Wang   serializeObject(Obj, "identifier",
47215bf0e56SZixu Wang                   serializeIdentifier(Record, API.getLanguage()));
47315bf0e56SZixu Wang   serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage()));
47489f6b26fSZixu Wang   serializeObject(Obj, "names", serializeNames(Record));
47589f6b26fSZixu Wang   serializeObject(
47689f6b26fSZixu Wang       Obj, "location",
47728d79314SDaniel Grumberg       serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true));
47889f6b26fSZixu Wang   serializeObject(Obj, "availbility",
47989f6b26fSZixu Wang                   serializeAvailability(Record.Availability));
48089f6b26fSZixu Wang   serializeObject(Obj, "docComment", serializeDocComment(Record.Comment));
48189f6b26fSZixu Wang   serializeArray(Obj, "declarationFragments",
48289f6b26fSZixu Wang                  serializeDeclarationFragments(Record.Declaration));
48328d79314SDaniel Grumberg   // TODO: Once we keep track of symbol access information serialize it
48428d79314SDaniel Grumberg   // correctly here.
48528d79314SDaniel Grumberg   Obj["accessLevel"] = "public";
48628d79314SDaniel Grumberg   serializeArray(Obj, "pathComponents", Array(PathComponents));
48789f6b26fSZixu Wang 
48889f6b26fSZixu Wang   return Obj;
48989f6b26fSZixu Wang }
49089f6b26fSZixu Wang 
491178aad9bSZixu Wang template <typename MemberTy>
492178aad9bSZixu Wang void SymbolGraphSerializer::serializeMembers(
493178aad9bSZixu Wang     const APIRecord &Record,
494178aad9bSZixu Wang     const SmallVector<std::unique_ptr<MemberTy>> &Members) {
495178aad9bSZixu Wang   for (const auto &Member : Members) {
496178aad9bSZixu Wang     auto MemberPathComponentGuard = makePathComponentGuard(Member->Name);
497178aad9bSZixu Wang     auto MemberRecord = serializeAPIRecord(*Member);
498178aad9bSZixu Wang     if (!MemberRecord)
499178aad9bSZixu Wang       continue;
500178aad9bSZixu Wang 
501178aad9bSZixu Wang     Symbols.emplace_back(std::move(*MemberRecord));
502178aad9bSZixu Wang     serializeRelationship(RelationshipKind::MemberOf, *Member, Record);
503178aad9bSZixu Wang   }
504178aad9bSZixu Wang }
505178aad9bSZixu Wang 
50671b4c226SZixu Wang StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) {
50771b4c226SZixu Wang   switch (Kind) {
50871b4c226SZixu Wang   case RelationshipKind::MemberOf:
50971b4c226SZixu Wang     return "memberOf";
5109b36e126SZixu Wang   case RelationshipKind::InheritsFrom:
5119b36e126SZixu Wang     return "inheritsFrom";
5129b36e126SZixu Wang   case RelationshipKind::ConformsTo:
5139b36e126SZixu Wang     return "conformsTo";
51471b4c226SZixu Wang   }
51571b4c226SZixu Wang   llvm_unreachable("Unhandled relationship kind");
51671b4c226SZixu Wang }
51771b4c226SZixu Wang 
51871b4c226SZixu Wang void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind,
5199b36e126SZixu Wang                                                   SymbolReference Source,
5209b36e126SZixu Wang                                                   SymbolReference Target) {
52171b4c226SZixu Wang   Object Relationship;
52271b4c226SZixu Wang   Relationship["source"] = Source.USR;
52371b4c226SZixu Wang   Relationship["target"] = Target.USR;
52471b4c226SZixu Wang   Relationship["kind"] = getRelationshipString(Kind);
52571b4c226SZixu Wang 
52671b4c226SZixu Wang   Relationships.emplace_back(std::move(Relationship));
52771b4c226SZixu Wang }
52871b4c226SZixu Wang 
52989f6b26fSZixu Wang void SymbolGraphSerializer::serializeGlobalRecord(const GlobalRecord &Record) {
53028d79314SDaniel Grumberg   auto GlobalPathComponentGuard = makePathComponentGuard(Record.Name);
53128d79314SDaniel Grumberg 
53289f6b26fSZixu Wang   auto Obj = serializeAPIRecord(Record);
53389f6b26fSZixu Wang   if (!Obj)
53489f6b26fSZixu Wang     return;
53589f6b26fSZixu Wang 
53689f6b26fSZixu Wang   if (Record.GlobalKind == GVKind::Function)
53728d79314SDaniel Grumberg     serializeObject(*Obj, "functionSignature",
53889f6b26fSZixu Wang                     serializeFunctionSignature(Record.Signature));
53989f6b26fSZixu Wang 
54089f6b26fSZixu Wang   Symbols.emplace_back(std::move(*Obj));
54189f6b26fSZixu Wang }
54289f6b26fSZixu Wang 
54371b4c226SZixu Wang void SymbolGraphSerializer::serializeEnumRecord(const EnumRecord &Record) {
54428d79314SDaniel Grumberg   auto EnumPathComponentGuard = makePathComponentGuard(Record.Name);
54571b4c226SZixu Wang   auto Enum = serializeAPIRecord(Record);
54671b4c226SZixu Wang   if (!Enum)
54771b4c226SZixu Wang     return;
54871b4c226SZixu Wang 
54971b4c226SZixu Wang   Symbols.emplace_back(std::move(*Enum));
550178aad9bSZixu Wang   serializeMembers(Record, Record.Constants);
55171b4c226SZixu Wang }
55271b4c226SZixu Wang 
5535bb5704cSZixu Wang void SymbolGraphSerializer::serializeStructRecord(const StructRecord &Record) {
55428d79314SDaniel Grumberg   auto StructPathComponentGuard = makePathComponentGuard(Record.Name);
5555bb5704cSZixu Wang   auto Struct = serializeAPIRecord(Record);
5565bb5704cSZixu Wang   if (!Struct)
5575bb5704cSZixu Wang     return;
5585bb5704cSZixu Wang 
5595bb5704cSZixu Wang   Symbols.emplace_back(std::move(*Struct));
560178aad9bSZixu Wang   serializeMembers(Record, Record.Fields);
5615bb5704cSZixu Wang }
5625bb5704cSZixu Wang 
5639b36e126SZixu Wang void SymbolGraphSerializer::serializeObjCContainerRecord(
5649b36e126SZixu Wang     const ObjCContainerRecord &Record) {
56528d79314SDaniel Grumberg   auto ObjCContainerPathComponentGuard = makePathComponentGuard(Record.Name);
5669b36e126SZixu Wang   auto ObjCContainer = serializeAPIRecord(Record);
5679b36e126SZixu Wang   if (!ObjCContainer)
5689b36e126SZixu Wang     return;
5699b36e126SZixu Wang 
5709b36e126SZixu Wang   Symbols.emplace_back(std::move(*ObjCContainer));
5719b36e126SZixu Wang 
572178aad9bSZixu Wang   serializeMembers(Record, Record.Ivars);
573178aad9bSZixu Wang   serializeMembers(Record, Record.Methods);
574178aad9bSZixu Wang   serializeMembers(Record, Record.Properties);
5759b36e126SZixu Wang 
5769b36e126SZixu Wang   for (const auto &Protocol : Record.Protocols)
5779b36e126SZixu Wang     // Record that Record conforms to Protocol.
5789b36e126SZixu Wang     serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
5799b36e126SZixu Wang 
580178aad9bSZixu Wang   if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record)) {
5819b36e126SZixu Wang     if (!ObjCInterface->SuperClass.empty())
5829b36e126SZixu Wang       // If Record is an Objective-C interface record and it has a super class,
5839b36e126SZixu Wang       // record that Record is inherited from SuperClass.
5849b36e126SZixu Wang       serializeRelationship(RelationshipKind::InheritsFrom, Record,
5859b36e126SZixu Wang                             ObjCInterface->SuperClass);
586178aad9bSZixu Wang 
587178aad9bSZixu Wang     // Members of categories extending an interface are serialized as members of
588178aad9bSZixu Wang     // the interface.
589178aad9bSZixu Wang     for (const auto *Category : ObjCInterface->Categories) {
590178aad9bSZixu Wang       serializeMembers(Record, Category->Ivars);
591178aad9bSZixu Wang       serializeMembers(Record, Category->Methods);
592178aad9bSZixu Wang       serializeMembers(Record, Category->Properties);
593178aad9bSZixu Wang 
594178aad9bSZixu Wang       // Surface the protocols of the the category to the interface.
595178aad9bSZixu Wang       for (const auto &Protocol : Category->Protocols)
596178aad9bSZixu Wang         serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol);
597178aad9bSZixu Wang     }
598178aad9bSZixu Wang   }
5999b36e126SZixu Wang }
6009b36e126SZixu Wang 
601529a0570SDaniel Grumberg void SymbolGraphSerializer::serializeMacroDefinitionRecord(
602529a0570SDaniel Grumberg     const MacroDefinitionRecord &Record) {
60328d79314SDaniel Grumberg   auto MacroPathComponentGuard = makePathComponentGuard(Record.Name);
604529a0570SDaniel Grumberg   auto Macro = serializeAPIRecord(Record);
60528d79314SDaniel Grumberg 
606529a0570SDaniel Grumberg   if (!Macro)
607529a0570SDaniel Grumberg     return;
608529a0570SDaniel Grumberg 
609529a0570SDaniel Grumberg   Symbols.emplace_back(std::move(*Macro));
610529a0570SDaniel Grumberg }
611529a0570SDaniel Grumberg 
6129fc45ca0SDaniel Grumberg void SymbolGraphSerializer::serializeTypedefRecord(
6139fc45ca0SDaniel Grumberg     const TypedefRecord &Record) {
6149fc45ca0SDaniel Grumberg   // Typedefs of anonymous types have their entries unified with the underlying
6159fc45ca0SDaniel Grumberg   // type.
6169fc45ca0SDaniel Grumberg   bool ShouldDrop = Record.UnderlyingType.Name.empty();
6179fc45ca0SDaniel Grumberg   // enums declared with `NS_OPTION` have a named enum and a named typedef, with
6189fc45ca0SDaniel Grumberg   // the same name
6199fc45ca0SDaniel Grumberg   ShouldDrop |= (Record.UnderlyingType.Name == Record.Name);
6209fc45ca0SDaniel Grumberg   if (ShouldDrop)
6219fc45ca0SDaniel Grumberg     return;
6229fc45ca0SDaniel Grumberg 
6239fc45ca0SDaniel Grumberg   auto TypedefPathComponentGuard = makePathComponentGuard(Record.Name);
6249fc45ca0SDaniel Grumberg   auto Typedef = serializeAPIRecord(Record);
6259fc45ca0SDaniel Grumberg   if (!Typedef)
6269fc45ca0SDaniel Grumberg     return;
6279fc45ca0SDaniel Grumberg 
6289fc45ca0SDaniel Grumberg   (*Typedef)["type"] = Record.UnderlyingType.USR;
6299fc45ca0SDaniel Grumberg 
6309fc45ca0SDaniel Grumberg   Symbols.emplace_back(std::move(*Typedef));
6319fc45ca0SDaniel Grumberg }
6329fc45ca0SDaniel Grumberg 
63328d79314SDaniel Grumberg SymbolGraphSerializer::PathComponentGuard
63428d79314SDaniel Grumberg SymbolGraphSerializer::makePathComponentGuard(StringRef Component) {
63528d79314SDaniel Grumberg   return PathComponentGuard(PathComponents, Component);
63628d79314SDaniel Grumberg }
63728d79314SDaniel Grumberg 
63889f6b26fSZixu Wang Object SymbolGraphSerializer::serialize() {
63989f6b26fSZixu Wang   Object Root;
64089f6b26fSZixu Wang   serializeObject(Root, "metadata", serializeMetadata());
64189f6b26fSZixu Wang   serializeObject(Root, "module", serializeModule());
64289f6b26fSZixu Wang 
64389f6b26fSZixu Wang   // Serialize global records in the API set.
64489f6b26fSZixu Wang   for (const auto &Global : API.getGlobals())
64589f6b26fSZixu Wang     serializeGlobalRecord(*Global.second);
64689f6b26fSZixu Wang 
64771b4c226SZixu Wang   // Serialize enum records in the API set.
64871b4c226SZixu Wang   for (const auto &Enum : API.getEnums())
64971b4c226SZixu Wang     serializeEnumRecord(*Enum.second);
65071b4c226SZixu Wang 
6515bb5704cSZixu Wang   // Serialize struct records in the API set.
6525bb5704cSZixu Wang   for (const auto &Struct : API.getStructs())
6535bb5704cSZixu Wang     serializeStructRecord(*Struct.second);
6545bb5704cSZixu Wang 
6559b36e126SZixu Wang   // Serialize Objective-C interface records in the API set.
6569b36e126SZixu Wang   for (const auto &ObjCInterface : API.getObjCInterfaces())
6579b36e126SZixu Wang     serializeObjCContainerRecord(*ObjCInterface.second);
6589b36e126SZixu Wang 
659d1d34bafSZixu Wang   // Serialize Objective-C protocol records in the API set.
660d1d34bafSZixu Wang   for (const auto &ObjCProtocol : API.getObjCProtocols())
661d1d34bafSZixu Wang     serializeObjCContainerRecord(*ObjCProtocol.second);
662d1d34bafSZixu Wang 
663529a0570SDaniel Grumberg   for (const auto &Macro : API.getMacros())
664529a0570SDaniel Grumberg     serializeMacroDefinitionRecord(*Macro.second);
665529a0570SDaniel Grumberg 
6669fc45ca0SDaniel Grumberg   for (const auto &Typedef : API.getTypedefs())
6679fc45ca0SDaniel Grumberg     serializeTypedefRecord(*Typedef.second);
6689fc45ca0SDaniel Grumberg 
66989f6b26fSZixu Wang   Root["symbols"] = std::move(Symbols);
67028d79314SDaniel Grumberg   Root["relationships"] = std::move(Relationships);
67189f6b26fSZixu Wang 
67289f6b26fSZixu Wang   return Root;
67389f6b26fSZixu Wang }
67489f6b26fSZixu Wang 
67589f6b26fSZixu Wang void SymbolGraphSerializer::serialize(raw_ostream &os) {
67689f6b26fSZixu Wang   Object root = serialize();
67789f6b26fSZixu Wang   if (Options.Compact)
67889f6b26fSZixu Wang     os << formatv("{0}", Value(std::move(root))) << "\n";
67989f6b26fSZixu Wang   else
68089f6b26fSZixu Wang     os << formatv("{0:2}", Value(std::move(root))) << "\n";
68189f6b26fSZixu Wang }
682