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
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021 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 SymbolKit
typealias Constraint = SymbolGraph.Symbol.Swift.GenericConstraint
extension Constraint.Kind {
/// The spelling to use when rendering this kind of constraint.
var spelling: String {
switch self {
case .conformance: return "conforms to"
case .sameType: return "is"
case .superclass: return "inherits"
}
}
}
/// A section that contains a list of generic constraints for a symbol.
///
/// The section contains a list of generic constraints that describe the conditions
/// when a symbol is available or conforms to a protocol. For example:
/// "Available when `Element` conforms to `Equatable` and `S` conforms to `StringLiteral`."
public struct ConformanceSection: Codable, Equatable {
/// A prefix with which to prepend availability constraints.
var availabilityPrefix: [RenderInlineContent] = [.text("Available when")]
/// A prefix with which to prepend conformance constraints.
var conformancePrefix: [RenderInlineContent] = [.text("Conforms when")]
/// The section constraints rendered as inline content.
let constraints: [RenderInlineContent]
/// Additional parameters to consider when rendering conformance constraints.
struct ConstraintRenderOptions {
/// Whether the symbol is a leaf symbol, such as a function or a property.
let isLeaf: Bool
/// The name of the parent symbol.
let parentName: String?
/// The symbol name of `Self`.
let selfName: String
}
/// Creates a new conformance section.
/// - Parameter constraints: The list of constraints to render.
/// - Parameter options: The list of options to apply while rendering.
///
/// Returns `nil` if the given constraints list is empty.
init?(constraints: [Constraint], options: ConstraintRenderOptions) {
// Groom somewhat a constraint list coming from the Swift compiler.
let constraints = ConformanceSection.filterConstraints(constraints, options: options)
// If no valid constraints are left return `nil`.
guard !constraints.isEmpty else { return nil }
// Checks if all requirements are on the same type & relation.
let areRequirementsSameTypeAndRelation = constraints.allSatisfy { constraint in
return (constraints[0].leftTypeName == constraint.leftTypeName)
&& (constraints[0].kind == constraint.kind)
}
// If all constraints are on the same type, fold the sentence and return
if areRequirementsSameTypeAndRelation {
self.constraints = ConformanceSection.groupRequirements(constraints) + [RenderInlineContent.text(".")]
return
}
// Render all constraints as a sentence.
let separators = NativeLanguage.english.listSeparators(itemsCount: constraints.count, listType: .union)
.map { RenderInlineContent.text($0) }
let rendered = constraints.map { constraint -> [RenderInlineContent] in
return [
RenderInlineContent.codeVoice(code: ConformanceSection.displayNameForConformingType(constraint.leftTypeName)),
RenderInlineContent.text(constraint.kind.spelling.spaceDelimited),
RenderInlineContent.codeVoice(code: constraint.rightTypeName)
]
}
// Adds "," or ", and" to the requirements wherever necessary.
var merged: [RenderInlineContent] = []
merged.reserveCapacity(rendered.count * 4) // 3 for each constraint and 1 for each separator
for (constraint, separator) in zip(rendered, separators) {
merged.append(contentsOf: constraint)
merged.append(separator)
}
merged.append(contentsOf: rendered.last!)
merged.append(.text("."))
self.constraints = merged
}
private static let selfPrefix = "Self."
/// Returns, modified if necessary, a conforming type's name for rendering.
static func displayNameForConformingType(_ typeName: String) -> String {
if typeName.hasPrefix(selfPrefix) {
return String(typeName.dropFirst(selfPrefix.count))
}
return typeName
}
/// Filters the list of constraints to the significant constraints only.
///
/// This method removes symbol graph constraints on `Self` that are always fulfilled.
static func filterConstraints(_ constraints: [Constraint], options: ConstraintRenderOptions) -> [Constraint] {
return constraints
.filter { constraint -> Bool in
if options.isLeaf {
// Leaf symbol.
if constraint.leftTypeName == "Self" && constraint.rightTypeName == options.parentName {
// The Swift compiler will sometimes include a constraint's to `Self`'s type,
// filter those generic constraints out.
return false
}
return true
} else {
// Non-leaf symbol.
if constraint.leftTypeName == "Self" && constraint.rightTypeName == options.selfName {
// The Swift compiler will sometimes include a constraint's to `Self`'s type,
// filter those generic constraints out.
return false
}
return true
}
}
}
/// Groups all input requirements into a single multipart requirement.
///
/// For example, converts the following repetitive constraints:
/// ```
/// Key conforms to Hashable, Key conforms to Equatable, Key conforms to Codable
/// ```
/// to the shorter version of:
/// ```
/// Key conforms to Hashable, Equatable, and Codable
/// ```
/// All requirements must be on the same type and with the same
/// relation kind, for example, "is a" or "conforms to". The `conformances` parameter
/// contains at least one requirement.
static func groupRequirements(_ constraints: [Constraint]) -> [RenderInlineContent] {
precondition(!constraints.isEmpty)
let constraintTypeNames = constraints.map { constraint in
return RenderInlineContent.codeVoice(code: constraint.rightTypeName)
}
let separators = NativeLanguage.english.listSeparators(itemsCount: constraints.count, listType: .union)
.map { return RenderInlineContent.text($0) }
let constraintCompoundName = zip(constraintTypeNames, separators).flatMap { [$0, $1] }
+ constraintTypeNames[separators.count...]
return [
RenderInlineContent.codeVoice(code: ConformanceSection.displayNameForConformingType(constraints[0].leftTypeName)),
RenderInlineContent.text(constraints[0].kind.spelling.spaceDelimited)
] + constraintCompoundName
}
}
private extension String {
/// Returns the string surrounded by spaces.
var spaceDelimited: String { return " \(self) "}
}
// Diffable conformance
extension ConformanceSection: RenderJSONDiffable {
/// Returns the differences between this ConformanceSection and the given one.
func difference(from other: ConformanceSection, at path: CodablePath) -> JSONPatchDifferences {
var diffBuilder = DifferenceBuilder(current: self, other: other, basePath: path)
diffBuilder.addDifferences(atKeyPath: \.availabilityPrefix, forKey: CodingKeys.availabilityPrefix)
diffBuilder.addDifferences(atKeyPath: \.conformancePrefix, forKey: CodingKeys.conformancePrefix)
diffBuilder.addDifferences(atKeyPath: \.constraints, forKey: CodingKeys.constraints)
return diffBuilder.differences
}
}
|