/
singletons.scala
364 lines (295 loc) · 11.1 KB
/
singletons.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
/*
* Copyright (c) 2013-15 Miles Sabin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package shapeless
import scala.language.dynamics
import scala.language.existentials
import scala.language.experimental.macros
import scala.reflect.macros.{ blackbox, whitebox }
import tag.@@
import scala.util.Try
trait Witness extends Serializable {
type T
val value: T {}
}
object Witness extends Dynamic {
type Aux[T0] = Witness { type T = T0 }
type Lt[Lub] = Witness { type T <: Lub }
implicit def apply[T]: Witness.Aux[T] = macro SingletonTypeMacros.materializeImpl[T]
implicit def apply[T](t: T): Witness.Lt[T] = macro SingletonTypeMacros.convertImpl
def mkWitness[T0](value0: T0): Aux[T0] =
new Witness {
type T = T0
val value = value0
}
implicit val witness0: Witness.Aux[_0] =
new Witness {
type T = _0
val value = Nat._0
}
implicit def witnessN[P <: Nat]: Witness.Aux[Succ[P]] =
new Witness {
type T = Succ[P]
val value = new Succ[P]()
}
def selectDynamic(tpeSelector: String): Any = macro SingletonTypeMacros.witnessTypeImpl
}
trait WitnessWith[TC[_]] extends Witness {
val instance: TC[T]
}
trait LowPriorityWitnessWith {
implicit def apply2[H, TC2[_ <: H, _], S <: H, T](t: T): WitnessWith.Lt[({ type λ[X] = TC2[S, X] })#λ, T] =
macro SingletonTypeMacros.convertInstanceImpl2[H, TC2, S]
}
object WitnessWith extends LowPriorityWitnessWith {
type Aux[TC[_], T0] = WitnessWith[TC] { type T = T0 }
type Lt[TC[_], Lub] = WitnessWith[TC] { type T <: Lub }
implicit def apply1[TC[_], T](t: T): WitnessWith.Lt[TC, T] = macro SingletonTypeMacros.convertInstanceImpl1[TC]
}
/**
* Provides the widen type of a singleton type.
*
* Type member `Out` of an implicitly available `Witness[T]` instance is the widen type
* of `T`, and the `apply` method explicitly converts a `T` to an `Out`.
*
* E.g. if `T` is ``Witness.`2`.T``, `Out` is `Int`.
*
* It somehow complements `Witness`, providing the corresponding non-witnessed standard type, if any.
*
* Example of use,
* {{
* val w = Widen[Witness.`2`.T]
* // w.Out is Int
* // w(2) is typed as Int
* }}
*
* @author Alexandre Archambault
*/
trait Widen[T] extends DepFn1[T] { type Out >: T }
object Widen {
def apply[T](implicit widen: Widen[T]): Aux[T, widen.Out] = widen
type Aux[T, Out0 >: T] = Widen[T] { type Out = Out0 }
def instance[T, Out0 >: T](f: T => Out0): Aux[T, Out0] =
new Widen[T] {
type Out = Out0
def apply(t: T) = f(t)
}
implicit def materialize[T, Out]: Aux[T, Out] = macro SingletonTypeMacros.materializeWiden[T, Out]
}
trait SingletonTypeUtils extends ReprTypes {
import c.universe.{ Try => _, _ }
import internal._, decorators._
def singletonOpsTpe = typeOf[syntax.SingletonOps]
val SymTpe = typeOf[scala.Symbol]
object LiteralSymbol {
def unapply(t: Tree): Option[String] = t match {
case q""" scala.Symbol.apply(${Literal(Constant(s: String))}) """ => Some(s)
case _ => None
}
}
object SingletonSymbolType {
val atatTpe = typeOf[@@[_,_]].typeConstructor
val TaggedSym = typeOf[tag.Tagged[_]].typeConstructor.typeSymbol
def apply(s: String): Type = appliedType(atatTpe, List(SymTpe, constantType(Constant(s))))
def unapply(t: Type): Option[String] =
t match {
case RefinedType(List(SymTpe, TypeRef(_, TaggedSym, List(ConstantType(Constant(s: String))))), _) => Some(s)
case _ => None
}
}
def mkSingletonSymbol(s: String): Tree = {
val sTpe = SingletonSymbolType(s)
q"""_root_.scala.Symbol($s).asInstanceOf[$sTpe]"""
}
object SingletonType {
def unapply(t: Tree): Option[Type] = (t, t.tpe) match {
case (Literal(k: Constant), _) => Some(constantType(k))
case (LiteralSymbol(s), _) => Some(SingletonSymbolType(s))
case (_, keyType @ SingleType(p, v)) if !v.isParameter && !isValueClass(v) => Some(keyType)
case (q""" $sops.narrow """, _) if sops.tpe <:< singletonOpsTpe =>
Some(sops.tpe.member(TypeName("T")).typeSignature)
case _ => None
}
}
def narrowValue(t: Tree): (Type, Tree) = {
t match {
case Literal(k: Constant) =>
val tpe = constantType(k)
(tpe, q"$t.asInstanceOf[$tpe]")
case LiteralSymbol(s) => (SingletonSymbolType(s), mkSingletonSymbol(s))
case _ => (t.tpe, t)
}
}
def parseLiteralType(typeStr: String): Option[Type] =
for {
parsed <- Try(c.parse(typeStr)).toOption
checked = c.typecheck(parsed, silent = true)
if checked.nonEmpty
tpe <- SingletonType.unapply(checked)
} yield tpe
def parseStandardType(typeStr: String): Option[Type] =
for {
parsed <- Try(c.parse(s"null.asInstanceOf[$typeStr]")).toOption
checked = c.typecheck(parsed, silent = true)
if checked.nonEmpty
} yield checked.tpe
def parseType(typeStr: String): Option[Type] =
parseStandardType(typeStr) orElse parseLiteralType(typeStr)
def typeCarrier(tpe: Type) =
mkTypeCarrier(tq"{ type T = $tpe }")
def fieldTypeCarrier(tpe: Type) =
mkTypeCarrier(tq"{ type T = $tpe ; type ->>[V] = Field[V] ; type Field[V] = _root_.shapeless.labelled.FieldType[$tpe,V] }")
def mkTypeCarrier(tree: Tree) = {
val carrier = c.typecheck(tree, mode = c.TYPEmode).tpe
// We can't yield a useful value here, so return Unit instead which is at least guaranteed
// to result in a runtime exception if the value is used in term position.
Literal(Constant(())).setType(carrier)
}
def isValueClass(sym: Symbol): Boolean = {
val tSym = sym.typeSignature.typeSymbol
tSym.isClass && tSym.asClass.isDerivedValueClass
}
}
class SingletonTypeMacros(val c: whitebox.Context) extends SingletonTypeUtils {
import syntax.SingletonOps
type SingletonOpsLt[Lub] = SingletonOps { type T <: Lub }
import c.universe._
import internal._
import decorators._
def mkWitness(sTpe: Type, s: Tree): Tree = {
q"""
_root_.shapeless.Witness.mkWitness[$sTpe]($s.asInstanceOf[$sTpe])
"""
}
def mkWitnessWith(parent: Type, sTpe: Type, s: Tree, i: Tree): Tree = {
val name = TypeName(c.freshName("anon$"))
val iTpe = i.tpe.finalResultType
q"""
{
final class $name extends $parent {
val instance: $iTpe = $i
type T = $sTpe
val value: $sTpe = $s
}
new $name
}
"""
}
def mkOps(sTpe: Type, w: Tree): Tree = {
val name = TypeName(c.freshName("anon$"))
q"""
{
final class $name extends _root_.shapeless.syntax.SingletonOps {
type T = $sTpe
val witness = $w
}
new $name
}
"""
}
def mkAttributedRef(pre: Type, sym: Symbol): Tree = {
val global = c.universe.asInstanceOf[scala.tools.nsc.Global]
val gPre = pre.asInstanceOf[global.Type]
val gSym = sym.asInstanceOf[global.Symbol]
global.gen.mkAttributedRef(gPre, gSym).asInstanceOf[Tree]
}
def extractSingletonValue(tpe: Type): Tree =
tpe match {
case ConstantType(c: Constant) => Literal(c)
case SingleType(p, v) if !v.isParameter && !isValueClass(v) => mkAttributedRef(p, v)
case SingletonSymbolType(c) => mkSingletonSymbol(c)
case _ =>
c.abort(c.enclosingPosition, s"Type argument $tpe is not a singleton type")
}
def materializeImpl[T: WeakTypeTag]: Tree = {
val tpe = weakTypeOf[T].dealias
mkWitness(tpe, extractSingletonValue(tpe))
}
def extractResult(t: Tree)(mkResult: (Type, Tree) => Tree): Tree =
(t.tpe, t.tree) match {
case (tpe @ ConstantType(c: Constant), _) =>
mkResult(tpe, Literal(c))
case (tpe @ SingleType(p, v), tree) if !v.isParameter && !isValueClass(v) =>
mkResult(tpe, tree)
case (SymTpe, LiteralSymbol(s)) =>
mkResult(SingletonSymbolType(s), mkSingletonSymbol(s))
case (tpe, tree) if tree.symbol.isTerm && tree.symbol.asTerm.isStable && !isValueClass(tree.symbol) =>
val sym = tree.symbol.asTerm
val pre = if(sym.owner.isClass) c.internal.thisType(sym.owner) else NoPrefix
val symTpe = c.internal.singleType(pre, sym)
mkResult(symTpe, q"$sym.asInstanceOf[$symTpe]")
case _ =>
c.abort(c.enclosingPosition, s"Expression ${t.tree} does not evaluate to a constant or a stable reference value")
}
def convertImpl(t: Tree): Tree = extractResult(t)(mkWitness)
def inferInstance(tci: Type): Tree = {
val i = c.inferImplicitValue(tci)
if(i == EmptyTree)
c.abort(c.enclosingPosition, s"Unable to resolve implicit value of type $tci")
i
}
def convertInstanceImpl1[TC[_]](t: Tree)
(implicit tcTag: WeakTypeTag[TC[_]]): Tree =
extractResult(t) { (sTpe, value) =>
val tc = tcTag.tpe.typeConstructor
val wwTC = typeOf[WitnessWith[Nothing]].typeConstructor
val parent = appliedType(wwTC, List(tc))
val tci = appliedType(tc, List(sTpe))
val i = inferInstance(tci)
mkWitnessWith(parent, sTpe, value, i)
}
def convertInstanceImpl2[H, TC2[_ <: H, _], S <: H](t: Tree)
(implicit tc2Tag: WeakTypeTag[TC2[_, _]], sTag: WeakTypeTag[S]): Tree =
extractResult(t) { (sTpe, value) =>
val tc2 = tc2Tag.tpe.typeConstructor
val s = sTag.tpe
val parent = weakTypeOf[WitnessWith[({ type λ[X] = TC2[S, X] })#λ]].map {
case TypeRef(prefix, sym, args) if sym.isFreeType =>
typeRef(NoPrefix, tc2.typeSymbol, args)
case tpe => tpe
}
val tci = appliedType(tc2, List(s, sTpe))
val i = inferInstance(tci)
mkWitnessWith(parent, sTpe, value, i)
}
def mkSingletonOps(t: Tree): Tree =
extractResult(t) { (tpe, tree) => mkOps(tpe, mkWitness(tpe, tree)) }
def narrowSymbol[S <: String : WeakTypeTag](t: Tree): Tree = {
(weakTypeOf[S], t.tree) match {
case (ConstantType(Constant(s1: String)), LiteralSymbol(s2)) if s1 == s2 =>
mkSingletonSymbol(s1)
case _ =>
c.abort(c.enclosingPosition, s"Expression ${t.tree} is not an appropriate Symbol literal")
}
}
def witnessTypeImpl(tpeSelector: Tree): Tree = {
val q"${tpeString: String}" = tpeSelector
val tpe =
parseLiteralType(tpeString)
.getOrElse(c.abort(c.enclosingPosition, s"Malformed literal $tpeString"))
fieldTypeCarrier(tpe)
}
def materializeWiden[T: WeakTypeTag, Out: WeakTypeTag]: Tree = {
val tpe = weakTypeOf[T].dealias
val widenTpe = tpe match {
case SingletonSymbolType(s) => symbolTpe
case _ => tpe.widen
}
if (widenTpe =:= tpe)
c.abort(c.enclosingPosition, s"Don't know how to widen $tpe")
else
q"_root_.shapeless.Widen.instance[$tpe, $widenTpe](x => x)"
}
}