@@ -202,12 +202,66 @@ struct ImageLiteralMacro: ExpressionMacro {
202
202
}
203
203
}
204
204
205
+ struct FilePathMacro : ExpressionMacro {
206
+ static var name : String { " filePath " }
207
+
208
+ static func apply(
209
+ _ macro: MacroExpansionExprSyntax , in context: MacroEvaluationContext
210
+ ) -> MacroResult < ExprSyntax > {
211
+ let fileName = context. sourceLocationConverter. location (
212
+ for: . init( utf8Offset: 0 )
213
+ ) . file ?? " <unknown file> "
214
+ let fileLiteral : ExprSyntax = #"" \#( fileName) ""#
215
+ if let leadingTrivia = macro. leadingTrivia {
216
+ return MacroResult ( fileLiteral. withLeadingTrivia ( leadingTrivia) )
217
+ }
218
+ return MacroResult ( fileLiteral)
219
+ }
220
+ }
221
+
222
+ struct FileIDMacro : ExpressionMacro {
223
+ static var name : String { " fileID " }
224
+
225
+ static func apply(
226
+ _ macro: MacroExpansionExprSyntax , in context: MacroEvaluationContext
227
+ ) -> MacroResult < ExprSyntax > {
228
+ var fileName = context. sourceLocationConverter. location (
229
+ for: . init( utf8Offset: 0 )
230
+ ) . file ?? " <unknown file> "
231
+
232
+ // Only keep everything after the last slash.
233
+ if let lastSlash = fileName. lastIndex ( of: " / " ) {
234
+ fileName = String ( fileName [ fileName. index ( after: lastSlash) ... ] )
235
+ }
236
+
237
+ let fileLiteral : ExprSyntax = #"" \#( context. moduleName) / \#( fileName) ""#
238
+ if let leadingTrivia = macro. leadingTrivia {
239
+ return MacroResult ( fileLiteral. withLeadingTrivia ( leadingTrivia) )
240
+ }
241
+ return MacroResult ( fileLiteral)
242
+ }
243
+ }
244
+
245
+ struct FileMacro : ExpressionMacro {
246
+ static var name : String { " file " }
247
+
248
+ static func apply(
249
+ _ macro: MacroExpansionExprSyntax , in context: MacroEvaluationContext
250
+ ) -> MacroResult < ExprSyntax > {
251
+ // FIXME: Macro evaluation context needs to know the semantics of #file,
252
+ // which is a feature check.
253
+ return FilePathMacro . apply ( macro, in: context)
254
+ }
255
+ }
256
+
205
257
extension MacroSystem {
206
258
public static var exampleSystem : MacroSystem {
207
259
var macroSystem = MacroSystem ( )
208
260
try ! macroSystem. add ( ColorLiteralMacro . self)
209
261
try ! macroSystem. add ( ColumnMacro . self)
262
+ try ! macroSystem. add ( FileIDMacro . self)
210
263
try ! macroSystem. add ( FileLiteralMacro . self)
264
+ try ! macroSystem. add ( FilePathMacro . self)
211
265
try ! macroSystem. add ( FunctionMacro . self)
212
266
try ! macroSystem. add ( ImageLiteralMacro . self)
213
267
try ! macroSystem. add ( LineMacro . self)
0 commit comments