-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatementsCache.scala
More file actions
534 lines (463 loc) · 17.7 KB
/
StatementsCache.scala
File metadata and controls
534 lines (463 loc) · 17.7 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package org.encalmo.utils
import scala.quoted.*
import org.encalmo.utils.StatementsCache.Scope
/** A cache for statements and symbols. It can be nested to create a hierarchy of caches. Captures Quotes context.
*/
class StatementsCache(val cacheId: String = "default")(implicit val quotes: Quotes) {
import quotes.reflect.*
private val statements: collection.mutable.ListBuffer[Statement] =
collection.mutable.ListBuffer.empty
protected val index: collection.mutable.Map[String, Ref] =
collection.mutable.Map.empty
protected val symbols: collection.mutable.Map[String, Symbol] =
collection.mutable.Map.empty
/** Lookup a method or value by name. */
def lookupStatement(name: String): Option[Statement] = {
index.get(name)
}
/** Lookup a symbol by name. */
def lookupSymbol(name: String): Option[quotes.reflect.Symbol] = {
symbols.get(name)
}
/** Add method or value definition to statements list and index reference to the definition by provided name */
protected def declare(
scope: StatementsCache.Scope,
name: String,
definition: Any,
reference: Any
): Unit = {
index.put(name, reference.asInstanceOf[quotes.reflect.Ref])
put(definition.asInstanceOf[quotes.reflect.ValOrDefDef])
}
/** Create a nested statements cache that fallbacks to lookup in the outer cache if statement or symbol is not found
* in the nested cache. Lists of statements stay separated.
*/
def createNestedScope(cacheId: String = "nested"): StatementsCache = {
val outer = this
new StatementsCache(outer.cacheId + " > " + cacheId)(using outer.quotes) {
/** Lookup a method or value by name in the nested cache or the outer caches. */
override def lookupStatement(name: String): Option[quotes.reflect.Statement] = {
this.index
.get(name)
.orElse(outer.lookupStatement(name).map(_.asInstanceOf[quotes.reflect.Statement]))
}
/** Lookup a symbol by name in the nested cache or the outer caches. */
override def lookupSymbol(name: String): Option[quotes.reflect.Symbol] = {
this.symbols
.get(name)
.orElse(outer.lookupSymbol(name).map(_.asInstanceOf[quotes.reflect.Symbol]))
}
override def declare(
scope: StatementsCache.Scope,
name: String,
definition: Any,
reference: Any
): Unit = {
scope match {
case StatementsCache.Scope.Local =>
this.index.put(name, reference.asInstanceOf[quotes.reflect.Ref])
this.put(definition.asInstanceOf[quotes.reflect.ValOrDefDef])
case StatementsCache.Scope.TopLevel =>
outer.declare(
scope,
name,
definition.asInstanceOf[outer.quotes.reflect.ValOrDefDef],
reference.asInstanceOf[outer.quotes.reflect.Term]
)
case StatementsCache.Scope.Outer =>
outer.declare(
StatementsCache.Scope.Local,
name,
definition.asInstanceOf[outer.quotes.reflect.ValOrDefDef],
reference.asInstanceOf[outer.quotes.reflect.Term]
)
}
}
}
}
/** Lookup named method call of type Unit and add to the statements list, otherwise abort with an error. */
def putMethodCall(methodName: String, parameters: List[Term]): Unit = {
lookupStatement(methodName) match {
case Some(methodRef) =>
put(methodRef.asInstanceOf[quotes.reflect.Ref].appliedToArgs(parameters))
case None =>
report.errorAndAbort("[" + cacheId + s"] Method call '$methodName' not found in statements cache")
}
}
/** Lookup or create a new method of type T and return the method call, if any */
def createMethodOf[T: Type](
methodName: String,
parameterNames: List[String],
parameterTypes: List[TypeRepr],
minMethodLinesCount: Int, // inline method body if it is smaller than this size
buildMethodBody: StatementsCache ?=> List[Tree] => Unit,
scope: StatementsCache.Scope = Scope.Local
): Either[Boolean, quotes.reflect.Ref] = {
lookupStatement(methodName) match {
case Some(methodRef) =>
Right(methodRef.asInstanceOf[quotes.reflect.Ref])
case None => {
if (parameterNames.length != parameterTypes.length)
then report.errorAndAbort("Parameter names and types must have the same length for method " + methodName)
val methodType = MethodType(parameterNames)(
(_: MethodType) => parameterTypes, // Argument types
(_: MethodType) => TypeRepr.of[T] // Return type
)
val methodSymbol: Symbol =
Symbol.newMethod(
Symbol.spliceOwner,
methodName,
methodType,
Flags.EmptyFlags,
Symbol.noSymbol
)
val methodDef = DefDef(
methodSymbol,
{
case List(argSymbols) =>
{
val nested = createNestedScope(
"createMethodOf[" + TypeRepr.of[T].show(using Printer.TypeReprShortCode) + "]:" + methodName
)
buildMethodBody(using nested)(argSymbols.map(_.asInstanceOf[quotes.reflect.Tree]))
if nested.statements.isEmpty
then None
else {
if (
TypeRepr.of[T] <:< TypeRepr.of[Unit]
&& !(nested.typeRepr <:< nested.quotes.reflect.TypeRepr.of[Unit])
)
then nested.put(nested.unit)
Some(nested.asTerm.asInstanceOf[Term])
}
}.map(_.changeOwner(methodSymbol))
case other =>
report.errorAndAbort("Unexpected parameter structure " + other + " for method " + methodName)
}
)
methodDef.rhs.match {
case None => Left(false)
case Some(rhs) =>
val exceedsMinMethodLinesCount = {
val code = rhs.show(using Printer.TreeCode)
val it = code.linesIterator
scala.util.boundary {
var count = 0
while (it.hasNext) {
it.next()
count += 1
if count >= minMethodLinesCount then {
scala.util.boundary.break(true)
}
}
false
}
}
if exceedsMinMethodLinesCount
then {
val methodRef = Ref(methodSymbol)
declare(scope, methodName, methodDef, methodRef)
Right(methodRef)
} else Left(true)
}
}
}
}
def inlineMethodBody(parameters: List[Term], buildMethodBody: StatementsCache ?=> List[Tree] => Unit): Unit = {
val nested = createNestedScope("inlineMethodBody")
buildMethodBody(using nested)(parameters)
put(nested.asTerm.asInstanceOf[Term])
}
/** Lookup or create a new method of type T and add the method call to the statements list */
def putMethodCallOf[T: Type](
methodName: String,
parameterNames: List[String],
parameterTypes: List[TypeRepr],
parameters: List[Term],
minMethodLinesCount: Int,
buildMethodBody: StatementsCache ?=> List[Tree] => Unit,
scope: StatementsCache.Scope
): Unit = {
if (parameters.length != parameterNames.length)
then report.errorAndAbort("Parameter lists must have the same length for method " + methodName)
createMethodOf[T](methodName, parameterNames, parameterTypes, minMethodLinesCount, buildMethodBody, scope).match {
case Right(methodRef) => put(methodRef.appliedToArgs(parameters))
case Left(nonEmpty) =>
if nonEmpty then inlineMethodBody(parameters, buildMethodBody)
}
}
/** Lookup or create a new method of type T and add the method call to the statements list */
def putMethodCallOf[T: Type](
methodName: String,
parameterNames: List[String],
parameterTypes: List[TypeRepr],
parameters: List[Term],
buildMethodBody: StatementsCache ?=> List[Tree] => Unit,
scope: StatementsCache.Scope = Scope.Local
): Unit = putMethodCallOf[T](
methodName = methodName,
parameterNames = parameterNames,
parameterTypes = parameterTypes,
parameters = parameters,
minMethodLinesCount = 4,
buildMethodBody = buildMethodBody,
scope = scope
)
/** Lookup or create a new method of type T and add the method call to the statements list */
def putParamlessMethodCallOf[T: Type](
methodName: String,
minMethodLinesCount: Int,
buildMethodBody: StatementsCache ?=> Unit,
scope: StatementsCache.Scope
): Unit = {
createMethodOf[T](methodName, Nil, Nil, minMethodLinesCount, _ => buildMethodBody, scope).match {
case Right(methodRef) => put(methodRef.appliedToArgs(Nil))
case Left(nonEmpty) =>
if nonEmpty then inlineMethodBody(Nil, _ => buildMethodBody)
}
}
/** Lookup or create a new method of type T and add the method call to the statements list */
def putParamlessMethodCallOf[T: Type](
methodName: String,
buildMethodBody: StatementsCache ?=> Unit,
scope: StatementsCache.Scope = Scope.Local
): Unit =
putParamlessMethodCallOf[T](
methodName = methodName,
minMethodLinesCount = 4,
buildMethodBody = buildMethodBody,
scope = scope
)
/** Lookup value reference by name and return the reference, otherwise abort with an error. */
def getValueRef(valueName: String): quotes.reflect.Ref = {
lookupStatement(valueName) match {
case Some(valueRef) =>
valueRef.asInstanceOf[quotes.reflect.Ref]
case None =>
report.errorAndAbort("[" + cacheId + s"] Value ref '$valueName' not found in statements cache")
}
}
/** Lookup or create a new value reference of type T and add the value definition to the statements list, then return
* the value reference
*/
def getValueRefOfExpr[T: Type](
valueName: String,
valueBody: => Expr[T],
scope: StatementsCache.Scope = Scope.Local
): quotes.reflect.Ref = {
lookupStatement(valueName) match {
case Some(valueRef) =>
valueRef.asInstanceOf[quotes.reflect.Ref]
case None => {
val valueSymbol: Symbol =
Symbol.newVal(
Symbol.spliceOwner,
valueName,
TypeRepr.of[T],
Flags.EmptyFlags,
Symbol.noSymbol
)
val valueDef = ValDef(valueSymbol, Some(valueBody.asTerm))
val valueRef = Ref(valueSymbol)
declare(scope, valueName, valueDef, valueRef)
valueRef
}
}
}
/** Lookup or create a new value reference of type T and add the value definition to the statements list, then return
* the value reference
*/
def getValueRefOfTerm[T: Type](
valueName: String,
valueBody: => quotes.reflect.Term,
scope: StatementsCache.Scope = Scope.Local
): quotes.reflect.Ref = {
lookupStatement(valueName) match {
case Some(valueRef) =>
valueRef.asInstanceOf[quotes.reflect.Ref]
case None => {
val valueSymbol: Symbol =
Symbol.newVal(
Symbol.spliceOwner,
valueName,
TypeRepr.of[T],
Flags.EmptyFlags,
Symbol.noSymbol
)
val valueDef = ValDef(valueSymbol, Some(valueBody))
val valueRef = Ref(valueSymbol)
declare(scope, valueName, valueDef, valueRef)
valueRef
}
}
}
/** Lookup symbol by name and return the symbol, otherwise abort with an error. */
def getSymbol(symbolName: String): Symbol = {
lookupSymbol(symbolName) match {
case Some(symbol) => symbol
case None =>
report.errorAndAbort("[" + cacheId + s"] Symbol '$symbolName' not found in statements cache")
}
}
/** Lookup or create a new symbol and add it to the statements list, then return the symbol */
def getSymbol(symbolName: String, symbolBody: => Symbol): Symbol = {
lookupSymbol(symbolName) match {
case Some(symbol) => symbol
case None =>
val symbol = symbolBody
symbols.put(symbolName, symbol)
symbol
}
}
def unit: Literal = {
Literal(UnitConstant())
}
def stringLiteral(value: String): Literal = {
Literal(StringConstant(value))
}
def addUnitStatement(): Unit = {
put(unit)
}
def put(statement: Statement): Unit = {
this.statements.append(statement)
}
def putAll(statements: Iterable[Statement]): Unit = {
this.statements.appendAll(statements)
}
def toList: List[Statement] = {
statements.toList
}
def typeRepr: TypeRepr = {
statements.lastOption
.map {
case term: Term => term.tpe
case statement => TypeRepr.of[Unit]
}
.getOrElse(TypeRepr.of[Unit])
}
/** Convert the statements list to a term, otherwise abort with an error. */
def asTerm: Term = {
if statements.isEmpty
then unit
else if statements.size == 1
then
statements.head match {
case term: Term => term
case statement => Block(statements.toList, unit)
}
else
statements.last match {
case term: Term => Block(statements.init.toList, term)
case statement => Block(statements.toList, unit)
}
}
/** Convert the statements list to a term of the outer cache type, otherwise abort with an error. */
def asTermOf(outer: StatementsCache): outer.quotes.reflect.Term = {
asTerm.asInstanceOf[outer.quotes.reflect.Term]
}
def asExprOfUnit: Expr[Unit] = {
Block(statements.toList, unit).asExprOf[Unit]
}
def asExprOf[T: Type]: Expr[T] = {
if statements.isEmpty
then
report.errorAndAbort(
"[" + cacheId + "] No statements to get block expression of type " + TypeRepr
.of[T]
.show(using Printer.TypeReprShortCode)
)
else if statements.size == 1
then
statements.head match {
case term: Term if term.tpe =:= TypeRepr.of[T] || term.tpe <:< TypeRepr.of[T] => term.asExprOf[T]
case term: Term =>
report.errorAndAbort(
"[" + cacheId + "] Expected first statement to be a term of type " + TypeRepr
.of[T]
.show(using Printer.TypeReprShortCode) + " but got: " + term.tpe.show(using Printer.TypeReprShortCode)
)
case statement =>
report.errorAndAbort(
"[" + cacheId + "] Expected first statement to be a term but got: " + statement.show(using Printer.TreeCode)
)
}
else
statements.last match {
case term: Term if term.tpe =:= TypeRepr.of[T] || term.tpe <:< TypeRepr.of[T] =>
Block(statements.init.toList, term).asExprOf[T]
case term: Term =>
report.errorAndAbort(
"[" + cacheId + "] Expected last statement to be a term of type " + TypeRepr
.of[T]
.show(using Printer.TypeReprShortCode) + " but got: " + term.tpe.show(using Printer.TypeReprShortCode)
)
case statement =>
report.errorAndAbort(
"[" + cacheId + "] Expected last statement to be a term but got: " + statement.show(using Printer.TreeCode)
)
}
}
def asExprOf[T: Type](returnExpr: Expr[T]): Expr[T] = {
Block(statements.toList, returnExpr.asTerm).asExprOf[T]
}
}
object StatementsCache {
enum Scope {
case TopLevel
case Outer
case Local
}
def block(using outer: StatementsCache)(buildBlock: StatementsCache ?=> Unit): outer.quotes.reflect.Term = {
val nested = outer.createNestedScope("block")
given nested.quotes.type = nested.quotes
buildBlock(using nested)
nested.asTerm.asInstanceOf[outer.quotes.reflect.Term]
}
def put(using cache: StatementsCache)(statement: cache.quotes.reflect.Statement): Unit = {
cache.put(statement)
}
def unit(using cache: StatementsCache): cache.quotes.reflect.Literal = {
cache.unit
}
def stringLiteral(using cache: StatementsCache)(value: String): cache.quotes.reflect.Literal = {
cache.stringLiteral(value)
}
extension (using cache: StatementsCache)(term: cache.quotes.reflect.Term) {
inline def applyToString: cache.quotes.reflect.Term =
StringUtils.applyToString(using cache)(term)
inline def methodCall(
methodName: String,
args: List[cache.quotes.reflect.Term],
moreArgs: List[cache.quotes.reflect.Term]*
): cache.quotes.reflect.Term =
MethodUtils.methodCall(term, methodName, args, moreArgs*)
inline def maybeMethodCall(
methodName: String,
args: List[cache.quotes.reflect.Term],
moreArgs: List[cache.quotes.reflect.Term]*
): Option[cache.quotes.reflect.Term] =
MethodUtils.maybeMethodCall(term, methodName, args, moreArgs*)
inline def callAsInstanceOf[T: Type]: cache.quotes.reflect.Term =
import cache.quotes.reflect.*
val asInstanceOfSym = defn.AnyClass.methodMember("asInstanceOf").head
TypeApply(
Select(term, asInstanceOfSym),
List(TypeTree.of[T])
)
inline def callAsInstanceOf(typeTree: cache.quotes.reflect.TypeTree): cache.quotes.reflect.Term =
import cache.quotes.reflect.*
val asInstanceOfSym = defn.AnyClass.methodMember("asInstanceOf").head
TypeApply(
Select(term, asInstanceOfSym),
List(typeTree)
)
}
extension (term: Any) {
inline def toTermOf(other: StatementsCache): other.quotes.reflect.Term =
term.asInstanceOf[other.quotes.reflect.Term]
inline def toTerm(using nested: StatementsCache): nested.quotes.reflect.Term =
term.asInstanceOf[nested.quotes.reflect.Term]
inline def toTypeRepr(using nested: StatementsCache): nested.quotes.reflect.TypeRepr =
term.asInstanceOf[nested.quotes.reflect.TypeRepr]
}
}