Skip to content

Commit d7481b8

Browse files
authored
[6.1] Add @AlternateRepresentation directive (#1155)
Fixes rdar://109417745. * Add `@AlternateRepresentation` directive Adds a new child directive to `@Metadata` which can be used in a symbol extension file by specifying the link to another symbol: ```swift @metadata { @AlternateRepresentation(``MyClass/property``) } ``` External links are also supported, as long as they're quoted: ```swift @metadata { @AlternateRepresentation("doc://com.example/documentation/MyClass/property") } ``` The intent of this directive is to define an alternate language representation for the current symbol, such that both symbols are considered to be alternate representations of the same symbol. Ideally two symbols which are equivalent would have the same USR and be resolved as the same symbol by the compiler, but this is not always the case. For the cases in which it is not feasible to change the source code to have them as one symbol, the `@AlternateRepresentation` directive can be used to manually link them as variants of each other. Discussion: ---------- A mutable topic reference type was chosen as the type for parsing&storing the link so that it can be parsed as an unresolved link at the directive parsing stage, and then later be updated to a resolved link at a later stage when the documentation context is resolving all links. A parsing failure diagnostic is returned if the link is invalid in any way: ``` AlternateRepresentation expects an argument for an unnamed parameter that's convertible to 'TopicReference' --> SynonymSample.docc/Symbol.md:4:31-4:37 2 | 3 | @metadata { 4 + @AlternateRepresentation("doc://") 5 | } 6 | ``` This commit adds the directive itself, but doesn't hook it up to other parts of SwiftDocC. Subsequent commits will add: - link resolution - rendering logic Alternatives considered: ----------------------- Considered other names such as `@Synonym`, `@Counterpart`, `@AlternativeDeclaration` and `@VariantOf`. In the end disqualified these as being confusing, and chose `@AlternateRepresentation` for being the one which strikes the best balance between readable and closeness to the technical term for this concept. * Resolve topic references in `@AlternateRepresentation` Adds logic in `DocumentationContext` which will resolve the references inside the alternate representation directive. The same logic is used as for resolving all other links. This is done outside the usual ReferenceResolver visit of the semantic object, because `Symbol` objects don't have access to the node metadata, where the unresolved link resides. If the link cannot be resolved, the usual diagnostic is emitted: ``` warning: 'MissingSymbol' doesn't exist at '/Synonyms' --> SynonymSample.docc/SymbolExtension2.md:4:19-4:32 2 | 3 | @metadata { 4 + @AlternateRepresentation(``Synonyms/MissingSymbol``) 5 | } ``` * Diagnose duplicate representations of `@AlternateRepresentation` If an `@AlternateRepresentation` clashes with already available source languages, this will now be reported as diagnostics. These diagnostics are performed in the final stage of registering a bundle, during the global analysis of the topic graph, where all nodes are available and all links will have been resolved. This is so that we have all the information we need for detecting duplicates. The following cases are detected: - if the symbol the alternate representation is being defined for (the "original" symbol) was already available in one of the languages the counterpart symbol is available in - if the alternate representations have duplicate source languages in common, i.e. if counterpart1 is available in Objective-C and counterpart2 is **also** available in Objective-C. Suggestions will be provided depending on context: - which languages are duplicate - all the languages the symbol is already available in will be available as part of the diagnostic explanation - if the `@AlternateRepresentation` directive is a duplicate, a suggestion will be made to remove it, with a suitable replacement - if the `@AlternateRepresentation` directive is a duplicate, a note pointing to the original directive will be added Example diagnostics: ``` warning: An alternate representation for Swift already exists This node is already available in Swift and Objective-C. SynonymSample.docc/SymbolExtension2.md:4:5: An alternate representation for Swift has already been defined by an @AlternateRepresentation directive. --> SynonymSample.docc/SymbolExtension2.md:5:5-5:57 3 | @metadata { 4 | @AlternateRepresentation(``Synonyms/Synonym-5zxmc``) 5 + @AlternateRepresentation(``Synonyms/Synonym-5zxmc``) | ╰─suggestion: Remove this alternate representation 6 | } 7 | ``` ``` warning: This node already has a representation in Swift This node is already available in Swift. --> SynonymSample.docc/SynonymExtension.md:5:5-5:56 3 | @metadata { 4 | @AlternateRepresentation(``Synonyms/Synonym-1wqxt``) 5 + @AlternateRepresentation(``Synonyms/OtherSynonym``) | ╰─suggestion: Replace the counterpart link with a node which isn't available in Swift 6 | } 7 | ``` * Emit diagnostics for non-symbol pages The `@AlternateRepresentation` directive is not expected for non-symbol pages, and we now emit diagnostics for this case. For example, if an `@AlternateDeclaration` directive is added to an article, the resulting diagnostic will be: ``` warning: Custom alternate representations are not supported for page kind 'Article' Alternate representations are only supported for symbols. --> ./SynonymSample.docc/Article.md:4:5-4:57 2 | 3 | @metadata { 4 + @AlternateRepresentation(``Synonyms/Synonym-5zxmc``) | ╰─suggestion: Remove this alternate representation 5 | } ``` And if a custom alternate declaration to an article is specified, the resulting dia gnostic will be: ``` warning: Page kind 'Article' is not allowed as a custom alternate language representation Symbols can only specify other symbols as custom language representations. --> ./SynonymSample.docc/Synonym-1wqxt.md:5:5-5:44 3 | @metadata { 4 | @AlternateRepresentation(``Synonyms/Synonym-5zxmc``) 5 + @AlternateRepresentation("doc:Article") | ╰─suggestion: Remove this alternate representation 6 | } ``` * Render alternate representations as node variants When rendering the variants of a node, use the topic references from the `@AlternateRepresentation` directives to populate more variants. There is no need to report diagnostics as they would have been reported during bundle registration. Link resolution would have already been performed at that point. Unresolved topic references are ignored, but all resolved references are added as variants. If there are multiple symbols per variant, Swift-DocC-Render prefers the first one that was added, which will always be the current node's symbol. There should be no breakage and change of behaviour for anyone not using `@AlternateRepresentation`, and the current symbol's variants will always be preferred over any other. * Add `AlternateRepresentation` to Metadata article (#1128) The metadata article curates a list of its child directives, with relevant topic titles. This adds `AlternateRepresentation` to that list, in the same section as `SupportedLanguage` as they both deal with language representations.
1 parent 1ba7e65 commit d7481b8

File tree

12 files changed

+861
-15
lines changed

12 files changed

+861
-15
lines changed

Sources/SwiftDocC/Infrastructure/DocumentationContext.swift

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,19 @@ public class DocumentationContext {
618618
resolver.visit(documentationNode.semantic)
619619
}
620620

621+
// Also resolve the node's alternate representations. This isn't part of the node's 'semantic' value (resolved above).
622+
if let alternateRepresentations = documentationNode.metadata?.alternateRepresentations {
623+
for alternateRepresentation in alternateRepresentations {
624+
let resolutionResult = resolver.resolve(
625+
alternateRepresentation.reference,
626+
in: bundle.rootReference,
627+
range: alternateRepresentation.originalMarkup.range,
628+
severity: .warning
629+
)
630+
alternateRepresentation.reference = .resolved(resolutionResult)
631+
}
632+
}
633+
621634
let problems: [Problem]
622635
if documentationNode.semantic is Article {
623636
// Diagnostics for articles have correct source ranges and don't need to be modified.
@@ -2822,6 +2835,9 @@ public class DocumentationContext {
28222835
}
28232836
}
28242837

2838+
// Run analysis to determine whether manually configured alternate representations are valid.
2839+
analyzeAlternateRepresentations()
2840+
28252841
// Run global ``TopicGraph`` global analysis.
28262842
analyzeTopicGraph()
28272843
}
@@ -3186,6 +3202,118 @@ extension DocumentationContext {
31863202
}
31873203
diagnosticEngine.emit(problems)
31883204
}
3205+
3206+
func analyzeAlternateRepresentations() {
3207+
var problems = [Problem]()
3208+
3209+
func listSourceLanguages(_ sourceLanguages: Set<SourceLanguage>) -> String {
3210+
sourceLanguages.sorted(by: { language1, language2 in
3211+
// Emit Swift first, then alphabetically.
3212+
switch (language1, language2) {
3213+
case (.swift, _): return true
3214+
case (_, .swift): return false
3215+
default: return language1.id < language2.id
3216+
}
3217+
}).map(\.name).list(finalConjunction: .and)
3218+
}
3219+
func removeAlternateRepresentationSolution(_ alternateRepresentation: AlternateRepresentation) -> [Solution] {
3220+
[Solution(
3221+
summary: "Remove this alternate representation",
3222+
replacements: alternateRepresentation.originalMarkup.range.map { [Replacement(range: $0, replacement: "")] } ?? [])]
3223+
}
3224+
3225+
for reference in knownPages {
3226+
guard let entity = try? self.entity(with: reference), let alternateRepresentations = entity.metadata?.alternateRepresentations else { continue }
3227+
3228+
var sourceLanguageToReference: [SourceLanguage: AlternateRepresentation] = [:]
3229+
for alternateRepresentation in alternateRepresentations {
3230+
// Check if the entity is not a symbol, as only symbols are allowed to specify custom alternate representations
3231+
guard entity.symbol != nil else {
3232+
problems.append(Problem(
3233+
diagnostic: Diagnostic(
3234+
source: alternateRepresentation.originalMarkup.range?.source,
3235+
severity: .warning,
3236+
range: alternateRepresentation.originalMarkup.range,
3237+
identifier: "org.swift.docc.AlternateRepresentation.UnsupportedPageKind",
3238+
summary: "Custom alternate representations are not supported for page kind \(entity.kind.name.singleQuoted)",
3239+
explanation: "Alternate representations are only supported for symbols."
3240+
),
3241+
possibleSolutions: removeAlternateRepresentationSolution(alternateRepresentation)
3242+
))
3243+
continue
3244+
}
3245+
3246+
guard case .resolved(.success(let alternateRepresentationReference)) = alternateRepresentation.reference,
3247+
let alternateRepresentationEntity = try? self.entity(with: alternateRepresentationReference) else {
3248+
continue
3249+
}
3250+
3251+
// Check if the resolved entity is not a symbol, as only symbols are allowed as custom alternate representations
3252+
guard alternateRepresentationEntity.symbol != nil else {
3253+
problems.append(Problem(
3254+
diagnostic: Diagnostic(
3255+
source: alternateRepresentation.originalMarkup.range?.source,
3256+
severity: .warning,
3257+
range: alternateRepresentation.originalMarkup.range,
3258+
identifier: "org.swift.docc.AlternateRepresentation.UnsupportedPageKind",
3259+
summary: "Page kind \(alternateRepresentationEntity.kind.name.singleQuoted) is not allowed as a custom alternate language representation",
3260+
explanation: "Symbols can only specify other symbols as custom language representations."
3261+
),
3262+
possibleSolutions: removeAlternateRepresentationSolution(alternateRepresentation)
3263+
))
3264+
continue
3265+
}
3266+
3267+
// Check if the documented symbol already has alternate representations from in-source annotations.
3268+
let duplicateSourceLanguages = alternateRepresentationEntity.availableSourceLanguages.intersection(entity.availableSourceLanguages)
3269+
if !duplicateSourceLanguages.isEmpty {
3270+
problems.append(Problem(
3271+
diagnostic: Diagnostic(
3272+
source: alternateRepresentation.originalMarkup.range?.source,
3273+
severity: .warning,
3274+
range: alternateRepresentation.originalMarkup.range,
3275+
identifier: "org.swift.docc.AlternateRepresentation.DuplicateLanguageDefinition",
3276+
summary: "\(entity.name.plainText.singleQuoted) already has a representation in \(listSourceLanguages(duplicateSourceLanguages))",
3277+
explanation: "Symbols can only specify custom alternate language representations for languages that the documented symbol doesn't already have a representation for."
3278+
),
3279+
possibleSolutions: [Solution(summary: "Replace this alternate language representation with a symbol which isn't available in \(listSourceLanguages(entity.availableSourceLanguages))", replacements: [])]
3280+
))
3281+
}
3282+
3283+
let duplicateAlternateLanguages = Set(sourceLanguageToReference.keys).intersection(alternateRepresentationEntity.availableSourceLanguages)
3284+
if !duplicateAlternateLanguages.isEmpty {
3285+
let notes: [DiagnosticNote] = duplicateAlternateLanguages.compactMap { duplicateAlternateLanguage in
3286+
guard let alreadyExistingRepresentation = sourceLanguageToReference[duplicateAlternateLanguage],
3287+
let range = alreadyExistingRepresentation.originalMarkup.range,
3288+
let source = range.source else {
3289+
return nil
3290+
}
3291+
3292+
return DiagnosticNote(source: source, range: range, message: "This directive already specifies an alternate \(duplicateAlternateLanguage.name) representation.")
3293+
}
3294+
problems.append(Problem(
3295+
diagnostic: Diagnostic(
3296+
source: alternateRepresentation.originalMarkup.range?.source,
3297+
severity: .warning,
3298+
range: alternateRepresentation.originalMarkup.range,
3299+
identifier: "org.swift.docc.AlternateRepresentation.DuplicateLanguageDefinition",
3300+
summary: "A custom alternate language representation for \(listSourceLanguages(duplicateAlternateLanguages)) has already been specified",
3301+
explanation: "Only one custom alternate language representation can be specified per language.",
3302+
notes: notes
3303+
),
3304+
possibleSolutions: removeAlternateRepresentationSolution(alternateRepresentation)
3305+
))
3306+
}
3307+
3308+
// Update mapping from source language to alternate declaration, for diagnostic purposes
3309+
for alreadySeenLanguage in alternateRepresentationEntity.availableSourceLanguages {
3310+
sourceLanguageToReference[alreadySeenLanguage] = alternateRepresentation
3311+
}
3312+
}
3313+
}
3314+
3315+
diagnosticEngine.emit(problems)
3316+
}
31893317
}
31903318

