Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add directive for linking symbols as alternate representations #1097

Merged
merged 5 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions Sources/SwiftDocC/Infrastructure/DocumentationContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,19 @@ public class DocumentationContext {
resolver.visit(documentationNode.semantic)
}

// Also resolve the node's alternate representations. This isn't part of the node's 'semantic' value (resolved above).
if let alternateRepresentations = documentationNode.metadata?.alternateRepresentations {
for alternateRepresentation in alternateRepresentations {
let resolutionResult = resolver.resolve(
alternateRepresentation.reference,
in: bundle.rootReference,
range: alternateRepresentation.originalMarkup.range,
severity: .warning
)
alternateRepresentation.reference = .resolved(resolutionResult)
}
}

let problems: [Problem]
if documentationNode.semantic is Article {
// Diagnostics for articles have correct source ranges and don't need to be modified.
Expand Down Expand Up @@ -2822,6 +2835,9 @@ public class DocumentationContext {
}
}

// Run analysis to determine whether manually configured alternate representations are valid.
analyzeAlternateRepresentations()

// Run global ``TopicGraph`` global analysis.
analyzeTopicGraph()
}
Expand Down Expand Up @@ -3186,6 +3202,118 @@ extension DocumentationContext {
}
diagnosticEngine.emit(problems)
}

func analyzeAlternateRepresentations() {
var problems = [Problem]()

func listSourceLanguages(_ sourceLanguages: Set<SourceLanguage>) -> String {
sourceLanguages.sorted(by: { language1, language2 in
// Emit Swift first, then alphabetically.
switch (language1, language2) {
case (.swift, _): return true
case (_, .swift): return false
default: return language1.id < language2.id
}
}).map(\.name).list(finalConjunction: .and)
}
func removeAlternateRepresentationSolution(_ alternateRepresentation: AlternateRepresentation) -> [Solution] {
[Solution(
summary: "Remove this alternate representation",
replacements: alternateRepresentation.originalMarkup.range.map { [Replacement(range: $0, replacement: "")] } ?? [])]
}

for reference in knownPages {
guard let entity = try? self.entity(with: reference), let alternateRepresentations = entity.metadata?.alternateRepresentations else { continue }

var sourceLanguageToReference: [SourceLanguage: AlternateRepresentation] = [:]
for alternateRepresentation in alternateRepresentations {
// Check if the entity is not a symbol, as only symbols are allowed to specify custom alternate representations
guard entity.symbol != nil else {
problems.append(Problem(
diagnostic: Diagnostic(
source: alternateRepresentation.originalMarkup.range?.source,
severity: .warning,
range: alternateRepresentation.originalMarkup.range,
identifier: "org.swift.docc.AlternateRepresentation.UnsupportedPageKind",
summary: "Custom alternate representations are not supported for page kind \(entity.kind.name.singleQuoted)",
explanation: "Alternate representations are only supported for symbols."
),
possibleSolutions: removeAlternateRepresentationSolution(alternateRepresentation)
))
continue
}

guard case .resolved(.success(let alternateRepresentationReference)) = alternateRepresentation.reference,
let alternateRepresentationEntity = try? self.entity(with: alternateRepresentationReference) else {
continue
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is the only place that checks that the link resolved we should emit a warning with the right link source range so that the developer knows that the link failed to resolve.

unresolvedReferenceProblem(...) can create the same type of diagnostic as for other unresolved links by passing the TopicReferenceResolutionErrorInfo from the TopicReferenceResolutionResult.failure(_:_:).

Copy link
Contributor Author

@anferbui anferbui Nov 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will already emit a diagnostic in the code below so I don't think it's also needed here, WDYT?

// 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
)
}

Since this ultimately ends up adding this diagnostic:

problems.append(unresolvedReferenceProblem(source: range?.source, range: range, severity: severity, uncuratedArticleMatch: uncuratedArticleMatch, errorInfo: error, fromSymbolLink: false))

(I can add a comment to explain why we don't need a diagnostic here)

}

// Check if the resolved entity is not a symbol, as only symbols are allowed as custom alternate representations
guard alternateRepresentationEntity.symbol != nil else {
problems.append(Problem(
diagnostic: Diagnostic(
source: alternateRepresentation.originalMarkup.range?.source,
severity: .warning,
range: alternateRepresentation.originalMarkup.range,
identifier: "org.swift.docc.AlternateRepresentation.UnsupportedPageKind",
summary: "Page kind \(alternateRepresentationEntity.kind.name.singleQuoted) is not allowed as a custom alternate language representation",
explanation: "Symbols can only specify other symbols as custom language representations."
),
possibleSolutions: removeAlternateRepresentationSolution(alternateRepresentation)
))
continue
}

// Check if the documented symbol already has alternate representations from in-source annotations.
let duplicateSourceLanguages = alternateRepresentationEntity.availableSourceLanguages.intersection(entity.availableSourceLanguages)
if !duplicateSourceLanguages.isEmpty {
problems.append(Problem(
diagnostic: Diagnostic(
source: alternateRepresentation.originalMarkup.range?.source,
severity: .warning,
range: alternateRepresentation.originalMarkup.range,
identifier: "org.swift.docc.AlternateRepresentation.DuplicateLanguageDefinition",
summary: "\(entity.name.plainText.singleQuoted) already has a representation in \(listSourceLanguages(duplicateSourceLanguages))",
explanation: "Symbols can only specify custom alternate language representations for languages that the documented symbol doesn't already have a representation for."
),
possibleSolutions: [Solution(summary: "Replace this alternate language representation with a symbol which isn't available in \(listSourceLanguages(entity.availableSourceLanguages))", replacements: [])]
))
}

let duplicateAlternateLanguages = Set(sourceLanguageToReference.keys).intersection(alternateRepresentationEntity.availableSourceLanguages)
if !duplicateAlternateLanguages.isEmpty {
let notes: [DiagnosticNote] = duplicateAlternateLanguages.compactMap { duplicateAlternateLanguage in
guard let alreadyExistingRepresentation = sourceLanguageToReference[duplicateAlternateLanguage],
let range = alreadyExistingRepresentation.originalMarkup.range,
let source = range.source else {
return nil
}

return DiagnosticNote(source: source, range: range, message: "This directive already specifies an alternate \(duplicateAlternateLanguage.name) representation.")
}
problems.append(Problem(
diagnostic: Diagnostic(
source: alternateRepresentation.originalMarkup.range?.source,
severity: .warning,
range: alternateRepresentation.originalMarkup.range,
identifier: "org.swift.docc.AlternateRepresentation.DuplicateLanguageDefinition",
summary: "A custom alternate language representation for \(listSourceLanguages(duplicateAlternateLanguages)) has already been specified",
explanation: "Only one custom alternate language representation can be specified per language.",
notes: notes
),
possibleSolutions: removeAlternateRepresentationSolution(alternateRepresentation)
))
}

// Update mapping from source language to alternate declaration, for diagnostic purposes
for alreadySeenLanguage in alternateRepresentationEntity.availableSourceLanguages {
sourceLanguageToReference[alreadySeenLanguage] = alternateRepresentation
}
}
}

