-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathGeneralMacros.scala
More file actions
1664 lines (1566 loc) · 71.9 KB
/
GeneralMacros.scala
File metadata and controls
1664 lines (1566 loc) · 71.9 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package singleton.ops.impl
import singleton.twoface.impl.TwoFaceAny
import scala.reflect.macros.{TypecheckException, whitebox}
private object MacroCache {
import scala.collection.mutable
val cache = mutable.Map.empty[Any, Any]
def get(key : Any) : Option[Any] = cache.get(key)
def add[V <: Any](key : Any, value : V) : V = {cache += (key -> value); value}
var errorCache : String = ""
def clearErrorCache() : Unit = errorCache = ""
def setErrorCache(msg : String) : Unit = errorCache = msg
def getErrorMessage : String = errorCache
}
trait GeneralMacros {
val c: whitebox.Context
import c.universe._
val defaultAnnotatedSym : Option[TypeSymbol] =
if (c.enclosingImplicits.isEmpty) None else c.enclosingImplicits.last.pt match {
case TypeRef(_,sym,_) => Some(sym.asType)
case x => Some(x.typeSymbol.asType)
}
private val func1Sym = symbolOf[Function1[_,_]]
object funcTypes {
val Arg = symbolOf[OpId.Arg]
val AcceptNonLiteral = symbolOf[OpId.AcceptNonLiteral]
val GetArg = symbolOf[OpId.GetArg]
val ImplicitFound = symbolOf[OpId.ImplicitFound]
val EnumCount = symbolOf[OpId.EnumCount]
val Id = symbolOf[OpId.Id]
val ToNat = symbolOf[OpId.ToNat]
val ToChar = symbolOf[OpId.ToChar]
val ToInt = symbolOf[OpId.ToInt]
val ToLong = symbolOf[OpId.ToLong]
val ToFloat = symbolOf[OpId.ToFloat]
val ToDouble = symbolOf[OpId.ToDouble]
val ToString = symbolOf[OpId.ToString]
val IsNat = symbolOf[OpId.IsNat]
val IsChar = symbolOf[OpId.IsChar]
val IsInt = symbolOf[OpId.IsInt]
val IsLong = symbolOf[OpId.IsLong]
val IsFloat = symbolOf[OpId.IsFloat]
val IsDouble = symbolOf[OpId.IsDouble]
val IsString = symbolOf[OpId.IsString]
val IsBoolean = symbolOf[OpId.IsBoolean]
val Negate = symbolOf[OpId.Negate]
val Abs = symbolOf[OpId.Abs]
val NumberOfLeadingZeros = symbolOf[OpId.NumberOfLeadingZeros]
val Floor = symbolOf[OpId.Floor]
val Ceil = symbolOf[OpId.Ceil]
val Round = symbolOf[OpId.Round]
val Sin = symbolOf[OpId.Sin]
val Cos = symbolOf[OpId.Cos]
val Tan = symbolOf[OpId.Tan]
val Sqrt = symbolOf[OpId.Sqrt]
val Log = symbolOf[OpId.Log]
val Log10 = symbolOf[OpId.Log10]
val Reverse = symbolOf[OpId.Reverse]
val ! = symbolOf[OpId.!]
val Require = symbolOf[OpId.Require]
val ITE = symbolOf[OpId.ITE]
val IsNonLiteral = symbolOf[OpId.IsNonLiteral]
val GetType = symbolOf[OpId.GetType]
val ==> = symbolOf[OpId.==>]
val + = symbolOf[OpId.+]
val - = symbolOf[OpId.-]
val * = symbolOf[OpId.*]
val / = symbolOf[OpId./]
val % = symbolOf[OpId.%]
val < = symbolOf[OpId.<]
val > = symbolOf[OpId.>]
val <= = symbolOf[OpId.<=]
val >= = symbolOf[OpId.>=]
val == = symbolOf[OpId.==]
val != = symbolOf[OpId.!=]
val && = symbolOf[OpId.&&]
val || = symbolOf[OpId.||]
val Pow = symbolOf[OpId.Pow]
val Min = symbolOf[OpId.Min]
val Max = symbolOf[OpId.Max]
val Substring = symbolOf[OpId.Substring]
val SubSequence = symbolOf[OpId.SubSequence]
val StartsWith = symbolOf[OpId.StartsWith]
val EndsWith = symbolOf[OpId.EndsWith]
val Head = symbolOf[OpId.Head]
val Tail = symbolOf[OpId.Tail]
val CharAt = symbolOf[OpId.CharAt]
val Length = symbolOf[OpId.Length]
val Matches = symbolOf[OpId.Matches]
val FirstMatch = symbolOf[OpId.FirstMatch]
val PrefixMatch = symbolOf[OpId.PrefixMatch]
val ReplaceFirstMatch = symbolOf[OpId.ReplaceFirstMatch]
val ReplaceAllMatches = symbolOf[OpId.ReplaceAllMatches]
}
////////////////////////////////////////////////////////////////////
// Code thanks to Shapeless
// https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/lazy.scala
////////////////////////////////////////////////////////////////////
def setAnnotation(msg: String, annotatedSym : TypeSymbol): Unit = {
import c.internal._
import decorators._
val tree0 =
c.typecheck(
q"""
new _root_.scala.annotation.implicitNotFound("dummy")
""",
silent = false
)
class SubstMessage extends Transformer {
val global = c.universe.asInstanceOf[scala.tools.nsc.Global]
override def transform(tree: Tree): Tree = {
super.transform {
tree match {
case Literal(Constant("dummy")) => Literal(Constant(msg))
case t => t
}
}
}
}
val tree = new SubstMessage().transform(tree0)
annotatedSym.setAnnotations(Annotation(tree))
()
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Calc
////////////////////////////////////////////////////////////////////
sealed trait Calc extends Product with Serializable {
val primitive : Primitive
val tpe : Type
}
object Calc {
implicit def getPrimitive(from : Calc) : Primitive = from.primitive
}
sealed trait Primitive extends Product with Serializable {
val dummyConstant : Any
val name : String
val tpe : Type
override def equals(that: Any): Boolean = {
val thatPrim = that.asInstanceOf[Primitive]
thatPrim.dummyConstant == dummyConstant && thatPrim.name == name && thatPrim.tpe =:= tpe
}
}
object Primitive {
case object Char extends Primitive {val dummyConstant = '\u0001';val name = "Char"; val tpe = typeOf[scala.Char]}
case object Int extends Primitive {val dummyConstant = 1; val name = "Int"; val tpe = typeOf[scala.Int]}
case object Long extends Primitive {val dummyConstant = 1L; val name = "Long"; val tpe = typeOf[scala.Long]}
case object Float extends Primitive {val dummyConstant = 1.0f; val name = "Float"; val tpe = typeOf[scala.Float]}
case object Double extends Primitive {val dummyConstant = 1.0; val name = "Double"; val tpe = typeOf[scala.Double]}
case object String extends Primitive {val dummyConstant = "1"; val name = "String"; val tpe = typeOf[java.lang.String]}
case object Boolean extends Primitive {val dummyConstant = true; val name = "Boolean"; val tpe = typeOf[scala.Boolean]}
case class Unknown(tpe : Type, name : String) extends Primitive {val dummyConstant: Any = None}
def fromLiteral(lit : Any) : Primitive = lit match {
case value : std.Char => Primitive.Char
case value : std.Int => Primitive.Int
case value : std.Long => Primitive.Long
case value : std.Float => Primitive.Float
case value : std.Double => Primitive.Double
case value : std.String => Primitive.String
case value : std.Boolean => Primitive.Boolean
case _ => abort(s"Unsupported literal type: $lit")
}
}
sealed trait CalcVal extends Calc {
val primitive : Primitive
val literal : Option[Any]
val tree : Tree
}
object CalcVal {
sealed trait Kind
object Lit extends Kind
object NLit extends Kind
implicit val lift = Liftable[CalcVal] {p => p.tree}
def unapply(arg: CalcVal): Option[(Any, Tree)] = Some((arg.literal.getOrElse(arg.dummyConstant), arg.tree))
def apply(value : Any, tree : Tree)(implicit kind : Kind) = kind match {
case Lit => CalcLit(value)
case NLit => CalcNLit(Primitive.fromLiteral(value), tree)
}
//use this when a literal calculation may fail
def mayFail(primitive: Primitive, value : => Any, tree : Tree)(implicit kind : Kind) = kind match {
case Lit => try{CalcLit(value)} catch {case e : Throwable => abort(e.getMessage)}
case NLit => CalcNLit(primitive, tree)
}
}
case class CalcLit(primitive : Primitive, value : Any) extends CalcVal {
val literal = Some(value)
val tpe : Type = constantTypeOf(value)
val tree : Tree = Literal(Constant(value))
}
object CalcLit {
object Char {
def unapply(arg: CalcLit): Option[std.Char] = arg match {
case CalcLit(Primitive.Char, value : std.Char) => Some(value)
case _ => None
}
}
object Int {
def unapply(arg: CalcLit): Option[std.Int] = arg match {
case CalcLit(Primitive.Int, value : std.Int) => Some(value)
case _ => None
}
}
object Long {
def unapply(arg: CalcLit): Option[std.Long] = arg match {
case CalcLit(Primitive.Long, value : std.Long) => Some(value)
case _ => None
}
}
object Float {
def unapply(arg: CalcLit): Option[std.Float] = arg match {
case CalcLit(Primitive.Float, value : std.Float) => Some(value)
case _ => None
}
}
object Double {
def unapply(arg: CalcLit): Option[std.Double] = arg match {
case CalcLit(Primitive.Double, value : std.Double) => Some(value)
case _ => None
}
}
object String {
def unapply(arg: CalcLit): Option[std.String] = arg match {
case CalcLit(Primitive.String, value : std.String) => Some(value)
case _ => None
}
}
object Boolean {
def unapply(arg: CalcLit): Option[std.Boolean] = arg match {
case CalcLit(Primitive.Boolean, value : std.Boolean) => Some(value)
case _ => None
}
}
def apply(t : Any) : CalcLit = CalcLit(Primitive.fromLiteral(t), t)
}
case class CalcNLit(primitive : Primitive, tree : Tree, tpe : Type) extends CalcVal {
val literal = None
}
object CalcNLit {
def apply(primitive: Primitive, tree: Tree): CalcNLit = new CalcNLit(primitive, tree, primitive.tpe)
}
sealed trait CalcType extends Calc
object CalcType {
case class Mark(primitive : Primitive) extends CalcType {
val tpe = primitive.tpe
}
case class TF(primitive : Primitive) extends CalcType {
val tpe = primitive.tpe
}
case class UB(primitive : Primitive) extends CalcType {
val tpe = primitive.tpe
}
def unapply(arg: CalcType): Option[Primitive] = Some(arg.primitive)
}
case class CalcUnknown(tpe : Type, treeOption : Option[Tree], opIntercept : Boolean) extends Calc {
override val primitive: Primitive = Primitive.Unknown(tpe, "Unknown")
}
object NonLiteralCalc {
def unapply(tpe: Type): Option[CalcType.Mark] = tpe match {
case TypeRef(_, sym, _) => sym match {
case t if t == symbolOf[Char] => Some(CalcType.Mark(Primitive.Char))
case t if t == symbolOf[Int] => Some(CalcType.Mark(Primitive.Int))
case t if t == symbolOf[Long] => Some(CalcType.Mark(Primitive.Long))
case t if t == symbolOf[Float] => Some(CalcType.Mark(Primitive.Float))
case t if t == symbolOf[Double] => Some(CalcType.Mark(Primitive.Double))
case t if t == symbolOf[java.lang.String] => Some(CalcType.Mark(Primitive.String))
case t if t == symbolOf[Boolean] => Some(CalcType.Mark(Primitive.Boolean))
case _ => None
}
case _ => None
}
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Calc Caching
////////////////////////////////////////////////////////////////////
object CalcCache {
import collection.mutable
import io.AnsiColor._
def deepCopyTree(t: Tree): Tree = {
val treeDuplicator = new Transformer {
// by default Transformers don’t copy trees which haven’t been modified,
// so we need to use use strictTreeCopier
override val treeCopy =
c.asInstanceOf[reflect.macros.runtime.Context].global.newStrictTreeCopier.asInstanceOf[TreeCopier]
}
treeDuplicator.transform(t)
}
final case class Key private (key : Type, argContext : List[Tree]) {
override def equals(that: Any): Boolean = {
val thatKey = that.asInstanceOf[Key]
(thatKey.key =:= key) && (thatKey.argContext.length == argContext.length) &&
ListZipper(thatKey.argContext, argContext).forall(_ equalsStructure _)
}
}
object Key {
implicit def fromType(key : Type) : Key = new Key(key, GetArgTree.argContext)
}
val cache = MacroCache.cache.asInstanceOf[mutable.Map[Key, Calc]]
def get(key : Type) : Option[Calc] = {
val k = Key.fromType(key)
cache.get(k).map {v =>
VerboseTraversal(s"${YELLOW}${BOLD}fetching${RESET} $k, $v")
val cloned = v match {
case lit : CalcLit => CalcLit(lit.value) //reconstruct internal literal tree
case nlit : CalcNLit => CalcNLit(nlit.primitive, deepCopyTree(nlit.tree))
case c => c
}
cloned
}
}
def add[V <: Calc](key : Type, value : V) : V = {
val k = Key.fromType(key)
cache += (k -> value)
VerboseTraversal(s"${GREEN}${BOLD}caching${RESET} $k -> $value")
value
}
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Code thanks to Paul Phillips
// https://github.com/paulp/psply/blob/master/src/main/scala/PsplyMacros.scala
////////////////////////////////////////////////////////////////////
import scala.reflect.internal.SymbolTable
object VerboseTraversal {
private val verboseTraversal = false
private val indentSize = 2
private var indent : Int = 0
private def indentStr : String = " " * (indentSize * indent)
def incIdent : Unit = if (verboseTraversal) {
indent = indent + 1
println("--" * indent + ">")
}
def decIdent : Unit = if (verboseTraversal) {
println("<" + "--" * indent)
indent = indent - 1
}
def apply(s : String) : Unit = {
if (verboseTraversal) println(indentStr + s.replaceAll("\n",s"\n$indentStr"))
}
}
/** Typecheck singleton types so as to obtain indirectly
* available known-at-compile-time values.
*/
object TypeCalc {
////////////////////////////////////////////////////////////////////////
// Calculates the integer value of Shapeless Nat
////////////////////////////////////////////////////////////////////////
object NatCalc {
def unapply(tp: Type): Option[CalcLit] = {
tp match {
case TypeRef(_, sym, args) if sym == symbolOf[shapeless.Succ[_]] =>
args.head match {
case NatCalc(CalcLit.Int(value)) => Some(CalcLit(value + 1))
case _ => abort(s"Given Nat type is defective: $tp, raw: ${showRaw(tp)}")
}
case TypeRef(_, sym, _) if sym == symbolOf[shapeless._0] =>
Some(CalcLit(0))
case TypeRef(pre, sym, Nil) =>
unapply(sym.info asSeenFrom (pre, sym.owner))
case _ =>
None
}
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Calculates the TwoFace values
////////////////////////////////////////////////////////////////////////
object TwoFaceCalc {
def unapplyArg(calcTFType : Option[CalcType.TF], tfArgType : Type): Option[Calc] = {
TypeCalc.unapply(tfArgType) match {
case Some(t : CalcLit) => Some(t)
case _ => calcTFType
}
}
def unapply(tp: Type) : Option[Calc] = {
val tfAnySym = symbolOf[TwoFaceAny[_,_]]
tp match {
case TypeRef(_, sym, args) if args.nonEmpty && tp.baseClasses.contains(tfAnySym) =>
VerboseTraversal(s"@@TwoFaceCalc@@\nTP: $tp\nRAW: ${showRaw(tp)}\nBaseCls:${tp.baseClasses}")
val calcTFType = sym match {
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.Char[_]]) => Some(CalcType.TF(Primitive.Char))
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.Int[_]]) => Some(CalcType.TF(Primitive.Int))
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.Long[_]]) => Some(CalcType.TF(Primitive.Long))
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.Float[_]]) => Some(CalcType.TF(Primitive.Float))
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.Double[_]]) => Some(CalcType.TF(Primitive.Double))
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.String[_]]) => Some(CalcType.TF(Primitive.String))
case t if tp.baseClasses.contains(symbolOf[TwoFaceAny.Boolean[_]]) => Some(CalcType.TF(Primitive.Boolean))
case _ => None
}
if (calcTFType.isDefined)
unapplyArg(calcTFType, tp.baseType(tfAnySym).typeArgs(1))
else
None
case _ => None
}
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Calculates the different Op wrappers by unapplying their argument.
////////////////////////////////////////////////////////////////////////
object OpCastCalc {
def unapply(tp: Type): Option[Calc] = {
tp match {
case TypeRef(_, sym, args) =>
sym match {
case t if t == symbolOf[OpNat[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpChar[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpInt[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpLong[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpFloat[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpDouble[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpString[_]] => Some(TypeCalc(args.head))
case t if t == symbolOf[OpBoolean[_]] => Some(TypeCalc(args.head))
case _ => None
}
case _ =>
None
}
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Calculates an Op
////////////////////////////////////////////////////////////////////////
object OpCalc {
private val opMacroSym = symbolOf[OpMacro[_,_,_,_]]
private var uncachingReason : Int = 0
def setUncachingReason(arg : Int) : Unit = {
uncachingReason = arg
}
def unapply(tp: Type): Option[Calc] = {
tp match {
case TypeRef(_, sym, ft :: tp :: _) if sym == opMacroSym && ft.typeSymbol == funcTypes.GetType =>
Some(CalcUnknown(tp, None, opIntercept = false))
case TypeRef(_, sym, args) if sym == opMacroSym =>
VerboseTraversal(s"@@OpCalc@@\nTP: $tp\nRAW: ${showRaw(tp)}")
val funcType = args.head.typeSymbol.asType
CalcCache.get(tp) match {
case None =>
val args = tp.typeArgs
lazy val aValue = TypeCalc(args(1))
lazy val bValue = TypeCalc(args(2))
lazy val cValue = TypeCalc(args(3))
//If function is set/get variable we keep the original string,
//otherwise we get the variable's value
val retVal = (funcType, aValue) match {
case (funcTypes.ImplicitFound, _) =>
setUncachingReason(1)
aValue match {
case CalcUnknown(t, _, false) => try {
c.typecheck(q"implicitly[$t]")
Some(CalcLit(true))
} catch {
case e : Throwable =>
Some(CalcLit(false))
}
case _ => Some(CalcLit(false))
}
case (funcTypes.EnumCount, _) =>
aValue match {
case CalcUnknown(t, _, false) => Some(CalcLit(t.typeSymbol.asClass.knownDirectSubclasses.size))
case _ => Some(CalcLit(0))
}
case (funcTypes.IsNat, _) =>
aValue match {
case CalcLit.Int(t) if t >= 0 => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsChar, _) =>
aValue.primitive match {
case Primitive.Char => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsInt, _) =>
aValue.primitive match {
case Primitive.Int => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsLong, _) =>
aValue.primitive match {
case Primitive.Long => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsFloat, _) =>
aValue.primitive match {
case Primitive.Float => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsDouble, _) =>
aValue.primitive match {
case Primitive.Double => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsString, _) =>
aValue.primitive match {
case Primitive.String => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsBoolean, _) =>
aValue.primitive match {
case Primitive.Boolean => Some(CalcLit(true))
case _ => Some(CalcLit(false))
}
case (funcTypes.IsNonLiteral, _) => //Looking for non literals
aValue match {
case t : CalcLit => Some(CalcLit(false))
case _ => Some(CalcLit(true)) //non-literal type (e.g., Int, Long,...)
}
case (funcTypes.ITE, CalcLit.Boolean(cond)) => //Special control case: ITE (If-Then-Else)
if (cond) Some(bValue) //true (then) part of the IF
else Some(cValue) //false (else) part of the IF
case (funcTypes.Arg, CalcLit.Int(argNum)) =>
bValue match { //Checking the argument type
case t : CalcLit => Some(t) //Literal argument is just a literal
case _ => //Got a type, so returning argument name
TypeCalc.unapply(args(3)) match {
case Some(t: CalcType) =>
val term = TermName(s"arg$argNum")
Some(CalcNLit(t, q"$term"))
case _ =>
None
}
}
case _ => //regular cases
opCalc(funcType, aValue, bValue, cValue) match {
case (res : CalcVal) => Some(res)
case u @ CalcUnknown(_,Some(_), _) => Some(u) //Accept unknown values with a tree
case oi @ CalcUnknown(_,_, true) => Some(oi) //Accept unknown op interception
case _ => None
}
}
if (uncachingReason > 0) VerboseTraversal(s"$uncachingReason:: Skipped caching of $tp")
else retVal.foreach{rv => CalcCache.add(tp, rv)}
retVal
case cached => cached
}
case _ => None
}
}
}
////////////////////////////////////////////////////////////////////////
def apply(tp: Type): Calc = {
TypeCalc.unapply(tp) match {
case Some(t : CalcVal) => t
case Some(t @ CalcType.UB(_)) => t
case Some(t @ CalcType.TF(_)) => CalcNLit(t, q"valueOf[$tp].getValue")
case Some(t : CalcType) => CalcNLit(t, q"valueOf[$tp]")
case Some(t : CalcUnknown) => t
case _ =>
VerboseTraversal(s"@@Unknown@@\nTP: $tp\nRAW: ${showRaw(tp)}")
CalcUnknown(tp, None, opIntercept = false)
}
}
def unapply(tp: Type): Option[Calc] = {
val g = c.universe.asInstanceOf[SymbolTable]
implicit def fixSymbolOps(sym: Symbol): g.Symbol = sym.asInstanceOf[g.Symbol]
VerboseTraversal(s"@@TypeCalc.unapply@@ ${c.enclosingPosition}\nTP: $tp\nRAW: ${showRaw(tp)}")
VerboseTraversal.incIdent
val tpCalc = tp match {
////////////////////////////////////////////////////////////////////////
// Value cases
////////////////////////////////////////////////////////////////////////
case ConstantType(ConstantCalc(t)) => Some(t) //Constant
case OpCalc(t) => Some(t) // Operational Function
case OpCastCalc(t) => Some(t) //Op Cast wrappers
case TwoFaceCalc(t) => Some(t) //TwoFace values
case NonLiteralCalc(t) => Some(t)// Non-literal values
case NatCalc(t) => Some(t) //For Shapeless Nat
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Tree traversal
////////////////////////////////////////////////////////////////////////
case tp @ ExistentialType(_, _) => unapply(tp.underlying)
case TypeBounds(lo, hi) => unapply(hi) match {
case Some(t : CalcLit) => Some(t)
//There can be cases, like in the following example, where we can extract a non-literal value.
// def foo2[W](w : TwoFace.Int[W])(implicit tfs : TwoFace.Int.Shell1[Negate, W, Int]) = -w+1
//We want to calculate `-w+1`, even though we have not provided a complete implicit.
//While returning `TwoFace.Int[Int](-w+1)` is possible in this case, we would rather reserve
//the ability to have a literal return type, so `TwoFace.Int[Negate[W]+1](-w+1)` is returned.
//So even if we can have a `Some(CalcType)` returning, we force it as an upper-bound calc type.
case Some(t) => Some(CalcType.UB(t))
case _ => None
}
case RefinedType(parents, scope) =>
parents.iterator map unapply collectFirst { case Some(x) => x }
case NullaryMethodType(tpe) => unapply(tpe)
case TypeRef(_, sym, _) if sym.isAliasType =>
val tpDealias = tp.dealias
if (tpDealias == tp)
abort("Unable to dealias type: " + showRaw(tp))
else
unapply(tpDealias)
case TypeRef(pre, sym, Nil) => unapply(sym.info asSeenFrom (pre, sym.owner))
case SingleType(pre, sym) => unapply(sym.info asSeenFrom (pre, sym.owner))
////////////////////////////////////////////////////////////////////////
case _ =>
VerboseTraversal("Exhausted search at: " + showRaw(tp))
None
}
VerboseTraversal.decIdent
tpCalc
}
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Calculates from a constant
////////////////////////////////////////////////////////////////////////
object ConstantCalc {
def unapply(constant: Constant): Option[CalcLit] = {
constant match {
case Constant(t : Char) => Some(CalcLit(t))
case Constant(t : Int) => Some(CalcLit(t))
case Constant(t : Long) => Some(CalcLit(t))
case Constant(t : Float) => Some(CalcLit(t))
case Constant(t : Double) => Some(CalcLit(t))
case Constant(t : String) => Some(CalcLit(t))
case Constant(t : Boolean) => Some(CalcLit(t))
case _ => None
}
}
}
////////////////////////////////////////////////////////////////////////
def abort(msg: String, annotatedSym : Option[TypeSymbol] = defaultAnnotatedSym, position : Position = c.enclosingPosition): Nothing = {
VerboseTraversal(s"!!!!!!aborted with: $msg at $annotatedSym, $defaultAnnotatedSym")
if (annotatedSym.isDefined) setAnnotation(msg, annotatedSym.get)
MacroCache.setErrorCache(msg) //propagating the error in case this is an inner implicit call for OpIntercept
c.abort(position, msg)
}
def buildWarningMsgLoc : String = s"${c.enclosingPosition.source.path}:${c.enclosingPosition.line}:${c.enclosingPosition.column}"
def buildWarningMsg(msg: String): String = s"Warning: $buildWarningMsgLoc $msg"
def buildWarningMsg(msg: Tree): Tree = q""" "Warning: " + $buildWarningMsgLoc + " " + $msg """
def constantTreeOf(t : Any) : Tree = Literal(Constant(t))
def constantTypeOf(t: Any) : Type = c.internal.constantType(Constant(t))
def genOpTreeLit(opTpe : Type, t: Any) : Tree = {
val outTpe = constantTypeOf(t)
val outTree = constantTreeOf(t)
val outWideTpe = outTpe.widen
val outTypeName = TypeName("Out" + wideTypeName(outTpe))
val outWideLiteral = outTree
q"""
new $opTpe {
type OutWide = $outWideTpe
type Out = $outTpe
type $outTypeName = $outTpe
final val value: $outTpe = $outWideLiteral
final val isLiteral = true
final val valueWide: $outWideTpe = $outWideLiteral
}
"""
}
def genOpTreeNat(opTpe : Type, t: Int) : Tree = {
val outWideTpe = typeOf[Int]
val outWideLiteral = constantTreeOf(t)
val outTypeName = TypeName("OutNat")
val outTpe = mkNatTpe(t)
val outTree = q"new ${mkNatTpt(t)}"
q"""
new $opTpe {
type OutWide = $outWideTpe
type Out = $outTpe
type $outTypeName = $outTpe
final val value: $outTpe = $outTree
final val isLiteral = true
final val valueWide: $outWideTpe = $outWideLiteral
}
"""
}
def genOpTreeNLit(opTpe : Type, calc : CalcNLit) : Tree = {
val valueTree = calc.tree
val outTpe = calc.tpe
q"""
new $opTpe {
type OutWide = $outTpe
type Out = $outTpe
final val value: $outTpe = $valueTree
final val isLiteral = false
final val valueWide: $outTpe = $valueTree
}
"""
}
def genOpTreeUnknown(opTpe : Type, calc : CalcUnknown) : Tree = {
val outTpe = calc.tpe
calc.treeOption match {
case Some(valueTree) =>
q"""
new $opTpe {
type OutWide = $outTpe
type Out = $outTpe
final lazy val value: $outTpe = $valueTree
final val isLiteral = false
final lazy val valueWide: $outTpe = $valueTree
}
"""
case None =>
q"""
new $opTpe {
type OutWide = $outTpe
type Out = $outTpe
final lazy val value: $outTpe = throw new IllegalArgumentException("This operation does not produce a value.")
final val isLiteral = false
final lazy val valueWide: $outTpe = throw new IllegalArgumentException("This operation does not produce a value.")
}
"""
}
}
def extractionFailed(tpe: Type) = {
val msg = s"Cannot extract value from $tpe\n" + "showRaw==> " + showRaw(tpe)
abort(msg)
}
def extractionFailed(tree: Tree) = {
val msg = s"Cannot extract value from $tree\n" + "showRaw==> " + showRaw(tree)
abort(msg)
}
def extractValueFromOpTree(opTree : c.Tree) : CalcVal = {
def outFindCond(elem : c.Tree) : Boolean = elem match {
case q"final val value : $valueTpe = $valueTree" => true
case _ => false
}
def getOut(opClsBlk : List[c.Tree]) : CalcVal = opClsBlk.find(outFindCond) match {
case Some(q"final val value : $valueTpe = $valueTree") =>
valueTree match {
case Literal(ConstantCalc(t)) => t
case _ => valueTpe match {
case NonLiteralCalc(t) => CalcNLit(t, q"$valueTree")
case _ => extractionFailed(opTree)
}
}
case _ => extractionFailed(opTree)
}
opTree match {
case q"""{
$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends ..$parents { $self => ..$opClsBlk }
$expr(...$exprss)
}""" => getOut(opClsBlk)
case _ => extractionFailed(opTree)
}
}
def extractValueFromNumTree(numValueTree : c.Tree) : CalcVal = {
val typedTree = c.typecheck(numValueTree)
TypeCalc(typedTree.tpe) match {
case t : CalcLit => t
case t : CalcType.UB => CalcNLit(t, numValueTree, typedTree.tpe)
case t : CalcNLit => CalcNLit(t, numValueTree)
case _ => extractionFailed(typedTree.tpe)
}
}
def extractValueFromTwoFaceTree(tfTree : c.Tree) : CalcVal = {
val typedTree = c.typecheck(tfTree)
TypeCalc(typedTree.tpe) match {
case t : CalcLit => t
case t : CalcType => CalcNLit(t, q"$tfTree.getValue")
case t : CalcNLit => CalcNLit(t, q"$tfTree.getValue")
case t =>
// println(t)
extractionFailed(typedTree.tpe)
}
}
def wideTypeName(tpe : Type) : String = tpe.widen.typeSymbol.name.toString
object HasOutValue {
def unapply(tree : Tree) : Option[Tree] = tree match {
case Apply(Apply(_,_), List(Block(ClassDef(_,_,_,Template(_,_,members)) :: _, _))) =>
members.collectFirst {
case ValDef(_,TermName("value "),_,t) => t
}
case _ => None
}
}
object GetArgTree {
def isMethodMacroCall : Boolean = c.enclosingImplicits.last.sym.isMacro
def getAllArgs(tree : Tree, lhs : Boolean) : List[Tree] = tree match {
case ValDef(_,_,_,Apply(_, t)) => t
case HasOutValue(valueTree) => List(valueTree)
case Apply(TypeApply(_,_), List(HasOutValue(valueTree))) => List(valueTree)
case Apply(Apply(_,_), _) => getAllArgsRecur(tree)
case Apply(TypeApply(_,_), _) => getAllArgsRecur(tree)
case Apply(_, args) => if (isMethodMacroCall || lhs) args else List(tree)
case t : Select => List(t)
case t : Literal => List(t)
case t : Ident => List(t)
case _ => getAllArgsRecur(tree)
}
def getAllArgsRecur(tree : Tree) : List[Tree] = tree match {
case Apply(fun, args) => getAllArgsRecur(fun) ++ args
case _ => List()
}
def getAllLHSArgs(tree : Tree) : List[Tree] = tree match {
case Apply(TypeApply(Select(t, _), _), _) => getAllArgs(t, true)
case TypeApply(Select(t, _), _) => getAllArgs(t, true)
case Select(t, _) => getAllArgs(t, true)
case _ => abort("Left-hand-side tree not found")
}
private var argListUsed = false
private lazy val argList = {
argListUsed = true
getAllArgs(c.enclosingImplicits.last.tree, false)
}
private var lhsArgListUsed = false
private lazy val lhsArgList = {
lhsArgListUsed = true
getAllLHSArgs(c.enclosingImplicits.last.tree)
}
def argContext : List[Tree] = (argListUsed, lhsArgListUsed) match {
case (false, false) => List()
case (true, false) => argList
case (false, true) => lhsArgList
case (true, true) => argList ++ lhsArgList
}
def apply(argIdx : Int, lhs : Boolean) : (Tree, Type) = {
val tree = c.enclosingImplicits.last.tree
// println(">>>>>>> enclosingImpl: ")// + c.enclosingImplicits.last)
// println("pt: " + c.enclosingImplicits.last.pt)
// println("tree: " + c.enclosingImplicits.last.tree)
// println("rawTree: " + showRaw(c.enclosingImplicits.last.tree))
val allArgs = if (lhs) lhsArgList else argList
// println("args: " + allArgs)
// println("<<<<<<< rawArgs" + showRaw(allArgs))
val argTree : Tree = if (argIdx < allArgs.length) c.typecheck(allArgs(argIdx))
else abort(s"Argument index($argIdx) is not smaller than the total number of arguments(${allArgs.length})")
val tpe = c.enclosingImplicits.last.pt match {
case TypeRef(_,sym,tp :: _) if (sym == func1Sym) => tp //conversion, so get the type from last.pt
case _ => argTree.tpe //not a conversion, so get the type from the tree
}
(argTree, tpe)
}
}
def extractFromArg(argIdx : Int, lhs : Boolean) : Calc = {
val (typedTree, tpe) = GetArgTree(argIdx, lhs)
VerboseTraversal(s"@@extractFromArg@@\nTP: $tpe\nRAW: ${showRaw(tpe)}\nTree: $typedTree")
TypeCalc(tpe) match {
case _ : CalcUnknown => CalcUnknown(tpe, Some(c.untypecheck(typedTree)), opIntercept = false)
case t : CalcNLit => CalcNLit(t, typedTree)
case t => t
}
}
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
// Three operands (Generic)
///////////////////////////////////////////////////////////////////////////////////////////
def materializeOpGen[F](implicit ev0: c.WeakTypeTag[F]): MaterializeOpAuxGen =
new MaterializeOpAuxGen(weakTypeOf[F])
def opCalc(funcType : TypeSymbol, aCalc : => Calc, bCalc : => Calc, cCalc : => Calc) : Calc = {
lazy val a = aCalc
lazy val b = bCalc
lazy val cArg = cCalc
def unsupported() : Calc = {
val opMacroTpe = typeOf[OpMacro[_,_,_,_]].typeConstructor
val opTpe = appliedType(opMacroTpe, List(funcType.toType, a.tpe, b.tpe, cArg.tpe))
val interceptTpe = typeOf[singleton.ops.OpIntercept[_]].typeConstructor
MacroCache.clearErrorCache()
try {
val itree = c.inferImplicitValue (
appliedType(interceptTpe, List(opTpe)),
silent = false
)
TypeCalc(itree.tpe.decls.head.info) match {
case t : CalcUnknown => t.copy(treeOption = Some(c.untypecheck(q"$itree.value")),opIntercept = true) //the unknown result must be marked properly so we allow it later
case t => t
}
} catch {
case TypecheckException(_, _) =>
MacroCache.getErrorMessage match {
case m if m.nonEmpty => abort(m)
case _ => (a, b) match {
case (_ : CalcVal, _ : CalcVal) => abort(s"Unsupported operation $opTpe")
case _ => CalcUnknown(funcType.toType, None, opIntercept = false)
}
}
}
}
//The output val is literal if all arguments are literal. Otherwise, it is non-literal.
lazy implicit val cvKind : CalcVal.Kind = (a, b, cArg) match {
case (_ : CalcLit, _ : CalcLit, _ : CalcLit) => CalcVal.Lit
case _ => CalcVal.NLit
}
def AcceptNonLiteral : Calc = Id //AcceptNonLiteral has a special handling in MaterializeOpAuxGen
def GetArg : Calc = (a, b) match {
case (CalcLit.Int(idx), CalcLit.Boolean(lhs)) if (idx >= 0) => extractFromArg(idx, lhs)
case _ => unsupported()
}
def Id : Calc = a match {
case (av : Calc) => av
case _ => unsupported()
}
def ToNat : Calc = ToInt //Same handling, but also has a special case to handle this in MaterializeOpAuxGen
def ToChar : Calc = a match {
case CalcVal(t : Char, tt) => CalcVal(t, q"$tt")
case CalcVal(t : Int, tt) => CalcVal(t.toChar, q"$tt.toChar")
case CalcVal(t : Long, tt) => CalcVal(t.toChar, q"$tt.toChar")
case CalcVal(t : Float, tt) => CalcVal(t.toChar, q"$tt.toChar")
case CalcVal(t : Double, tt) => CalcVal(t.toChar, q"$tt.toChar")
case _ => unsupported()
}
def ToInt : Calc = a match {
case CalcVal(t : Char, tt) => CalcVal(t.toInt, q"$tt.toInt")
case CalcVal(t : Int, tt) => CalcVal(t, q"$tt")
case CalcVal(t : Long, tt) => CalcVal(t.toInt, q"$tt.toInt")
case CalcVal(t : Float, tt) => CalcVal(t.toInt, q"$tt.toInt")
case CalcVal(t : Double, tt) => CalcVal(t.toInt, q"$tt.toInt")
case CalcVal(t : String, tt) => CalcVal(t.toInt, q"$tt.toInt")
case _ => unsupported()
}
def ToLong : Calc = a match {
case CalcVal(t : Char, tt) => CalcVal(t.toLong, q"$tt.toLong")
case CalcVal(t : Int, tt) => CalcVal(t.toLong, q"$tt.toLong")
case CalcVal(t : Long, tt) => CalcVal(t, q"$tt")
case CalcVal(t : Float, tt) => CalcVal(t.toLong, q"$tt.toLong")
case CalcVal(t : Double, tt) => CalcVal(t.toLong, q"$tt.toLong")
case CalcVal(t : String, tt) => CalcVal(t.toLong, q"$tt.toLong")
case _ => unsupported()
}
def ToFloat : Calc = a match {
case CalcVal(t : Char, tt) => CalcVal(t.toFloat, q"$tt.toFloat")
case CalcVal(t : Int, tt) => CalcVal(t.toFloat, q"$tt.toFloat")
case CalcVal(t : Long, tt) => CalcVal(t.toFloat, q"$tt.toFloat")
case CalcVal(t : Float, tt) => CalcVal(t, q"$tt")
case CalcVal(t : Double, tt) => CalcVal(t.toFloat, q"$tt.toFloat")
case CalcVal(t : String, tt) => CalcVal(t.toFloat, q"$tt.toFloat")
case _ => unsupported()
}
def ToDouble : Calc = a match {
case CalcVal(t : Char, tt) => CalcVal(t.toDouble, q"$tt.toDouble")
case CalcVal(t : Int, tt) => CalcVal(t.toDouble, q"$tt.toDouble")
case CalcVal(t : Long, tt) => CalcVal(t.toDouble, q"$tt.toDouble")
case CalcVal(t : Float, tt) => CalcVal(t.toDouble, q"$tt.toDouble")
case CalcVal(t : Double, tt) => CalcVal(t, q"$tt")
case CalcVal(t : String, tt) => CalcVal(t.toDouble, q"$tt.toDouble")
case _ => unsupported()
}
def ToString : Calc = a match {
case CalcVal(t : Char, tt) => CalcVal(t.toString, q"$tt.toString")
case CalcVal(t : Int, tt) => CalcVal(t.toString, q"$tt.toString")
case CalcVal(t : Long, tt) => CalcVal(t.toString, q"$tt.toString")
case CalcVal(t : Float, tt) => CalcVal(t.toString, q"$tt.toString")
case CalcVal(t : Double, tt) => CalcVal(t.toString, q"$tt.toString")
case CalcVal(t : String, tt) => CalcVal(t, q"$tt")
case CalcVal(t : Boolean, tt) => CalcVal(t.toString, q"$tt.toString")