|
| 1 | +import SwiftSyntax |
| 2 | + |
| 3 | +/// A protocol that represents a declaration group, such as a `struct`, `class`, `enum`, or `protocol`. |
| 4 | +/// This protocol defines common properties that all declaration groups should have. |
| 5 | +public protocol DeclGroupProtocol { |
| 6 | + /// The identifier of the declaration group. |
| 7 | + var identifier: String { get } |
| 8 | + |
| 9 | + /// All members declared within the declaration group. |
| 10 | + var members: [Decl] { get } |
| 11 | + |
| 12 | + /// All properties declared within the declaration group. |
| 13 | + var properties: [Property] { get } |
| 14 | + |
| 15 | + /// All types that the declaration group inherits from or conforms to. |
| 16 | + var inheritedTypes: [Type] { get } |
| 17 | +} |
| 18 | + |
| 19 | +extension DeclGroupProtocol where UnderlyingSyntax: DeclGroupSyntax, Self: RepresentableBySyntax { |
| 20 | + /// Attempts to initialize the wrapper from an arbitrary declaration group. |
| 21 | + /// |
| 22 | + /// - Parameter syntax: The syntax node representing the declaration group. |
| 23 | + /// - Note: This initializer will return `nil` if the syntax node does not match the expected type. |
| 24 | + public init?(_ syntax: any DeclGroupSyntax) { |
| 25 | + guard let syntax = syntax as? UnderlyingSyntax else { return nil } |
| 26 | + self.init(syntax) |
| 27 | + } |
| 28 | + |
| 29 | + public var members: [Decl] { |
| 30 | + _syntax.memberBlock.members.map(\.decl).map(Decl.init) |
| 31 | + } |
| 32 | + |
| 33 | + public var properties: [Property] { |
| 34 | + members.compactMap(\.asVariable).flatMap { variable in |
| 35 | + var bindings = variable._syntax.bindings.flatMap { binding in |
| 36 | + Property.properties(from: binding, in: variable) |
| 37 | + } |
| 38 | + // For the declaration `var a, b: Int` where `a` doesn't have an annotation, |
| 39 | + // `a` gets given the type of `b` (`Int`). To implement this, we 'drag' the |
| 40 | + // type annotations backwards over the non-annotated bindings. |
| 41 | + var lastSeenType: Type? |
| 42 | + for (i, binding) in bindings.enumerated().reversed() { |
| 43 | + if let type = binding.type { |
| 44 | + lastSeenType = type |
| 45 | + } else { |
| 46 | + bindings[i].type = lastSeenType |
| 47 | + } |
| 48 | + } |
| 49 | + return bindings |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public var inheritedTypes: [Type] { |
| 54 | + _syntax.inheritanceClause?.inheritedTypes.map(\.type).map(Type.init) ?? [] |
| 55 | + } |
| 56 | + |
| 57 | + public var accessLevel: AccessModifier? { |
| 58 | + AccessModifier(firstModifierOfKindIn: _syntax.modifiers) |
| 59 | + } |
| 60 | + |
| 61 | + public var declarationContext: DeclarationContextModifier? { |
| 62 | + DeclarationContextModifier(firstModifierOfKindIn: _syntax.modifiers) |
| 63 | + } |
| 64 | +} |
0 commit comments