forked from apple/swift-docc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DocumentationNode.swift
716 lines (618 loc) · 34 KB
/
DocumentationNode.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import Markdown
import SymbolKit
/// A documentation node holds all the information about a documentation entity's content.
///
/// Information about relationships between documentation entities can be retrieved from the ``DocumentationContext``. The documentation context is also used
/// to look up nodes by their unique ``reference``.
public struct DocumentationNode {
/// The unique reference to the node.
public var reference: ResolvedTopicReference
/// The type of node.
public var kind: Kind
/// The programming language in which the node is relevant.
public var sourceLanguage: SourceLanguage
/// All the languages in which the node is available.
public var availableSourceLanguages: Set<SourceLanguage>
/// All of the traits that make up the different variants of this node.
public var availableVariantTraits: Set<DocumentationDataVariantsTrait> {
return Set(
availableSourceLanguages
.map(\.id)
.map(DocumentationDataVariantsTrait.init(interfaceLanguage:))
)
}
/// The names of the platforms for which the node is available.
public var platformNames: Set<String>?
/// The name of the node.
public var name: Name
/// The markup that makes up the content of this documentation node.
///
/// After the ``semantic`` object is created, consulting this property is likely incorrect because
/// it does not include information such as resolved links.
public var markup: Markup
/// The parsed documentation structure that's described by the documentation content of this documentation node.
public var semantic: Semantic!
/// The symbol that backs this node if it's backed by a symbol, otherwise `nil`.
public var symbol: SymbolGraph.Symbol?
/// The unified symbol data that backs this node, if it's backed by a symbol; otherwise `nil`.
public var unifiedSymbol: UnifiedSymbolGraph.Symbol?
/// If true, the node was created implicitly and should not generally be rendered as a page of documentation.
public var isVirtual: Bool
/// The authored options for this node.
///
/// Allows for control of settings such as automatic see also generation.
public var options: Options?
/// Authored metadata for the node.
///
/// Documentation authors can add metadata to a page using the ``Metadata`` directive.
public var metadata: Metadata?
/// A discrete unit of documentation
struct DocumentationChunk {
/// The source of a documentation chunk: either a documentation extension file or an in-source documentation comment.
enum Source {
/// The documentation comes from a documentation extension file.
case documentationExtension
/// The documentation comes from an in-source documentation comment.
case sourceCode(location: SymbolGraph.Symbol.Location?)
}
let source: Source
let markup: Markup
}
/// Where the documentation for the current node came from: source code or documentation extension.
///
/// Documentation can exist in source code comments and extension files. This property stores each
/// piece of documentation and indicates where the documentation originated. All of the chunks are
/// combined to form the complete documentation for this node and stored in the ``DocumentationNode/markup``
/// property.
var docChunks: [DocumentationChunk]
/// Linkable in-content sections.
var anchorSections = [AnchorSection]()
/// Collects any sections in the node content that could be
/// linked to from other nodes' content.
private mutating func updateAnchorSections() {
// Scrub article discussion headings.
let discussionSections: [DiscussionSection]
if let discussion = (semantic as? Article)?.discussion {
discussionSections = [discussion]
} else if let discussionVariants = (semantic as? Symbol)?.discussionVariants {
discussionSections = discussionVariants.allValues.map(\.variant)
} else {
return
}
for discussion in discussionSections {
for child in discussion.content {
// For any non-H1 Heading sections found in the topic's discussion
// create an `AnchorSection` and add it to `anchorSections`
// so we can index all anchors found in the bundle for link resolution.
if let heading = child as? Heading, heading.level > 1 {
anchorSections.append(
AnchorSection(reference: reference.withFragment(heading.plainText), title: heading.plainText)
)
}
}
}
}
/// Initializes a documentation node with all its initial values.
///
/// - Parameters:
/// - reference: The unique reference to the node.
/// - kind: The type of node.
/// - sourceLanguage: The programming language in which the node is relevant.
/// - availableSourceLanguages: All the languages in which the node is available.
/// - name: The name of the node.
/// - markup: The markup that makes up the content for the node.
/// - semantic: The parsed documentation structure that's described by the documentation content.
/// - platformNames: The names of the platforms for which the node is available.
public init(reference: ResolvedTopicReference, kind: Kind, sourceLanguage: SourceLanguage, availableSourceLanguages: Set<SourceLanguage>? = nil, name: Name, markup: Markup, semantic: Semantic?, platformNames: Set<String>? = nil, isVirtual: Bool = false) {
self.reference = reference
self.kind = kind
self.sourceLanguage = sourceLanguage
self.availableSourceLanguages = availableSourceLanguages ?? Set([sourceLanguage])
self.name = name
self.markup = markup
self.semantic = semantic
self.symbol = nil
self.platformNames = platformNames
self.docChunks = [DocumentationChunk(source: .sourceCode(location: nil), markup: markup)]
self.isVirtual = isVirtual
if let article = semantic as? Article {
self.options = article.options[.local]
self.metadata = article.metadata
} else {
self.options = nil
self.metadata = nil
}
updateAnchorSections()
}
/// Initializes a documentation node to represent a symbol from a symbol graph.
///
/// - Parameters:
/// - reference: The unique reference to the node.
/// - symbol: The symbol to create a documentation node for.
/// - platformNames: The names of the platforms for which the node is available.
/// - moduleName: The name of the module that the symbol belongs to.
/// - article: The documentation extension content for this symbol.
/// - problems: A mutable collection of problems to update with any problem encountered while initializing the node.
/// > Warning: Using this initializer will not report any diagnostics raised during the initialization of `DocumentationNode`.
@available(*, deprecated, message: "Use init(reference:symbol:platformName:moduleName:article:engine:) instead")
public init(reference: ResolvedTopicReference, symbol: SymbolGraph.Symbol, platformName: String?, moduleName: String, article: Article?, problems: inout [Problem]) {
let assumedModuleReference = ResolvedTopicReference(bundleIdentifier: reference.bundleIdentifier, path: reference.pathComponents.prefix(2).joined(separator: "/"), sourceLanguage: reference.sourceLanguage)
self.init(reference: reference, symbol: symbol, platformName: platformName, moduleReference: assumedModuleReference, article: article, engine: DiagnosticEngine())
}
/// Initializes a node without parsing its documentation source.
///
/// - Parameters:
/// - reference: The unique reference to the node.
/// - symbol: The symbol to create a documentation node for.
/// - platformName: The name of the platforms for which the node is available.
/// - moduleName: The name of the module that the symbol belongs to.
init(reference: ResolvedTopicReference, unifiedSymbol: UnifiedSymbolGraph.Symbol, moduleData: SymbolGraph.Module, moduleReference: ResolvedTopicReference) {
self.reference = reference
guard let defaultSymbol = unifiedSymbol.defaultSymbol else {
fatalError("Unexpectedly failed to get 'defaultSymbol' from 'unifiedSymbol'.")
}
self.kind = Self.kind(for: defaultSymbol)
self.sourceLanguage = reference.sourceLanguage
self.name = .symbol(declaration: .init([.plain(defaultSymbol.names.title)]))
self.symbol = defaultSymbol
self.unifiedSymbol = unifiedSymbol
self.isVirtual = moduleData.isVirtual
self.markup = Document()
self.docChunks = []
self.tags = (returns: [], throws: [], parameters: [])
let platformName = moduleData.platform.name
let symbolAvailabilityVariants = DocumentationDataVariants(
symbolData: unifiedSymbol.mixins,
platformName: platformName
) { mixins in
mixins[SymbolGraph.Symbol.Availability.mixinKey] as? SymbolGraph.Symbol.Availability
}
let endpointVariants = DocumentationDataVariants(
symbolData: unifiedSymbol.mixins,
platformName: platformName
) { mixins -> HTTPEndpointSection? in
if let endpoint = mixins[SymbolGraph.Symbol.HTTP.Endpoint.mixinKey] as? SymbolGraph.Symbol.HTTP.Endpoint {
return HTTPEndpointSection(endpoint: endpoint)
}
return nil
}
var languages = Set([reference.sourceLanguage])
var operatingSystemName = platformName.map({ Set([$0]) }) ?? []
for (_, symbolAvailability) in symbolAvailabilityVariants.allValues {
let (sourceLanguages, otherDomains) = symbolAvailability.availability
.compactMap({ $0.domain?.rawValue })
.categorize(where: SourceLanguage.init(knownLanguageName:))
languages.formUnion(sourceLanguages)
operatingSystemName.formUnion(otherDomains)
}
self.platformNames = Set(
operatingSystemName.map { name in
PlatformName(operatingSystemName: name).rawValue
}
)
self.availableSourceLanguages = reference.sourceLanguages
let extendedModule: String? = unifiedSymbol.mixins
.first(where: { $0.0.platform == platformName })?.value
.getValueIfPresent(for: SymbolGraph.Symbol.Swift.Extension.self)?.extendedModule
let semanticSymbol = Symbol(
kindVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.kind,
platformName: platformName
),
titleVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.names,
platformName: platformName,
keyPath: \.title
),
subHeadingVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.names,
platformName: platformName,
keyPath: \.subHeading
),
navigatorVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.names,
platformName: platformName,
keyPath: \.navigator
),
roleHeadingVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.kind,
platformName: platformName,
keyPath: \.displayName
),
platformNameVariants: DocumentationDataVariants(
defaultVariantValue: platformName.map(PlatformName.init(operatingSystemName:))
),
moduleReference: moduleReference,
extendedModule: extendedModule,
externalIDVariants: DocumentationDataVariants(defaultVariantValue: unifiedSymbol.uniqueIdentifier),
accessLevelVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.accessLevel,
platformName: platformName,
keyPath: \.rawValue
),
availabilityVariants: symbolAvailabilityVariants,
deprecatedSummaryVariants: .empty,
mixinsVariants: DocumentationDataVariants(
symbolData: unifiedSymbol.mixins,
platformName: platformName
),
relationshipsVariants: DocumentationDataVariants(
defaultVariantValue: RelationshipsSection()
),
abstractSectionVariants: .empty,
discussionVariants: .empty,
topicsVariants: .empty,
seeAlsoVariants: .empty,
returnsSectionVariants: .empty,
parametersSectionVariants: .empty,
dictionaryKeysSectionVariants: .empty,
httpEndpointSectionVariants: endpointVariants,
httpBodySectionVariants: .empty,
httpParametersSectionVariants: .empty,
httpResponsesSectionVariants: .empty,
redirectsVariants: .empty,
crossImportOverlayModule: moduleData.bystanders.map({ (moduleData.name, $0) })
)
try! semanticSymbol.mergeDeclarations(unifiedSymbol: unifiedSymbol)
self.semantic = semanticSymbol
}
/// Given an optional documentation extension, initializes the node's documentation content.
///
/// - Parameters:
/// - article: An optional documentation extension article.
/// - engine: A diagnostics engine.
mutating func initializeSymbolContent(documentationExtension: Article?, engine: DiagnosticEngine) {
precondition(unifiedSymbol != nil && symbol != nil, "You can only call initializeSymbolContent() on a symbol node.")
let (markup, docChunks) = Self.contentFrom(
documentedSymbol: unifiedSymbol?.documentedSymbol,
documentationExtension: documentationExtension,
engine: engine
)
self.markup = markup
self.docChunks = docChunks
// Parse the structured markup
let markupModel = DocumentationMarkup(markup: markup)
let symbolAvailability = symbol!.mixins.getValueIfPresent(for: SymbolGraph.Symbol.Availability.self)
// Use a deprecation summary from the symbol docs or article content.
var deprecated: DeprecatedSection? = markupModel.deprecation.map { DeprecatedSection.init(content: $0.elements) }
// When deprecation is not authored explicitly, try using a deprecation message from annotation.
if deprecated == nil, let symbolAvailability = symbolAvailability {
let availabilityData = AvailabilityParser(symbolAvailability)
deprecated = availabilityData.deprecationMessage().map(DeprecatedSection.init(text:))
}
// Merge in the symbol documentation content
let semantic = self.semantic as! Symbol
if let displayName = documentationExtension?.metadata?.displayName {
switch displayName.style {
case .conceptual:
self.name = .conceptual(title: displayName.name)
case .symbol:
self.name = .symbol(declaration: .init([.plain(displayName.name)]))
}
semantic.titleVariants = semantic.titleVariants.map { _ in
displayName.name
}
}
// Symbol is a by-reference type so we're updating the original `semantic` property instance.
semantic.abstractSectionVariants = DocumentationDataVariants(
defaultVariantValue: markupModel.abstractSection
)
semantic.discussionVariants = DocumentationDataVariants(
defaultVariantValue: markupModel.discussionSection
)
semantic.topicsVariants = DocumentationDataVariants(
defaultVariantValue: markupModel.topicsSection
)
semantic.seeAlsoVariants = DocumentationDataVariants(
defaultVariantValue: markupModel.seeAlsoSection
)
semantic.deprecatedSummaryVariants = DocumentationDataVariants(
defaultVariantValue: deprecated
)
semantic.redirectsVariants = DocumentationDataVariants(
defaultVariantValue: documentationExtension?.redirects
)
if let returns = markupModel.discussionTags?.returns, !returns.isEmpty {
semantic.returnsSectionVariants = DocumentationDataVariants(
defaultVariantValue: ReturnsSection(content: returns[0].contents)
)
}
if let parameters = markupModel.discussionTags?.parameters, !parameters.isEmpty {
semantic.parametersSectionVariants = DocumentationDataVariants(
defaultVariantValue: ParametersSection(parameters: parameters)
)
}
if let keys = markupModel.discussionTags?.dictionaryKeys, !keys.isEmpty {
// Record the keys extracted from the markdown
semantic.dictionaryKeysSectionVariants[.fallback] = DictionaryKeysSection(dictionaryKeys:keys)
}
if let parameters = markupModel.discussionTags?.httpParameters, !parameters.isEmpty {
// Record the parameters extracted from the markdown
semantic.httpParametersSectionVariants[.fallback] = HTTPParametersSection(parameters: parameters)
}
if let body = markupModel.discussionTags?.httpBody {
// Record the body extracted from the markdown
semantic.httpBodySectionVariants[.fallback] = HTTPBodySection(body: body)
}
if let responses = markupModel.discussionTags?.httpResponses, !responses.isEmpty {
// Record the responses extracted from the markdown
semantic.httpResponsesSectionVariants[.fallback] = HTTPResponsesSection(responses: responses)
}
options = documentationExtension?.options[.local]
self.metadata = documentationExtension?.metadata
updateAnchorSections()
}
/// Given a symbol and an optional article returns documentation content.
/// - Parameters:
/// - symbol: A symbol graph symbol.
/// - article: An optional article with documentation content.
/// - engine: A diagnostics engine to use for problems found while parsing content.
/// - Returns: The prepared node documentation content.
static func contentFrom(
documentedSymbol: SymbolGraph.Symbol?,
documentationExtension: Article?,
engine: DiagnosticEngine
) -> (markup: Markup, docChunks: [DocumentationChunk]) {
let markup: Markup
var documentationChunks: [DocumentationChunk]
// We should ignore the symbol's documentation comment if it wasn't provided
// or if the documentation extension was set to override.
let ignoreDocComment = documentedSymbol?.docComment == nil
|| documentationExtension?.metadata?.documentationOptions?.behavior == .override
if let documentationExtensionMarkup = documentationExtension?.markup, ignoreDocComment {
markup = documentationExtensionMarkup
documentationChunks = [
DocumentationChunk(source: .documentationExtension, markup: documentationExtensionMarkup)
]
} else if let symbol = documentedSymbol, let docComment = symbol.docComment {
let docCommentString = docComment.lines.map { $0.text }.joined(separator: "\n")
let documentOptions: ParseOptions = [.parseBlockDirectives, .parseSymbolLinks, .parseMinimalDoxygen]
let docCommentMarkup = Document(parsing: docCommentString, options: documentOptions)
let docCommentDirectives = docCommentMarkup.children.compactMap({ $0 as? BlockDirective })
if !docCommentDirectives.isEmpty {
let location = symbol.mixins.getValueIfPresent(
for: SymbolGraph.Symbol.Location.self
)?.url()
for directive in docCommentDirectives {
let range = docCommentMarkup.child(at: directive.indexInParent)?.range
// Only throw warnings for known directive names.
//
// This is important so that we avoid throwing warnings when building
// Objective-C/C documentation that includes doxygen commands.
guard BlockDirective.allKnownDirectiveNames.contains(directive.name) else {
continue
}
// Renderable directives are processed like any other piece of structured markdown (tables, lists, etc.)
// and so are inherently supported in doc comments.
guard DirectiveIndex.shared.renderableDirectives[directive.name] == nil else {
continue
}
let diagnostic = Diagnostic(
source: location,
severity: .warning,
range: range,
identifier: "org.swift.docc.UnsupportedDocCommentDirective",
summary: "The \(directive.name.singleQuoted) directive is not supported in symbol source documentation",
explanation: "Found \(directive.name.singleQuoted) in \(symbol.absolutePath.singleQuoted)"
)
var problem = Problem(diagnostic: diagnostic, possibleSolutions: [])
if let offset = docComment.lines.first?.range {
problem.offsetWithRange(offset)
}
engine.emit(problem)
}
}
documentationChunks = [
DocumentationChunk(
source: .sourceCode(location: symbol.mixins.getValueIfPresent(for: SymbolGraph.Symbol.Location.self)),
markup: docCommentMarkup
)
]
if let documentationExtensionMarkup = documentationExtension?.markup {
// An `Article` always starts with a level 1 heading (and return `nil` if that's not the first child).
// For documentation extension files, this heading is a link to the symbol—which isn't part of the content—so it is ignored.
let documentationExtensionChildren = documentationExtensionMarkup.children.dropFirst().compactMap { $0 as? BlockMarkup }
documentationChunks.append(DocumentationChunk(source: .documentationExtension, markup: documentationExtensionMarkup))
markup = Document(Array(docCommentMarkup.blockChildren) + documentationExtensionChildren)
} else {
markup = docCommentMarkup
}
} else {
markup = Document()
documentationChunks = [DocumentationChunk(source: .sourceCode(location: nil), markup: markup)]
}
return (markup: markup, docChunks: documentationChunks)
}
/// Returns a documentation node kind for the given symbol kind.
/// - Parameter symbol: A symbol graph symbol.
/// - Returns: A documentation node kind.
static func kind(for symbol: SymbolGraph.Symbol) -> Kind {
return Self.kind(forKind: symbol.kind.identifier)
}
static func kind(forKind symbolKind: SymbolGraph.Symbol.KindIdentifier) -> Kind {
switch symbolKind {
case .`associatedtype`: return .associatedType
case .`class`: return .class
case .`deinit`: return .deinitializer
case .dictionary: return .dictionary
case .dictionaryKey: return .dictionaryKey
case .`enum`: return .enumeration
case .`case`: return .enumerationCase
case .`func`: return .function
case .httpRequest: return .httpRequest
case .httpParameter: return .httpParameter
case .httpBody: return .httpBody
case .httpResponse: return .httpResponse
case .`operator`: return .operator
case .`init`: return .initializer
case .ivar: return .instanceVariable
case .macro: return .macro
case .`method`: return .instanceMethod
case .`property`: return .instanceProperty
case .`protocol`: return .protocol
case .snippet: return .snippet
case .`struct`: return .structure
case .`subscript`: return .instanceSubscript
case .`typeMethod`: return .typeMethod
case .`typeProperty`: return .typeProperty
case .`typeSubscript`: return .typeSubscript
case .`typealias`: return .typeAlias
case .`var`: return .globalVariable
case .module: return .module
case .extendedModule: return .extendedModule
case .extendedStructure: return .extendedStructure
case .extendedClass: return .extendedClass
case .extendedEnumeration: return .extendedEnumeration
case .extendedProtocol: return .extendedProtocol
case .unknownExtendedType: return .unknownExtendedType
default: return .unknown
}
}
@available(*, deprecated, message: "Use init(reference:symbol:platformName:moduleReference:article:engine:bystanderModules:) instead")
public init(reference: ResolvedTopicReference, symbol: SymbolGraph.Symbol, platformName: String?, moduleName: String, article: Article?, engine: DiagnosticEngine) {
let assumedModuleReference = ResolvedTopicReference(bundleIdentifier: reference.bundleIdentifier, path: reference.pathComponents.prefix(2).joined(separator: "/"), sourceLanguage: reference.sourceLanguage)
self.init(reference: reference, symbol: symbol, platformName: platformName, moduleReference: assumedModuleReference, article: article, engine: engine)
}
/// Initializes a documentation node to represent a symbol from a symbol graph.
///
/// - Parameters:
/// - reference: The unique reference to the node.
/// - symbol: The symbol to create a documentation node for.
/// - platformNames: The names of the platforms for which the node is available.
/// - moduleName: The name of the module that the symbol belongs to.
/// - article: The documentation extension content for this symbol.
/// - engine:The engine that collects any problems encountered during initialization.
/// - bystanderModules: An optional list of cross-import module names.
public init(reference: ResolvedTopicReference, symbol: SymbolGraph.Symbol, platformName: String?, moduleReference: ResolvedTopicReference, article: Article?, engine: DiagnosticEngine) {
self.reference = reference
guard reference.sourceLanguage == .swift else {
fatalError("""
Only Swift symbols are currently supported. \
This initializer is only called with symbols from the symbol graph, which currently only supports Swift.
"""
)
}
self.kind = Self.kind(for: symbol)
self.sourceLanguage = reference.sourceLanguage
if let displayName = article?.metadata?.displayName {
switch displayName.style {
case .conceptual:
self.name = .conceptual(title: displayName.name)
case .symbol:
self.name = .symbol(declaration: .init([.plain(displayName.name)]))
}
} else {
self.name = .symbol(declaration: .init([.plain(symbol.names.title)]))
}
self.symbol = symbol
// Prefer content sections coming from an article (documentation extension file)
var deprecated: DeprecatedSection?
let (markup, docChunks) = Self.contentFrom(documentedSymbol: symbol, documentationExtension: article, engine: engine)
self.markup = markup
self.docChunks = docChunks
let symbolAvailability = symbol.mixins[SymbolGraph.Symbol.Availability.mixinKey] as? SymbolGraph.Symbol.Availability
var languages = Set([reference.sourceLanguage])
var operatingSystemName = platformName.map({ Set([$0]) }) ?? []
let availabilityDomains = symbolAvailability?.availability.compactMap({ $0.domain?.rawValue })
if let (sourceLanguages, otherDomains) = availabilityDomains?.categorize(where: SourceLanguage.init(knownLanguageName:)) {
languages.formUnion(sourceLanguages)
operatingSystemName.formUnion(otherDomains)
}
platformNames = Set(operatingSystemName.map { PlatformName(operatingSystemName: $0).rawValue })
availableSourceLanguages = languages
if let article = article {
// Prefer authored deprecation summary over docs.
deprecated = article.deprecationSummary.map { DeprecatedSection.init(content: $0.elements) }
}
if deprecated == nil, let symbolAvailability = symbolAvailability {
let availabilityData = AvailabilityParser(symbolAvailability)
deprecated = availabilityData.deprecationMessage().map(DeprecatedSection.init(text:))
}
// Parse the structured markup
let markupModel = DocumentationMarkup(markup: markup)
self.semantic = Symbol(
kindVariants: .init(swiftVariant: symbol.kind),
titleVariants: .init(swiftVariant: symbol.names.title),
subHeadingVariants: .init(swiftVariant: symbol.names.subHeading),
navigatorVariants: .init(swiftVariant: symbol.names.navigator),
roleHeadingVariants: .init(swiftVariant: symbol.kind.displayName),
platformNameVariants: .init(swiftVariant: platformName.map(PlatformName.init(operatingSystemName:))),
moduleReference: moduleReference,
externalIDVariants: .init(swiftVariant: symbol.identifier.precise),
accessLevelVariants: .init(swiftVariant: symbol.accessLevel.rawValue),
availabilityVariants: .init(swiftVariant: symbolAvailability),
deprecatedSummaryVariants: .init(swiftVariant: deprecated),
mixinsVariants: .init(swiftVariant: symbol.mixins),
relationshipsVariants: .init(swiftVariant: RelationshipsSection()),
abstractSectionVariants: .init(swiftVariant: markupModel.abstractSection),
discussionVariants: .init(swiftVariant: markupModel.discussionSection),
topicsVariants: .init(swiftVariant: markupModel.topicsSection),
seeAlsoVariants: .init(swiftVariant: markupModel.seeAlsoSection),
returnsSectionVariants: .init(swiftVariant: markupModel.discussionTags.flatMap({ $0.returns.isEmpty ? nil : ReturnsSection(content: $0.returns[0].contents) })),
parametersSectionVariants: .init(swiftVariant: markupModel.discussionTags.flatMap({ $0.parameters.isEmpty ? nil : ParametersSection(parameters: $0.parameters) })),
dictionaryKeysSectionVariants: .init(swiftVariant: markupModel.discussionTags.flatMap({ $0.dictionaryKeys.isEmpty ? nil : DictionaryKeysSection(dictionaryKeys: $0.dictionaryKeys) })),
httpEndpointSectionVariants: .empty,
httpBodySectionVariants: .empty,
httpParametersSectionVariants: .empty,
httpResponsesSectionVariants: .empty,
redirectsVariants: .init(swiftVariant: article?.redirects)
)
self.isVirtual = symbol.isVirtual
updateAnchorSections()
}
public enum Error: DescribedError {
case missingMarkup
public var errorDescription: String {
switch self {
case .missingMarkup: return "Markup not found."
}
}
}
/// Initializes a documentation node to represent an article.
///
/// - Parameters:
/// - reference: The unique reference to the node.
/// - article: The documentation extension content for this symbol.
/// - problems: A mutable collection of problems to update with any problem encountered while initializing the node.
init(reference: ResolvedTopicReference, article: Article) throws {
guard let articleMarkup = article.markup else {
throw Error.missingMarkup
}
self.reference = reference
self.kind = .article
self.semantic = article
self.sourceLanguage = reference.sourceLanguage
self.name = .conceptual(title: article.title?.title ?? "")
self.availableSourceLanguages = [reference.sourceLanguage]
self.docChunks = [DocumentationChunk(source: .documentationExtension, markup: articleMarkup)]
self.markup = articleMarkup
self.isVirtual = false
self.options = article.options[.local]
self.metadata = article.metadata
updateAnchorSections()
}
/// The collection of parsed callout tags for return values, thrown errors, and parameters.
///
/// When the symbol's markup contains callout tags like this:
/// ```
/// - Parameter name: Description of the name parameter.
/// - Throws: Description of potential errors.
/// - Returns: Description of the return value.
/// ```
/// That markup is parsed into collections of ``Parameter`` values, ``Throw`` values, and ``Return`` values.
///
/// The markup for the callout tags is excluded from the markup for the ``DiscussionSection``.
public typealias Tags = (returns: [Return], throws: [Throw], parameters: [Parameter])
/// Callout tags found in the symbol's markup.
///
/// These tags contain information about the symbol's return values, potential errors, and parameters.
public var tags: Tags = (returns: [], throws: [], parameters: [])
}