/
MainModule.scala
1587 lines (1431 loc) · 51.7 KB
/
MainModule.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
import cats.data.{Chain, Validated, ValidatedNel, NonEmptyList}
import cats.{Eval, MonadError, Traverse}
import com.monovore.decline.{Argument, Command, Help, Opts}
import cats.parse.{Parser0 => P0, Parser => P}
import org.typelevel.paiges.Doc
import scala.util.{Failure, Success, Try}
import CollectionUtils.listToUnique
import Identifier.Bindable
import IorMethods.IorExtension
import LocationMap.Colorize
import cats.implicits._
/** This is an implementation of the CLI tool where Path is abstracted. The idea
* is to allow it to be testable and usable in scalajs where we don't have
* file-IO
*/
abstract class MainModule[IO[_]](implicit
val moduleIOMonad: MonadError[IO, Throwable]
) {
type Path
implicit def pathArg: Argument[Path]
def readPath(p: Path): IO[String]
def readPackages(paths: List[Path]): IO[List[Package.Typed[Unit]]]
def readInterfaces(paths: List[Path]): IO[List[Package.Interface]]
/** given an ordered list of prefered roots, if a packFile starts with one of
* these roots, return a PackageName based on the rest
*/
def pathPackage(roots: List[Path], packFile: Path): Option[PackageName]
/** Modules optionally have the capability to combine paths into a tree
*/
def resolvePath: Option[(Path, PackageName) => IO[Option[Path]]]
/** some modules have paths that form directory trees
*
* if the given path is a directory, return Some and all the first children.
*/
def unfoldDir: Option[Path => IO[Option[IO[List[Path]]]]]
def hasExtension(str: String): Path => Boolean
// we can do side effects in here
def delay[A](a: => A): IO[A]
//////////////////////////////
// Below here are concrete and should not use override
//////////////////////////////
final def withEC[A](fn: Par.EC => IO[A]): IO[A] =
delay(Par.newService())
.flatMap { es =>
fn(Par.ecFromService(es))
.flatMap { a =>
delay {
Par.shutdownService(es)
a
}
}
.recoverWith { case e =>
delay {
Par.shutdownService(es)
}.flatMap(_ => moduleIOMonad.raiseError[A](e))
}
}
final def run(args: List[String]): Either[Help, IO[Output]] =
MainCommand.command
.parse(args.toList)
.map(_.run.widen)
sealed abstract class FileKind(val name: String)
object FileKind {
case object Source extends FileKind("source")
case object Iface extends FileKind("interface")
case object Pack extends FileKind("package")
}
sealed abstract class GraphOutput
object GraphOutput {
case object Dot extends GraphOutput
case object Json extends GraphOutput
val jsonOrDot: Opts[GraphOutput] =
Opts
.option[String]("graph_format", "format of graph, either json or dot")
.mapValidated {
case "json" => Validated.valid(Json)
case "dot" => Validated.valid(Dot)
case other =>
Validated.invalidNel(s"\"$other\" invalid, expected json or dot")
}
.withDefault(Json)
}
sealed abstract class Output
object Output {
case class TestOutput(
tests: List[(PackageName, Option[Eval[Test]])],
colorize: Colorize
) extends Output
case class EvaluationResult(
value: Eval[Value],
tpe: rankn.Type,
doc: Eval[Doc]
) extends Output
case class JsonOutput(json: Json, output: Option[Path]) extends Output
case class CompileOut(
packList: List[Package.Typed[Any]],
ifout: Option[Path],
output: Option[Path]
) extends Output
case class TranspileOut(outs: List[(NonEmptyList[String], Doc)], base: Path)
extends Output
case class ShowOutput(
packages: List[Package.Typed[Any]],
ifaces: List[Package.Interface],
output: Option[Path]
) extends Output
case class DepsOutput(
depinfo: List[(Path, PackageName, FileKind, List[PackageName])],
output: Option[Path],
style: GraphOutput
) extends Output
}
sealed abstract class MainException extends Exception {
def command: MainCommand
}
object MainException {
case class NoInputs(command: MainCommand) extends MainException
case class ParseErrors(
command: MainCommand,
errors: NonEmptyList[MainCommand.ParseError],
color: Colorize
) extends MainException {
def messages: List[String] =
errors.toList.flatMap {
case MainCommand.ParseError.ParseFailure(pf, path) =>
// we should never be partial here
val (r, c) = pf.locations.toLineCol(pf.position).get
val ctx = pf.showContext(color)
List(
s"failed to parse $path:${r + 1}:${c + 1}",
ctx.render(80)
)
case MainCommand.ParseError.FileError(path, err) =>
err match {
case e
if e.getClass.getName == "java.nio.file.NoSuchFileException" =>
// This class isn't present in scalajs, use the String
List(s"file not found: $path")
case _ =>
List(
s"failed to parse $path",
err.getMessage,
err.getClass.toString
)
}
}
}
case class PackageErrors(
command: MainCommand,
sourceMap: PackageMap.SourceMap,
errors: NonEmptyList[PackageError],
color: Colorize
) extends MainException {
def messages: List[String] =
errors.toList.distinct
.map(_.message(sourceMap, color))
}
}
def mainExceptionToString(ex: Throwable): Option[String] =
ex match {
case me: MainException =>
me match {
case MainException.NoInputs(cmd) =>
val name = cmd.name
Some(s"no inputs given to $name")
case pe @ MainException.ParseErrors(_, _, _) =>
Some(pe.messages.mkString("\n"))
case pe @ MainException.PackageErrors(_, _, _, _) =>
Some(pe.messages.mkString("\n"))
}
case _ =>
None
}
sealed abstract class MainCommand(val name: String) {
type Result <: Output
def run: IO[Result]
}
object MainCommand {
def parseInputs[F[_]: Traverse](
paths: F[Path],
packRes: PackageResolver
): IO[ValidatedNel[ParseError, F[((Path, LocationMap), Package.Parsed)]]] =
// we use IO(traverse) so we can accumulate all the errors in parallel easily
// if do this with parseFile returning an IO, we need to do IO.Par[Validated[...]]
// and use the composed applicative... too much work for the same result
paths
.traverse { path =>
val defaultPack = packRes.packageNameFor(path)
parseFile(Package.parser(defaultPack), path)
.map(_.map { case (lm, parsed) =>
((path, lm), parsed)
})
}
.map(_.sequence)
def parseHeaders[F[_]: Traverse](
paths: F[Path],
packRes: PackageResolver
): IO[ValidatedNel[ParseError, F[(Path, Package.Header)]]] =
// we use IO(traverse) so we can accumulate all the errors in parallel easily
// if do this with parseFile returning an IO, we need to do IO.Par[Validated[...]]
// and use the composed applicative... too much work for the same result
paths
.traverse { path =>
val defaultPack = packRes.packageNameFor(path)
readPath(path).map { str =>
parseStart(Package.headerParser(defaultPack), path, str)
.map { case (_, pp) => (path, pp) }
}
}
.map(_.sequence)
private def flatTrav[A, B, C](va: Validated[A, B])(
fn: B => IO[Validated[A, C]]
): IO[Validated[A, C]] =
va.traverse(fn).map(_.andThen(identity _))
/** This parses all the given paths and returns them first, and if the
* PackageResolver supports it, we look for any missing dependencies that
* are not already included
*/
def parseAllInputs(
paths: List[Path],
included: Set[PackageName],
packRes: PackageResolver
): IO[
ValidatedNel[ParseError, List[((Path, LocationMap), Package.Parsed)]]
] =
parseInputs(paths, packRes)
.flatMap {
flatTrav(_) { parsed =>
val done = included ++ parsed.toList.map(_._2.name)
val allImports = parsed.toList.flatMap(_._2.imports.map(_.pack))
val missing: List[PackageName] = allImports.filterNot(done)
parseTransitivePacks(missing, packRes, done)
.map(_.map { case (searched, _) => parsed ::: searched.toList })
}
}
type ParseTransResult = ValidatedNel[
ParseError,
(Chain[((Path, LocationMap), Package.Parsed)], Set[PackageName])
]
private def parseTransitive(
search: PackageName,
packRes: PackageResolver,
done: Set[PackageName]
): IO[ParseTransResult] = {
val maybeReadPack: IO[Option[(Path, String)]] =
if (done(search)) {
moduleIOMonad.pure(Option.empty[(Path, String)])
} else {
packRes
.pathFor(search)
.flatMap(_.traverse { path =>
readPath(path).map((path, _))
})
}
val optParsed: IO[
ValidatedNel[ParseError, Option[((Path, LocationMap), Package.Parsed)]]
] =
maybeReadPack.map { opt =>
opt.traverse { case (path, str) =>
val defaultPack = packRes.packageNameFor(path)
parseString(Package.parser(defaultPack), path, str)
.map { case (lm, parsed) =>
((path, lm), parsed)
}
}
}
def imports(p: Package.Parsed): List[PackageName] =
p.imports.map(_.pack)
val newDone = done + search
optParsed.flatMap {
flatTrav(_) {
case None =>
moduleIOMonad.pure(
Validated.valid(
(Chain.empty[((Path, LocationMap), Package.Parsed)], newDone)
): ParseTransResult
)
case Some(item @ (_, pack)) =>
val imps = imports(pack).filterNot(done)
parseTransitivePacks(imps, packRes, newDone)
.map(_.map { case (newPacks, newDone) =>
(item +: newPacks, newDone)
})
}
}
}
private def parseTransitivePacks(
search: List[PackageName],
packRes: PackageResolver,
done: Set[PackageName]
): IO[ParseTransResult] =
search.foldM(Validated.valid((Chain.empty, done)): ParseTransResult) {
(prev, impPack) =>
flatTrav(prev) { case (acc, prevDone) =>
parseTransitive(impPack, packRes, prevDone)
.map(_.map { case (newPacks, newDone) =>
(acc ++ newPacks, newDone)
})
}
}
sealed trait ParseError
object ParseError {
case class ParseFailure(error: Parser.Error.ParseFailure, path: Path)
extends ParseError
case class FileError(readPath: Path, error: Throwable) extends ParseError
}
def parseString[A](
p: P0[A],
path: Path,
str: String
): ValidatedNel[ParseError, (LocationMap, A)] =
Parser.parse(p, str).leftMap { nel =>
nel.map { case pf @ Parser.Error.ParseFailure(_, _, _) =>
ParseError.ParseFailure(pf, path)
}
}
def parseStart[A](
p0: P0[A],
path: Path,
str: String
): ValidatedNel[ParseError, (LocationMap, A)] = {
val lm = LocationMap(str)
p0.parse(str) match {
case Right((_, a)) =>
Validated.valid((lm, a))
case Left(err) =>
val idx = err.failedAtOffset
Validated.invalidNel(
ParseError.ParseFailure(
Parser.Error.ParseFailure(idx, lm, err.expected),
path
)
)
}
}
def parseFile[A](
p: P0[A],
path: Path
): IO[ValidatedNel[ParseError, (LocationMap, A)]] =
parseFileOrError(p, path)
.map {
case Right(v) => v
case Left(err) =>
Validated.invalidNel(ParseError.FileError(path, err))
}
/** If we cannot read the file, return the throwable, else parse
*/
def parseFileOrError[A](
p: P0[A],
path: Path
): IO[Either[Throwable, ValidatedNel[ParseError, (LocationMap, A)]]] =
readPath(path).attempt
.map(_.map(parseString(p, path, _)))
/** like typecheck, but a no-op for empty lists
*/
def typeCheck0(
cmd: MainCommand,
inputs: List[Path],
ifs: List[Package.Interface],
errColor: Colorize,
packRes: PackageResolver
)(implicit
ec: Par.EC
): IO[(PackageMap.Inferred, List[(Path, PackageName)])] =
NonEmptyList.fromList(inputs) match {
case None =>
// we should still return the predef
// if it is not in ifs
val useInternalPredef =
!ifs.exists { (p: Package.Interface) =>
p.name == PackageName.PredefName
}
if (useInternalPredef) {
moduleIOMonad.pure(
(PackageMap.fromIterable(PackageMap.predefCompiled :: Nil), Nil)
)
} else {
moduleIOMonad.pure((PackageMap.empty, Nil))
}
case Some(nel) => typeCheck(cmd, nel, ifs, errColor, packRes)
}
def typeCheck(
cmd: MainCommand,
inputs: NonEmptyList[Path],
ifs: List[Package.Interface],
errColor: Colorize,
packRes: PackageResolver
)(implicit
ec: Par.EC
): IO[(PackageMap.Inferred, List[(Path, PackageName)])] =
parseAllInputs(inputs.toList, ifs.map(_.name).toSet, packRes)
.flatMap { ins =>
moduleIOMonad.fromTry {
// Now we have completed all IO, here we do all the checks we need for correctness
toTry(cmd, ins, errColor)
.flatMap { packs =>
// TODO, we could use applicative, to report both duplicate packages and the other
// errors
NonEmptyList.fromList(packs) match {
case Some(packs) =>
val packsString = packs.map { case ((path, lm), parsed) =>
((path.toString, lm), parsed)
}
PackageMap
.typeCheckParsed[String](packsString, ifs, "predef")
.strictToValidated match {
case Validated.Valid(p) =>
val pathToName: List[(Path, PackageName)] =
packs.map { case ((path, _), p) =>
(path, p.name)
}.toList
Success((p, pathToName))
case Validated.Invalid(errs) =>
val sourceMap = PackageMap.buildSourceMap(packs)
Failure(
MainException.PackageErrors(
cmd,
sourceMap,
errs,
errColor
)
)
}
case None =>
Success((PackageMap.empty, Nil))
}
}
}
}
def buildPackMap(
cmd: MainCommand,
srcs: List[Path],
deps: List[Path],
errColor: Colorize,
packRes: PackageResolver
)(implicit
ec: Par.EC
): IO[(PackageMap.Typed[Any], List[(Path, PackageName)])] =
for {
packs <- readPackages(deps)
ifaces = packs.map(Package.interfaceOf(_))
packsList <- typeCheck0(cmd, srcs, ifaces, errColor, packRes)
(thesePacks, lst) = packsList
packMap = packs.foldLeft(PackageMap.toAnyTyped(thesePacks))(_ + _)
} yield (packMap, lst)
/** This allows us to use either a path or packagename to select the main
* file
*/
sealed abstract class MainIdentifier {
def path: Option[Path]
def addIfAbsent(paths: List[Path]): List[Path] =
path match {
case Some(p) if !paths.contains(p) => p :: paths
case _ => paths
}
def getMain(
ps: List[(Path, PackageName)]
): IO[(PackageName, Option[Bindable])]
}
object MainIdentifier {
case class FromPackage(mainPackage: PackageName, value: Option[Bindable])
extends MainIdentifier {
def path: Option[Path] = None
def getMain(
ps: List[(Path, PackageName)]
): IO[(PackageName, Option[Bindable])] =
moduleIOMonad.pure((mainPackage, value))
}
case class FromFile(mainFile: Path) extends MainIdentifier {
def path: Option[Path] = Some(mainFile)
def getMain(
ps: List[(Path, PackageName)]
): IO[(PackageName, Option[Bindable])] =
ps.collectFirst { case (path, pn) if path == mainFile => pn } match {
case Some(p) => moduleIOMonad.pure((p, None))
case None =>
moduleIOMonad.raiseError(
new Exception(
s"could not find file $mainFile in parsed sources"
)
)
}
}
def opts(
pnOpts: Opts[(PackageName, Option[Bindable])],
fileOpts: Opts[Path]
): Opts[MainIdentifier] =
pnOpts
.map { case (p, i) => FromPackage(p, i) }
.orElse(fileOpts.map(FromFile(_)))
def list(
packs: Opts[List[(PackageName, Option[Bindable])]],
files: Opts[List[Path]]
): Opts[List[MainIdentifier]] =
(packs, files).mapN { (ps, fs) =>
ps.map { case (p, i) => FromPackage(p, i) } ::: fs.map(FromFile(_))
}
def addAnyAbsent(
ms: List[MainIdentifier],
paths: List[Path]
): List[Path] = {
val present = paths.toSet
val toAdd = ms.iterator.flatMap(_.path).filterNot(present).toList
toAdd ::: paths
}
}
/** This is a class that names packages based on path and finds packages
* based on imports
*/
sealed abstract class PackageResolver {
def pathFor(name: PackageName): IO[Option[Path]]
def packageNameFor(path: Path): Option[PackageName]
}
object PackageResolver {
case object ExplicitOnly extends PackageResolver {
def pathFor(name: PackageName): IO[Option[Path]] =
moduleIOMonad.pure(Option.empty[Path])
def packageNameFor(path: Path): Option[PackageName] = None
}
case class LocalRoots(
roots: NonEmptyList[Path],
optResolvePath: Option[(Path, PackageName) => IO[Option[Path]]]
) extends PackageResolver {
def pathFor(name: PackageName): IO[Option[Path]] =
optResolvePath match {
case None => moduleIOMonad.pure(Option.empty[Path])
case Some(resolvePath) =>
def step(p: List[Path]): IO[Either[List[Path], Option[Path]]] =
p match {
case Nil =>
moduleIOMonad.pure(Right[List[Path], Option[Path]](None))
case phead :: ptail =>
resolvePath(phead, name).map {
case None => Left[List[Path], Option[Path]](ptail)
case some @ Some(_) =>
Right[List[Path], Option[Path]](some)
}
}
moduleIOMonad.tailRecM(roots.toList)(step)
}
def packageNameFor(path: Path): Option[PackageName] =
pathPackage(roots.toList, path)
}
}
sealed abstract class Transpiler(val name: String) {
def renderAll(
pm: PackageMap.Typed[Any],
externals: List[String],
evaluators: List[String]
)(implicit ec: Par.EC): IO[List[(NonEmptyList[String], Doc)]]
}
object Transpiler {
case object PythonTranspiler extends Transpiler("python") {
def renderAll(
pm: PackageMap.Typed[Any],
externals: List[String],
evaluators: List[String]
)(implicit ec: Par.EC): IO[List[(NonEmptyList[String], Doc)]] = {
import codegen.python.PythonGen
val allExternals = pm.allExternals
val cmp = MatchlessFromTypedExpr.compile(pm)
moduleIOMonad.catchNonFatal {
val parsedExt =
externals.map(Parser.unsafeParse(PythonGen.externalParser, _))
val extMap = listToUnique(parsedExt.flatten)(
{ case (p, b, _, _) => (p, b) },
{ case (_, _, m, f) => (m, f) },
"expected each package/name to map to just one file"
).get
val exts = extMap.keySet
val intrinsic = PythonGen.intrinsicValues
val missingExternals =
allExternals.iterator.flatMap { case (p, names) =>
val missing = names.filterNot { case n =>
exts((p, n)) || intrinsic.get(p).exists(_(n))
}
if (missing.isEmpty) Nil
else (p, missing.sorted) :: Nil
}.toList
if (missingExternals.isEmpty) {
val tests = pm.toMap.iterator.flatMap { case (n, pack) =>
Package.testValue(pack).iterator.map { case (bn, _, _) =>
(n, bn)
}
}.toMap
val parsedEvals =
evaluators.map(Parser.unsafeParse(PythonGen.evaluatorParser, _))
val typeEvalMap = listToUnique(parsedEvals.flatten)(
t => t._1,
t => t._2,
"expected each type to have to just one evaluator"
).get
val evalMap = pm.toMap.iterator.flatMap { case (n, p) =>
val optEval = p.program.lets.findLast { case (_, _, te) =>
typeEvalMap.contains(te.getType)
}
optEval.map { case (b, _, te) =>
val (m, i) = typeEvalMap(te.getType)
(n, (b, m, i))
}
}.toMap
val docs = PythonGen
.renderAll(cmp, extMap, tests, evalMap)
.iterator
.map { case (_, (path, doc)) =>
(path.map(_.name), doc)
}
.toList
// python also needs empty __init__.py files in every parent directory
def prefixes[A](
paths: List[(NonEmptyList[String], A)]
): List[(NonEmptyList[String], Doc)] = {
val inits =
paths.map { case (path, _) =>
val parent = path.init
val initPy = parent :+ "__init__.py"
NonEmptyList.fromListUnsafe(initPy)
}.toSet
inits.toList.sorted.map(p => (p, Doc.empty))
}
prefixes(docs) ::: docs
} else {
// we need to render this nicer
val missingDoc =
missingExternals
.sortBy(_._1)
.map { case (p, names) =>
(Doc.text("package") + Doc.lineOrSpace + Doc.text(
p.asString
) + Doc.lineOrSpace +
Doc.char('[') +
Doc.intercalate(
Doc.comma + Doc.lineOrSpace,
names.map(b => Doc.text(b.sourceCodeRepr))
) + Doc.char(']')).nested(4)
}
val message = Doc.text(
"Missing external values:"
) + (Doc.line + Doc.intercalate(Doc.line, missingDoc)).nested(4)
throw new IllegalArgumentException(message.renderTrim(80))
}
}
}
}
val all: List[Transpiler] = List(PythonTranspiler)
implicit def argumentForTranspiler: Argument[Transpiler] =
new Argument[Transpiler] {
val nameTo = all.iterator.map(t => (t.name, t)).toMap
def defaultMetavar: String = "transpiler"
def read(string: String): ValidatedNel[String, Transpiler] =
nameTo.get(string) match {
case Some(t) => Validated.valid(t)
case None =>
val keys = nameTo.keys.toList.sorted.mkString(",")
Validated.invalidNel(
s"unknown transpiler: $string, expected one of: $keys"
)
}
}
val opt: Opts[Transpiler] =
Opts.option[Transpiler]("lang", "language to transpile to")
}
sealed abstract class JsonInput {
def read: IO[String]
}
object JsonInput {
case class FromString(asString: String) extends JsonInput {
def read = moduleIOMonad.pure(asString)
}
case class FromPath(path: Path) extends JsonInput {
def read = readPath(path)
}
}
sealed abstract class JsonMode
object JsonMode {
case object Write extends JsonMode
case class Apply(in: JsonInput) extends JsonMode
case class Traverse(in: JsonInput) extends JsonMode
}
type PathGen = org.bykn.bosatsu.PathGen[IO, Path]
val PathGen = org.bykn.bosatsu.PathGen
sealed abstract class Inputs
object Inputs {
// This allows interfaces
class Compile(
srcs: PathGen,
ifaces: PathGen,
packageResolver: PackageResolver
) extends Inputs {
private def inNel(cmd: MainCommand): IO[NonEmptyList[Path]] =
srcs.read.flatMap { ins =>
NonEmptyList.fromList(ins) match {
case Some(nel) => moduleIOMonad.pure(nel)
case None =>
moduleIOMonad.raiseError(MainException.NoInputs(cmd))
}
}
def compile(cmd: MainCommand, errColor: Colorize)(implicit
ec: Par.EC
): IO[(PackageMap.Inferred, List[(Path, PackageName)])] =
for {
ifpaths <- ifaces.read
ifs <- readInterfaces(ifpaths)
ins <- inNel(cmd)
packPath <- typeCheck(
cmd,
ins,
ifs,
errColor,
packageResolver
)
} yield packPath
}
class Show(
srcs: PathGen,
ifaces: PathGen,
includes: PathGen,
packageResolver: PackageResolver
) extends Inputs {
def loadAndCompile(cmd: MainCommand, errColor: Colorize)(implicit
ec: Par.EC
): IO[(List[Package.Interface], List[Package.Typed[Any]])] =
(
srcs.read,
ifaces.read.flatMap(readInterfaces),
includes.read.flatMap(readPackages)
)
.flatMapN {
case (Nil, ifaces, packs) =>
moduleIOMonad.pure((ifaces, packs))
case (h :: t, ifaces, packs) =>
val packIfs = packs.map(Package.interfaceOf(_))
for {
packPath <- typeCheck(
cmd,
NonEmptyList(h, t),
ifaces ::: packIfs,
errColor,
packageResolver
)
allPacks = (PackageMap.fromIterable(
packs
) ++ packPath._1.toMap.map(_._2)).toMap.toList.map(_._2)
} yield (ifaces, allPacks)
}
}
class Deps(
srcs: PathGen,
ifaces: PathGen,
includes: PathGen,
val packageResolver: PackageResolver
) extends Inputs {
def srcList: IO[List[Path]] = srcs.read
def readIfaces: IO[List[(Path, Package.Interface)]] =
for {
ifPaths <- ifaces.read
withIf <- readInterfaces(ifPaths).map(ifPaths.zip(_))
} yield withIf
def readPacks: IO[List[(Path, Package.Typed[Any])]] =
for {
pPaths <- includes.read
withPs <- readPackages(pPaths).map(pPaths.zip(_))
} yield withPs
}
class Runtime(
srcs: PathGen,
includes: PathGen,
packageResolver: PackageResolver
) extends Inputs {
def packMap(
cmd: MainCommand,
mis: List[MainIdentifier],
errColor: Colorize
)(implicit
ec: Par.EC
): IO[(PackageMap.Typed[Any], List[(Path, PackageName)])] =
for {
ins <- srcs.read
ds <- includes.read
ins1 = MainIdentifier.addAnyAbsent(mis, ins)
pn <-
if (ds.isEmpty && ins1.isEmpty)
moduleIOMonad.raiseError(MainException.NoInputs(cmd))
else
buildPackMap(
cmd,
srcs = ins1,
deps = ds,
errColor,
packageResolver
)
} yield pn
}
private def pathGen(
arg: String,
help: String,
ext: String
): Opts[PathGen] = {
val direct = Opts
.options[Path](arg, help = help)
.orEmpty
.map(paths => paths.foldMap(PathGen.Direct[IO, Path](_): PathGen))
unfoldDir match {
case None => direct
case Some(unfold) =>
val select = hasExtension(ext)
val child1 = Opts
.options[Path](arg + "_dir", help = s"all $help in directory")
.orEmpty
.map { paths =>
paths.foldMap(
PathGen
.ChildrenOfDir[IO, Path](_, select, false, unfold): PathGen
)
}
val childMany = Opts
.options[Path](
arg + "_all_subdir",
help = s"all $help recursively in all directories"
)
.orEmpty
.map { paths =>
paths.foldMap(
PathGen
.ChildrenOfDir[IO, Path](_, select, true, unfold): PathGen
)
}
(direct, child1, childMany).mapN { (a, b, c) =>
(a :: b :: c :: Nil).combineAll
}
}
}
private val srcs =
pathGen("input", help = "input source files", ".bosatsu")
private val ifaces =
pathGen("interface", help = "interface files", ".bosatsig")
private val includes = pathGen(
"include",
help = "compiled packages to include files",
".bosatsu_package"
)
private val packRoot =
Opts.options[Path](
"package_root",
help = "for implicit package names, consider these paths as roots"
)
private val packSearch =
resolvePath match {
case None => Opts(None)
case some @ Some(_) =>
Opts
.flag(
"search",
help =
"if set, we search the package_roots for imports not explicitly given"
)
.orFalse
.map {
case true => some
case false => None
}
}
private val packRes: Opts[PackageResolver] =
(packRoot
.product(packSearch))
.orNone
.map {
case None => PackageResolver.ExplicitOnly
case Some((paths, search)) =>
PackageResolver.LocalRoots(paths, search)
}
// type-checking and writing protos should be explicit. search option isn't supported
private val noSearchRes: Opts[PackageResolver] =
packRoot.orNone
.map {
case None => PackageResolver.ExplicitOnly
case Some(paths) => PackageResolver.LocalRoots(paths, None)
}
val compileOpts: Opts[Inputs.Compile] =
(srcs, ifaces, noSearchRes).mapN(new Compile(_, _, _))
val runtimeOpts: Opts[Inputs.Runtime] =
(srcs, includes, packRes).mapN(new Runtime(_, _, _))
val showOpts: Opts[Inputs.Show] =
(srcs, ifaces, includes, packRes).mapN(new Show(_, _, _, _))
val depsOpts: Opts[Inputs.Deps] =
(srcs, ifaces, includes, packRes).mapN(new Deps(_, _, _, _))
}
case class TranspileCommand(
inputs: Inputs.Runtime,
errColor: Colorize,
generator: Transpiler,
outDir: Path,
exts: List[Path],
evals: List[Path]
) extends MainCommand("transpile") {
// case class TranspileOut(outs: Map[PackageName, (List[String], Doc)], base: Path) extends Output
type Result = Output.TranspileOut
def run =
withEC { implicit ec =>
for {