|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import SwiftSyntax |
| 14 | +import SwiftSyntaxBuilder |
| 15 | +import SyntaxSupport |
| 16 | +import Utils |
| 17 | + |
| 18 | +let syntaxTraitsFile = SourceFileSyntax { |
| 19 | + for trait in TRAITS { |
| 20 | + ProtocolDeclSyntax(""" |
| 21 | + // MARK: - \(trait.traitName)Syntax |
| 22 | + |
| 23 | + public protocol \(trait.traitName)Syntax: SyntaxProtocol |
| 24 | + """) { |
| 25 | + |
| 26 | + for child in trait.children { |
| 27 | + VariableDeclSyntax("var \(raw: child.swiftName): \(raw: child.typeName)\(raw: child.isOptional ? "?" : "") { get }") |
| 28 | + FunctionDeclSyntax("func with\(raw: child.name)(_ newChild: \(raw: child.typeName)?) -> Self") |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + ExtensionDecl("public extension SyntaxProtocol") { |
| 33 | + FunctionDeclSyntax(""" |
| 34 | + /// Check whether the non-type erased version of this syntax node conforms to |
| 35 | + /// `\(raw: trait.traitName)Syntax`. |
| 36 | + /// Note that this will incur an existential conversion. |
| 37 | + func isProtocol(_: \(raw: trait.traitName)Syntax.Protocol) -> Bool { |
| 38 | + return self.asProtocol(\(raw: trait.traitName)Syntax.self) != nil |
| 39 | + } |
| 40 | + """) |
| 41 | + |
| 42 | + FunctionDeclSyntax(""" |
| 43 | + /// Return the non-type erased version of this syntax node if it conforms to |
| 44 | + /// `\(raw: trait.traitName)Syntax`. Otherwise return `nil`. |
| 45 | + /// Note that this will incur an existential conversion. |
| 46 | + func asProtocol(_: \(raw: trait.traitName)Syntax.Protocol) -> \(raw: trait.traitName)Syntax? { |
| 47 | + return Syntax(self).asProtocol(SyntaxProtocol.self) as? \(raw: trait.traitName)Syntax |
| 48 | + } |
| 49 | + """) |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + for node in SYNTAX_NODES where !node.isBase && !node.traits.isEmpty { |
| 54 | + ExtensionDeclSyntax("extension \(raw: node.name): \(raw: node.traits.map { $0 + "Syntax" }.joined(separator: ", ")) {}") |
| 55 | + } |
| 56 | +} |
0 commit comments