/
PythonGen.scala
1923 lines (1777 loc) · 63.8 KB
/
PythonGen.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
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 org.bykn.bosatsu.codegen.python
import cats.Monad
import cats.data.{NonEmptyList, State}
import cats.parse.{Parser => P}
import org.bykn.bosatsu.{
PackageName,
Identifier,
Matchless,
Par,
Parser,
RecursionKind
}
import org.bykn.bosatsu.rankn.Type
import org.typelevel.paiges.Doc
import Identifier.Bindable
import Matchless._
import cats.implicits._
object PythonGen {
import Code.{ValueLike, Statement, Expression}
type Module = NonEmptyList[Code.Ident]
sealed abstract class Env[+A]
object Env {
import Code._
def pure[A](a: A): Env[A] = envMonad.pure(a)
implicit def envMonad: Monad[Env] =
new Monad[Env] {
import Impl._
val m = Monad[State[EnvState, *]]
def pure[A](a: A): Env[A] = EnvImpl(m.pure(a))
override def map[A, B](ea: Env[A])(fn: A => B): Env[B] =
EnvImpl(m.map(ea.state)(fn))
def flatMap[A, B](ea: Env[A])(fn: A => Env[B]): Env[B] =
EnvImpl(m.flatMap(ea.state)(fn.andThen(_.state)))
def tailRecM[A, B](a: A)(fn: A => Env[Either[A, B]]): Env[B] =
EnvImpl(m.tailRecM(a)(fn.andThen(_.state)))
}
private object Impl {
case class EnvState(
imports: Map[Module, Code.Ident],
bindings: Map[Bindable, (Int, List[Code.Ident])],
tops: Set[Bindable],
nextTmp: Long
) {
private def bindInc(b: Bindable, inc: Int)(
fn: Int => Code.Ident
): (EnvState, Code.Ident) = {
val (c, s) = bindings.getOrElse(b, (0, Nil))
val pname = fn(c)
(
copy(
bindings = bindings.updated(b, (c + inc, pname :: s))
),
pname
)
}
def bind(b: Bindable): (EnvState, Code.Ident) =
bindInc(b, 1) { c =>
Code.Ident(escapeRaw("___b", b.asString + c.toString))
}
// in loops we need to substitute
// bindings for mutable variables
def subs(b: Bindable, c: Code.Ident): EnvState =
bindInc(b, 0)(_ => c)._1
def deref(b: Bindable): Code.Ident =
// see if we are shadowing, or top level
bindings.get(b) match {
case Some((_, h :: _)) => h
case _ if tops(b) => escape(b)
case other =>
// $COVERAGE-OFF$
throw new IllegalStateException(
s"unexpected deref: $b with bindings: $other"
)
// $COVERAGE-ON$
}
def unbind(b: Bindable): EnvState =
bindings.get(b) match {
case Some((cnt, _ :: tail)) =>
copy(bindings = bindings.updated(b, (cnt, tail)))
case other =>
// $COVERAGE-OFF$
throw new IllegalStateException(
s"invalid scope: $other for $b with $bindings"
)
// $COVERAGE-ON$
}
def getNextTmp: (EnvState, Long) =
(copy(nextTmp = nextTmp + 1L), nextTmp)
def topLevel(b: Bindable): (EnvState, Code.Ident) =
(copy(tops = tops + b), escape(b))
def addImport(mod: Module): (EnvState, Code.Ident) =
imports.get(mod) match {
case Some(alias) => (this, alias)
case None =>
val impNumber = imports.size
val alias = Code.Ident(
escapeRaw("___i", mod.last.name + impNumber.toString)
)
(copy(imports = imports.updated(mod, alias)), alias)
}
def importStatements: List[Code.Import] =
imports.iterator
.map { case (path, alias) =>
val modName = path.map(_.name).toList.mkString(".")
Code.Import(modName, Some(alias))
}
.toList
.sortBy(_.modname)
}
implicit class EnvOps[A](val env: Env[A]) extends AnyVal {
def state: State[EnvState, A] =
env.asInstanceOf[EnvImpl[A]].state
}
def emptyState: EnvState =
EnvState(Map.empty, Map.empty, Set.empty, 0L)
case class EnvImpl[A](state: State[EnvState, A]) extends Env[A]
def env[A](fn: EnvState => (EnvState, A)): Env[A] =
EnvImpl(State(fn))
def read[A](fn: EnvState => A): Env[A] =
EnvImpl(State(state => (state, fn(state))))
def update(fn: EnvState => EnvState): Env[Unit] =
EnvImpl(State(state => (fn(state), ())))
def run[A](env: Env[A]): (EnvState, A) =
env.state.run(emptyState).value
}
def render(env: Env[List[Statement]]): Doc = {
val (state, stmts) = Impl.run(env)
val imps = state.importStatements
val impDocs = Doc.intercalate(Doc.hardLine, imps.map(Code.toDoc))
val twoLines = Doc.hardLine + Doc.hardLine
Doc.intercalate(twoLines, impDocs :: stmts.map(Code.toDoc))
}
// allocate a unique identifier for b
def bind(b: Bindable): Env[Code.Ident] =
Impl.env(_.bind(b))
// point this name to the top level name
def subs(b: Bindable, i: Code.Ident): Env[Unit] =
Impl.update(_.subs(b, i))
// get the mapping for a name in scope
def deref(b: Bindable): Env[Code.Ident] =
Impl.read(_.deref(b))
// release the current scope for b
def unbind(b: Bindable): Env[Unit] =
Impl.update(_.unbind(b))
def nameForAnon(long: Long): Env[Code.Ident] =
Env.pure(Code.Ident(s"___a$long"))
def newAssignableVar: Env[Code.Ident] =
Impl
.env(_.getNextTmp)
.map { long =>
Code.Ident(s"___t$long")
}
def importPackage(pack: PackageName): Env[Code.Ident] =
importEscape(pack.parts)
def importEscape(parts: NonEmptyList[String]): Env[Code.Ident] =
importLiteral(parts.map(escapeModule))
def importLiteral(parts: NonEmptyList[Code.Ident]): Env[Code.Ident] =
Impl.env(_.addImport(parts))
// top level names are imported across files so they have
// to be consistently transformed
def topLevelName(n: Bindable): Env[Code.Ident] =
Impl.env(_.topLevel(n))
def onLastsM(
cs: List[ValueLike]
)(fn: List[Expression] => Env[ValueLike]): Env[ValueLike] = {
def loop(
cs: List[ValueLike],
setup: List[Statement],
args: List[Expression]
): Env[ValueLike] =
cs match {
case Nil =>
val res = fn(args.reverse)
NonEmptyList.fromList(setup) match {
case None => res
case Some(nel) =>
val stmts = nel.reverse
val stmt = Code.block(stmts.head, stmts.tail: _*)
res.map(stmt.withValue(_))
}
case (e: Expression) :: t => loop(t, setup, e :: args)
case (ifelse @ IfElse(_, _)) :: tail =>
// we allocate a result and assign
// the result on each value
Env.newAssignableVar.flatMap { v =>
loop(tail, (v := ifelse) :: setup, v :: args)
}
case WithValue(decl, v) :: tail =>
loop(v :: tail, decl :: setup, args)
}
loop(cs, Nil, Nil)
}
def onLasts(cs: List[ValueLike])(
fn: List[Expression] => ValueLike
): Env[ValueLike] =
onLastsM(cs)(fn.andThen(Env.pure(_)))
def onLastM(
c: ValueLike
)(fn: Expression => Env[ValueLike]): Env[ValueLike] =
onLastsM(c :: Nil) {
case x :: Nil => fn(x)
case other =>
// $COVERAGE-OFF$
throw new IllegalStateException(
s"expected list to have size 1: $other"
)
// $COVERAGE-ON$
}
def onLast(c: ValueLike)(fn: Expression => ValueLike): Env[ValueLike] =
onLastM(c)(fn.andThen(Env.pure(_)))
def onLast2(c1: ValueLike, c2: ValueLike)(
fn: (Expression, Expression) => ValueLike
): Env[ValueLike] =
onLasts(c1 :: c2 :: Nil) {
case x1 :: x2 :: Nil => fn(x1, x2)
case other =>
// $COVERAGE-OFF$
throw new IllegalStateException(
s"expected list to have size 2: $other"
)
// $COVERAGE-ON$
}
def ifElse(
conds: NonEmptyList[(ValueLike, ValueLike)],
elseV: ValueLike
): Env[ValueLike] =
// for all the non-expression conditions, we need to defer evaluating them
// until they are really needed
conds match {
case NonEmptyList((cx: Expression, t), Nil) =>
(t, elseV) match {
case (tx: Expression, elseX: Expression) =>
Env.pure(Ternary(tx, cx, elseX).simplify)
case _ =>
Env.pure(IfElse(NonEmptyList.one((cx, t)), elseV))
}
case NonEmptyList((cx: Expression, t), rh :: rt) =>
val head = (cx, t)
ifElse(NonEmptyList(rh, rt), elseV).map {
case IfElse(crest, er) =>
// preserve IfElse chains
IfElse(head :: crest, er)
case nestX: Expression =>
t match {
case tx: Expression =>
Ternary(tx, cx, nestX).simplify
case _ =>
IfElse(NonEmptyList.one(head), nestX)
}
case nest =>
IfElse(NonEmptyList.one(head), nest)
}
case NonEmptyList((cx, t), rest) =>
for {
// allocate a new unshadowable var
cv <- Env.newAssignableVar
res <- ifElse(NonEmptyList((cv, t), rest), elseV)
} yield (cv := cx).withValue(res)
}
def ifElseS(
cond: ValueLike,
thenS: Statement,
elseS: Statement
): Env[Statement] =
cond match {
case x: Expression => Env.pure(Code.ifElseS(x, thenS, elseS))
case WithValue(stmt, vl) =>
ifElseS(vl, thenS, elseS).map(stmt +: _)
case v =>
// this is a branch, don't multiply code by writing on each
// branch, that could give an exponential blowup
Env.newAssignableVar
.map { tmp =>
Code.block(
tmp := v,
Code.ifElseS(tmp, thenS, elseS)
)
}
}
def andCode(c1: ValueLike, c2: ValueLike): Env[ValueLike] =
(c1, c2) match {
case (t: Expression, c2) if t.simplify == Code.Const.True =>
Env.pure(c2)
case (_, x2: Expression) =>
onLast(c1)(_.evalAnd(x2))
case _ =>
// we know that c2 is not a simple expression
// res = False
// if c1:
// res = c2
Env.onLastM(c1) { x1 =>
for {
res <- Env.newAssignableVar
ifstmt <- ifElseS(x1, res := c2, Code.Pass)
} yield {
Code
.block(
res := Code.Const.False,
ifstmt
)
.withValue(res)
}
}
}
def makeDef(
defName: Code.Ident,
arg: NonEmptyList[Code.Ident],
v: ValueLike
): Code.Def =
Code.Def(defName, arg.toList, toReturn(v))
def replaceTailCallWithAssign(name: Ident, argSize: Int, body: ValueLike)(
onArgs: List[Expression] => Statement
): Env[ValueLike] = {
val initBody = body
def loop(body: ValueLike): Env[ValueLike] =
body match {
case a @ Apply(fn0, args0) =>
if (fn0 == name) {
if (args0.length == argSize) {
val all = onArgs(args0)
// set all the values and return the empty tuple
Env.pure(all.withValue(Code.Const.Unit))
} else {
// $COVERAGE-OFF$
throw new IllegalStateException(
s"expected a tailcall for $name in $initBody, but found: $a"
)
// $COVERAGE-ON$
}
} else {
Env.pure(a)
}
case Parens(p) => loop(p).flatMap(onLast(_)(Parens(_)))
case IfElse(ifCases, elseCase) =>
// only the result types are in tail position, we don't need to recurse on conds
val ifs = ifCases.traverse { case (cond, res) =>
loop(res).map((cond, _))
}
(ifs, loop(elseCase))
.mapN(ifElse(_, _))
.flatten
case Ternary(ifTrue, cond, ifFalse) =>
// both results are in the tail position
(loop(ifTrue), loop(ifFalse)).mapN { (t, f) =>
ifElse(NonEmptyList.one((cond, t)), f)
}.flatten
case WithValue(stmt, v) =>
loop(v).map(stmt.withValue(_))
// the rest cannot have a call in the tail position
case DotSelect(_, _) | Op(_, _, _) | Lambda(_, _) | MakeTuple(_) |
MakeList(_) | SelectItem(_, _) | SelectRange(_, _, _) | Ident(_) |
PyBool(_) | PyString(_) | PyInt(_) =>
Env.pure(body)
}
loop(initBody)
}
// these are always recursive so we can use def to define them
def buildLoop(
selfName: Ident,
fnMutArgs: NonEmptyList[(Ident, Ident)],
body: ValueLike
): Env[Statement] = {
/*
* bodyUpdate = body except App(foo, args) is replaced with
* reseting the inputs, and setting cont to True and having
* the value ()
*
* def foo(a)(b)(c):
* cont = True
* res = ()
* while cont:
* cont = False
* res = bodyUpdate
* return res
*/
val fnArgs = fnMutArgs.map(_._1)
val mutArgs = fnMutArgs.map(_._2)
def assignMut(cont: Code.Ident)(args: List[Expression]): Statement = {
// do the replacement in one atomic go. otherwise
// we could mutate a variable a later expression depends on
// some times we generate code that does x = x, remove those cases
val (left, right) =
mutArgs.toList.zip(args).filter { case (x, y) => x != y }.unzip
Code.block(
cont := Const.True,
if (left.isEmpty) Pass
else if (left.lengthCompare(1) == 0) {
left.head := right.head
} else {
(MakeTuple(left) := MakeTuple(right))
}
)
}
for {
cont <- Env.newAssignableVar
ac = assignMut(cont)(fnArgs.toList)
res <- Env.newAssignableVar
ar = (res := Code.Const.Unit)
body1 <- replaceTailCallWithAssign(selfName, mutArgs.length, body)(
assignMut(cont)
)
setRes = res := body1
loop = While(cont, (cont := false) +: setRes)
newBody = (ac +: ar +: loop).withValue(res)
} yield makeDef(selfName, fnArgs, newBody)
}
}
private[this] val base62Items =
(('0' to '9') ++ ('A' to 'Z') ++ ('a' to 'z')).toSet
private def toBase62(c: Char): String =
if (base62Items(c)) c.toString
else if (c == '_') "__"
else {
def toChar(i0: Int): Char =
if (i0 < 0) {
// $COVERAGE-OFF$
sys.error(s"invalid in: $i0")
// $COVERAGE-ON$
} else if (i0 < 10) (i0 + '0'.toInt).toChar
else if (i0 < 36) (i0 - 10 + 'A'.toInt).toChar
else if (i0 < 62) (i0 - 36 + 'a'.toInt).toChar
else {
// $COVERAGE-OFF$
sys.error(s"invalid int: $i0")
// $COVERAGE-ON$
}
def toString(i: Int): String =
if (i < 62) toChar(i).toString
else {
val i0 = i % 62
val i1 = i / 62
toString(i1) + toChar(i0)
}
"_" + toString(c.toInt) + "_"
}
private def escapeRaw(prefix: String, str: String): String =
str.map(toBase62).mkString(prefix, "", "")
private def unBase62(
str: String,
offset: Int,
bldr: java.lang.StringBuilder
): Int = {
var idx = offset
var num = 0
while (idx < str.length) {
val c = str.charAt(idx)
idx += 1
if (c == '_') {
if (idx != offset + 1) {
// done
val numC = num.toChar
bldr.append(numC)
return (idx - offset)
} else {
// "__" decodes to "_"
bldr.append('_')
return (idx - offset)
}
} else {
val base =
if (c <= '9') '0'.toInt
else if (c <= 'Z') ('A'.toInt - 10)
else ('a'.toInt - 36)
num = num * 62 + c.toInt - base
}
}
return -1
}
// we escape by prefixing by three underscores, ___ and n (for name)
// we use other ___x escapes for different name spaces, e.g. tmps, and anons
// then we escape _ by __ and any character outside the allowed
// range by _base 62_
// ___t: tmp
// ___a anons
// ___n: name
// ___m: modules
// ___i: import alias
// ___b: shadowable (internal) names
def escape(n: Bindable): Code.Ident = {
val str = n.asString
if (
!str.startsWith("___") && Code.python2Name.matcher(str).matches && !Code
.pyKeywordList(str)
) Code.Ident(str)
else {
// we need to escape
Code.Ident(escapeRaw("___n", str))
}
}
def escapeModule(str: String): Code.Ident =
if (
!str.startsWith("___") && Code.python2Name.matcher(str).matches && !Code
.pyKeywordList(str)
) Code.Ident(str)
else {
// we need to escape
Code.Ident(escapeRaw("___m", str))
}
def unescape(ident: Code.Ident): Option[Bindable] = {
val str = ident.name
val res = if (str.startsWith("___n")) {
val bldr = new java.lang.StringBuilder()
var idx = 4
while (idx < str.length) {
val c = str.charAt(idx)
idx += 1
if (c == '_') {
val res = unBase62(str, idx, bldr)
if (res < 1) return None
else {
idx += res
}
} else {
bldr.append(c)
}
}
bldr.toString()
} else {
str
}
if (str.isEmpty) None
else {
Identifier
.optionParse(Identifier.bindableParser, res)
.orElse(Some(Identifier.Backticked(res)))
}
}
/** Remap is used to handle remapping external values
*/
private def apply(packName: PackageName, name: Bindable, me: Expr)(
remap: (PackageName, Bindable) => Env[Option[ValueLike]]
): Env[Statement] = {
val ops = new Impl.Ops(packName, remap)
// if we have a top level let rec with the same name, handle it more cleanly
me match {
case Let(Right((n1, RecursionKind.NonRecursive)), inner, Local(n2))
if ((n1 === name) && (n2 === name)) =>
// we can just bind now at the top level
for {
nm <- Env.topLevelName(name)
res <- inner match {
case fn: FnExpr => ops.topFn(nm, fn, None)
case _ => ops.loop(inner, None).map(nm := _)
}
} yield res
case Let(Right((n1, RecursionKind.Recursive)), fn: FnExpr, Local(n2))
if (n1 === name) && (n2 === name) =>
for {
nm <- Env.topLevelName(name)
res <- ops.topFn(nm, fn, None)
} yield res
case fn: FnExpr =>
for {
nm <- Env.topLevelName(name)
res <- ops.topFn(nm, fn, None)
} yield res
case _ =>
for {
// name is not in scope yet
ve <- ops.loop(me, None)
nm <- Env.topLevelName(name)
} yield nm := ve
}
}
private def addUnitTest(name: Bindable): Env[Statement] =
// we could inspect the Expr, but for now, we will just put
// everything in a single test:
// class BosatsuTests(unittest.TestCase):
// def test_all(self):
// # iterate through making assertions
//
(
Env.importLiteral(NonEmptyList.one(Code.Ident("unittest"))),
Env.newAssignableVar,
Env.topLevelName(name)
)
.mapN { (importedName, tmpVar, testName) =>
import Impl._
val loopName = Code.Ident("test_loop")
val argName = Code.Ident("value")
val selfName = Code.Ident("self")
val isAssertion: Code.Expression =
argName.get(0) =:= 0
// Assertion(bool, msg)
val testAssertion: Code.Statement =
Code.Call(
Code.Apply(
selfName.dot(Code.Ident("assertTrue")),
argName.get(1) :: argName.get(2) :: Nil
)
)
// TestSuite(suiteName, tests)
val testSuite: Code.Statement =
Code.block(
tmpVar := argName.get(2), // get the test list
Code.While(
isNonEmpty(tmpVar),
Code.block(
Code.Call(Code.Apply(loopName, headList(tmpVar) :: Nil)),
tmpVar := tailList(tmpVar)
)
)
)
val loopBody: Code.Statement =
Code.IfStatement(
NonEmptyList.one((isAssertion, testAssertion)),
Some(testSuite)
)
val recTest =
Code.Def(loopName, argName :: Nil, loopBody)
val body =
Code.block(recTest, Code.Call(Code.Apply(loopName, testName :: Nil)))
val defBody =
Code.Def(Code.Ident("test_all"), selfName :: Nil, body)
Code.ClassDef(
Code.Ident("BosatsuTests"),
List(importedName.dot(Code.Ident("TestCase"))),
defBody
)
}
private def addMainEval(
name: Bindable,
mod: Module,
ci: Code.Ident
): Env[Statement] =
/*
* this does:
* if __name__ == "__main__":
* from Module import ci
* ci(name)
*/
(Env.importLiteral(mod), Env.topLevelName(name))
.mapN { (importedName, argName) =>
Code.mainStatement(
Code.Call(importedName.dot(ci)(argName))
)
}
private val modParser: P[(Module, Code.Ident)] = {
val identParser: P[Code.Ident] = Parser.py2Ident.map(Code.Ident(_))
P.repSep(identParser, min = 2, sep = P.char('.'))
.map { items =>
// min = 2 ensures this is safe
(NonEmptyList.fromListUnsafe(items.init.toList), items.last)
}
}
// parses a nested map with
//
// { packageName: { bind: foo.bar.baz } }
//
val externalParser: P[List[(PackageName, Bindable, Module, Code.Ident)]] = {
val inner: P[List[(Bindable, (Module, Code.Ident))]] =
Parser.dictLikeParser(Identifier.bindableParser, modParser)
val outer: P[List[(PackageName, List[(Bindable, (Module, Code.Ident))])]] =
Parser.maybeSpacesAndLines.with1 *> Parser.dictLikeParser(
PackageName.parser,
inner
) <* Parser.maybeSpacesAndLines
outer.map { items =>
items.flatMap { case (p, bs) =>
bs.map { case (b, (m, i)) => (p, b, m, i) }
}
}
}
// parses a map of of evaluators
// { fullyqualifiedType: foo.bar.baz, }
val evaluatorParser: P[List[(Type, (Module, Code.Ident))]] =
Parser.maybeSpacesAndLines.with1 *> Parser.dictLikeParser(
Type.fullyResolvedParser,
modParser
) <* Parser.maybeSpacesAndLines
// compile a set of packages given a set of external remappings
def renderAll(
pm: Map[PackageName, List[(Bindable, Expr)]],
externals: Map[(PackageName, Bindable), (Module, Code.Ident)],
tests: Map[PackageName, Bindable],
evaluators: Map[PackageName, (Bindable, Module, Code.Ident)]
)(implicit ec: Par.EC): Map[PackageName, (Module, Doc)] = {
val externalRemap: (PackageName, Bindable) => Env[Option[ValueLike]] = {
(p, b) =>
externals.get((p, b)) match {
case None => Env.pure(None)
case Some((m, i)) =>
Env
.importLiteral(m)
.map(alias => Some(Code.DotSelect(alias, i)))
}
}
val all = pm.toList
.traverse { case (p, lets) =>
Par.start {
val stmts0: Env[List[Statement]] =
lets
.traverse { case (b, x) =>
apply(p, b, x)(externalRemap)
}
val evalStmt: Env[Option[Statement]] =
evaluators.get(p).traverse { case (b, m, c) =>
addMainEval(b, m, c)
}
val testStmt: Env[Option[Statement]] =
tests.get(p).traverse(addUnitTest)
val stmts = (stmts0, testStmt, evalStmt)
.mapN { (s, optT, optM) =>
s :++ optT.toList :++ optM.toList
}
def modName(p: NonEmptyList[String]): Module =
p match {
case NonEmptyList(h, Nil) =>
val Code.Ident(m) = escapeModule(h)
NonEmptyList.one(Code.Ident(m + ".py"))
case NonEmptyList(h, t1 :: t2) =>
escapeModule(h) :: modName(NonEmptyList(t1, t2))
}
(p, (modName(p.parts), Env.render(stmts)))
}
}
Par.await(all).toMap
}
// These are values replaced with python operations
def intrinsicValues: Map[PackageName, Set[Bindable]] =
Map((PackageName.PredefName, Impl.PredefExternal.results.keySet))
private object Impl {
val emptyList: Expression =
Code.MakeTuple(Code.fromInt(0) :: Nil)
def consList(head: Expression, tail: Expression): Expression =
Code.MakeTuple(List(Code.fromInt(1), head, tail))
def isNonEmpty(expr: Expression): Expression =
Code.Op(expr.get(0), Code.Const.Neq, Code.fromInt(0)).simplify
def headList(lst: Expression): Expression =
lst.get(1).simplify
def tailList(lst: Expression): Expression =
lst.get(2).simplify
object PredefExternal {
private val cmpFn: List[ValueLike] => Env[ValueLike] = { input =>
Env.onLast2(input.head, input.tail.head) { (arg0, arg1) =>
Code
.Ternary(
0,
arg0 :< arg1,
Code.Ternary(1, arg0 =:= arg1, 2)
)
.simplify
}
}
val results: Map[Bindable, (List[ValueLike] => Env[ValueLike], Int)] =
Map(
(
Identifier.unsafeBindable("add"),
(
input => Env.onLast2(input.head, input.tail.head)(_.evalPlus(_)),
2
)
),
(
Identifier.unsafeBindable("sub"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(_.evalMinus(_))
},
2
)
),
(
Identifier.unsafeBindable("times"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(_.evalTimes(_))
},
2
)
),
(
Identifier.unsafeBindable("div"),
(
{ input =>
Env.onLast2(input.head, input.tail.head) { (a, b) =>
Code
.Ternary(
Code.Op(a, Code.Const.Div, b),
b, // 0 is false in python
0
)
.simplify
}
},
2
)
),
(
Identifier.unsafeBindable("mod_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head) { (a, b) =>
Code
.Ternary(
Code.Op(a, Code.Const.Mod, b),
b, // 0 is false in python
a
)
.simplify
}
},
2
)
),
(Identifier.unsafeBindable("cmp_Int"), (cmpFn, 2)),
(
Identifier.unsafeBindable("eq_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(
_.eval(Code.Const.Eq, _)
)
},
2
)
),
(
Identifier.unsafeBindable("shift_left_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(
_.eval(Code.Const.BitwiseShiftLeft, _)
)
},
2
)
),
(
Identifier.unsafeBindable("shift_right_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(
_.eval(Code.Const.BitwiseShiftRight, _)
)
},
2
)
),
(
Identifier.unsafeBindable("and_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(
_.eval(Code.Const.BitwiseAnd, _)
)
},
2
)
),
(
Identifier.unsafeBindable("or_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(
_.eval(Code.Const.BitwiseOr, _)
)
},
2
)
),
(
Identifier.unsafeBindable("xor_Int"),
(
{ input =>
Env.onLast2(input.head, input.tail.head)(
_.eval(Code.Const.BitwiseXor, _)
)
},
2
)
),
(
Identifier.unsafeBindable("not_Int"),
(
{
// leverage not(x) == -1 - x
input => Env.onLast(input.head)(Code.fromInt(-1).evalMinus(_))
},
2
)
),
(
Identifier.unsafeBindable("gcd_Int"),
(
{ input =>
(
Env.newAssignableVar,
Env.newAssignableVar,
Env.newAssignableVar
).mapN { (tmpa, tmpb, tmpc) =>