forked from com-lihaoyi/sourcecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMacros.scala
More file actions
266 lines (222 loc) · 7.76 KB
/
Macros.scala
File metadata and controls
266 lines (222 loc) · 7.76 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package sourcecode
import scala.language.implicitConversions
import scala.quoted._
trait NameMacros {
inline implicit def generate: Name =
${ Macros.nameImpl }
}
trait NameMachineMacros {
inline implicit def generate: Name.Machine =
${ Macros.nameMachineImpl }
}
trait FullNameMacros {
inline implicit def generate: FullName =
${ Macros.fullNameImpl }
}
trait FullNameMachineMacros {
inline implicit def generate: FullName.Machine =
${ Macros.fullNameMachineImpl }
}
trait FileMacros {
inline implicit def generate: sourcecode.File =
${ Macros.fileImpl }
}
trait FileNameMacros {
inline implicit def generate: sourcecode.FileName =
${ Macros.fileNameImpl }
}
trait LineMacros {
inline implicit def generate: sourcecode.Line =
${ Macros.lineImpl }
}
trait EnclosingMacros {
inline implicit def generate: Enclosing =
${ Macros.enclosingImpl }
}
trait EnclosingMachineMacros {
inline implicit def generate: Enclosing.Machine =
${ Macros.enclosingMachineImpl }
}
trait PkgMacros {
inline implicit def generate: Pkg =
${ Macros.pkgImpl }
}
trait TextMacros {
inline implicit def generate[T](v: => T): Text[T] = ${ Macros.text('v) }
inline def apply[T](v: => T): Text[T] = ${ Macros.text('v) }
}
trait ArgsMacros {
inline implicit def generate: Args =
${ Macros.argsImpl }
}
object Util{
def isSynthetic(using Quotes)(s: quotes.reflect.Symbol) = isSyntheticName(getName(s))
def isSyntheticName(name: String) = {
name == "<init>" || (name.startsWith("<local ") && name.endsWith(">")) || name == "$anonfun" || name == "macro"
}
def getName(using Quotes)(s: quotes.reflect.Symbol) = {
s.name.trim
.stripSuffix("$") // meh
}
}
object Macros {
def findOwner(using Quotes)(owner: quotes.reflect.Symbol, skipIf: quotes.reflect.Symbol => Boolean): quotes.reflect.Symbol = {
var owner0 = owner
while(skipIf(owner0)) owner0 = owner0.owner
owner0
}
def actualOwner(using Quotes)(owner: quotes.reflect.Symbol): quotes.reflect.Symbol =
findOwner(owner, owner0 => Util.isSynthetic(owner0) || Util.getName(owner0) == "ev")
/**
* In Scala 3, macro `mcr()` is expanded to:
*
* val macro = ...
* macro
*
* Where n is an ordinal. This method returns the first owner that is not
* such a synthetic variable.
*/
def nonMacroOwner(using Quotes)(owner: quotes.reflect.Symbol): quotes.reflect.Symbol =
findOwner(owner, owner0 => { owner0.flags.is(quotes.reflect.Flags.Macro) && Util.getName(owner0) == "macro"})
def nameImpl(using Quotes): Expr[Name] = {
import quotes.reflect._
val owner = actualOwner(Symbol.spliceOwner)
val simpleName = Util.getName(owner)
'{Name(${Expr(simpleName)})}
}
private def adjustName(s: String): String =
// Required to get the same name from dotty
if (s.startsWith("<local ") && s.endsWith("$>"))
s.stripSuffix("$>") + ">"
else
s
def nameMachineImpl(using Quotes): Expr[Name.Machine] = {
import quotes.reflect._
val owner = nonMacroOwner(Symbol.spliceOwner)
val simpleName = adjustName(Util.getName(owner))
'{Name.Machine(${Expr(simpleName)})}
}
def fullNameImpl(using Quotes): Expr[FullName] = {
import quotes.reflect._
@annotation.tailrec def cleanChunk(chunk: String): String =
val refined = chunk.stripPrefix("_$").stripSuffix("$")
if chunk != refined then cleanChunk(refined) else refined
val owner = actualOwner(Symbol.spliceOwner)
val fullName =
owner.fullName.trim
.split("\\.", -1)
.filterNot(Util.isSyntheticName)
.map(cleanChunk)
.mkString(".")
'{FullName(${Expr(fullName)})}
}
def fullNameMachineImpl(using Quotes): Expr[FullName.Machine] = {
import quotes.reflect._
val owner = nonMacroOwner(Symbol.spliceOwner)
val fullName = owner.fullName.trim
.split("\\.", -1)
.map(_.stripPrefix("_$").stripSuffix("$")) // meh
.map(adjustName)
.mkString(".")
'{FullName.Machine(${Expr(fullName)})}
}
def fileImpl(using Quotes): Expr[sourcecode.File] = {
import quotes.reflect._
val file = quotes.reflect.Position.ofMacroExpansion.sourceFile.jpath.toAbsolutePath.toString
'{sourcecode.File(${Expr(file)})}
}
def fileNameImpl(using Quotes): Expr[sourcecode.FileName] = {
val name = quotes.reflect.Position.ofMacroExpansion.sourceFile.jpath.getFileName.toString
'{sourcecode.FileName(${Expr(name)})}
}
def lineImpl(using Quotes): Expr[sourcecode.Line] = {
val line = quotes.reflect.Position.ofMacroExpansion.startLine + 1
'{sourcecode.Line(${Expr(line)})}
}
def enclosingImpl(using Quotes): Expr[Enclosing] = {
import quotes.reflect._
val path = enclosing(machine = false)(!Util.isSynthetic(_))
'{Enclosing(${Expr(path)})}
}
def enclosingMachineImpl(using Quotes): Expr[Enclosing.Machine] = {
val path = enclosing(machine = true)(_ => true)
'{Enclosing.Machine(${Expr(path)})}
}
def pkgImpl(using Quotes): Expr[Pkg] = {
val path = enclosing(machine = false) {
case s if s.isPackageDef => true
case _ => false
}
'{Pkg(${Expr(path)})}
}
def argsImpl(using qctx: Quotes): Expr[Args] = {
import quotes.reflect._
val param: List[List[ValDef]] = {
def nearestEnclosingMethod(owner: Symbol): List[List[ValDef]] =
owner match {
case defSym if defSym.isDefDef =>
defSym.tree.asInstanceOf[DefDef].paramss
// FIXME Could be a List[TypeDef] too, although I'm not
// sure under which conditions this can happen…
.map(_.asInstanceOf[List[ValDef]])
case classSym if classSym.isClassDef =>
classSym.tree.asInstanceOf[ClassDef].constructor.paramss
// FIXME Could be a List[TypeDef] too, although I'm not
// sure under which conditions this can happen…
.map(_.asInstanceOf[List[ValDef]])
case _ =>
nearestEnclosingMethod(owner.owner)
}
nearestEnclosingMethod(Symbol.spliceOwner)
}
val texts0 = param.map(_.foldRight('{List.empty[Text[_]]}) {
case (vd @ ValDef(nme, _, optV), l) =>
'{Text(${optV.fold('None)(_.asExpr)}, ${Expr(nme)}) :: $l}
})
val texts = texts0.foldRight('{List.empty[List[Text[_]]]}) {
case (l, acc) =>
'{$l :: $acc}
}
'{Args($texts)}
}
def text[T: Type](v: Expr[T])(using Quotes): Expr[sourcecode.Text[T]] = {
import quotes.reflect._
val txt = v.asTerm.pos.sourceCode.get
'{sourcecode.Text[T]($v, ${Expr(txt)})}
}
sealed trait Chunk
object Chunk{
case class PkgObj(name: String) extends Chunk
case class ClsTrt(name: String) extends Chunk
case class ValVarLzyDef(name: String) extends Chunk
}
def enclosing(using Quotes)(machine: Boolean)(filter: quotes.reflect.Symbol => Boolean): String = {
import quotes.reflect._
var current = Symbol.spliceOwner
if (!machine)
current = actualOwner(current)
else
current = nonMacroOwner(current)
var path = List.empty[Chunk]
while(current != Symbol.noSymbol && current != defn.RootPackage && current != defn.RootClass){
if (filter(current)) {
val chunk = current match {
case sym if
sym.isValDef || sym.isDefDef => Chunk.ValVarLzyDef.apply
case sym if
sym.isPackageDef ||
sym.moduleClass != Symbol.noSymbol => Chunk.PkgObj.apply
case sym if sym.isClassDef => Chunk.ClsTrt.apply
case _ => Chunk.PkgObj.apply
}
path = chunk(Util.getName(current).stripSuffix("$")) :: path
}
current = current.owner
}
path.map{
case Chunk.PkgObj(s) => adjustName(s) + "."
case Chunk.ClsTrt(s) => adjustName(s) + "#"
case Chunk.ValVarLzyDef(s) => adjustName(s) + " "
}.mkString.dropRight(1)
}
}