-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
macro_definition.swift
83 lines (76 loc) · 2.73 KB
/
macro_definition.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
import _CompilerPluginSupport
struct StringifyMacro: _CompilerPlugin {
static func _name() -> (UnsafePointer<UInt8>, count: Int) {
var name = "customStringify"
return name.withUTF8 { buffer in
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: buffer.count)
result.initialize(from: buffer.baseAddress!, count: buffer.count)
return (UnsafePointer(result), count: buffer.count)
}
}
static func _genericSignature() -> (UnsafePointer<UInt8>?, count: Int) {
var genSig = "<T>"
return genSig.withUTF8 { buffer in
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: buffer.count)
result.initialize(from: buffer.baseAddress!, count: buffer.count)
return (UnsafePointer(result), count: buffer.count)
}
}
static func _typeSignature() -> (UnsafePointer<UInt8>, count: Int) {
var typeSig = "(T) -> (T, String)"
return typeSig.withUTF8 { buffer in
let result = UnsafeMutablePointer<UInt8>.allocate(capacity: buffer.count)
result.initialize(from: buffer.baseAddress!, count: buffer.count)
return (UnsafePointer(result), count: buffer.count)
}
}
static func _kind() -> _CompilerPluginKind {
.expressionMacro
}
static func _rewrite(
targetModuleName: UnsafePointer<UInt8>,
targetModuleNameCount: Int,
filePath: UnsafePointer<UInt8>,
filePathCount: Int,
sourceFileText: UnsafePointer<UInt8>,
sourceFileTextCount: Int,
localSourceText: UnsafePointer<UInt8>,
localSourceTextCount: Int
) -> (UnsafePointer<UInt8>?, count: Int) {
let meeTextBuffer = UnsafeBufferPointer(
start: localSourceText, count: localSourceTextCount)
let meeText = String(decoding: meeTextBuffer, as: UTF8.self)
let prefix = "#customStringify("
guard meeText.starts(with: prefix), meeText.last == ")" else {
return (nil, 0)
}
let expr = meeText.dropFirst(prefix.count).dropLast()
// Or use regex...
// let match = meeText.firstMatch {
// "#customStringify"
// ZeroOrMore {
// CharacterClass(.whitespace, .newlineSequence)
// }
// "("
// Capture(OneOrMore(.any))
// ")"
// ZeroOrMore {
// CharacterClass(.whitespace, .newlineSequence)
// }
// }
// guard let expr = match?.1 else {
// return (nil, count: 0)
// }
var resultString = "(\(expr), #\"\(expr)\"#)"
return resultString.withUTF8 { buffer in
let result = UnsafeMutableBufferPointer<UInt8>.allocate(
capacity: buffer.count + 1)
_ = result.initialize(from: buffer)
result[buffer.count] = 0
return (UnsafePointer(result.baseAddress), buffer.count)
}
}
}
public var allMacros: [Any.Type] {
[StringifyMacro.self]
}