1 //===- ExtractAPI/Serialization/SymbolGraphSerializer.cpp -------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file implements the SymbolGraphSerializer. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/ExtractAPI/Serialization/SymbolGraphSerializer.h" 15 #include "clang/Basic/SourceLocation.h" 16 #include "clang/Basic/Version.h" 17 #include "clang/ExtractAPI/DeclarationFragments.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/STLFunctionalExtras.h" 20 #include "llvm/Support/Casting.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Support/Path.h" 23 #include "llvm/Support/VersionTuple.h" 24 #include <optional> 25 #include <type_traits> 26 27 using namespace clang; 28 using namespace clang::extractapi; 29 using namespace llvm; 30 using namespace llvm::json; 31 32 namespace { 33 34 /// Helper function to inject a JSON object \p Obj into another object \p Paren 35 /// at position \p Key. 36 void serializeObject(Object &Paren, StringRef Key, std::optional<Object> Obj) { 37 if (Obj) 38 Paren[Key] = std::move(*Obj); 39 } 40 41 /// Helper function to inject a StringRef \p String into an object \p Paren at 42 /// position \p Key 43 void serializeString(Object &Paren, StringRef Key, 44 std::optional<std::string> String) { 45 if (String) 46 Paren[Key] = std::move(*String); 47 } 48 49 /// Helper function to inject a JSON array \p Array into object \p Paren at 50 /// position \p Key. 51 void serializeArray(Object &Paren, StringRef Key, std::optional<Array> Array) { 52 if (Array) 53 Paren[Key] = std::move(*Array); 54 } 55 56 /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version 57 /// format. 58 /// 59 /// A semantic version object contains three numeric fields, representing the 60 /// \c major, \c minor, and \c patch parts of the version tuple. 61 /// For example version tuple 1.0.3 is serialized as: 62 /// \code 63 /// { 64 /// "major" : 1, 65 /// "minor" : 0, 66 /// "patch" : 3 67 /// } 68 /// \endcode 69 /// 70 /// \returns \c std::nullopt if the version \p V is empty, or an \c Object 71 /// containing the semantic version representation of \p V. 72 std::optional<Object> serializeSemanticVersion(const VersionTuple &V) { 73 if (V.empty()) 74 return std::nullopt; 75 76 Object Version; 77 Version["major"] = V.getMajor(); 78 Version["minor"] = V.getMinor().value_or(0); 79 Version["patch"] = V.getSubminor().value_or(0); 80 return Version; 81 } 82 83 /// Serialize the OS information in the Symbol Graph platform property. 84 /// 85 /// The OS information in Symbol Graph contains the \c name of the OS, and an 86 /// optional \c minimumVersion semantic version field. 87 Object serializeOperatingSystem(const Triple &T) { 88 Object OS; 89 OS["name"] = T.getOSTypeName(T.getOS()); 90 serializeObject(OS, "minimumVersion", 91 serializeSemanticVersion(T.getMinimumSupportedOSVersion())); 92 return OS; 93 } 94 95 /// Serialize the platform information in the Symbol Graph module section. 96 /// 97 /// The platform object describes a target platform triple in corresponding 98 /// three fields: \c architecture, \c vendor, and \c operatingSystem. 99 Object serializePlatform(const Triple &T) { 100 Object Platform; 101 Platform["architecture"] = T.getArchName(); 102 Platform["vendor"] = T.getVendorName(); 103 Platform["operatingSystem"] = serializeOperatingSystem(T); 104 return Platform; 105 } 106 107 /// Serialize a source position. 108 Object serializeSourcePosition(const PresumedLoc &Loc) { 109 assert(Loc.isValid() && "invalid source position"); 110 111 Object SourcePosition; 112 SourcePosition["line"] = Loc.getLine(); 113 SourcePosition["character"] = Loc.getColumn(); 114 115 return SourcePosition; 116 } 117 118 /// Serialize a source location in file. 119 /// 120 /// \param Loc The presumed location to serialize. 121 /// \param IncludeFileURI If true, include the file path of \p Loc as a URI. 122 /// Defaults to false. 123 Object serializeSourceLocation(const PresumedLoc &Loc, 124 bool IncludeFileURI = false) { 125 Object SourceLocation; 126 serializeObject(SourceLocation, "position", serializeSourcePosition(Loc)); 127 128 if (IncludeFileURI) { 129 std::string FileURI = "file://"; 130 // Normalize file path to use forward slashes for the URI. 131 FileURI += sys::path::convert_to_slash(Loc.getFilename()); 132 SourceLocation["uri"] = FileURI; 133 } 134 135 return SourceLocation; 136 } 137 138 /// Serialize a source range with begin and end locations. 139 Object serializeSourceRange(const PresumedLoc &BeginLoc, 140 const PresumedLoc &EndLoc) { 141 Object SourceRange; 142 serializeObject(SourceRange, "start", serializeSourcePosition(BeginLoc)); 143 serializeObject(SourceRange, "end", serializeSourcePosition(EndLoc)); 144 return SourceRange; 145 } 146 147 /// Serialize the availability attributes of a symbol. 148 /// 149 /// Availability information contains the introduced, deprecated, and obsoleted 150 /// versions of the symbol for a given domain (roughly corresponds to a 151 /// platform) as semantic versions, if not default. Availability information 152 /// also contains flags to indicate if the symbol is unconditionally unavailable 153 /// or deprecated, i.e. \c __attribute__((unavailable)) and \c 154 /// __attribute__((deprecated)). 155 /// 156 /// \returns \c std::nullopt if the symbol has default availability attributes, 157 /// or an \c Array containing the formatted availability information. 158 std::optional<Array> 159 serializeAvailability(const AvailabilitySet &Availabilities) { 160 if (Availabilities.isDefault()) 161 return std::nullopt; 162 163 Array AvailabilityArray; 164 165 if (Availabilities.isUnconditionallyDeprecated()) { 166 Object UnconditionallyDeprecated; 167 UnconditionallyDeprecated["domain"] = "*"; 168 UnconditionallyDeprecated["isUnconditionallyDeprecated"] = true; 169 AvailabilityArray.emplace_back(std::move(UnconditionallyDeprecated)); 170 } 171 172 // Note unconditionally unavailable records are skipped. 173 174 for (const auto &AvailInfo : Availabilities) { 175 Object Availability; 176 Availability["domain"] = AvailInfo.Domain; 177 if (AvailInfo.Unavailable) 178 Availability["isUnconditionallyUnavailable"] = true; 179 else { 180 serializeObject(Availability, "introducedVersion", 181 serializeSemanticVersion(AvailInfo.Introduced)); 182 serializeObject(Availability, "deprecatedVersion", 183 serializeSemanticVersion(AvailInfo.Deprecated)); 184 serializeObject(Availability, "obsoletedVersion", 185 serializeSemanticVersion(AvailInfo.Obsoleted)); 186 } 187 AvailabilityArray.emplace_back(std::move(Availability)); 188 } 189 190 return AvailabilityArray; 191 } 192 193 /// Get the language name string for interface language references. 194 StringRef getLanguageName(Language Lang) { 195 switch (Lang) { 196 case Language::C: 197 return "c"; 198 case Language::ObjC: 199 return "objective-c"; 200 case Language::CXX: 201 return "c++"; 202 203 // Unsupported language currently 204 case Language::ObjCXX: 205 case Language::OpenCL: 206 case Language::OpenCLCXX: 207 case Language::CUDA: 208 case Language::RenderScript: 209 case Language::HIP: 210 case Language::HLSL: 211 212 // Languages that the frontend cannot parse and compile 213 case Language::Unknown: 214 case Language::Asm: 215 case Language::LLVM_IR: 216 llvm_unreachable("Unsupported language kind"); 217 } 218 219 llvm_unreachable("Unhandled language kind"); 220 } 221 222 /// Serialize the identifier object as specified by the Symbol Graph format. 223 /// 224 /// The identifier property of a symbol contains the USR for precise and unique 225 /// references, and the interface language name. 226 Object serializeIdentifier(const APIRecord &Record, Language Lang) { 227 Object Identifier; 228 Identifier["precise"] = Record.USR; 229 Identifier["interfaceLanguage"] = getLanguageName(Lang); 230 231 return Identifier; 232 } 233 234 /// Serialize the documentation comments attached to a symbol, as specified by 235 /// the Symbol Graph format. 236 /// 237 /// The Symbol Graph \c docComment object contains an array of lines. Each line 238 /// represents one line of striped documentation comment, with source range 239 /// information. 240 /// e.g. 241 /// \code 242 /// /// This is a documentation comment 243 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' First line. 244 /// /// with multiple lines. 245 /// ^~~~~~~~~~~~~~~~~~~~~~~' Second line. 246 /// \endcode 247 /// 248 /// \returns \c std::nullopt if \p Comment is empty, or an \c Object containing 249 /// the formatted lines. 250 std::optional<Object> serializeDocComment(const DocComment &Comment) { 251 if (Comment.empty()) 252 return std::nullopt; 253 254 Object DocComment; 255 Array LinesArray; 256 for (const auto &CommentLine : Comment) { 257 Object Line; 258 Line["text"] = CommentLine.Text; 259 serializeObject(Line, "range", 260 serializeSourceRange(CommentLine.Begin, CommentLine.End)); 261 LinesArray.emplace_back(std::move(Line)); 262 } 263 serializeArray(DocComment, "lines", LinesArray); 264 265 return DocComment; 266 } 267 268 /// Serialize the declaration fragments of a symbol. 269 /// 270 /// The Symbol Graph declaration fragments is an array of tagged important 271 /// parts of a symbol's declaration. The fragments sequence can be joined to 272 /// form spans of declaration text, with attached information useful for 273 /// purposes like syntax-highlighting etc. For example: 274 /// \code 275 /// const int pi; -> "declarationFragments" : [ 276 /// { 277 /// "kind" : "keyword", 278 /// "spelling" : "const" 279 /// }, 280 /// { 281 /// "kind" : "text", 282 /// "spelling" : " " 283 /// }, 284 /// { 285 /// "kind" : "typeIdentifier", 286 /// "preciseIdentifier" : "c:I", 287 /// "spelling" : "int" 288 /// }, 289 /// { 290 /// "kind" : "text", 291 /// "spelling" : " " 292 /// }, 293 /// { 294 /// "kind" : "identifier", 295 /// "spelling" : "pi" 296 /// } 297 /// ] 298 /// \endcode 299 /// 300 /// \returns \c std::nullopt if \p DF is empty, or an \c Array containing the 301 /// formatted declaration fragments array. 302 std::optional<Array> 303 serializeDeclarationFragments(const DeclarationFragments &DF) { 304 if (DF.getFragments().empty()) 305 return std::nullopt; 306 307 Array Fragments; 308 for (const auto &F : DF.getFragments()) { 309 Object Fragment; 310 Fragment["spelling"] = F.Spelling; 311 Fragment["kind"] = DeclarationFragments::getFragmentKindString(F.Kind); 312 if (!F.PreciseIdentifier.empty()) 313 Fragment["preciseIdentifier"] = F.PreciseIdentifier; 314 Fragments.emplace_back(std::move(Fragment)); 315 } 316 317 return Fragments; 318 } 319 320 /// Serialize the \c names field of a symbol as specified by the Symbol Graph 321 /// format. 322 /// 323 /// The Symbol Graph names field contains multiple representations of a symbol 324 /// that can be used for different applications: 325 /// - \c title : The simple declared name of the symbol; 326 /// - \c subHeading : An array of declaration fragments that provides tags, 327 /// and potentially more tokens (for example the \c +/- symbol for 328 /// Objective-C methods). Can be used as sub-headings for documentation. 329 Object serializeNames(const APIRecord &Record) { 330 Object Names; 331 if (auto *CategoryRecord = 332 dyn_cast_or_null<const ObjCCategoryRecord>(&Record)) 333 Names["title"] = 334 (CategoryRecord->Interface.Name + " (" + Record.Name + ")").str(); 335 else 336 Names["title"] = Record.Name; 337 338 serializeArray(Names, "subHeading", 339 serializeDeclarationFragments(Record.SubHeading)); 340 DeclarationFragments NavigatorFragments; 341 NavigatorFragments.append(Record.Name, 342 DeclarationFragments::FragmentKind::Identifier, 343 /*PreciseIdentifier*/ ""); 344 serializeArray(Names, "navigator", 345 serializeDeclarationFragments(NavigatorFragments)); 346 347 return Names; 348 } 349 350 Object serializeSymbolKind(APIRecord::RecordKind RK, Language Lang) { 351 auto AddLangPrefix = [&Lang](StringRef S) -> std::string { 352 return (getLanguageName(Lang) + "." + S).str(); 353 }; 354 355 Object Kind; 356 switch (RK) { 357 case APIRecord::RK_Unknown: 358 llvm_unreachable("Records should have an explicit kind"); 359 break; 360 case APIRecord::RK_GlobalFunction: 361 Kind["identifier"] = AddLangPrefix("func"); 362 Kind["displayName"] = "Function"; 363 break; 364 case APIRecord::RK_GlobalFunctionTemplate: 365 Kind["identifier"] = AddLangPrefix("func"); 366 Kind["displayName"] = "Function Template"; 367 break; 368 case APIRecord::RK_GlobalFunctionTemplateSpecialization: 369 Kind["identifier"] = AddLangPrefix("func"); 370 Kind["displayName"] = "Function Template Specialization"; 371 break; 372 case APIRecord::RK_GlobalVariableTemplate: 373 Kind["identifier"] = AddLangPrefix("var"); 374 Kind["displayName"] = "Global Variable Template"; 375 break; 376 case APIRecord::RK_GlobalVariableTemplateSpecialization: 377 Kind["identifier"] = AddLangPrefix("var"); 378 Kind["displayName"] = "Global Variable Template Specialization"; 379 break; 380 case APIRecord::RK_GlobalVariableTemplatePartialSpecialization: 381 Kind["identifier"] = AddLangPrefix("var"); 382 Kind["displayName"] = "Global Variable Template Partial Specialization"; 383 break; 384 case APIRecord::RK_GlobalVariable: 385 Kind["identifier"] = AddLangPrefix("var"); 386 Kind["displayName"] = "Global Variable"; 387 break; 388 case APIRecord::RK_EnumConstant: 389 Kind["identifier"] = AddLangPrefix("enum.case"); 390 Kind["displayName"] = "Enumeration Case"; 391 break; 392 case APIRecord::RK_Enum: 393 Kind["identifier"] = AddLangPrefix("enum"); 394 Kind["displayName"] = "Enumeration"; 395 break; 396 case APIRecord::RK_StructField: 397 Kind["identifier"] = AddLangPrefix("property"); 398 Kind["displayName"] = "Instance Property"; 399 break; 400 case APIRecord::RK_Struct: 401 Kind["identifier"] = AddLangPrefix("struct"); 402 Kind["displayName"] = "Structure"; 403 break; 404 case APIRecord::RK_CXXField: 405 Kind["identifier"] = AddLangPrefix("property"); 406 Kind["displayName"] = "Instance Property"; 407 break; 408 case APIRecord::RK_Union: 409 Kind["identifier"] = AddLangPrefix("union"); 410 Kind["displayName"] = "Union"; 411 break; 412 case APIRecord::RK_StaticField: 413 Kind["identifier"] = AddLangPrefix("type.property"); 414 Kind["displayName"] = "Type Property"; 415 break; 416 case APIRecord::RK_ClassTemplate: 417 case APIRecord::RK_ClassTemplateSpecialization: 418 case APIRecord::RK_ClassTemplatePartialSpecialization: 419 case APIRecord::RK_CXXClass: 420 Kind["identifier"] = AddLangPrefix("class"); 421 Kind["displayName"] = "Class"; 422 break; 423 case APIRecord::RK_Concept: 424 Kind["identifier"] = AddLangPrefix("concept"); 425 Kind["displayName"] = "Concept"; 426 break; 427 case APIRecord::RK_CXXStaticMethod: 428 Kind["identifier"] = AddLangPrefix("type.method"); 429 Kind["displayName"] = "Static Method"; 430 break; 431 case APIRecord::RK_CXXInstanceMethod: 432 Kind["identifier"] = AddLangPrefix("method"); 433 Kind["displayName"] = "Instance Method"; 434 break; 435 case APIRecord::RK_CXXConstructorMethod: 436 Kind["identifier"] = AddLangPrefix("method"); 437 Kind["displayName"] = "Constructor"; 438 break; 439 case APIRecord::RK_CXXDestructorMethod: 440 Kind["identifier"] = AddLangPrefix("method"); 441 Kind["displayName"] = "Destructor"; 442 break; 443 case APIRecord::RK_ObjCIvar: 444 Kind["identifier"] = AddLangPrefix("ivar"); 445 Kind["displayName"] = "Instance Variable"; 446 break; 447 case APIRecord::RK_ObjCInstanceMethod: 448 Kind["identifier"] = AddLangPrefix("method"); 449 Kind["displayName"] = "Instance Method"; 450 break; 451 case APIRecord::RK_ObjCClassMethod: 452 Kind["identifier"] = AddLangPrefix("type.method"); 453 Kind["displayName"] = "Type Method"; 454 break; 455 case APIRecord::RK_ObjCInstanceProperty: 456 Kind["identifier"] = AddLangPrefix("property"); 457 Kind["displayName"] = "Instance Property"; 458 break; 459 case APIRecord::RK_ObjCClassProperty: 460 Kind["identifier"] = AddLangPrefix("type.property"); 461 Kind["displayName"] = "Type Property"; 462 break; 463 case APIRecord::RK_ObjCInterface: 464 Kind["identifier"] = AddLangPrefix("class"); 465 Kind["displayName"] = "Class"; 466 break; 467 case APIRecord::RK_ObjCCategory: 468 Kind["identifier"] = AddLangPrefix("class.extension"); 469 Kind["displayName"] = "Class Extension"; 470 break; 471 case APIRecord::RK_ObjCCategoryModule: 472 Kind["identifier"] = AddLangPrefix("module.extension"); 473 Kind["displayName"] = "Module Extension"; 474 break; 475 case APIRecord::RK_ObjCProtocol: 476 Kind["identifier"] = AddLangPrefix("protocol"); 477 Kind["displayName"] = "Protocol"; 478 break; 479 case APIRecord::RK_MacroDefinition: 480 Kind["identifier"] = AddLangPrefix("macro"); 481 Kind["displayName"] = "Macro"; 482 break; 483 case APIRecord::RK_Typedef: 484 Kind["identifier"] = AddLangPrefix("typealias"); 485 Kind["displayName"] = "Type Alias"; 486 break; 487 } 488 489 return Kind; 490 } 491 492 /// Serialize the symbol kind information. 493 /// 494 /// The Symbol Graph symbol kind property contains a shorthand \c identifier 495 /// which is prefixed by the source language name, useful for tooling to parse 496 /// the kind, and a \c displayName for rendering human-readable names. 497 Object serializeSymbolKind(const APIRecord &Record, Language Lang) { 498 return serializeSymbolKind(Record.getKind(), Lang); 499 } 500 501 template <typename RecordTy> 502 std::optional<Object> 503 serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::true_type) { 504 const auto &FS = Record.Signature; 505 if (FS.empty()) 506 return std::nullopt; 507 508 Object Signature; 509 serializeArray(Signature, "returns", 510 serializeDeclarationFragments(FS.getReturnType())); 511 512 Array Parameters; 513 for (const auto &P : FS.getParameters()) { 514 Object Parameter; 515 Parameter["name"] = P.Name; 516 serializeArray(Parameter, "declarationFragments", 517 serializeDeclarationFragments(P.Fragments)); 518 Parameters.emplace_back(std::move(Parameter)); 519 } 520 521 if (!Parameters.empty()) 522 Signature["parameters"] = std::move(Parameters); 523 524 return Signature; 525 } 526 527 template <typename RecordTy> 528 std::optional<Object> 529 serializeFunctionSignatureMixinImpl(const RecordTy &Record, std::false_type) { 530 return std::nullopt; 531 } 532 533 /// Serialize the function signature field, as specified by the 534 /// Symbol Graph format. 535 /// 536 /// The Symbol Graph function signature property contains two arrays. 537 /// - The \c returns array is the declaration fragments of the return type; 538 /// - The \c parameters array contains names and declaration fragments of the 539 /// parameters. 540 /// 541 /// \returns \c std::nullopt if \p FS is empty, or an \c Object containing the 542 /// formatted function signature. 543 template <typename RecordTy> 544 void serializeFunctionSignatureMixin(Object &Paren, const RecordTy &Record) { 545 serializeObject(Paren, "functionSignature", 546 serializeFunctionSignatureMixinImpl( 547 Record, has_function_signature<RecordTy>())); 548 } 549 550 template <typename RecordTy> 551 std::optional<std::string> serializeAccessMixinImpl(const RecordTy &Record, 552 std::true_type) { 553 const auto &AccessControl = Record.Access; 554 std::string Access; 555 if (AccessControl.empty()) 556 return std::nullopt; 557 Access = AccessControl.getAccess(); 558 return Access; 559 } 560 561 template <typename RecordTy> 562 std::optional<std::string> serializeAccessMixinImpl(const RecordTy &Record, 563 std::false_type) { 564 return std::nullopt; 565 } 566 567 template <typename RecordTy> 568 void serializeAccessMixin(Object &Paren, const RecordTy &Record) { 569 auto accessLevel = serializeAccessMixinImpl(Record, has_access<RecordTy>()); 570 if (!accessLevel.has_value()) 571 accessLevel = "public"; 572 serializeString(Paren, "accessLevel", accessLevel); 573 } 574 575 template <typename RecordTy> 576 std::optional<Object> serializeTemplateMixinImpl(const RecordTy &Record, 577 std::true_type) { 578 const auto &Template = Record.Templ; 579 if (Template.empty()) 580 return std::nullopt; 581 582 Object Generics; 583 Array GenericParameters; 584 for (const auto Param : Template.getParameters()) { 585 Object Parameter; 586 Parameter["name"] = Param.Name; 587 Parameter["index"] = Param.Index; 588 Parameter["depth"] = Param.Depth; 589 GenericParameters.emplace_back(std::move(Parameter)); 590 } 591 if (!GenericParameters.empty()) 592 Generics["parameters"] = std::move(GenericParameters); 593 594 Array GenericConstraints; 595 for (const auto Constr : Template.getConstraints()) { 596 Object Constraint; 597 Constraint["kind"] = Constr.Kind; 598 Constraint["lhs"] = Constr.LHS; 599 Constraint["rhs"] = Constr.RHS; 600 GenericConstraints.emplace_back(std::move(Constraint)); 601 } 602 603 if (!GenericConstraints.empty()) 604 Generics["constraints"] = std::move(GenericConstraints); 605 606 return Generics; 607 } 608 609 template <typename RecordTy> 610 std::optional<Object> serializeTemplateMixinImpl(const RecordTy &Record, 611 std::false_type) { 612 return std::nullopt; 613 } 614 615 template <typename RecordTy> 616 void serializeTemplateMixin(Object &Paren, const RecordTy &Record) { 617 serializeObject(Paren, "swiftGenerics", 618 serializeTemplateMixinImpl(Record, has_template<RecordTy>())); 619 } 620 621 struct PathComponent { 622 StringRef USR; 623 StringRef Name; 624 APIRecord::RecordKind Kind; 625 626 PathComponent(StringRef USR, StringRef Name, APIRecord::RecordKind Kind) 627 : USR(USR), Name(Name), Kind(Kind) {} 628 }; 629 630 template <typename RecordTy> 631 bool generatePathComponents( 632 const RecordTy &Record, const APISet &API, 633 function_ref<void(const PathComponent &)> ComponentTransformer) { 634 SmallVector<PathComponent, 4> ReverseComponenents; 635 ReverseComponenents.emplace_back(Record.USR, Record.Name, Record.getKind()); 636 const auto *CurrentParent = &Record.ParentInformation; 637 bool FailedToFindParent = false; 638 while (CurrentParent && !CurrentParent->empty()) { 639 PathComponent CurrentParentComponent(CurrentParent->ParentUSR, 640 CurrentParent->ParentName, 641 CurrentParent->ParentKind); 642 643 auto *ParentRecord = CurrentParent->ParentRecord; 644 // Slow path if we don't have a direct reference to the ParentRecord 645 if (!ParentRecord) 646 ParentRecord = API.findRecordForUSR(CurrentParent->ParentUSR); 647 648 // If the parent is a category extended from internal module then we need to 649 // pretend this belongs to the associated interface. 650 if (auto *CategoryRecord = 651 dyn_cast_or_null<ObjCCategoryRecord>(ParentRecord)) { 652 if (!CategoryRecord->IsFromExternalModule) { 653 ParentRecord = API.findRecordForUSR(CategoryRecord->Interface.USR); 654 CurrentParentComponent = PathComponent(CategoryRecord->Interface.USR, 655 CategoryRecord->Interface.Name, 656 APIRecord::RK_ObjCInterface); 657 } 658 } 659 660 // The parent record doesn't exist which means the symbol shouldn't be 661 // treated as part of the current product. 662 if (!ParentRecord) { 663 FailedToFindParent = true; 664 break; 665 } 666 667 ReverseComponenents.push_back(std::move(CurrentParentComponent)); 668 CurrentParent = &ParentRecord->ParentInformation; 669 } 670 671 for (const auto &PC : reverse(ReverseComponenents)) 672 ComponentTransformer(PC); 673 674 return FailedToFindParent; 675 } 676 677 Object serializeParentContext(const PathComponent &PC, Language Lang) { 678 Object ParentContextElem; 679 ParentContextElem["usr"] = PC.USR; 680 ParentContextElem["name"] = PC.Name; 681 ParentContextElem["kind"] = serializeSymbolKind(PC.Kind, Lang)["identifier"]; 682 return ParentContextElem; 683 } 684 685 template <typename RecordTy> 686 Array generateParentContexts(const RecordTy &Record, const APISet &API, 687 Language Lang) { 688 Array ParentContexts; 689 generatePathComponents( 690 Record, API, [Lang, &ParentContexts](const PathComponent &PC) { 691 ParentContexts.push_back(serializeParentContext(PC, Lang)); 692 }); 693 694 return ParentContexts; 695 } 696 } // namespace 697 698 /// Defines the format version emitted by SymbolGraphSerializer. 699 const VersionTuple SymbolGraphSerializer::FormatVersion{0, 5, 3}; 700 701 Object SymbolGraphSerializer::serializeMetadata() const { 702 Object Metadata; 703 serializeObject(Metadata, "formatVersion", 704 serializeSemanticVersion(FormatVersion)); 705 Metadata["generator"] = clang::getClangFullVersion(); 706 return Metadata; 707 } 708 709 Object SymbolGraphSerializer::serializeModule() const { 710 Object Module; 711 // The user is expected to always pass `--product-name=` on the command line 712 // to populate this field. 713 Module["name"] = API.ProductName; 714 serializeObject(Module, "platform", serializePlatform(API.getTarget())); 715 return Module; 716 } 717 718 bool SymbolGraphSerializer::shouldSkip(const APIRecord &Record) const { 719 // Skip explicitly ignored symbols. 720 if (IgnoresList.shouldIgnore(Record.Name)) 721 return true; 722 723 // Skip unconditionally unavailable symbols 724 if (Record.Availabilities.isUnconditionallyUnavailable()) 725 return true; 726 727 // Filter out symbols prefixed with an underscored as they are understood to 728 // be symbols clients should not use. 729 if (Record.Name.startswith("_")) 730 return true; 731 732 return false; 733 } 734 735 template <typename RecordTy> 736 std::optional<Object> 737 SymbolGraphSerializer::serializeAPIRecord(const RecordTy &Record) const { 738 if (shouldSkip(Record)) 739 return std::nullopt; 740 741 Object Obj; 742 serializeObject(Obj, "identifier", 743 serializeIdentifier(Record, API.getLanguage())); 744 serializeObject(Obj, "kind", serializeSymbolKind(Record, API.getLanguage())); 745 serializeObject(Obj, "names", serializeNames(Record)); 746 serializeObject( 747 Obj, "location", 748 serializeSourceLocation(Record.Location, /*IncludeFileURI=*/true)); 749 serializeArray(Obj, "availability", 750 serializeAvailability(Record.Availabilities)); 751 serializeObject(Obj, "docComment", serializeDocComment(Record.Comment)); 752 serializeArray(Obj, "declarationFragments", 753 serializeDeclarationFragments(Record.Declaration)); 754 SmallVector<StringRef, 4> PathComponentsNames; 755 // If this returns true it indicates that we couldn't find a symbol in the 756 // hierarchy. 757 if (generatePathComponents(Record, API, 758 [&PathComponentsNames](const PathComponent &PC) { 759 PathComponentsNames.push_back(PC.Name); 760 })) 761 return {}; 762 763 serializeArray(Obj, "pathComponents", Array(PathComponentsNames)); 764 765 serializeFunctionSignatureMixin(Obj, Record); 766 serializeAccessMixin(Obj, Record); 767 serializeTemplateMixin(Obj, Record); 768 769 return Obj; 770 } 771 772 template <typename MemberTy> 773 void SymbolGraphSerializer::serializeMembers( 774 const APIRecord &Record, 775 const SmallVector<std::unique_ptr<MemberTy>> &Members) { 776 // Members should not be serialized if we aren't recursing. 777 if (!ShouldRecurse) 778 return; 779 for (const auto &Member : Members) { 780 auto MemberRecord = serializeAPIRecord(*Member); 781 if (!MemberRecord) 782 continue; 783 784 Symbols.emplace_back(std::move(*MemberRecord)); 785 serializeRelationship(RelationshipKind::MemberOf, *Member, Record); 786 } 787 } 788 789 StringRef SymbolGraphSerializer::getRelationshipString(RelationshipKind Kind) { 790 switch (Kind) { 791 case RelationshipKind::MemberOf: 792 return "memberOf"; 793 case RelationshipKind::InheritsFrom: 794 return "inheritsFrom"; 795 case RelationshipKind::ConformsTo: 796 return "conformsTo"; 797 case RelationshipKind::ExtensionTo: 798 return "extensionTo"; 799 } 800 llvm_unreachable("Unhandled relationship kind"); 801 } 802 803 StringRef SymbolGraphSerializer::getConstraintString(ConstraintKind Kind) { 804 switch (Kind) { 805 case ConstraintKind::Conformance: 806 return "conformance"; 807 case ConstraintKind::ConditionalConformance: 808 return "conditionalConformance"; 809 } 810 llvm_unreachable("Unhandled constraint kind"); 811 } 812 813 void SymbolGraphSerializer::serializeRelationship(RelationshipKind Kind, 814 SymbolReference Source, 815 SymbolReference Target) { 816 Object Relationship; 817 Relationship["source"] = Source.USR; 818 Relationship["target"] = Target.USR; 819 Relationship["targetFallback"] = Target.Name; 820 Relationship["kind"] = getRelationshipString(Kind); 821 822 Relationships.emplace_back(std::move(Relationship)); 823 } 824 825 void SymbolGraphSerializer::visitGlobalFunctionRecord( 826 const GlobalFunctionRecord &Record) { 827 auto Obj = serializeAPIRecord(Record); 828 if (!Obj) 829 return; 830 831 Symbols.emplace_back(std::move(*Obj)); 832 } 833 834 void SymbolGraphSerializer::visitGlobalVariableRecord( 835 const GlobalVariableRecord &Record) { 836 auto Obj = serializeAPIRecord(Record); 837 if (!Obj) 838 return; 839 840 Symbols.emplace_back(std::move(*Obj)); 841 } 842 843 void SymbolGraphSerializer::visitEnumRecord(const EnumRecord &Record) { 844 auto Enum = serializeAPIRecord(Record); 845 if (!Enum) 846 return; 847 848 Symbols.emplace_back(std::move(*Enum)); 849 serializeMembers(Record, Record.Constants); 850 } 851 852 void SymbolGraphSerializer::visitStructRecord(const StructRecord &Record) { 853 auto Struct = serializeAPIRecord(Record); 854 if (!Struct) 855 return; 856 857 Symbols.emplace_back(std::move(*Struct)); 858 serializeMembers(Record, Record.Fields); 859 } 860 861 void SymbolGraphSerializer::visitStaticFieldRecord( 862 const StaticFieldRecord &Record) { 863 auto StaticField = serializeAPIRecord(Record); 864 if (!StaticField) 865 return; 866 Symbols.emplace_back(std::move(*StaticField)); 867 serializeRelationship(RelationshipKind::MemberOf, Record, Record.Context); 868 } 869 870 void SymbolGraphSerializer::visitCXXClassRecord(const CXXClassRecord &Record) { 871 auto Class = serializeAPIRecord(Record); 872 if (!Class) 873 return; 874 875 Symbols.emplace_back(std::move(*Class)); 876 serializeMembers(Record, Record.Fields); 877 serializeMembers(Record, Record.Methods); 878 879 for (const auto Base : Record.Bases) 880 serializeRelationship(RelationshipKind::InheritsFrom, Record, Base); 881 } 882 883 void SymbolGraphSerializer::visitClassTemplateRecord( 884 const ClassTemplateRecord &Record) { 885 auto Class = serializeAPIRecord(Record); 886 if (!Class) 887 return; 888 889 Symbols.emplace_back(std::move(*Class)); 890 serializeMembers(Record, Record.Fields); 891 serializeMembers(Record, Record.Methods); 892 893 for (const auto Base : Record.Bases) 894 serializeRelationship(RelationshipKind::InheritsFrom, Record, Base); 895 } 896 897 void SymbolGraphSerializer::visitClassTemplateSpecializationRecord( 898 const ClassTemplateSpecializationRecord &Record) { 899 auto Class = serializeAPIRecord(Record); 900 if (!Class) 901 return; 902 903 Symbols.emplace_back(std::move(*Class)); 904 serializeMembers(Record, Record.Fields); 905 serializeMembers(Record, Record.Methods); 906 907 for (const auto Base : Record.Bases) 908 serializeRelationship(RelationshipKind::InheritsFrom, Record, Base); 909 } 910 911 void SymbolGraphSerializer::visitClassTemplatePartialSpecializationRecord( 912 const ClassTemplatePartialSpecializationRecord &Record) { 913 auto Class = serializeAPIRecord(Record); 914 if (!Class) 915 return; 916 917 Symbols.emplace_back(std::move(*Class)); 918 serializeMembers(Record, Record.Fields); 919 serializeMembers(Record, Record.Methods); 920 921 for (const auto Base : Record.Bases) 922 serializeRelationship(RelationshipKind::InheritsFrom, Record, Base); 923 } 924 925 void SymbolGraphSerializer::visitConceptRecord(const ConceptRecord &Record) { 926 auto Concept = serializeAPIRecord(Record); 927 if (!Concept) 928 return; 929 930 Symbols.emplace_back(std::move(*Concept)); 931 } 932 933 void SymbolGraphSerializer::visitGlobalVariableTemplateRecord( 934 const GlobalVariableTemplateRecord &Record) { 935 auto GlobalVariableTemplate = serializeAPIRecord(Record); 936 if (!GlobalVariableTemplate) 937 return; 938 Symbols.emplace_back(std::move(*GlobalVariableTemplate)); 939 } 940 941 void SymbolGraphSerializer::visitGlobalVariableTemplateSpecializationRecord( 942 const GlobalVariableTemplateSpecializationRecord &Record) { 943 auto GlobalVariableTemplateSpecialization = serializeAPIRecord(Record); 944 if (!GlobalVariableTemplateSpecialization) 945 return; 946 Symbols.emplace_back(std::move(*GlobalVariableTemplateSpecialization)); 947 } 948 949 void SymbolGraphSerializer:: 950 visitGlobalVariableTemplatePartialSpecializationRecord( 951 const GlobalVariableTemplatePartialSpecializationRecord &Record) { 952 auto GlobalVariableTemplatePartialSpecialization = serializeAPIRecord(Record); 953 if (!GlobalVariableTemplatePartialSpecialization) 954 return; 955 Symbols.emplace_back(std::move(*GlobalVariableTemplatePartialSpecialization)); 956 } 957 958 void SymbolGraphSerializer::visitGlobalFunctionTemplateRecord( 959 const GlobalFunctionTemplateRecord &Record) { 960 auto GlobalFunctionTemplate = serializeAPIRecord(Record); 961 if (!GlobalFunctionTemplate) 962 return; 963 Symbols.emplace_back(std::move(*GlobalFunctionTemplate)); 964 } 965 966 void SymbolGraphSerializer::visitGlobalFunctionTemplateSpecializationRecord( 967 const GlobalFunctionTemplateSpecializationRecord &Record) { 968 auto GlobalFunctionTemplateSpecialization = serializeAPIRecord(Record); 969 if (!GlobalFunctionTemplateSpecialization) 970 return; 971 Symbols.emplace_back(std::move(*GlobalFunctionTemplateSpecialization)); 972 } 973 974 void SymbolGraphSerializer::visitObjCContainerRecord( 975 const ObjCContainerRecord &Record) { 976 auto ObjCContainer = serializeAPIRecord(Record); 977 if (!ObjCContainer) 978 return; 979 980 Symbols.emplace_back(std::move(*ObjCContainer)); 981 982 serializeMembers(Record, Record.Ivars); 983 serializeMembers(Record, Record.Methods); 984 serializeMembers(Record, Record.Properties); 985 986 for (const auto &Protocol : Record.Protocols) 987 // Record that Record conforms to Protocol. 988 serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol); 989 990 if (auto *ObjCInterface = dyn_cast<ObjCInterfaceRecord>(&Record)) { 991 if (!ObjCInterface->SuperClass.empty()) 992 // If Record is an Objective-C interface record and it has a super class, 993 // record that Record is inherited from SuperClass. 994 serializeRelationship(RelationshipKind::InheritsFrom, Record, 995 ObjCInterface->SuperClass); 996 997 // Members of categories extending an interface are serialized as members of 998 // the interface. 999 for (const auto *Category : ObjCInterface->Categories) { 1000 serializeMembers(Record, Category->Ivars); 1001 serializeMembers(Record, Category->Methods); 1002 serializeMembers(Record, Category->Properties); 1003 1004 // Surface the protocols of the category to the interface. 1005 for (const auto &Protocol : Category->Protocols) 1006 serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol); 1007 } 1008 } 1009 } 1010 1011 void SymbolGraphSerializer::visitObjCCategoryRecord( 1012 const ObjCCategoryRecord &Record) { 1013 if (!Record.IsFromExternalModule) 1014 return; 1015 1016 // Check if the current Category' parent has been visited before, if so skip. 1017 if (!visitedCategories.contains(Record.Interface.Name)) { 1018 visitedCategories.insert(Record.Interface.Name); 1019 Object Obj; 1020 serializeObject(Obj, "identifier", 1021 serializeIdentifier(Record, API.getLanguage())); 1022 serializeObject(Obj, "kind", 1023 serializeSymbolKind(APIRecord::RK_ObjCCategoryModule, 1024 API.getLanguage())); 1025 Obj["accessLevel"] = "public"; 1026 Symbols.emplace_back(std::move(Obj)); 1027 } 1028 1029 Object Relationship; 1030 Relationship["source"] = Record.USR; 1031 Relationship["target"] = Record.Interface.USR; 1032 Relationship["targetFallback"] = Record.Interface.Name; 1033 Relationship["kind"] = getRelationshipString(RelationshipKind::ExtensionTo); 1034 Relationships.emplace_back(std::move(Relationship)); 1035 1036 auto ObjCCategory = serializeAPIRecord(Record); 1037 1038 if (!ObjCCategory) 1039 return; 1040 1041 Symbols.emplace_back(std::move(*ObjCCategory)); 1042 serializeMembers(Record, Record.Methods); 1043 serializeMembers(Record, Record.Properties); 1044 1045 // Surface the protocols of the category to the interface. 1046 for (const auto &Protocol : Record.Protocols) 1047 serializeRelationship(RelationshipKind::ConformsTo, Record, Protocol); 1048 } 1049 1050 void SymbolGraphSerializer::visitMacroDefinitionRecord( 1051 const MacroDefinitionRecord &Record) { 1052 auto Macro = serializeAPIRecord(Record); 1053 1054 if (!Macro) 1055 return; 1056 1057 Symbols.emplace_back(std::move(*Macro)); 1058 } 1059 1060 void SymbolGraphSerializer::serializeSingleRecord(const APIRecord *Record) { 1061 switch (Record->getKind()) { 1062 case APIRecord::RK_Unknown: 1063 llvm_unreachable("Records should have a known kind!"); 1064 case APIRecord::RK_GlobalFunction: 1065 visitGlobalFunctionRecord(*cast<GlobalFunctionRecord>(Record)); 1066 break; 1067 case APIRecord::RK_GlobalVariable: 1068 visitGlobalVariableRecord(*cast<GlobalVariableRecord>(Record)); 1069 break; 1070 case APIRecord::RK_Enum: 1071 visitEnumRecord(*cast<EnumRecord>(Record)); 1072 break; 1073 case APIRecord::RK_Struct: 1074 visitStructRecord(*cast<StructRecord>(Record)); 1075 break; 1076 case APIRecord::RK_StaticField: 1077 visitStaticFieldRecord(*cast<StaticFieldRecord>(Record)); 1078 break; 1079 case APIRecord::RK_CXXClass: 1080 visitCXXClassRecord(*cast<CXXClassRecord>(Record)); 1081 break; 1082 case APIRecord::RK_ObjCInterface: 1083 visitObjCContainerRecord(*cast<ObjCInterfaceRecord>(Record)); 1084 break; 1085 case APIRecord::RK_ObjCProtocol: 1086 visitObjCContainerRecord(*cast<ObjCProtocolRecord>(Record)); 1087 break; 1088 case APIRecord::RK_ObjCCategory: 1089 visitObjCCategoryRecord(*cast<ObjCCategoryRecord>(Record)); 1090 break; 1091 case APIRecord::RK_MacroDefinition: 1092 visitMacroDefinitionRecord(*cast<MacroDefinitionRecord>(Record)); 1093 break; 1094 case APIRecord::RK_Typedef: 1095 visitTypedefRecord(*cast<TypedefRecord>(Record)); 1096 break; 1097 default: 1098 if (auto Obj = serializeAPIRecord(*Record)) { 1099 Symbols.emplace_back(std::move(*Obj)); 1100 auto &ParentInformation = Record->ParentInformation; 1101 if (!ParentInformation.empty()) 1102 serializeRelationship(RelationshipKind::MemberOf, *Record, 1103 *ParentInformation.ParentRecord); 1104 } 1105 break; 1106 } 1107 } 1108 1109 void SymbolGraphSerializer::visitTypedefRecord(const TypedefRecord &Record) { 1110 // Typedefs of anonymous types have their entries unified with the underlying 1111 // type. 1112 bool ShouldDrop = Record.UnderlyingType.Name.empty(); 1113 // enums declared with `NS_OPTION` have a named enum and a named typedef, with 1114 // the same name 1115 ShouldDrop |= (Record.UnderlyingType.Name == Record.Name); 1116 if (ShouldDrop) 1117 return; 1118 1119 auto Typedef = serializeAPIRecord(Record); 1120 if (!Typedef) 1121 return; 1122 1123 (*Typedef)["type"] = Record.UnderlyingType.USR; 1124 1125 Symbols.emplace_back(std::move(*Typedef)); 1126 } 1127 1128 Object SymbolGraphSerializer::serialize() { 1129 traverseAPISet(); 1130 return serializeCurrentGraph(); 1131 } 1132 1133 Object SymbolGraphSerializer::serializeCurrentGraph() { 1134 Object Root; 1135 serializeObject(Root, "metadata", serializeMetadata()); 1136 serializeObject(Root, "module", serializeModule()); 1137 1138 Root["symbols"] = std::move(Symbols); 1139 Root["relationships"] = std::move(Relationships); 1140 1141 return Root; 1142 } 1143 1144 void SymbolGraphSerializer::serialize(raw_ostream &os) { 1145 Object root = serialize(); 1146 if (Options.Compact) 1147 os << formatv("{0}", Value(std::move(root))) << "\n"; 1148 else 1149 os << formatv("{0:2}", Value(std::move(root))) << "\n"; 1150 } 1151 1152 std::optional<Object> 1153 SymbolGraphSerializer::serializeSingleSymbolSGF(StringRef USR, 1154 const APISet &API) { 1155 APIRecord *Record = API.findRecordForUSR(USR); 1156 if (!Record) 1157 return {}; 1158 1159 Object Root; 1160 APIIgnoresList EmptyIgnores; 1161 SymbolGraphSerializer Serializer(API, EmptyIgnores, 1162 /*Options.Compact*/ {true}, 1163 /*ShouldRecurse*/ false); 1164 Serializer.serializeSingleRecord(Record); 1165 serializeObject(Root, "symbolGraph", Serializer.serializeCurrentGraph()); 1166 1167 Language Lang = API.getLanguage(); 1168 serializeArray(Root, "parentContexts", 1169 generateParentContexts(*Record, API, Lang)); 1170 1171 Array RelatedSymbols; 1172 1173 for (const auto &Fragment : Record->Declaration.getFragments()) { 1174 // If we don't have a USR there isn't much we can do. 1175 if (Fragment.PreciseIdentifier.empty()) 1176 continue; 1177 1178 APIRecord *RelatedRecord = API.findRecordForUSR(Fragment.PreciseIdentifier); 1179 1180 // If we can't find the record let's skip. 1181 if (!RelatedRecord) 1182 continue; 1183 1184 Object RelatedSymbol; 1185 RelatedSymbol["usr"] = RelatedRecord->USR; 1186 RelatedSymbol["declarationLanguage"] = getLanguageName(Lang); 1187 // TODO: once we record this properly let's serialize it right. 1188 RelatedSymbol["accessLevel"] = "public"; 1189 RelatedSymbol["filePath"] = RelatedRecord->Location.getFilename(); 1190 RelatedSymbol["moduleName"] = API.ProductName; 1191 RelatedSymbol["isSystem"] = RelatedRecord->IsFromSystemHeader; 1192 1193 serializeArray(RelatedSymbol, "parentContexts", 1194 generateParentContexts(*RelatedRecord, API, Lang)); 1195 RelatedSymbols.push_back(std::move(RelatedSymbol)); 1196 } 1197 1198 serializeArray(Root, "relatedSymbols", RelatedSymbols); 1199 return Root; 1200 } 1201