-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathMacroExpansionContext.swift
189 lines (168 loc) · 6.49 KB
/
MacroExpansionContext.swift
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
188
189
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if compiler(>=6)
public import SwiftDiagnostics
public import SwiftSyntax
import SwiftSyntaxBuilder
#else
import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxBuilder
#endif
/// Interface to extract information about the context in which a given
/// macro is expanded.
public protocol MacroExpansionContext: AnyObject {
/// Generate a unique name for use in the macro.
///
/// - Parameters:
/// - name: The name to use as a basis for the uniquely-generated name,
/// which will appear in the unique name that's produced here.
///
/// - Returns: an identifier token containing a unique name that will not
/// conflict with any other name in a well-formed program.
func makeUniqueName(_ name: String) -> TokenSyntax
/// Produce a diagnostic while expanding the macro.
func diagnose(_ diagnostic: Diagnostic)
/// Retrieve a source location for the given syntax node.
///
/// - Parameters:
/// - node: The syntax node whose source location to produce.
/// - position: The position within the syntax node for the resulting
/// location.
/// - filePathMode: How the file name contained in the source location is
/// formed.
///
/// - Returns: the source location within the given node, or `nil` if the
/// given syntax node is not rooted in a source file that the macro
/// expansion context knows about.
func location(
of node: some SyntaxProtocol,
at position: PositionInSyntaxNode,
filePathMode: SourceLocationFilePathMode
) -> AbstractSourceLocation?
/// Return an array of enclosing lexical contexts for the purpose of macros,
/// starting from the syntax node at which the macro expansion occurs
/// and containing all "context" nodes including functions, closures, types,
/// properties, subscripts, and extensions.
///
/// Lexical contexts will have many of their details stripped out to prevent
/// macros from having visibility into unrelated code. For example, functions
/// and closures have their bodies removed, types and extensions have their
/// member lists emptied, and properties and subscripts have their accessor
/// blocks removed.
///
/// The first entry in the array is the innermost context. For attached
/// macros, this is often the declaration to which the macro is attached.
/// This array can be empty if there is no context, for example when a
/// freestanding macro is used at file scope.
var lexicalContext: [Syntax] { get }
}
extension MacroExpansionContext {
/// Retrieve a source location for the given syntax node's starting token
/// (after leading trivia) using file naming according to `#fileID`.
///
/// - Parameters:
/// - node: The syntax node whose source location to produce.
///
/// - Returns: the source location within the given node, or `nil` if the
/// given syntax node is not rooted in a source file that the macro
/// expansion context knows about.
public func location(
of node: some SyntaxProtocol
) -> AbstractSourceLocation? {
return location(of: node, at: .afterLeadingTrivia, filePathMode: .fileID)
}
#if compiler(>=6.0)
@available(*, deprecated, message: "`MacroExpansionContext` conformance must implement `lexicalContext`")
public var lexicalContext: [Syntax] {
return []
}
#else
public var lexicalContext: [Syntax] {
fatalError(
"`MacroExpansionContext` conformance must implement `lexicalContext`"
)
}
#endif
}
private enum MacroExpansionContextError: DiagnosticMessage {
case internalError(SyntaxStringInterpolationInvalidNodeTypeError)
case missingError
var message: String {
switch self {
case .internalError(let error):
return "Internal macro error: \(error.description)"
case .missingError:
return "macro expansion failed without generating an error"
}
}
var severity: DiagnosticSeverity { .error }
var diagnosticID: MessageID {
.init(domain: "SwiftDiagnostics", id: "MacroExpansionContextError")
}
}
extension MacroExpansionContext {
/// Adds diagnostics from the error thrown during a macro expansion.
public func addDiagnostics(from error: Error, node: some SyntaxProtocol) {
// Inspect the error to form an appropriate set of diagnostics.
var diagnostics: [Diagnostic]
if let error = error as? SyntaxStringInterpolationInvalidNodeTypeError {
let diagnostic = Diagnostic(
node: Syntax(node),
message: MacroExpansionContextError.internalError(error)
)
diagnostics = [diagnostic]
} else {
diagnostics = error.asDiagnostics(at: node)
}
// Emit the diagnostics.
for diagnostic in diagnostics {
diagnose(diagnostic)
}
// Handle possibility that none of the diagnostics was an error.
if !diagnostics.contains(
where: { $0.diagMessage.severity == .error }
) {
diagnose(
Diagnostic(
node: Syntax(node),
message: MacroExpansionContextError.missingError
)
)
}
}
}
/// Describe the position within a syntax node that can be used to compute
/// source locations.
public enum PositionInSyntaxNode {
/// Refers to the start of the syntax node's leading trivia, which is
/// the first source location covered by the syntax node.
case beforeLeadingTrivia
/// Refers to the start of the syntax node's first token, which
/// immediately follows the leading trivia.
case afterLeadingTrivia
/// Refers to the end of the syntax node's last token, right before the
/// trailing trivia.
case beforeTrailingTrivia
/// Refers just past the end of the source text that is covered by the
/// syntax node, after all trailing trivia.
case afterTrailingTrivia
}
/// Describes the source location file path
public enum SourceLocationFilePathMode {
/// A file ID consisting of the module name and file name (without full path),
/// as would be generated by the macro expansion `#fileID`.
case fileID
/// A full path name as would be generated by the macro expansion `#filePath`,
/// e.g., `/home/taylor/alison.swift`.
case filePath
}