31913319
extension GraphCollector.GraphKind {

Sources/SwiftDocC/Model/Rendering/RenderNodeTranslator.swift

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1852,23 +1852,45 @@ public struct RenderNodeTranslator: SemanticVisitor {
18521852
private func variants(for documentationNode: DocumentationNode) -> [RenderNode.Variant] {
18531853
let generator = PresentationURLGenerator(context: context, baseURL: bundle.baseURL)
18541854

1855-
return documentationNode.availableSourceLanguages
1856-
.sorted(by: { language1, language2 in
1855+
var allVariants: [SourceLanguage: ResolvedTopicReference] = documentationNode.availableSourceLanguages.reduce(into: [:]) { partialResult, language in
1856+
partialResult[language] = identifier
1857+
}
1858+
1859+
// Apply alternate representations
1860+
if let alternateRepresentations = documentationNode.metadata?.alternateRepresentations {
1861+
for alternateRepresentation in alternateRepresentations {
1862+
// Only alternate representations which were able to be resolved to a reference should be included as an alternate representation.
1863+
// Unresolved alternate representations can be ignored, as they would have been reported during link resolution.
1864+
guard case .resolved(.success(let alternateRepresentationReference)) = alternateRepresentation.reference else {
1865+
continue
1866+
}
1867+
1868+
// Add the language representations of the alternate symbol as additional variants for the current symbol.
1869+
// Symbols can only specify custom alternate language representations for languages that the documented symbol doesn't already have a representation for.
1870+
// If the current symbol and its custom alternate representation share language representations, the custom language representation is ignored.
1871+
allVariants.merge(
1872+
alternateRepresentationReference.sourceLanguages.map { ($0, alternateRepresentationReference) }
1873+
) { existing, _ in existing }
1874+
}
1875+
}
1876+
1877+
return allVariants
1878+
.sorted(by: { variant1, variant2 in
18571879
// Emit Swift first, then alphabetically.
1858-
switch (language1, language2) {
1880+
switch (variant1.key, variant2.key) {
18591881
case (.swift, _): return true
18601882
case (_, .swift): return false
1861-
default: return language1.id < language2.id
1862-
}
1863-
})
1864-
.map { sourceLanguage in
1865-
RenderNode.Variant(
1866-
traits: [.interfaceLanguage(sourceLanguage.id)],
1867-
paths: [
1868-
generator.presentationURLForReference(identifier).path
1869-
]
1870-
)
1883+
default: return variant1.key.id < variant2.key.id
18711884
}
1885+
})
1886+
.map { sourceLanguage, reference in
1887+
RenderNode.Variant(
1888+
traits: [.interfaceLanguage(sourceLanguage.id)],
1889+
paths: [
1890+
generator.presentationURLForReference(reference).path
1891+
]
1892+
)
1893+
}
18721894
}
18731895

18741896
private mutating func convertFragments(_ fragments: [SymbolGraph.Symbol.DeclarationFragments.Fragment]) -> [DeclarationRenderSection.Token] {
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
This source file is part of the Swift.org open source project
3+
4+
Copyright (c) 2024 Apple Inc. and the Swift project authors
5+
Licensed under Apache License v2.0 with Runtime Library Exception
6+
7+
See https://swift.org/LICENSE.txt for license information
8+
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
9+
*/
10+
11+
import Foundation
12+
import Markdown
13+
14+
15+
/// A directive that configures an alternate language representation of a symbol.
16+
///
17+
/// An API that can be called from more than one source language has more than one language representation.
18+
///
19+
/// Whenever possible, prefer to define alternative language representations for a symbol by using in-source annotations
20+
/// such as the `@objc` and `@_objcImplementation` attributes in Swift,
21+
/// or the `NS_SWIFT_NAME` macro in Objective C.
22+
///
23+
/// If your source language doesn’t have a mechanism for specifying alternate representations or if your intended alternate representation isn't compatible with those attributes,
24+
/// you can use the `@AlternateRepresentation` directive to specify another symbol that should be considered an alternate representation of the documented symbol.
25+
///
26+
/// ```md
27+
/// @Metadata {
28+
/// @AlternateRepresentation(MyApp/MyClass/property)
29+
/// }
30+
/// ```
31+
/// If you prefer, you can wrap the symbol link in a set of double backticks (\`\`), or use any other supported syntax for linking to symbols.
32+
/// For more information about linking to symbols, see <doc:linking-to-symbols-and-other-content>.
33+
///
34+
/// This provides a hint to the renderer as to the alternate language representations for the current symbol.
35+
/// The renderer may use this hint to provide a link to these alternate symbols.
36+
/// For example, Swift-DocC-Render shows a toggle between supported languages, where switching to a different language representation will redirect to the documentation for the configured alternate symbol.
37+
///
38+
/// ### Special considerations
39+
///
40+
/// Links containing a colon (`:`) must be wrapped in quotes:
41+
/// ```md
42+
/// @Metadata {
43+
/// @AlternateRepresentation("doc://com.example/documentation/MyClass/property")
44+
/// @AlternateRepresentation("MyClass/myFunc(_:_:)")
45+
/// }
46+
/// ```
47+
///
48+
/// The `@AlternateRepresentation` directive only specifies an alternate language representation in one direction.
49+
/// To define a two-way relationship, add an `@AlternateRepresentation` directive, linking to this symbol, to the other symbol as well.
50+
///
51+
/// You can only configure custom alternate language representations for languages that the documented symbol doesn't already have a language representation for,
52+
/// either from in-source annotations or from a previous `@AlternateRepresentation` directive.
53+
public final class AlternateRepresentation: Semantic, AutomaticDirectiveConvertible {
54+
public static let introducedVersion = "6.1"
55+
56+
// Directive parameter definition
57+
58+
/// A link to another symbol that should be considered an alternate language representation of the current symbol.
59+
///
60+
/// If you prefer, you can wrap the symbol link in a set of double backticks (\`\`).
61+
@DirectiveArgumentWrapped(
62+
name: .unnamed,
63+
parseArgument: { _, argumentValue in
64+
// Allow authoring of links with leading and trailing "``"s
65+
var argumentValue = argumentValue
66+
if argumentValue.hasPrefix("``"), argumentValue.hasSuffix("``") {
67+
argumentValue = String(argumentValue.dropFirst(2).dropLast(2))
68+
}
69+
guard let url = ValidatedURL(parsingAuthoredLink: argumentValue), !url.components.path.isEmpty else {
70+
return nil
71+
}
72+
return .unresolved(UnresolvedTopicReference(topicURL: url))
73+
}
74+
)
75+
public internal(set) var reference: TopicReference
76+
77+
static var keyPaths: [String : AnyKeyPath] = [
78+
"reference" : \AlternateRepresentation._reference
79+
]
80+
81+
// Boiler-plate required by conformance to AutomaticDirectiveConvertible
82+
83+
public var originalMarkup: Markdown.BlockDirective
84+
85+
@available(*, deprecated, message: "Do not call directly. Required for 'AutomaticDirectiveConvertible")
86+
init(originalMarkup: Markdown.BlockDirective) {
87+
self.originalMarkup = originalMarkup
88+
}
89+
}

Sources/SwiftDocC/Semantics/Metadata/Metadata.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import Markdown
1919
///
2020
/// ### Child Directives
2121
///
22+
/// - ``AlternateRepresentation``
2223
/// - ``DocumentationExtension``
2324
/// - ``TechnologyRoot``
2425
/// - ``DisplayName``
@@ -77,6 +78,9 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {
7778

7879
@ChildDirective
7980
var redirects: [Redirect]? = nil
81+
82+
@ChildDirective(requirements: .zeroOrMore)
83+
var alternateRepresentations: [AlternateRepresentation]
8084

8185
static var keyPaths: [String : AnyKeyPath] = [
8286
"documentationOptions" : \Metadata._documentationOptions,
@@ -91,6 +95,7 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {
9195
"_pageColor" : \Metadata.__pageColor,
9296
"titleHeading" : \Metadata._titleHeading,
9397
"redirects" : \Metadata._redirects,
98+
"alternateRepresentations" : \Metadata._alternateRepresentations,
9499
]
95100

96101
@available(*, deprecated, message: "Do not call directly. Required for 'AutomaticDirectiveConvertible'.")
@@ -100,7 +105,7 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {
100105

101106
func validate(source: URL?, for bundle: DocumentationBundle, in context: DocumentationContext, problems: inout [Problem]) -> Bool {
102107
// Check that something is configured in the metadata block
103-
if documentationOptions == nil && technologyRoot == nil && displayName == nil && pageImages.isEmpty && customMetadata.isEmpty && callToAction == nil && availability.isEmpty && pageKind == nil && pageColor == nil && titleHeading == nil && redirects == nil {
108+
if documentationOptions == nil && technologyRoot == nil && displayName == nil && pageImages.isEmpty && customMetadata.isEmpty && callToAction == nil && availability.isEmpty && pageKind == nil && pageColor == nil && titleHeading == nil && redirects == nil && alternateRepresentations.isEmpty {
104109
let diagnostic = Diagnostic(
105110
source: source,
106111
severity: .information,

Sources/SwiftDocC/Utility/MarkupExtensions/BlockDirectiveExtensions.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ extension BlockDirective {
4141
Metadata.directiveName,
4242
Metadata.Availability.directiveName,
4343
Metadata.PageKind.directiveName,
44+
AlternateRepresentation.directiveName,
4445
MultipleChoice.directiveName,
4546
Options.directiveName,
4647
PageColor.directiveName,

0 commit comments

Comments
 (0)