-
Notifications
You must be signed in to change notification settings - Fork 1
/
PlatformProductCaseGeneration.scala
365 lines (318 loc) · 15.3 KB
/
PlatformProductCaseGeneration.scala
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
package pipez.internal
import pipez.internal.Definitions.{ Context, Result }
import pipez.internal.ProductCaseGeneration.inputNameMatchesOutputName
import scala.collection.immutable.ListMap
import scala.util.chaining.*
import scala.quoted.{ Type as _, * }
private[internal] trait PlatformProductCaseGeneration[Pipe[_, _], In, Out]
extends ProductCaseGeneration[Pipe, In, Out] {
self: PlatformDefinitions[Pipe, In, Out] & PlatformGenerators[Pipe, In, Out] =>
import quotes.*
import quotes.reflect.*
final def isTuple[A: Type]: Boolean =
TypeRepr.of[A].typeSymbol.fullName.startsWith("scala.Tuple")
final def isCaseClass[A: Type]: Boolean =
val sym = TypeRepr.of[A].typeSymbol
sym.isClassDef && sym.flags.is(Flags.Case) && !sym.flags.is(Flags.Abstract) && isPublic(sym.primaryConstructor)
final def isCaseObject[A: Type]: Boolean =
val sym = TypeRepr.of[A].typeSymbol
def isScala2Enum = sym.flags.is(Flags.Case | Flags.Module)
def isScala3Enum = sym.flags.is(Flags.Case | Flags.Enum | Flags.JavaStatic)
(isScala2Enum || isScala3Enum) && isPublic(sym)
final def isJavaBean[A: Type]: Boolean =
val sym = TypeRepr.of[A].typeSymbol
sym.isClassDef && !sym.flags.is(Flags.Abstract) && sym.declarations.exists(
isDefaultConstructor
) && (sym.declaredMethods.exists(isJavaSetter) || sym.declaredMethods.exists(isVar))
private def isPublic(sym: Symbol): Boolean =
!sym.flags.is(Flags.Private) && !sym.flags.is(Flags.PrivateLocal) && !sym.flags.is(Flags.Protected)
private def isDefaultConstructor(ctor: Symbol): Boolean =
ctor.isClassConstructor && ctor.paramSymss.filterNot(_.exists(_.isType)).flatten.isEmpty && isPublic(ctor)
private def isJavaGetter(getter: Symbol): Boolean =
ProductCaseGeneration.isGetterName(getter.name) && getter.paramSymss.flatten.isEmpty && isPublic(getter)
private def isJavaSetter(setter: Symbol): Boolean =
ProductCaseGeneration.isSetterName(setter.name) && setter.paramSymss.flatten.size == 1 && isPublic(setter)
private def isVar(setter: Symbol): Boolean =
setter.isValDef && setter.flags.is(Flags.Mutable)
final private case class Getter[Extracted, ExtractedField](
tpe: Type[ExtractedField],
get: Expr[Extracted] => Expr[ExtractedField]
)
private def extractGetters[Extracted: Type]: ListMap[String, Getter[Extracted, Any]] = {
val sym = TypeRepr.of[Extracted].typeSymbol
// apparently each case field is duplicated: "a" and "a ", "_1" and "_1" o_0 - the first is method, the other val
// the exceptions are cases in Scala 3 enum: they only have vals
(sym.caseFields.filter(if (sym.flags.is(Flags.Enum)) _.isValDef else _.isDefDef) ++ sym.declaredMethods.filter(
isJavaGetter
)).map { method =>
val name = method.name
name -> Getter[Extracted, Any](
tpe = returnType[Any](TypeRepr.of[In].memberType(method)),
get =
if (method.paramSymss.isEmpty) (in: Expr[Extracted]) => in.asTerm.select(method).appliedToArgss(Nil).asExpr
else (in: Expr[Extracted]) => in.asTerm.select(method).appliedToNone.asExpr
)
}.to(ListMap)
}
final def extractProductInData(settings: Settings): DerivationResult[ProductInData] =
extractGetters[In]
.map { case (name, Getter(tpe, get)) =>
name -> ProductInData.Getter(name, tpe, get, Path.Field(Path.Root, name))
}
.pipe(ProductInData(_))
.pipe(DerivationResult.pure)
.logSuccess(data => s"Resolved input: $data")
private def fallbackValueGetters(settings: Settings): Map[String, FieldFallback[?]] =
settings.fallbackValues
.collect { case ConfigEntry.AddFallbackValue(fallbackType, fallbackValue) =>
extractGetters(fallbackType).map { case (name, Getter(fallbackFieldType, extractFallbackValue)) =>
name -> FieldFallback.Value(fallbackFieldType, extractFallbackValue(fallbackValue))
}
}
.fold(Map.empty[String, FieldFallback[?]])((left, right) => right ++ left) // preserve first rather than last
final def extractProductOutData(settings: Settings): DerivationResult[ProductOutData] =
if (isJavaBean[Out]) {
// Java Bean case
val sym = TypeRepr.of[Out].typeSymbol
val defaultConstructor = DerivationResult.fromOption(
sym.declarations.find(isDefaultConstructor).map { ctor =>
ctor.paramSymss match {
// new Bean[...]
case typeArgs :: Nil if typeArgs.exists(_.isType) =>
New(TypeTree.of[Out])
.select(ctor)
.appliedToTypes(TypeRepr.of[Out].typeArgs)
.appliedToArgss(Nil)
.asExpr
.asExprOf[Out]
// new Bean[...]()
case typeArgs :: Nil :: Nil if typeArgs.exists(_.isType) =>
New(TypeTree.of[Out])
.select(ctor)
.appliedToTypes(TypeRepr.of[Out].typeArgs)
.appliedToNone
.asExpr
.asExprOf[Out]
// new Bean
case Nil =>
New(TypeTree.of[Out]).select(ctor).appliedToArgss(Nil).asExpr.asExprOf[Out]
// new Bean()
case Nil :: Nil =>
New(TypeTree.of[Out]).select(ctor).appliedToNone.asExpr.asExprOf[Out]
case _ =>
??? // should never happen due to isDefaultConstructor filtering
}
}
)(DerivationError.MissingPublicConstructor)
val fallbackValues = fallbackValueGetters(settings)
val setters = sym.declaredMethods
.filter(s => isJavaSetter(s) || isVar(s))
.map { setter =>
val name = setter.name
name -> ProductOutData.Setter[Any](
name = name,
tpe = {
val MethodType(_, List(tpe), _) = TypeRepr.of[Out].memberType(setter): @unchecked
tpe.asType.asInstanceOf[Type[Any]]
},
set = (out: Expr[Out], value: Expr[Any]) =>
out.asTerm.select(setter).appliedTo(value.asTerm).asExpr.asExprOf[Unit],
fallback = fallbackValues
.collectFirst {
case (fallbackName, fallback)
if inputNameMatchesOutputName(name, fallbackName, settings.isFieldCaseInsensitive) =>
fallback
}
.getOrElse(FieldFallback.Unavailable)
)
}
.to(ListMap)
.pipe(DerivationResult.pure(_))
defaultConstructor
.map2(setters)(ProductOutData.JavaBean(_, _))
.logSuccess(data => s"Resolved Java Bean output: $data")
} else if (isCaseObject[Out]) {
// case object case
val sym = TypeRepr.of[Out].typeSymbol
ProductOutData
.CaseClass(
if (sym.flags.is(Flags.Case | Flags.Enum | Flags.JavaStatic)) {
// Scala 3 case object (enum's case without parameters)
params => Ref(sym).asExpr.asExprOf[Out]
} else {
// Scala 2 case object
params => Ref(sym.companionModule).asExpr.asExprOf[Out]
},
List.empty
)
.pipe(DerivationResult.pure(_))
.logSuccess(data => s"Resolved case object output: $data")
} else {
// case class case
(for {
primaryConstructor <- DerivationResult.fromOption(
Option(TypeRepr.of[Out].typeSymbol.primaryConstructor).filter(s => !s.isNoSymbol)
)(DerivationError.MissingPublicConstructor)
pair <- resolveTypeArgsForMethodArguments(TypeRepr.of[Out], primaryConstructor)
(typeByName, typeParams) = pair
// default value for case class field n (1 indexed) is obtained from Companion.apply$default$n
fallbackValues = primaryConstructor.paramSymss
.pipe(if (typeParams.nonEmpty) ps => ps.tail else ps => ps)
.headOption
.toList
.flatten
.zipWithIndex
.collect {
case (param, idx) if param.flags.is(Flags.HasDefault) =>
val mod = TypeRepr.of[Out].typeSymbol.companionModule
val sym = mod.declaredMethod("apply$default$" + (idx + 1)).head
param.name -> FieldFallback.Default(Ref(mod).select(sym).asExpr.asInstanceOf[Expr[Any]])
}
.toMap ++ fallbackValueGetters(settings) // we want defaults to be overridden by provided values
} yield ProductOutData.CaseClass(
params =>
New(TypeTree.of[Out])
.select(primaryConstructor)
.pipe(if (typeParams.nonEmpty) tree => tree.appliedToTypes(typeParams) else tree => tree)
.appliedToArgss(params.map(_.map(_.asTerm)))
.asExpr
.asExprOf[Out],
primaryConstructor.paramSymss.pipe(if (typeParams.nonEmpty) ps => ps.tail else ps => ps).map { params =>
params
.map { param =>
val name = param.name
param.name -> ProductOutData.ConstructorParam(
name = name,
tpe = typeByName(name).asType.asInstanceOf[Type[Any]],
fallback = fallbackValues
.collectFirst {
case (fallbackName, fallback)
if inputNameMatchesOutputName(name, fallbackName, settings.isFieldCaseInsensitive) =>
fallback
}
.getOrElse(FieldFallback.Unavailable)
)
}
.to(ListMap)
}
)).logSuccess(data => s"Resolved case class output: $data")
}
final def generateProductCode(generatorData: ProductGeneratorData): DerivationResult[Expr[Pipe[In, Out]]] =
generatorData match {
case ProductGeneratorData.CaseClass(constructor, results) => generateCaseClass(constructor, results)
case ProductGeneratorData.JavaBean(defaultConstructor, results) => generateJavaBean(defaultConstructor, results)
}
private def generateCaseClass(
constructor: Constructor,
outputParameterLists: List[List[ProductGeneratorData.OutputValue]]
): DerivationResult[Expr[Pipe[In, Out]]] = {
val paramToIdx: Map[ProductGeneratorData.OutputValue.Result[?], Expr[Int]] = outputParameterLists.flatten
.collect { case result: ProductGeneratorData.OutputValue.Result[?] => result }
.zipWithIndex
.map { case (result, idx) => result -> Literal(IntConstant(idx)).asExpr.asExprOf[Int] }
.toMap
def constructorParams(in: Expr[In], ctx: Expr[Context], arr: Expr[Array[Any]]): List[List[Expr[?]]] =
outputParameterLists.map(
_.map {
case ProductGeneratorData.OutputValue.Pure(_, caller) =>
caller(in, ctx)
case r @ ProductGeneratorData.OutputValue.Result(tpe, _) =>
implicit val tpee: Type[Any] = tpe.asInstanceOf[Type[Any]]
'{ $arr(${ paramToIdx(r) }).asInstanceOf[tpee.Underlying] }
}
)
val arrSize = Literal(IntConstant(paramToIdx.size)).asExpr.asExprOf[Int]
val initialValue: Expr[Result[Array[Any]]] = pureResult('{ scala.Array.ofDim[scala.Any]($arrSize) })
@scala.annotation.tailrec
def generateBody(
in: Expr[In],
ctx: Expr[Context],
arrayResult: Expr[Result[Array[Any]]],
params: List[(ProductGeneratorData.OutputValue.Result[?], Expr[Int])]
): Expr[Result[Out]] =
params match {
// all values are taken directly from input and wrapped in Result
case Nil =>
pureResult(constructor(constructorParams(in, ctx, null)))
// last param - after adding the last value to array we extract all values from it into constructor
case (param, idx) :: Nil =>
val rightCode = param.caller(in, ctx).asInstanceOf[Expr[Result[Any]]]
implicit val rightType: Type[Any] = param.tpe.asInstanceOf[Type[Any]]
val fun: Expr[(Array[Any], Any) => Out] =
'{ (left: Array[Any], right: rightType.Underlying) =>
left($idx) = right
${ constructor(constructorParams(in, ctx, '{ left })) }
}
mergeResults[Array[Any], Any, Out](ctx, arrayResult, rightCode, fun)
// we combine Array's Result with a param's Result, store param in array and iterate further
case (param, idx) :: tail =>
val rightCode = param.caller(in, ctx).asInstanceOf[Expr[Result[Any]]]
implicit val rightType: Type[Any] = param.tpe.asInstanceOf[Type[Any]]
val fun: Expr[(Array[Any], Any) => Array[Any]] =
'{ (left: Array[Any], right: rightType.Underlying) =>
left($idx) = right
left
}
generateBody(in, ctx, mergeResults[Array[Any], Any, Array[Any]](ctx, arrayResult, rightCode, fun), tail)
}
val body: Expr[Pipe[In, Out]] = lift[In, Out]('{ (in: In, ctx: Context) =>
${ generateBody('{ in }, '{ ctx }, initialValue, paramToIdx.toList) }
})
DerivationResult
.pure(body)
.log(s"Case class derivation, constructor params: $outputParameterLists")
.logSuccess(code => s"Generated code: ${previewCode(code)}")
}
private def generateJavaBean(
defaultConstructor: Expr[Out],
outputSettersList: List[(ProductGeneratorData.OutputValue, ProductOutData.Setter[?])]
): DerivationResult[Expr[Pipe[In, Out]]] = {
def pureValues(in: Expr[In], ctx: Expr[Context], result: Expr[Out]): List[Expr[Unit]] =
outputSettersList.collect { case (ProductGeneratorData.OutputValue.Pure(_, caller), setter) =>
setter.asInstanceOf[ProductOutData.Setter[Any]].set(result, caller(in, ctx).asInstanceOf[Expr[Unit]])
}
val resultValues: List[(ProductGeneratorData.OutputValue.Result[?], ProductOutData.Setter[?])] =
outputSettersList.collect { case (r: ProductGeneratorData.OutputValue.Result[?], s: ProductOutData.Setter[?]) =>
r -> s
}
def initialValue(in: Expr[In], ctx: Expr[Context]): Expr[Result[Out]] = pureResult(
'{
val result: Out = ${ defaultConstructor }
${ pureValues(in, ctx, '{ result }).fold[Expr[Unit]]('{ () })((a, b) => '{ ${ a }; ${ b } }) }
result
}
)
@scala.annotation.tailrec
def generateBody(
in: Expr[In],
ctx: Expr[Context],
outResult: Expr[Result[Out]],
params: List[(ProductGeneratorData.OutputValue.Result[?], ProductOutData.Setter[?])]
): Expr[Result[Out]] =
params match {
// all values are taken directly from input and wrapped in Result
case Nil =>
outResult
// we have Out object on left and value to put into setter on right
case (param, setter) :: tail =>
type Right
val rightCode = param.caller(in, ctx).asInstanceOf[Expr[Result[Right]]]
implicit val paramTpe: Type[Right] = param.tpe.asInstanceOf[Type[Right]]
val fun: Expr[(Out, Any) => Out] =
'{ (left: Out, right: paramTpe.Underlying) =>
${ setter.asInstanceOf[ProductOutData.Setter[Right]].set('{ left }, '{ right }) }
left
}.asInstanceOf[Expr[(Out, Any) => Out]]
generateBody(in, ctx, mergeResults(ctx, outResult, rightCode, fun), tail)
}
val body: Expr[Pipe[In, Out]] = lift[In, Out](
'{ (in: In, ctx: Context) =>
${ generateBody('{ in }, '{ ctx }, initialValue('{ in }, '{ ctx }), resultValues) }
}
)
DerivationResult
.pure(body)
.log(s"Java Beans derivation, setters: $outputSettersList")
.logSuccess(code => s"Generated code: ${previewCode(code)}")
}
}