-
Notifications
You must be signed in to change notification settings - Fork 3
/
Factory.scala
376 lines (355 loc) · 13.3 KB
/
Factory.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
366
367
368
369
370
371
372
373
374
375
376
package com.thoughtworks.feature
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
import com.thoughtworks.Extractor._
import scala.annotation.{StaticAnnotation, compileTimeOnly}
/** A factory to create new instances, especially dynamic mix-ins.
*
* @note The factory may contain abstract parameters of abstract types
*
* {{{
* trait Outer {
* trait AbstractParameterApi
* type AbstractParameter <: AbstractParameterApi
*
* trait InnerApi {
* def foo: AbstractParameter
* }
* type Inner <: InnerApi
* }
*
* new Outer {
* type Inner = InnerApi
* val innerFactory = Factory[Inner]
* }
* }}}
*
* @example Given a trait that contains an **implicit** abstract method annotated as [[Factory.inject @inject]].
*
* {{{
* import com.thoughtworks.feature.Factory.inject
* trait Foo[A] {
* @inject implicit def orderingA: Ordering[A]
* }
* }}}
*
* When creating a factory for the trait
*
* {{{
* val factory = Factory[Foo[Int]]
* }}}
*
* Then the `@inject` method will be replaced to an implicit value.
*
* {{{
* val foo = factory.newInstance()
* foo.orderingA should be(implicitly[Ordering[Int]])
* }}}
*
* It will not compile if no implicit value found.
*
* For example, `Foo[Symbol]` requires an implicit value of type `Ordering[Symbol]`, which is not availble.
*
* {{{
* "Factory[Foo[Symbol]]" shouldNot compile
* }}}
*
* @example Given a trait that contains an abstract method annotated as [[Factory.inject @inject]].
*
* {{{
* import com.thoughtworks.feature.Factory.inject
* trait Foo[A] {
* @inject def orderingA: Ordering[A]
* }
* }}}
*
* When creating a factory for the trait
*
* {{{
* val factory = Factory[Foo[Int]]
* }}}
*
* Then the `@inject` method will be replaced to an implicit value.
*
* {{{
* val foo = factory.newInstance()
* foo.orderingA should be(implicitly[Ordering[Int]])
* }}}
*
* It will not compile if no implicit value found.
*
* For example, `Foo[Symbol]` requires an implicit value of type `Ordering[Symbol]`, which is not availble.
*
* {{{
* "Factory[Foo[Symbol]]" shouldNot compile
* }}}
*
*
* @example Given two traits that have no abstract member.
*
* {{{
* trait Foo
* trait Bar
* }}}
*
* When creating a factory for mix-in type of the two types.
*
* {{{
* val factory = Factory[Foo with Bar]
* }}}
*
* Then the [[newInstance]] method of the factory should accept no parameters.
*
* {{{
* val fooBar: Foo with Bar = factory.newInstance()
* fooBar should be(a[Foo])
* fooBar should be(a[Bar])
* }}}
*
* @example Given a trait that has an abstract member.
* {{{
* trait Foo {
* var bar: Int
* }
* }}}
* When creating a factory for the trait.
* {{{
* val factory = Factory[Foo]
* }}}
* Then the [[newInstance]] method of the factory should accept one parameter.
* {{{
* val foo: Foo = factory.newInstance(bar = 1)
* foo.bar should be(1)
* }}}
*
* @author 杨博 (Yang Bo) <pop.atry@gmail.com>
*/
trait Factory[Output] {
/** A function type that returns `Output`.
*
* The parameter types are all abstract members in `Output`
*/
type Constructor
/** Returns an instance of `Output`, which overrides abstract members in `Output` according to parameters pass to this [[newInstance]] method. */
val newInstance: Constructor
}
object Factory {
final class inject extends StaticAnnotation
type Aux[Output, Constructor0] = Factory[Output] {
type Constructor = Constructor0
}
implicit def apply[Output]: Factory[Output] = macro Macros.apply[Output]
private[Factory] final class Macros(val c: whitebox.Context) {
import c.universe._
implicit final class Unzip4[A, B, C, D](val xs: Iterable[(A, B, C, D)]) {
def unzip4: (List[A], List[B], List[C], List[D]) =
xs.foldRight[(List[A], List[B], List[C], List[D])]((Nil, Nil, Nil, Nil)) { (x, res) =>
val (a, b, c, d) = x
(a :: res._1, b :: res._2, c :: res._3, d :: res._4)
}
}
private def demixin(t: Type): Stream[Type] = {
t.dealias match {
case RefinedType(superTypes, refinedScope) if refinedScope.isEmpty =>
superTypes.toStream.flatMap(demixin)
case notRefinedType =>
Stream(notRefinedType)
}
}
private val injectType = typeOf[inject]
def apply[Output: WeakTypeTag]: Tree = {
val output = weakTypeOf[Output]
val componentTypes = demixin(output).distinct
val mixinClassName = TypeName(c.freshName("Anonymous"))
final class OverrideUntyper(baseClass: Symbol) extends Untyper[c.universe.type](c.universe) {
private def replaceThisValue: PartialFunction[Type, Tree] = {
case tt @ ThisType(symbol) if symbol == baseClass =>
This(mixinClassName)
}
override def singletonValue: PartialFunction[Type, Tree] = {
replaceThisValue.orElse(super.singletonValue)
}
private def replaceTypeArguments: PartialFunction[Type, Tree] = {
def superUntype = super.untype;
{
case tpe @ TypeRef(NoPrefix, s, superUntype.extract.forall(typeArguments)) =>
tq"${super.untype(internal
.typeRef(NoPrefix, s, Nil)
.asSeenFrom(output, baseClass))}[..$typeArguments]"
}
}
override def untype: PartialFunction[Type, Tree] = {
replaceTypeArguments.orElse(super.untype)
}
}
val (overridenSymbols, injects) = (for {
baseClass <- output.baseClasses.reverse
member <- baseClass.info.decls
if member.isTerm && {
internal.initialize(member)
member.annotations.exists { a =>
a.tree.tpe <:< injectType
}
} && !member.asTerm.isSetter
} yield {
val memberSymbol = member.asTerm
val methodName = memberSymbol.name.toTermName
val methodType = memberSymbol.info
val untyper = new OverrideUntyper(baseClass)
val resultTypeTree = untyper.untype(methodType.finalResultType)
val modifiers = Modifiers(
Flag.OVERRIDE |
(if (memberSymbol.isImplicit) Flag.IMPLICIT else NoFlags) |
(if (memberSymbol.isLazy) Flag.LAZY else NoFlags)
)
val result =
if (memberSymbol.isVar || memberSymbol.setter != NoSymbol) {
q"""$modifiers var $methodName = {
val $methodName = ()
_root_.com.thoughtworks.feature.The.apply[$resultTypeTree].value
}
"""
} else if (memberSymbol.isVal || memberSymbol.isGetter || memberSymbol.isStable) {
q"""
$modifiers val $methodName = {
val $methodName = ()
_root_.com.thoughtworks.feature.The.apply[$resultTypeTree].value
}
"""
} else {
val argumentTrees = methodType.paramLists.map(_.map { argumentSymbol =>
if (argumentSymbol.asTerm.isImplicit) {
q"implicit val ${argumentSymbol.name.toTermName}: ${untyper
.untype(argumentSymbol.info)}"
} else {
q"val ${argumentSymbol.name.toTermName}: ${untyper.untype(argumentSymbol.info)}"
}
})
q"""
$modifiers def $methodName[..${methodType.typeArgs}](...$argumentTrees) = {
val $methodName = ()
_root_.com.thoughtworks.feature.The.apply[$resultTypeTree].value
}
"""
}
// c.info(c.enclosingPosition, show(result), true)
memberSymbol -> result
}).unzip
val injectedMembers: Map[TermName, Iterable[Symbol]] = overridenSymbols.groupBy(_.name).withDefaultValue(Nil)
val (proxies, parameterTypeTrees, parameterTrees, refinedTree) = (for {
member <- output.members
if member.isTerm && member.isAbstract && injectedMembers(member.name.toTermName).forall { injectedMember =>
!(injectedMember.infoIn(output) <:< member.infoIn(output))
} && !member.asTerm.isSetter
} yield {
val memberSymbol = member.asTerm
val methodName = memberSymbol.name.toTermName
val argumentName = TermName(c.freshName(methodName.toString))
val methodType = memberSymbol.infoIn(output)
val untyper = new OverrideUntyper(member.owner)
val resultTypeTree = untyper.untype(methodType.finalResultType)
if (memberSymbol.isVar || memberSymbol.setter != NoSymbol) {
(q"override var $methodName = $argumentName",
resultTypeTree,
q"val $argumentName: $resultTypeTree",
q"val $methodName: $resultTypeTree")
} else if (memberSymbol.isVal || memberSymbol.isGetter || memberSymbol.isStable) {
(q"override val $methodName = $argumentName",
resultTypeTree,
q"val $argumentName: $resultTypeTree",
q"val $methodName: $resultTypeTree")
} else {
val (argumentTrees, argumentTypeTrees, argumentIdTrees) = methodType.paramLists
.map(_.map { argumentSymbol =>
val argumentTypeTree = untyper.untype(argumentSymbol.info)
val argumentName = argumentSymbol.name.toTermName
val argumentTree = if (argumentSymbol.asTerm.isImplicit) {
q"implicit val $argumentName: $argumentTypeTree"
} else {
q"val $argumentName: $argumentTypeTree"
}
(argumentTree, argumentTypeTree, Ident(argumentName))
}.unzip3)
.unzip3
val functionTypeTree = if (argumentTypeTrees.isEmpty) {
tq"${definitions.ByNameParamClass}[$resultTypeTree]"
} else {
argumentTypeTrees.foldRight(resultTypeTree) { (arguments, result) =>
tq"..$arguments => $result"
}
}
(q"override def $methodName[..${methodType.typeArgs}](...$argumentTrees) = $argumentName",
functionTypeTree,
q"val $argumentName: $functionTypeTree",
q"val $methodName: $functionTypeTree")
}
}).unzip4
val (defProxies, valProxies) = proxies.partition(_.isDef)
val overridenTypes =
(for {
baseClass <- output.baseClasses.reverse
member <- baseClass.info.decls
if member.isType
} yield member)
.groupBy(_.name.toString)
.withFilter {
_._2.forall {
_.info match {
case TypeBounds(_, _) => true
case _ => false
}
}
}
.map {
case (name, members) =>
val lowerBounds = members.collect(scala.Function.unlift[Symbol, Tree] { memberSymbol =>
val TypeBounds(_, lowerBound) = memberSymbol.info
if (lowerBound =:= definitions.AnyTpe) {
None
} else {
val untyper = new OverrideUntyper(memberSymbol.owner)
Some(untyper.untype(lowerBound))
}
})
val typeTree = if (lowerBounds.isEmpty) {
TypeTree(definitions.AnyTpe)
} else {
CompoundTypeTree(Template(lowerBounds, noSelfType, Nil))
}
val result = q"override type ${TypeName(name)} = $typeTree"
// c.info(c.enclosingPosition, show(result), true)
result
}
val makeNew = TermName(c.freshName("makeNew"))
val constructorMethod = TermName(c.freshName("constructor"))
val newInstance = TermName(c.freshName("newInstance"))
val refinedOutput = TypeName(c.freshName("RefinedOutput"))
val result = q"""
def $makeNew[$refinedOutput]($newInstance: (..$parameterTypeTrees) => $refinedOutput): _root_.com.thoughtworks.feature.Factory.Aux[
$output,
((..$parameterTypeTrees) => $refinedOutput) {
def apply(..$refinedTree): $refinedOutput
}] = new _root_.com.thoughtworks.feature.Factory[$output] {
type Constructor = ((..$parameterTypeTrees) => $refinedOutput) {
def apply(..$refinedTree): $refinedOutput
}
override val newInstance: Constructor = $newInstance
}
def $constructorMethod(..$parameterTrees) = {
final class $mixinClassName extends {
..$overridenTypes
..$valProxies
} with ..$componentTypes {
..$defProxies
..$injects
}
new $mixinClassName
}
val $newInstance = $constructorMethod _
$makeNew($newInstance)
"""
// c.info(c.enclosingPosition, show(result), true)
result
}
}
}