-
Notifications
You must be signed in to change notification settings - Fork 128
/
DocumentationContext.swift
3251 lines (2835 loc) · 173 KB
/
DocumentationContext.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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-2024 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 type that provides information about documentation bundles and their content.
@available(*, deprecated, message: "Pass the context its inputs at initialization instead. This deprecated API will be removed after 6.2 is released")
public protocol DocumentationContextDataProvider {
/// An object to notify when bundles are added or removed.
var delegate: DocumentationContextDataProviderDelegate? { get set }
/// The documentation bundles that this data provider provides.
var bundles: [BundleIdentifier: DocumentationBundle] { get }
/// Returns the data for the specified `url` in the provided `bundle`.
///
/// - Parameters:
/// - url: The URL of the file to read.
/// - bundle: The bundle that the file is a part of.
///
/// - Throws: When the file cannot be found in the workspace.
func contentsOfURL(_ url: URL, in bundle: DocumentationBundle) throws -> Data
}
/// An object that responds to changes in available documentation bundles for a specific provider.
@available(*, deprecated, message: "Pass the context its inputs at initialization instead. This deprecated API will be removed after 6.2 is released")
public protocol DocumentationContextDataProviderDelegate: AnyObject {
/// Called when the `dataProvider` has added a new documentation bundle to its list of `bundles`.
///
/// - Parameters:
/// - dataProvider: The provider that added this bundle.
/// - bundle: The bundle that was added.
///
/// - Note: This method is called after the `dataProvider` has been added the bundle to its `bundles` property.
func dataProvider(_ dataProvider: DocumentationContextDataProvider, didAddBundle bundle: DocumentationBundle) throws
/// Called when the `dataProvider` has removed a documentation bundle from its list of `bundles`.
///
/// - Parameters:
/// - dataProvider: The provider that removed this bundle.
/// - bundle: The bundle that was removed.
///
/// - Note: This method is called after the `dataProvider` has been removed the bundle from its `bundles` property.
func dataProvider(_ dataProvider: DocumentationContextDataProvider, didRemoveBundle bundle: DocumentationBundle) throws
}
/// Documentation bundles use a string value as a unique identifier.
///
/// This value is typically a reverse host name, for example: `com.<organization-name>.<product-name>`.
///
/// Documentation links may include the bundle identifier---as a host component of the URL---to reference content in a specific documentation bundle.
public typealias BundleIdentifier = String
/// The documentation context manages the in-memory model for the built documentation.
///
/// A ``DocumentationWorkspace`` discovers serialized documentation bundles from a variety of sources (files on disk, databases, or web services), provides them to the `DocumentationContext`,
/// and notifies the context when bundles are added or removed using the ``DocumentationContextDataProviderDelegate`` protocol.
///
/// When a documentation bundle is registered with the context, all of its content is loaded into memory and relationships between documentation entities are built. When this is done, the context can be queried
/// about documentation entities, resources, and relationships between entities.
///
/// ## Topics
///
/// ### Getting documentation resources
///
/// - ``entity(with:)``
/// - ``resource(with:trait:)``
///
/// ### Getting documentation relationships
///
/// - ``children(of:kind:)``
/// - ``parents(of:)``
///
public class DocumentationContext {
/// An error that's encountered while interacting with a ``SwiftDocC/DocumentationContext``.
public enum ContextError: DescribedError {
/// The node couldn't be found in the documentation context.
case notFound(URL)
/// The file wasn't UTF-8 encoded.
case utf8StringDecodingFailed(url: URL)
/// We allow a symbol declaration with no OS (for REST & Plist symbols)
/// but if such a declaration is found the symbol can have only one declaration.
case unexpectedEmptyPlatformName(String)
/// The bundle registration operation is cancelled externally.
case registrationDisabled
public var errorDescription: String {
switch self {
case .notFound(let url):
return "Couldn't find the requested node '\(url)' in the documentation context."
case .utf8StringDecodingFailed(let url):
return "The file at '\(url)' could not be read because it was not valid UTF-8."
case .unexpectedEmptyPlatformName(let symbolIdentifier):
return "Declaration without operating system name for symbol \(symbolIdentifier) cannot be merged with more declarations with operating system name for the same symbol"
case .registrationDisabled:
return "The bundle registration operation is cancelled externally."
}
}
}
/// A class that resolves documentation links by orchestrating calls to other link resolver implementations.
public var linkResolver: LinkResolver
private enum _Provider {
@available(*, deprecated, message: "Use 'DataProvider' instead. This deprecated API will be removed after 6.2 is released")
case legacy(DocumentationContextDataProvider)
case new(DataProvider)
}
private var dataProvider: _Provider
/// The provider of documentation bundles for this context.
@available(*, deprecated, message: "Use 'DataProvider' instead. This deprecated API will be removed after 6.2 is released")
private var _legacyDataProvider: DocumentationContextDataProvider! {
get {
switch dataProvider {
case .legacy(let legacyDataProvider):
legacyDataProvider
case .new:
nil
}
}
set {
dataProvider = .legacy(newValue)
}
}
func contentsOfURL(_ url: URL, in bundle: DocumentationBundle) throws -> Data {
switch dataProvider {
case .legacy(let legacyDataProvider):
return try legacyDataProvider.contentsOfURL(url, in: bundle)
case .new(let dataProvider):
assert(self.bundle?.identifier == bundle.identifier, "New code shouldn't pass unknown bundle identifiers to 'DocumentationContext.bundle(identifier:)'.")
return try dataProvider.contents(of: url)
}
}
/// The documentation bundle that is registered with the context.
var bundle: DocumentationBundle?
/// A collection of configuration for this context.
public package(set) var configuration: Configuration {
get { _configuration }
@available(*, deprecated, message: "Pass a configuration at initialization. This property will become read-only after Swift 6.2 is released.")
set { _configuration = newValue }
}
// Having a deprecated setter above requires a computed property.
private var _configuration: Configuration
/// The graph of all the documentation content and their relationships to each other.
///
/// > Important: The topic graph has no awareness of source language specific edges.
var topicGraph = TopicGraph()
/// User-provided global options for this documentation conversion.
var options: Options?
/// The set of all manually curated references if `shouldStoreManuallyCuratedReferences` was true at the time of processing and has remained `true` since.. Nil if curation has not been processed yet.
public private(set) var manuallyCuratedReferences: Set<ResolvedTopicReference>?
@available(*, deprecated, renamed: "tutorialTableOfContentsReferences", message: "Use 'tutorialTableOfContentsReferences' This deprecated API will be removed after 6.2 is released")
public var rootTechnologies: [ResolvedTopicReference] {
tutorialTableOfContentsReferences
}
/// The tutorial table-of-contents nodes in the topic graph.
public var tutorialTableOfContentsReferences: [ResolvedTopicReference] {
return topicGraph.nodes.values.compactMap { node in
guard node.kind == .tutorialTableOfContents && parents(of: node.reference).isEmpty else {
return nil
}
return node.reference
}
}
/// The root module nodes of the Topic Graph.
///
/// This property is initialized during the registration of a documentation bundle.
public private(set) var rootModules: [ResolvedTopicReference]!
/// The topic reference of the root module, if it's the only registered module.
var soleRootModuleReference: ResolvedTopicReference? {
guard rootModules.count > 1 else {
return rootModules.first
}
// There are multiple "root modules" but some may be "virtual".
// Removing those may leave only one root module left.
let nonVirtualModules = rootModules.filter {
topicGraph.nodes[$0]?.isVirtual ?? false
}
return nonVirtualModules.count == 1 ? nonVirtualModules.first : nil
}
typealias LocalCache = ContentCache<DocumentationNode>
typealias ExternalCache = ContentCache<LinkResolver.ExternalEntity>
/// Map of document URLs to topic references.
var documentLocationMap = BidirectionalMap<URL, ResolvedTopicReference>()
/// A storage of already created documentation nodes for the local documentation content.
///
/// The documentation cache is built up incrementally as local content is registered with the documentation context.
///
/// First, the context adds all symbols, with both their references and symbol IDs for lookup. The ``SymbolGraphRelationshipsBuilder`` looks up documentation
/// nodes by their symbol's ID when it builds up in-memory relationships between symbols. Later, the context adds articles and other conceptual content with only their
/// references for lookup.
var documentationCache = LocalCache()
/// The asset managers for each documentation bundle, keyed by the bundle's identifier.
var assetManagers = [BundleIdentifier: DataAssetManager]()
/// A list of non-topic links that can be resolved.
var nodeAnchorSections = [ResolvedTopicReference: AnchorSection]()
/// A storage of externally resolved content.
///
/// The external cache is built up in two steps;
/// - While the context processes the local symbols, a ``GlobalExternalSymbolResolver`` or ``ExternalPathHierarchyResolver`` may add entities
/// for any external symbols that are referenced by a relationship or by a declaration token identifier in the local symbol graph files.
/// - Before the context finishes registering content, a ``ExternalDocumentationSource`` or ``ExternalPathHierarchyResolver`` may add entities
/// for any external links in the local content that the external source or external resolver could successfully resolve.
var externalCache = ExternalCache()
/// Returns the local or external reference for a known symbol ID.
func localOrExternalReference(symbolID: String) -> ResolvedTopicReference? {
documentationCache.reference(symbolID: symbolID) ?? externalCache.reference(symbolID: symbolID)
}
/// A list of all the problems that was encountered while registering and processing the documentation bundles in this context.
public var problems: [Problem] {
return diagnosticEngine.problems
}
/// The engine that collects problems encountered while registering and processing the documentation bundles in this context.
public var diagnosticEngine: DiagnosticEngine
/// All the link references that have been resolved from external sources, either successfully or not.
///
/// The unsuccessful links are tracked so that the context doesn't attempt to re-resolve the unsuccessful links during rendering which runs concurrently for each page.
var externallyResolvedLinks = [ValidatedURL: TopicReferenceResolutionResult]()
/// A temporary structure to hold a semantic value that hasn't yet had its links resolved.
///
/// These temporary values are only expected to exist while the documentation is being built. Once the documentation bundles have been fully registered and the topic graph
/// has been built, the documentation context shouldn't hold any semantic result values anymore.
struct SemanticResult<S: Semantic> {
/// The ``Semantic`` value with unresolved links.
var value: S
/// The source of the document that produces the ``value``.
var source: URL
/// The Topic Graph node for this value.
var topicGraphNode: TopicGraph.Node
}
/// Temporary storage for articles before they are curated and moved to the documentation cache.
///
/// This storage is only used while the documentation context is being built. Once the documentation bundles have been fully registered and the topic graph
/// has been built, this list of uncurated articles will be empty.
///
/// The key to lookup an article is the reference to the article itself.
var uncuratedArticles = [ResolvedTopicReference: SemanticResult<Article>]()
/// Temporary storage for documentation extension files before they are curated and moved to the documentation cache.
///
/// This storage is only used while the documentation context is being built. Once the documentation bundles have been fully registered and the topic graph
/// has been built, this list of uncurated documentation extensions will be empty.
///
/// The key to lookup a documentation extension file is the symbol reference from its title (level 1 heading).
var uncuratedDocumentationExtensions = [ResolvedTopicReference: SemanticResult<Article>]()
/// Mentions of symbols within articles.
var articleSymbolMentions = ArticleSymbolMentions()
/// Initializes a documentation context with a given `dataProvider` and registers all the documentation bundles that it provides.
///
/// - Parameters:
/// - dataProvider: The data provider to register bundles from.
/// - diagnosticEngine: The pre-configured engine that will collect problems encountered during compilation.
/// - configuration: A collection of configuration for the created context.
/// - Throws: If an error is encountered while registering a documentation bundle.
@available(*, deprecated, message: "Pass the context its inputs at initialization instead. This deprecated API will be removed after 6.2 is released")
public init(
dataProvider: DocumentationContextDataProvider,
diagnosticEngine: DiagnosticEngine = .init(),
configuration: Configuration = .init()
) throws {
self.dataProvider = .legacy(dataProvider)
self.diagnosticEngine = diagnosticEngine
self._configuration = configuration
self.linkResolver = LinkResolver(dataProvider: FileManager.default)
_legacyDataProvider.delegate = self
for bundle in dataProvider.bundles.values {
try register(bundle)
}
}
/// Initializes a documentation context with a given `bundle`.
///
/// - Parameters:
/// - bundle: The bundle to register with the context.
/// - fileManager: The file manager that the context uses to read files from the bundle.
/// - diagnosticEngine: The pre-configured engine that will collect problems encountered during compilation.
/// - configuration: A collection of configuration for the created context.
/// - Throws: If an error is encountered while registering a documentation bundle.
package init(
bundle: DocumentationBundle,
dataProvider: DataProvider,
diagnosticEngine: DiagnosticEngine = .init(),
configuration: Configuration = .init()
) throws {
self.bundle = bundle
self.dataProvider = .new(dataProvider)
self.diagnosticEngine = diagnosticEngine
self._configuration = configuration
self.linkResolver = LinkResolver(dataProvider: dataProvider)
ResolvedTopicReference.enableReferenceCaching(for: bundle.identifier)
try register(bundle)
}
/// Respond to a new `bundle` being added to the `dataProvider` by registering it.
///
/// - Parameters:
/// - dataProvider: The provider that added this bundle.
/// - bundle: The bundle that was added.
@available(*, deprecated, message: "Pass the context its inputs at initialization instead. This deprecated API will be removed after 6.2 is released")
public func dataProvider(_ dataProvider: DocumentationContextDataProvider, didAddBundle bundle: DocumentationBundle) throws {
try benchmark(wrap: Benchmark.Duration(id: "bundle-registration")) {
// Enable reference caching for this documentation bundle.
ResolvedTopicReference.enableReferenceCaching(for: bundle.identifier)
try self.register(bundle)
}
}
/// Respond to a new `bundle` being removed from the `dataProvider` by unregistering it.
///
/// - Parameters:
/// - dataProvider: The provider that removed this bundle.
/// - bundle: The bundle that was removed.
@available(*, deprecated, message: "Pass the context its inputs at initialization instead. This deprecated API will be removed after 6.2 is released")
public func dataProvider(_ dataProvider: DocumentationContextDataProvider, didRemoveBundle bundle: DocumentationBundle) throws {
linkResolver.localResolver?.unregisterBundle(identifier: bundle.identifier)
// Purge the reference cache for this bundle and disable reference caching for
// this bundle moving forward.
ResolvedTopicReference.purgePool(for: bundle.identifier)
unregister(bundle)
}
/// The documentation bundles that are currently registered with the context.
@available(*, deprecated, message: "Use 'bundle' instead. This deprecated API will be removed after 6.2 is released")
public var registeredBundles: some Collection<DocumentationBundle> {
_registeredBundles
}
/// Returns the `DocumentationBundle` with the given `identifier` if it's registered with the context, otherwise `nil`.
@available(*, deprecated, message: "Use 'bundle' instead. This deprecated API will be removed after 6.2 is released")
public func bundle(identifier: String) -> DocumentationBundle? {
_bundle(identifier: identifier)
}
// Remove these when removing `registeredBundles` and `bundle(identifier:)`.
// These exist so that internal code that need to be compatible with legacy data providers can access the bundles without deprecation warnings.
var _registeredBundles: [DocumentationBundle] {
switch dataProvider {
case .legacy(let legacyDataProvider):
Array(legacyDataProvider.bundles.values)
case .new:
bundle.map { [$0] } ?? []
}
}
func _bundle(identifier: String) -> DocumentationBundle? {
switch dataProvider {
case .legacy(let legacyDataProvider):
return legacyDataProvider.bundles[identifier]
case .new:
assert(bundle?.identifier == identifier, "New code shouldn't pass unknown bundle identifiers to 'DocumentationContext.bundle(identifier:)'.")
return bundle?.identifier == identifier ? bundle : nil
}
}
/// Perform semantic analysis on a given `document` at a given `source` location and append any problems found to `problems`.
///
/// - Parameters:
/// - document: The document to analyze.
/// - source: The location of the document.
/// - bundle: The bundle that the document belongs to.
/// - problems: A mutable collection of problems to update with any problem encountered during the semantic analysis.
/// - Returns: The result of the semantic analysis.
private func analyze(_ document: Document, at source: URL, in bundle: DocumentationBundle, engine: DiagnosticEngine) -> Semantic? {
var analyzer = SemanticAnalyzer(source: source, context: self, bundle: bundle)
let result = analyzer.visit(document)
engine.emit(analyzer.problems)
return result
}
/// Perform global analysis of compiled Markup
///
/// Global analysis differs from semantic analysis in that no transformation is expected to occur. The
/// analyses performed in this method don't transform documents, they only inspect them.
///
/// Global checks are generally not expected to be run on tutorials or tutorial articles. The structure of
/// tutorial content is very different from the expected structure of most documentation. If a checker is
/// only checking content, it can probably be run on all types of documentation without issue. If the
/// checker needs to check (or makes assumptions about) structure, it should probably be run only on
/// non-tutorial content. If tutorial-related docs need to be checked or analyzed in some way (such as
/// checking for the existence of a child directive), a semantic analyzer is probably the better solution.
/// Tutorial content is highly structured and will be parsed into models that can be analyzed in a
/// type-safe manner.
///
/// - Parameters:
/// - document: The document to analyze.
/// - source: The location of the document.
private func check(_ document: Document, at source: URL) {
var checker = CompositeChecker([
AbstractContainsFormattedTextOnly(sourceFile: source).any(),
DuplicateTopicsSections(sourceFile: source).any(),
InvalidAdditionalTitle(sourceFile: source).any(),
MissingAbstract(sourceFile: source).any(),
NonOverviewHeadingChecker(sourceFile: source).any(),
SeeAlsoInTopicsHeadingChecker(sourceFile: source).any(),
])
checker.visit(document)
diagnosticEngine.emit(checker.problems)
}
/// A cache of plain string module names, keyed by the module node reference.
private var moduleNameCache: [ResolvedTopicReference: (displayName: String, symbolName: String)] = [:]
/// Find the known plain string module name for a given module reference.
///
/// - Note: Looking up module names requires that the module names have been pre-resolved. This happens automatically at the end of bundle registration.
///
/// - Parameter moduleReference: The module reference to find the module name for.
/// - Returns: The plain string name for the referenced module.
func moduleName(forModuleReference moduleReference: ResolvedTopicReference) -> (displayName: String, symbolName: String) {
if let name = moduleNameCache[moduleReference] {
return name
}
// If no name is found it's considered a programmer error; either that the names haven't been resolved yet
// or that the passed argument isn't a reference to a known module.
if moduleNameCache.isEmpty {
fatalError("Incorrect use of API: '\(#function)' requires that bundles have finished registering.")
}
fatalError("Incorrect use of API: '\(#function)' can only be used with known module references")
}
/// Attempts to resolve the module names of all root modules.
///
/// This allows the module names to quickly be looked up using ``moduleName(forModuleReference:)``
func preResolveModuleNames() {
for reference in rootModules {
if let node = try? entity(with: reference) {
// A module node should always have a symbol.
// Remove the fallback value and force unwrap `node.symbol` on the main branch: https://github.com/swiftlang/swift-docc/issues/249
moduleNameCache[reference] = (node.name.plainText, node.symbol?.names.title ?? reference.lastPathComponent)
}
}
}
/// Attempts to resolve links external to the given bundle.
///
/// The link resolution results are collected in ``externallyResolvedLinks``.
///
/// - Parameters:
/// - references: A list of references to local nodes to visit to collect links.
/// - localBundleID: The local bundle ID, used to identify and skip absolute fully qualified local links.
private func preResolveExternalLinks(references: [ResolvedTopicReference], localBundleID: BundleIdentifier) {
preResolveExternalLinks(semanticObjects: references.compactMap({ reference -> ReferencedSemanticObject? in
guard let node = try? entity(with: reference), let semantic = node.semantic else { return nil }
return (reference: reference, semantic: semantic)
}), localBundleID: localBundleID)
}
/// A tuple of a semantic object and its reference in the topic graph.
private typealias ReferencedSemanticObject = (reference: ResolvedTopicReference, semantic: Semantic)
/// Converts a semantic result to a referenced semantic object by removing the generic constraint.
private func referencedSemanticObject(from: SemanticResult<some Semantic>) -> ReferencedSemanticObject {
return (reference: from.topicGraphNode.reference, semantic: from.value)
}
/// Attempts to resolve links external to the given bundle by visiting the given list of semantic objects.
///
/// The resolved references are collected in ``externallyResolvedLinks``.
///
/// - Parameters:
/// - semanticObjects: A list of semantic objects to visit to collect links.
/// - localBundleID: The local bundle ID, used to identify and skip absolute fully qualified local links.
private func preResolveExternalLinks(semanticObjects: [ReferencedSemanticObject], localBundleID: BundleIdentifier) {
// If there are no external resolvers added we will not resolve any links.
guard !configuration.externalDocumentationConfiguration.sources.isEmpty else { return }
let collectedExternalLinks = Synchronized([String: Set<UnresolvedTopicReference>]())
semanticObjects.concurrentPerform { _, semantic in
autoreleasepool {
// Walk the node and extract external link references.
var externalLinksCollector = ExternalReferenceWalker(localBundleID: localBundleID)
externalLinksCollector.visit(semantic)
// Avoid any synchronization overhead if there are no references to add.
guard !externalLinksCollector.collectedExternalReferences.isEmpty else { return }
// Add the link pairs to `collectedExternalLinks`.
collectedExternalLinks.sync {
for (bundleID, collectedLinks) in externalLinksCollector.collectedExternalReferences {
$0[bundleID, default: []].formUnion(collectedLinks)
}
}
}
}
for (bundleID, collectedLinks) in collectedExternalLinks.sync({ $0 }) {
guard let externalResolver = configuration.externalDocumentationConfiguration.sources[bundleID] else {
continue
}
for externalLink in collectedLinks {
let unresolvedURL = externalLink.topicURL
let result = externalResolver.resolve(.unresolved(externalLink))
externallyResolvedLinks[unresolvedURL] = result
if case .success(let resolvedReference) = result {
// Add the resolved entity to the documentation cache.
if let externallyResolvedNode = externalEntity(with: resolvedReference) {
externalCache[resolvedReference] = externallyResolvedNode
}
if unresolvedURL.absoluteString != resolvedReference.absoluteString,
let resolvedURL = ValidatedURL(resolvedReference.url) {
// If the resolved reference has a different URL than the authored link, cache both URLs so we can resolve both unresolved and resolved references.
//
// The two main examples when this would happen are:
// - when resolving a redirected article and the authored link was the old URL
// - when resolving a symbol with multiple language representations and the authored link wasn't the canonical URL
externallyResolvedLinks[resolvedURL] = result
}
}
}
}
}
/// A resolved documentation node along with any relevant problems.
private typealias LinkResolveResult = (reference: ResolvedTopicReference, node: DocumentationNode, problems: [Problem])
/**
Attempt to resolve links in curation-only documentation, converting any ``TopicReferences`` from `.unresolved` to `.resolved` where possible.
*/
private func resolveLinks(curatedReferences: Set<ResolvedTopicReference>, bundle: DocumentationBundle) {
let references = Array(curatedReferences)
let results = Synchronized<[LinkResolveResult]>([])
results.sync({ $0.reserveCapacity(references.count) })
func inheritsDocumentationFromOtherModule(_ documentationNode: DocumentationNode, symbolOriginReference: ResolvedTopicReference) -> Bool {
// Check that this symbol only has documentation from an in-source documentation comment
guard documentationNode.docChunks.count == 1,
case .sourceCode = documentationNode.docChunks.first?.source
else {
return false
}
// Check that that documentation comment is inherited from a symbol belonging to another module
guard let symbolSemantic = documentationNode.semantic as? Symbol,
let originSymbolSemantic = documentationCache[symbolOriginReference]?.semantic as? Symbol
else {
return false
}
return symbolSemantic.moduleReference != originSymbolSemantic.moduleReference
}
let resolveNodeWithReference: (ResolvedTopicReference) -> Void = { [unowned self] reference in
guard var documentationNode = try? entity(with: reference),
documentationNode.semantic is Article || documentationNode.semantic is Symbol
else {
return
}
let symbolOriginReference = (documentationNode.semantic as? Symbol)?.origin.flatMap { origin in
documentationCache.reference(symbolID: origin.identifier)
}
// Check if we should skip resolving links for inherited documentation from other modules.
if !configuration.externalMetadata.inheritDocs,
let symbolOriginReference,
inheritsDocumentationFromOtherModule(documentationNode, symbolOriginReference: symbolOriginReference)
{
// Don't resolve any links for this symbol.
return
}
var resolver = ReferenceResolver(context: self, bundle: bundle, rootReference: reference, inheritanceParentReference: symbolOriginReference)
// Update the node with the markup that contains resolved references instead of authored links.
documentationNode.semantic = autoreleasepool {
// We use an autorelease pool to release used memory as soon as possible, since the resolver will copy each semantic value
// to rewrite it and replace the authored links with resolved reference strings instead.
resolver.visit(documentationNode.semantic)
}
// Also resolve the node's alternate declaration. This isn't part of the node's 'semantic' value (resolved above).
documentationNode.metadata?.alternateDeclarations.forEach { synonym in
resolver.resolve(
synonym: synonym,
range: synonym.originalMarkup.range,
severity: .warning
)
}
let problems: [Problem]
if documentationNode.semantic is Article {
// Diagnostics for articles have correct source ranges and don't need to be modified.
problems = resolver.problems
} else {
// Diagnostics for in-source documentation comments need to be offset based on the start location of the comment in the source file.
// Get the source location
let inSourceDocumentationCommentInfo = documentationNode.inSourceDocumentationChunk
// Post-process and filter out unwanted diagnostics (for example from inherited documentation comments)
problems = resolver.problems.compactMap { problem in
guard let source = problem.diagnostic.source else {
// Ignore any diagnostic without a source location. These can't be meaningfully presented to the user.
return nil
}
if source == inSourceDocumentationCommentInfo?.url, let offset = inSourceDocumentationCommentInfo?.offset {
// Diagnostics from an in-source documentation comment need to be offset based on the location of that documentation comment.
var modifiedProblem = problem
modifiedProblem.offsetWithRange(offset)
return modifiedProblem
}
// Diagnostics from documentation extension files have correct source ranges and don't need to be modified.
return problem
}
}
// Also resolve the node's page images. This isn't part of the node's 'semantic' value (resolved above).
let pageImageProblems = documentationNode.metadata?.pageImages.compactMap { pageImage in
return resolver.resolve(
resource: pageImage.source,
range: pageImage.originalMarkup.range,
severity: .warning
)
} ?? []
let result: LinkResolveResult = (reference: reference, node: documentationNode, problems: problems + pageImageProblems)
results.sync({ $0.append(result) })
}
// Resolve links concurrently if there are no external resolvers.
references.concurrentPerform { reference -> Void in
resolveNodeWithReference(reference)
}
for result in results.sync({ $0 }) {
documentationCache[result.reference] = result.node
if FeatureFlags.current.isExperimentalMentionedInEnabled {
// Record symbol links as symbol "mentions" for automatic cross references
// on rendered symbol documentation.
if let article = result.node.semantic as? Article,
case .article = DocumentationContentRenderer.roleForArticle(article, nodeKind: result.node.kind)
{
for markup in article.abstractSection?.content ?? [] {
var mentions = SymbolLinkCollector(context: self, article: result.node.reference, baseWeight: 2)
mentions.visit(markup)
}
for markup in article.discussion?.content ?? [] {
var mentions = SymbolLinkCollector(context: self, article: result.node.reference, baseWeight: 1)
mentions.visit(markup)
}
}
}
assert(
// If this is a symbol, verify that the reference exist in the in the symbolIndex
result.node.symbol.map { documentationCache.reference(symbolID: $0.identifier.precise) == result.reference }
?? true, // Nothing to check for non-symbols
"Previous versions stored symbolIndex and documentationCache separately and updated both. This assert verifies that that's no longer necessary."
)
diagnosticEngine.emit(result.problems)
}
mergeFallbackLinkResolutionResults()
}
/// Attempt to resolve links in imported documentation, converting any ``TopicReferences`` from `.unresolved` to `.resolved` where possible.
///
/// This function is passed pages that haven't been added to the topic graph yet. Calling this function will load the documentation entity for each of these pages
/// and add nodes and relationships for some in-page semantics the `topicGraph`. After calling this function, these pages should be accessed by looking them
/// up in the context, not from the arrays that was passed as arguments.
///
/// - Parameters:
/// - tutorialTableOfContentsResults: The list of temporary 'tutorial table-of-contents' pages.
/// - tutorials: The list of temporary 'tutorial' pages.
/// - tutorialArticles: The list of temporary 'tutorialArticle' pages.
/// - bundle: The bundle to resolve links against.
private func resolveLinks(
tutorialTableOfContents tutorialTableOfContentsResults: [SemanticResult<TutorialTableOfContents>],
tutorials: [SemanticResult<Tutorial>],
tutorialArticles: [SemanticResult<TutorialArticle>],
bundle: DocumentationBundle
) {
let sourceLanguages = soleRootModuleReference.map { self.sourceLanguages(for: $0) } ?? [.swift]
// Tutorial table-of-contents
for tableOfContentsResult in tutorialTableOfContentsResults {
autoreleasepool {
let url = tableOfContentsResult.source
var resolver = ReferenceResolver(context: self, bundle: bundle)
let tableOfContents = resolver.visit(tableOfContentsResult.value) as! TutorialTableOfContents
diagnosticEngine.emit(resolver.problems)
// Add to document map
documentLocationMap[url] = tableOfContentsResult.topicGraphNode.reference
let tableOfContentsReference = tableOfContentsResult.topicGraphNode.reference.withSourceLanguages(sourceLanguages)
let tutorialTableOfContentsNode = DocumentationNode(
reference: tableOfContentsReference,
kind: .tutorialTableOfContents,
sourceLanguage: Self.defaultLanguage(in: sourceLanguages),
availableSourceLanguages: sourceLanguages,
name: .conceptual(title: tableOfContents.intro.title),
markup: tableOfContents.originalMarkup,
semantic: tableOfContents
)
documentationCache[tableOfContentsReference] = tutorialTableOfContentsNode
// Update the reference in the topic graph with the table-of-contents page's available languages.
topicGraph.updateReference(
tableOfContentsResult.topicGraphNode.reference,
newReference: tableOfContentsReference
)
let anonymousVolumeName = "$volume"
for volume in tableOfContents.volumes {
// Graph node: Volume
let volumeReference = tutorialTableOfContentsNode.reference.appendingPath(volume.name ?? anonymousVolumeName)
let volumeNode = TopicGraph.Node(reference: volumeReference, kind: .volume, source: .file(url: url), title: volume.name ?? anonymousVolumeName)
topicGraph.addNode(volumeNode)
// Graph edge: Tutorial table-of-contents -> Volume
topicGraph.addEdge(from: tableOfContentsResult.topicGraphNode, to: volumeNode)
for chapter in volume.chapters {
// Graph node: Module
let baseNodeReference: ResolvedTopicReference
if volume.name == nil {
baseNodeReference = tutorialTableOfContentsNode.reference
} else {
baseNodeReference = volumeNode.reference
}
let chapterReference = baseNodeReference.appendingPath(chapter.name)
let chapterNode = TopicGraph.Node(reference: chapterReference, kind: .chapter, source: .file(url: url), title: chapter.name)
topicGraph.addNode(chapterNode)
// Graph edge: Volume -> Chapter
topicGraph.addEdge(from: volumeNode, to: chapterNode)
for tutorialReference in chapter.topicReferences {
guard case let .resolved(.success(tutorialReference)) = tutorialReference.topic,
let tutorialNode = topicGraph.nodeWithReference(tutorialReference) else {
continue
}
// Graph edge: Chapter -> Tutorial | TutorialArticle
topicGraph.addEdge(from: chapterNode, to: tutorialNode)
}
}
}
}
}
// Tutorials
for tutorialResult in tutorials {
autoreleasepool {
let url = tutorialResult.source
let unresolvedTutorial = tutorialResult.value
var resolver = ReferenceResolver(context: self, bundle: bundle)
let tutorial = resolver.visit(unresolvedTutorial) as! Tutorial
diagnosticEngine.emit(resolver.problems)
// Add to document map
documentLocationMap[url] = tutorialResult.topicGraphNode.reference
let tutorialReference = tutorialResult.topicGraphNode.reference.withSourceLanguages(sourceLanguages)
let tutorialNode = DocumentationNode(
reference: tutorialReference,
kind: .tutorial,
sourceLanguage: Self.defaultLanguage(in: sourceLanguages),
availableSourceLanguages: sourceLanguages,
name: .conceptual(title: tutorial.intro.title),
markup: tutorial.originalMarkup,
semantic: tutorial
)
documentationCache[tutorialReference] = tutorialNode
// Update the reference in the topic graph with the tutorial's available languages.
topicGraph.updateReference(
tutorialResult.topicGraphNode.reference,
newReference: tutorialReference
)
}
}
// Tutorial Articles
for articleResult in tutorialArticles {
autoreleasepool {
let url = articleResult.source
let unresolvedTutorialArticle = articleResult.value
var resolver = ReferenceResolver(context: self, bundle: bundle)
let article = resolver.visit(unresolvedTutorialArticle) as! TutorialArticle
diagnosticEngine.emit(resolver.problems)
// Add to document map
documentLocationMap[url] = articleResult.topicGraphNode.reference
let articleReference = articleResult.topicGraphNode.reference.withSourceLanguages(sourceLanguages)
let articleNode = DocumentationNode(
reference: articleReference,
kind: .tutorialArticle,
sourceLanguage: Self.defaultLanguage(in: sourceLanguages),
availableSourceLanguages: sourceLanguages,
name: .conceptual(title: article.title ?? ""),
markup: article.originalMarkup,
semantic: article
)
documentationCache[articleReference] = articleNode
// Update the reference in the topic graph with the article's available languages.
topicGraph.updateReference(
articleResult.topicGraphNode.reference,
newReference: articleReference
)
}
}
// Articles are resolved in a separate pass
}
private func registerDocuments(from bundle: DocumentationBundle) throws -> (
tutorialTableOfContentsResults: [SemanticResult<TutorialTableOfContents>],
tutorials: [SemanticResult<Tutorial>],
tutorialArticles: [SemanticResult<TutorialArticle>],
articles: [SemanticResult<Article>],
documentationExtensions: [SemanticResult<Article>]
) {
// First, try to understand the basic structure of the document by
// analyzing it and putting references in as "unresolved".
var tutorialTableOfContentsResults = [SemanticResult<TutorialTableOfContents>]()
var tutorials = [SemanticResult<Tutorial>]()
var tutorialArticles = [SemanticResult<TutorialArticle>]()
var articles = [SemanticResult<Article>]()
var documentationExtensions = [SemanticResult<Article>]()
var references: [ResolvedTopicReference: URL] = [:]
let decodeError = Synchronized<Error?>(nil)
// Load and analyze documents concurrently
let analyzedDocuments: [(URL, Semantic)] = bundle.markupURLs.concurrentPerform { url, results in
guard decodeError.sync({ $0 == nil }) else { return }
do {
let data = try contentsOfURL(url, in: bundle)
let source = String(decoding: data, as: UTF8.self)
let document = Document(parsing: source, source: url, options: [.parseBlockDirectives, .parseSymbolLinks])
// Check for non-inclusive language in all types of docs if that diagnostic severity is required.
if configuration.externalMetadata.diagnosticLevel >= NonInclusiveLanguageChecker.severity {
var langChecker = NonInclusiveLanguageChecker(sourceFile: url)
langChecker.visit(document)
diagnosticEngine.emit(langChecker.problems)
}
guard let analyzed = analyze(document, at: url, in: bundle, engine: diagnosticEngine) else {
return
}
// Only check non-tutorial documents from markup.
if analyzed is Article {
check(document, at: url)
}
results.append((url, analyzed))
} catch {
decodeError.sync({ $0 = error })
}
}
// Rethrow the decoding error if decoding failed.
if let error = decodeError.sync({ $0 }) {
throw error
}
// to preserve the order of documents by url
let analyzedDocumentsSorted = analyzedDocuments.sorted(by: \.0.absoluteString)
for analyzedDocument in analyzedDocumentsSorted {
// Store the references we encounter to ensure they're unique. The file name is currently the only part of the URL considered for the topic reference, so collisions may occur.
let (url, analyzed) = analyzedDocument
let path = NodeURLGenerator.pathForSemantic(analyzed, source: url, bundle: bundle)
let reference = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: path, sourceLanguage: .swift)
// Since documentation extensions' filenames have no impact on the URL of pages, there is no need to enforce unique filenames for them.
// At this point we consider all articles with an H1 containing link a "documentation extension."
let isDocumentationExtension = (analyzed as? Article)?.title?.child(at: 0) is AnyLink
if let firstFoundAtURL = references[reference], !isDocumentationExtension {
let problem = Problem(
diagnostic: Diagnostic(
source: url,
severity: .warning,
range: nil,
identifier: "org.swift.docc.DuplicateReference",
summary: """
Redeclaration of '\(firstFoundAtURL.lastPathComponent)'; this file will be skipped
""",
explanation: """
This content was already declared at '\(firstFoundAtURL)'
"""
),
possibleSolutions: []
)
diagnosticEngine.emit(problem)
continue
}
if !isDocumentationExtension {
references[reference] = url
}
/*
Add all topic graph nodes up front before resolution starts, because
there may be circular linking.
*/
if let tableOfContents = analyzed as? TutorialTableOfContents {
let topicGraphNode = TopicGraph.Node(reference: reference, kind: .tutorialTableOfContents, source: .file(url: url), title: tableOfContents.intro.title)
topicGraph.addNode(topicGraphNode)
let result = SemanticResult(value: tableOfContents, source: url, topicGraphNode: topicGraphNode)
tutorialTableOfContentsResults.append(result)
} else if let tutorial = analyzed as? Tutorial {
let topicGraphNode = TopicGraph.Node(reference: reference, kind: .tutorial, source: .file(url: url), title: tutorial.title ?? "")
topicGraph.addNode(topicGraphNode)
let result = SemanticResult(value: tutorial, source: url, topicGraphNode: topicGraphNode)
tutorials.append(result)
insertLandmarks(tutorial.landmarks, from: topicGraphNode, source: url)
} else if let tutorialArticle = analyzed as? TutorialArticle {
let topicGraphNode = TopicGraph.Node(reference: reference, kind: .tutorialArticle, source: .file(url: url), title: tutorialArticle.title ?? "")
topicGraph.addNode(topicGraphNode)
let result = SemanticResult(value: tutorialArticle, source: url, topicGraphNode: topicGraphNode)
tutorialArticles.append(result)
insertLandmarks(tutorialArticle.landmarks, from: topicGraphNode, source: url)
} else if let article = analyzed as? Article {
// Here we create a topic graph node with the prepared data but we don't add it to the topic graph just yet
// because we don't know where in the hierarchy the article belongs, we will add it later when crawling the manual curation via Topics task groups.
let topicGraphNode = TopicGraph.Node(reference: reference, kind: .article, source: .file(url: url), title: article.title!.plainText)
let result = SemanticResult(value: article, source: url, topicGraphNode: topicGraphNode)
// Separate articles that look like documentation extension files from other articles, so that the documentation extension files can be matched up with a symbol.
// Some links might not resolve in the final documentation hierarchy and we will emit warnings for those later on when we finalize the bundle discovery phase.
if isDocumentationExtension {
documentationExtensions.append(result)
// Warn for an incorrect root page metadata directive.
if let technologyRoot = result.value.metadata?.technologyRoot {
let diagnostic = Diagnostic(source: url, severity: .warning, range: article.metadata?.technologyRoot?.originalMarkup.range, identifier: "org.swift.docc.UnexpectedTechnologyRoot", summary: "Documentation extension files can't become technology roots.")
let solutions: [Solution]
if let range = technologyRoot.originalMarkup.range {
solutions = [
Solution(summary: "Remove the TechnologyRoot directive", replacements: [Replacement(range: range, replacement: "")])
]
} else {
solutions = []