diagnosticEngine.emit(problems)
}
}

extension GraphCollector.GraphKind {
Expand Down
48 changes: 35 additions & 13 deletions Sources/SwiftDocC/Model/Rendering/RenderNodeTranslator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1852,23 +1852,45 @@ public struct RenderNodeTranslator: SemanticVisitor {
private func variants(for documentationNode: DocumentationNode) -> [RenderNode.Variant] {
let generator = PresentationURLGenerator(context: context, baseURL: bundle.baseURL)

return documentationNode.availableSourceLanguages
.sorted(by: { language1, language2 in
var allVariants: [SourceLanguage: ResolvedTopicReference] = documentationNode.availableSourceLanguages.reduce(into: [:]) { partialResult, language in
partialResult[language] = identifier
}

// Apply alternate representations
if let alternateRepresentations = documentationNode.metadata?.alternateRepresentations {
for alternateRepresentation in alternateRepresentations {
// Only alternate representations which were able to be resolved to a reference should be included as an alternate representation.
// Unresolved alternate representations can be ignored, as they would have been reported during link resolution.
guard case .resolved(.success(let alternateRepresentationReference)) = alternateRepresentation.reference else {
continue
}

// Add the language representations of the alternate symbol as additional variants for the current symbol.
// Symbols can only specify custom alternate language representations for languages that the documented symbol doesn't already have a representation for.
// If the current symbol and its custom alternate representation share language representations, the custom language representation is ignored.
allVariants.merge(
alternateRepresentationReference.sourceLanguages.map { ($0, alternateRepresentationReference) }
) { existing, _ in existing }
}
}

return allVariants
.sorted(by: { variant1, variant2 in
// Emit Swift first, then alphabetically.
switch (language1, language2) {
switch (variant1.key, variant2.key) {
case (.swift, _): return true
case (_, .swift): return false
default: return language1.id < language2.id
}
})
.map { sourceLanguage in
RenderNode.Variant(
traits: [.interfaceLanguage(sourceLanguage.id)],
paths: [
generator.presentationURLForReference(identifier).path
]
)
default: return variant1.key.id < variant2.key.id
}
})
.map { sourceLanguage, reference in
RenderNode.Variant(
traits: [.interfaceLanguage(sourceLanguage.id)],
paths: [
generator.presentationURLForReference(reference).path
]
)
}
}

private mutating func convertFragments(_ fragments: [SymbolGraph.Symbol.DeclarationFragments.Fragment]) -> [DeclarationRenderSection.Token] {
Expand Down
89 changes: 89 additions & 0 deletions Sources/SwiftDocC/Semantics/Metadata/AlternateRepresentation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
This source file is part of the Swift.org open source project

Copyright (c) 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


/// A directive that configures an alternate language representations of a symbol.
///
/// An API that can be called from more than one source language has more than one language representation.
///
/// Whenever possible, prefer to define alternative language representations for a symbol by using in-source annotations
/// such as the `@objc` and `@_objcImplementation` attributes in Swift,
/// or the `NS_SWIFT_NAME` macro in Objective C.
///
/// 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,
/// you can use the `@AlternateRepresentation` directive to specify another symbol that should be considered an alternate representation of the documented symbol.
///
/// ```md
/// @Metadata {
/// @AlternateRepresentation(MyApp/MyClass/property)
/// }
/// ```
/// 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.
/// For more information about linking to symbols, see <doc:linking-to-symbols-and-other-content>.
///
/// This provides a hint to the renderer as to the alternate language representations for the current symbol.
/// The renderer may use this hint to provide a link to these alternate symbols.
/// 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.
///
/// ### Special considerations
///
/// Links containing a colon (`:`) must be wrapped in quotes:
anferbui marked this conversation as resolved.
Show resolved Hide resolved
/// ```md
/// @Metadata {
/// @AlternateRepresentation("doc://com.example/documentation/MyClass/property")
/// @AlternateRepresentation("MyClass/myFunc(_:_:)")
/// }
/// ```
///
/// The `@AlternateRepresentation` directive only specifies an alternate language representation in one direction.
/// To define a two-way relationship, add an `@AlternateRepresentation` directive, linking to this symbol, to the other symbol as well.
///
/// You can only configure custom alternate language representations for languages that the documented symbol doesn't already have a language representation for,
/// either from in-source annotations or from a previous `@AlternateRepresentation` directive.
public final class AlternateRepresentation: Semantic, AutomaticDirectiveConvertible {
public static let introducedVersion = "6.1"

// Directive parameter definition

/// A link to another symbol that should be considered an alternate language representation of the current symbol.
///
/// If you prefer, you can wrap the symbol link in a set of double backticks (\`\`).
@DirectiveArgumentWrapped(
name: .unnamed,
parseArgument: { _, argumentValue in
// Allow authoring of links with leading and trailing "``"s
var argumentValue = argumentValue
if argumentValue.hasPrefix("``"), argumentValue.hasSuffix("``") {
argumentValue = String(argumentValue.dropFirst(2).dropLast(2))
}
guard let url = ValidatedURL(parsingAuthoredLink: argumentValue), !url.components.path.isEmpty else {
return nil
anferbui marked this conversation as resolved.
Show resolved Hide resolved
}
return .unresolved(UnresolvedTopicReference(topicURL: url))
}
)
public internal(set) var reference: TopicReference

static var keyPaths: [String : AnyKeyPath] = [
"reference" : \AlternateRepresentation._reference
]

// Boiler-plate required by conformance to AutomaticDirectiveConvertible

public var originalMarkup: Markdown.BlockDirective

@available(*, deprecated, message: "Do not call directly. Required for 'AutomaticDirectiveConvertible")
init(originalMarkup: Markdown.BlockDirective) {
self.originalMarkup = originalMarkup
}
}
7 changes: 6 additions & 1 deletion Sources/SwiftDocC/Semantics/Metadata/Metadata.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import Markdown
///
/// ### Child Directives
///
/// - ``AlternateRepresentation``
/// - ``DocumentationExtension``
/// - ``TechnologyRoot``
/// - ``DisplayName``
Expand Down Expand Up @@ -77,6 +78,9 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {

@ChildDirective
var redirects: [Redirect]? = nil

@ChildDirective(requirements: .zeroOrMore)
var alternateRepresentations: [AlternateRepresentation]

static var keyPaths: [String : AnyKeyPath] = [
"documentationOptions" : \Metadata._documentationOptions,
Expand All @@ -91,6 +95,7 @@ public final class Metadata: Semantic, AutomaticDirectiveConvertible {
"_pageColor" : \Metadata.__pageColor,
"titleHeading" : \Metadata._titleHeading,
"redirects" : \Metadata._redirects,
"alternateRepresentations" : \Metadata._alternateRepresentations,
]

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

func validate(source: URL?, for bundle: DocumentationBundle, in context: DocumentationContext, problems: inout [Problem]) -> Bool {
// Check that something is configured in the metadata block
if documentationOptions == nil && technologyRoot == nil && displayName == nil && pageImages.isEmpty && customMetadata.isEmpty && callToAction == nil && availability.isEmpty && pageKind == nil && pageColor == nil && titleHeading == nil && redirects == nil {
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 {
let diagnostic = Diagnostic(
source: source,
severity: .information,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ extension BlockDirective {
Metadata.directiveName,
Metadata.Availability.directiveName,
Metadata.PageKind.directiveName,
AlternateRepresentation.directiveName,
MultipleChoice.directiveName,
Options.directiveName,
PageColor.directiveName,
Expand Down
Loading