-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Build.scala
1605 lines (1374 loc) · 68.8 KB
/
Build.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
import java.io.File
import java.nio.file._
import Modes._
import com.jsuereth.sbtpgp.PgpKeys
import sbt.Keys._
import sbt._
import complete.DefaultParsers._
import pl.project13.scala.sbt.JmhPlugin
import pl.project13.scala.sbt.JmhPlugin.JmhKeys.Jmh
import sbt.Package.ManifestAttributes
import sbt.plugins.SbtPlugin
import sbt.ScriptedPlugin.autoImport._
import xerial.sbt.pack.PackPlugin
import xerial.sbt.pack.PackPlugin.autoImport._
import xerial.sbt.Sonatype.autoImport._
import dotty.tools.sbtplugin.DottyPlugin.autoImport._
import dotty.tools.sbtplugin.DottyPlugin.makeScalaInstance
import dotty.tools.sbtplugin.DottyIDEPlugin.{ installCodeExtension, prepareCommand, runProcess }
import dotty.tools.sbtplugin.DottyIDEPlugin.autoImport._
import org.scalajs.sbtplugin.ScalaJSPlugin
import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._
import sbtbuildinfo.BuildInfoPlugin
import sbtbuildinfo.BuildInfoPlugin.autoImport._
import scala.util.Properties.isJavaAtLeast
object MyScalaJSPlugin extends AutoPlugin {
import Build._
override def requires: Plugins = ScalaJSPlugin
override def projectSettings: Seq[Setting[_]] = Def.settings(
commonBootstrappedSettings,
// Replace the JVM JUnit dependency by the Scala.js one
libraryDependencies ~= {
_.filter(!_.name.startsWith("junit-interface"))
},
libraryDependencies +=
("org.scala-js" %% "scalajs-junit-test-runtime" % scalaJSVersion % "test").withDottyCompat(scalaVersion.value),
// Typecheck the Scala.js IR found on the classpath
scalaJSLinkerConfig ~= (_.withCheckIR(true)),
// Exclude all these projects from `configureIDE/launchIDE` since they
// take time to compile, print a bunch of warnings, and are rarely edited.
excludeFromIDE := true
)
}
object Build {
val referenceVersion = "3.0.0-M2"
val baseVersion = "3.0.0-RC1"
val baseSbtDottyVersion = "0.4.7"
// Versions used by the vscode extension to create a new project
// This should be the latest published releases.
// TODO: Have the vscode extension fetch these numbers from the Internet
// instead of hardcoding them ?
val publishedDottyVersion = referenceVersion
val publishedSbtDottyVersion = "0.4.6"
/** scala-library version required to compile Dotty.
*
* Both the non-bootstrapped and bootstrapped version should match, unless
* we're in the process of upgrading to a new major version of
* scala-library.
*/
def stdlibVersion(implicit mode: Mode): String = mode match {
case NonBootstrapped => "2.13.4"
case Bootstrapped => "2.13.4"
}
val dottyOrganization = "org.scala-lang"
val dottyGithubUrl = "https://github.com/lampepfl/dotty"
val dottyGithubRawUserContentUrl = "https://raw.githubusercontent.com/lampepfl/dotty"
val isRelease = sys.env.get("RELEASEBUILD") == Some("yes")
val dottyVersion = {
def isNightly = sys.env.get("NIGHTLYBUILD") == Some("yes")
if (isRelease)
baseVersion
else if (isNightly)
baseVersion + "-bin-" + VersionUtil.commitDate + "-" + VersionUtil.gitHash + "-NIGHTLY"
else
baseVersion + "-bin-SNAPSHOT"
}
val dottyNonBootstrappedVersion = dottyVersion + "-nonbootstrapped"
val sbtDottyName = "sbt-dotty"
val sbtDottyVersion = {
if (isRelease) baseSbtDottyVersion else baseSbtDottyVersion + "-SNAPSHOT"
}
val agentOptions = List(
// "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"
// "-agentpath:/home/dark/opt/yjp-2013-build-13072/bin/linux-x86-64/libyjpagent.so"
// "-agentpath:/Applications/YourKit_Java_Profiler_2015_build_15052.app/Contents/Resources/bin/mac/libyjpagent.jnilib",
// "-XX:+HeapDumpOnOutOfMemoryError", "-Xmx1g", "-Xss2m"
)
// Packages all subprojects to their jars
val packageAll = taskKey[Map[String, String]]("Package everything needed to run tests")
// Run tests with filter through vulpix test suite
val testCompilation = inputKey[Unit]("runs integration test with the supplied filter")
// Spawns a repl with the correct classpath
val repl = inputKey[Unit]("run the REPL with correct classpath")
// Used to compile files similar to ./bin/scalac script
val scalac = inputKey[Unit]("run the compiler using the correct classpath, or the user supplied classpath")
// Used to run binaries similar to ./bin/scala script
val scala = inputKey[Unit]("run compiled binary using the correct classpath, or the user supplied classpath")
// Compiles the documentation and static site
val genDocs = inputKey[Unit]("run dottydoc to generate static documentation site")
// Shorthand for compiling a docs site
val dottydoc = inputKey[Unit]("run dottydoc")
// Only available in vscode-dotty
val unpublish = taskKey[Unit]("Unpublish a package")
// Settings used to configure the test language server
val ideTestsCompilerVersion = taskKey[String]("Compiler version to use in IDE tests")
val ideTestsCompilerArguments = taskKey[Seq[String]]("Compiler arguments to use in IDE tests")
val ideTestsDependencyClasspath = taskKey[Seq[File]]("Dependency classpath to use in IDE tests")
val fetchScalaJSSource = taskKey[File]("Fetch the sources of Scala.js")
lazy val SourceDeps = config("sourcedeps")
// Settings shared by the build (scoped in ThisBuild). Used in build.sbt
lazy val thisBuildSettings = Def.settings(
organization := dottyOrganization,
organizationName := "LAMP/EPFL",
organizationHomepage := Some(url("http://lamp.epfl.ch")),
scalacOptions ++= Seq(
"-feature",
"-deprecation",
"-unchecked",
"-Xfatal-warnings",
"-encoding", "UTF8",
"-language:existentials,higherKinds,implicitConversions,postfixOps"
),
javacOptions in (Compile, compile) ++= Seq("-Xlint:unchecked", "-Xlint:deprecation"),
// Override `runCode` from sbt-dotty to use the language-server and
// vscode extension from the source repository of dotty instead of a
// published version.
runCode := (run in `scala3-language-server`).toTask("").value,
// Avoid various sbt craziness involving classloaders and parallelism
fork in run := true,
fork in Test := true,
parallelExecution in Test := false,
outputStrategy := Some(StdoutOutput),
// enable verbose exception messages for JUnit
testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v"),
)
// Settings shared globally (scoped in Global). Used in build.sbt
lazy val globalSettings = Def.settings(
onLoad := (onLoad in Global).value andThen { state =>
def exists(submodule: String) = {
val path = Paths.get(submodule)
Files.exists(path) && {
val fileStream = Files.list(path)
try fileStream.iterator().hasNext
finally fileStream.close()
}
}
// Copy default configuration from .vscode-template/ unless configuration files already exist in .vscode/
sbt.IO.copyDirectory(new File(".vscode-template/"), new File(".vscode/"), overwrite = false)
state
},
// I find supershell more distracting than helpful
useSuperShell := false,
// Credentials to release to Sonatype
credentials ++= (
for {
username <- sys.env.get("SONATYPE_USER")
password <- sys.env.get("SONATYPE_PW")
} yield Credentials("Sonatype Nexus Repository Manager", "oss.sonatype.org", username, password)
).toList,
PgpKeys.pgpPassphrase := sys.env.get("PGP_PW").map(_.toCharArray()),
PgpKeys.useGpgPinentry := true,
javaOptions ++= {
val ciOptions = // propagate if this is a CI build
sys.props.get("dotty.drone.mem") match {
case Some(prop) => List("-Xmx" + prop)
case _ => List()
}
// Do not cut off the bottom of large stack traces (default is 1024)
"-XX:MaxJavaStackTraceDepth=1000000" :: agentOptions ::: ciOptions
},
excludeLintKeys ++= Set(
// We set these settings in `commonSettings`, if a project
// uses `commonSettings` but overrides `unmanagedSourceDirectories`,
// sbt will complain if we don't exclude them here.
Keys.scalaSource, Keys.javaSource
),
)
lazy val disableDocSetting =
// Disable scaladoc generation, it's way too slow and we'll replace it
// by dottydoc anyway. We still publish an empty -javadoc.jar to make
// sonatype happy.
sources in (Compile, doc) := Seq()
lazy val commonSettings = publishSettings ++ Seq(
scalaSource in Compile := baseDirectory.value / "src",
scalaSource in Test := baseDirectory.value / "test",
javaSource in Compile := baseDirectory.value / "src",
javaSource in Test := baseDirectory.value / "test",
resourceDirectory in Compile := baseDirectory.value / "resources",
resourceDirectory in Test := baseDirectory.value / "test-resources",
// Prevent sbt from rewriting our dependencies
scalaModuleInfo ~= (_.map(_.withOverrideScalaVersion(false))),
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % Test,
// If someone puts a source file at the root (e.g., for manual testing),
// don't pick it up as part of any project.
sourcesInBase := false,
)
// Settings used for projects compiled only with Java
lazy val commonJavaSettings = commonSettings ++ Seq(
version := dottyVersion,
scalaVersion := referenceVersion,
// Do not append Scala versions to the generated artifacts
crossPaths := false,
// Do not depend on the Scala library
autoScalaLibrary := false,
excludeFromIDE := true,
disableDocSetting
)
// Settings used when compiling dotty (both non-bootstrapped and bootstrapped)
lazy val commonDottySettings = commonSettings ++ Seq(
// Manually set the standard library to use
autoScalaLibrary := false
)
lazy val commonScala2Settings = commonSettings ++ Seq(
scalaVersion := stdlibVersion(Bootstrapped),
moduleName ~= { _.stripSuffix("-scala2") },
version := dottyVersion,
target := baseDirectory.value / ".." / "out" / "scala-2" / name.value,
disableDocSetting
)
// Settings used when compiling dotty with the reference compiler
lazy val commonNonBootstrappedSettings = commonDottySettings ++ Seq(
unmanagedSourceDirectories in Compile += baseDirectory.value / "src-non-bootstrapped",
version := dottyNonBootstrappedVersion,
scalaVersion := referenceVersion,
excludeFromIDE := true,
disableDocSetting
)
// Settings used when compiling dotty with a non-bootstrapped dotty
lazy val commonBootstrappedSettings = commonDottySettings ++ Seq(
unmanagedSourceDirectories in Compile += baseDirectory.value / "src-bootstrapped",
version := dottyVersion,
scalaVersion := dottyNonBootstrappedVersion,
scalaCompilerBridgeBinaryJar := {
Some((packageBin in (`scala3-sbt-bridge`, Compile)).value)
},
// Use the same name as the non-bootstrapped projects for the artifacts.
// Remove the `js` suffix because JS artifacts are published using their special crossVersion.
// The order of the two `stripSuffix`es is important, so that
// scala3-library-bootstrappedjs becomes scala3-library.
moduleName ~= { _.stripSuffix("js").stripSuffix("-bootstrapped") },
// Enforce that the only Scala 2 classfiles we unpickle come from scala-library
/*
scalacOptions ++= {
val cp = (dependencyClasspath in `scala3-library` in Compile).value
val scalaLib = findArtifactPath(cp, "scala-library")
Seq("-Yscala2-unpickler", scalaLib)
},
*/
// sbt gets very unhappy if two projects use the same target
target := baseDirectory.value / ".." / "out" / "bootstrap" / name.value,
// Compile using the non-bootstrapped and non-published dotty
managedScalaInstance := false,
scalaInstance := {
val externalNonBootstrappedDeps = externalDependencyClasspath.in(`scala3-doc`, Compile).value
val scalaLibrary = findArtifact(externalNonBootstrappedDeps, "scala-library")
// IMPORTANT: We need to use actual jars to form the ScalaInstance and not
// just directories containing classfiles because sbt maintains a cache of
// compiler instances. This cache is invalidated based on timestamps
// however this is only implemented on jars, directories are never
// invalidated.
val tastyCore = packageBin.in(`tasty-core`, Compile).value
val dottyLibrary = packageBin.in(`scala3-library`, Compile).value
val dottyInterfaces = packageBin.in(`scala3-interfaces`, Compile).value
val dottyCompiler = packageBin.in(`scala3-compiler`, Compile).value
val dottyDoc = packageBin.in(`scala3-doc`, Compile).value
val allJars = Seq(tastyCore, dottyLibrary, dottyInterfaces, dottyCompiler, dottyDoc) ++ externalNonBootstrappedDeps.map(_.data)
makeScalaInstance(
state.value,
scalaVersion.value,
scalaLibrary,
dottyLibrary,
dottyCompiler,
allJars
)
},
// sbt-dotty defines `scalaInstance in doc` so we need to override it manually
scalaInstance in doc := scalaInstance.value,
disableDocSetting,
)
lazy val commonBenchmarkSettings = Seq(
mainClass in (Jmh, run) := Some("dotty.tools.benchmarks.Bench"), // custom main for jmh:run
javaOptions += "-DBENCH_COMPILER_CLASS_PATH=" + Attributed.data((fullClasspath in (`scala3-bootstrapped`, Compile)).value).mkString("", File.pathSeparator, ""),
javaOptions += "-DBENCH_CLASS_PATH=" + Attributed.data((fullClasspath in (`scala3-library-bootstrapped`, Compile)).value).mkString("", File.pathSeparator, "")
)
/** Projects -------------------------------------------------------------- */
val dottyCompilerBootstrappedRef = LocalProject("scala3-compiler-bootstrapped")
/** External dependencies we may want to put on the compiler classpath. */
def externalCompilerClasspathTask: Def.Initialize[Task[Def.Classpath]] =
// Even if we're running the non-bootstrapped compiler, we want the
// dependencies of the bootstrapped compiler since we want to put them on
// the compiler classpath, not the JVM classpath.
externalDependencyClasspath.in(dottyCompilerBootstrappedRef, Runtime)
// The root project:
// - aggregates other projects so that "compile", "test", etc are run on all projects at once.
// - publishes its own empty artifact "dotty" that depends on "scala3-library" and "scala3-compiler",
// this is only necessary for compatibility with sbt which currently hardcodes the "dotty" artifact name
lazy val scala3 = project.in(file(".")).asDottyRoot(NonBootstrapped)
lazy val `scala3-bootstrapped` = project.asDottyRoot(Bootstrapped)
lazy val `scala3-interfaces` = project.in(file("interfaces")).
settings(commonJavaSettings)
private lazy val dottydocClasspath = Def.task {
val jars = (packageAll in `scala3-compiler`).value
val dottyLib = jars("scala3-library")
val otherDeps = (dependencyClasspath in Compile).value.map(_.data).mkString(File.pathSeparator)
val externalDeps = externalCompilerClasspathTask.value
dottyLib + File.pathSeparator + findArtifactPath(externalDeps, "scala-library")
}
lazy val commonDocSettings = Seq(
baseDirectory in (Compile, run) := baseDirectory.value / "..",
baseDirectory in Test := baseDirectory.value / "..",
libraryDependencies ++= {
val flexmarkVersion = "0.42.12"
Seq(
"com.vladsch.flexmark" % "flexmark" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-gfm-tasklist" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-gfm-tables" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-autolink" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-anchorlink" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-emoji" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-gfm-strikethrough" % flexmarkVersion,
"com.vladsch.flexmark" % "flexmark-ext-yaml-front-matter" % flexmarkVersion,
Dependencies.`jackson-dataformat-yaml`,
"nl.big-o" % "liqp" % "0.6.7"
)
}
)
def dottyDocSettings(implicit mode: Mode) = Seq(
connectInput in run := true,
javaOptions ++= (javaOptions in `scala3-compiler`).value,
javaOptions += "-Xss3m",
genDocs := Def.inputTaskDyn {
val dottydocExtraArgs = spaceDelimited("<arg>").parsed
// Make majorVersion available at dotty.epfl.ch/versions/latest-nightly-base
// Used by sbt-dotty to resolve the latest nightly
val majorVersion = (scalaBinaryVersion in LocalProject("scala3-library-bootstrapped")).value
IO.write(file("./docs/_site/versions/latest-nightly-base"), majorVersion)
// This file is used by GitHub Pages when the page is available in a custom domain
IO.write(file("./docs/_site/CNAME"), "dotty.epfl.ch")
val sources = unmanagedSources.in(dottyLibrary, Compile).value
val args = Seq(
"-siteroot", "docs",
"-project", "Dotty",
"-project-version", dottyVersion,
"-project-url", dottyGithubUrl,
"-project-logo", "scala3-logo.svg",
"-classpath", dottydocClasspath.value,
"-Yerased-terms"
) ++ dottydocExtraArgs
(runMain in Compile).toTask(
s""" dotty.tools.dottydoc.Main ${args.mkString(" ")} ${sources.mkString(" ")}"""
)
}.evaluated,
dottydoc := Def.inputTaskDyn {
val args = spaceDelimited("<arg>").parsed
val cp = dottydocClasspath.value
(runMain in Compile).toTask(s" dotty.tools.dottydoc.Main -classpath $cp " + args.mkString(" "))
}.evaluated,
)
lazy val `scala3-doc` = project.in(file("doc-tool")).asDottyDoc(NonBootstrapped)
lazy val `scala3-doc-bootstrapped` = project.in(file("doc-tool")).asDottyDoc(Bootstrapped)
def dottyDoc(implicit mode: Mode): Project = mode match {
case NonBootstrapped => `scala3-doc`
case Bootstrapped => `scala3-doc-bootstrapped`
}
/** Find an artifact with the given `name` in `classpath` */
def findArtifact(classpath: Def.Classpath, name: String): File = classpath
.find(_.get(artifact.key).exists(_.name == name))
.getOrElse(throw new MessageOnlyException(s"Artifact for $name not found in $classpath"))
.data
/** Like `findArtifact` but returns the absolute path of the entry as a string */
def findArtifactPath(classpath: Def.Classpath, name: String): String =
findArtifact(classpath, name).getAbsolutePath
// Settings shared between scala3-compiler and scala3-compiler-bootstrapped
lazy val commonDottyCompilerSettings = Seq(
// set system in/out for repl
connectInput in run := true,
// Generate compiler.properties, used by sbt
resourceGenerators in Compile += Def.task {
import java.util._
import java.text._
val file = (resourceManaged in Compile).value / "compiler.properties"
val dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss")
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"))
val contents = //2.11.11.v20170413-090219-8a413ba7cc
s"""version.number=${version.value}
|maven.version.number=${version.value}
|git.hash=${VersionUtil.gitHash}
|copyright.string=Copyright 2002-${Calendar.getInstance().get(Calendar.YEAR)}, LAMP/EPFL
""".stripMargin
if (!(file.exists && IO.read(file) == contents)) {
IO.write(file, contents)
}
Seq(file)
}.taskValue,
// get libraries onboard
libraryDependencies ++= Seq(
"org.scala-lang.modules" % "scala-asm" % "7.3.1-scala-1", // used by the backend
Dependencies.`compiler-interface`,
"org.jline" % "jline-reader" % "3.15.0", // used by the REPL
"org.jline" % "jline-terminal" % "3.15.0",
"org.jline" % "jline-terminal-jna" % "3.15.0" // needed for Windows
),
// For convenience, change the baseDirectory when running the compiler
baseDirectory in (Compile, run) := baseDirectory.value / "..",
// And when running the tests
baseDirectory in Test := baseDirectory.value / "..",
test in Test := {
// Exclude VulpixMetaTests
(testOnly in Test).toTask(" -- --exclude-categories=dotty.VulpixMetaTests").value
},
testOptions in Test += Tests.Argument(
TestFrameworks.JUnit,
"--run-listener=dotty.tools.ContextEscapeDetector",
),
// Spawn new JVM in run and test
// Add git-hash used to package the distribution to the manifest to know it in runtime and report it in REPL
packageOptions += ManifestAttributes(("Git-Hash", VersionUtil.gitHash)),
javaOptions ++= {
val managedSrcDir = {
// Populate the directory
(managedSources in Compile).value
(sourceManaged in Compile).value
}
val externalDeps = externalCompilerClasspathTask.value
val jars = packageAll.value
Seq(
"-Ddotty.tests.dottyCompilerManagedSources=" + managedSrcDir,
"-Ddotty.tests.classes.dottyInterfaces=" + jars("scala3-interfaces"),
"-Ddotty.tests.classes.dottyLibrary=" + jars("scala3-library"),
"-Ddotty.tests.classes.dottyCompiler=" + jars("scala3-compiler"),
"-Ddotty.tests.classes.tastyCore=" + jars("tasty-core"),
"-Ddotty.tests.classes.compilerInterface=" + findArtifactPath(externalDeps, "compiler-interface"),
"-Ddotty.tests.classes.scalaLibrary=" + findArtifactPath(externalDeps, "scala-library"),
"-Ddotty.tests.classes.scalaAsm=" + findArtifactPath(externalDeps, "scala-asm"),
"-Ddotty.tests.classes.jlineTerminal=" + findArtifactPath(externalDeps, "jline-terminal"),
"-Ddotty.tests.classes.jlineReader=" + findArtifactPath(externalDeps, "jline-reader"),
)
},
javaOptions += (
s"-Ddotty.tools.dotc.semanticdb.test=${(ThisBuild / baseDirectory).value/"tests"/"semanticdb"}"
),
testCompilation := Def.inputTaskDyn {
val args = spaceDelimited("<arg>").parsed
if (args.contains("--help")) {
println(
s"""
|usage: testCompilation [--help] [--from-tasty] [--update-checkfiles] [<filter>]
|
|By default runs tests in dotty.tools.dotc.*CompilationTests excluding tests tagged with dotty.SlowTests.
|
| --help show this message
| --from-tasty runs tests in dotty.tools.dotc.FromTastyTests
| --update-checkfiles override the checkfiles that did not match with the current output
| <filter> substring of the path of the tests file
|
""".stripMargin
)
(testOnly in Test).toTask(" not.a.test")
}
else {
val updateCheckfile = args.contains("--update-checkfiles")
val fromTasty = args.contains("--from-tasty")
val args1 = if (updateCheckfile | fromTasty) args.filter(x => x != "--update-checkfiles" && x != "--from-tasty") else args
val test = if (fromTasty) "dotty.tools.dotc.FromTastyTests" else "dotty.tools.dotc.*CompilationTests"
val cmd = s" $test -- --exclude-categories=dotty.SlowTests" +
(if (updateCheckfile) " -Ddotty.tests.updateCheckfiles=TRUE" else "") +
(if (args1.nonEmpty) " -Ddotty.tests.filter=" + args1.mkString(" ") else "")
(testOnly in Test).toTask(cmd)
}
}.evaluated,
scala := {
val args: List[String] = spaceDelimited("<arg>").parsed.toList
val externalDeps = externalCompilerClasspathTask.value
val jars = packageAll.value
val scalaLib = findArtifactPath(externalDeps, "scala-library")
val dottyLib = jars("scala3-library")
def run(args: List[String]): Unit = {
val fullArgs = insertClasspathInArgs(args, List(".", dottyLib, scalaLib).mkString(File.pathSeparator))
runProcess("java" :: fullArgs, wait = true)
}
if (args.isEmpty) {
println("Couldn't run `scala` without args. Use `repl` to run the repl or add args to run the dotty application")
} else if (scalaLib == "") {
println("Couldn't find scala-library on classpath, please run using script in bin dir instead")
} else if (args.contains("-with-compiler")) {
val args1 = args.filter(_ != "-with-compiler")
val asm = findArtifactPath(externalDeps, "scala-asm")
val dottyCompiler = jars("scala3-compiler")
val dottyStaging = jars("scala3-staging")
val dottyTastyInspector = jars("scala3-tasty-inspector")
val dottyInterfaces = jars("scala3-interfaces")
val tastyCore = jars("tasty-core")
run(insertClasspathInArgs(args1, List(dottyCompiler, dottyInterfaces, asm, dottyStaging, dottyTastyInspector, tastyCore).mkString(File.pathSeparator)))
} else run(args)
},
run := scalac.evaluated,
scalac := runCompilerMain().evaluated,
repl := runCompilerMain(repl = true).evaluated,
/* Add the sources of scalajs-ir.
* To guarantee that dotty can bootstrap without depending on a version
* of scalajs-ir built with a different Scala compiler, we add its
* sources instead of depending on the binaries.
*/
ivyConfigurations += SourceDeps.hide,
transitiveClassifiers := Seq("sources"),
libraryDependencies +=
("org.scala-js" %% "scalajs-ir" % scalaJSVersion % "sourcedeps").withDottyCompat(scalaVersion.value),
sourceGenerators in Compile += Def.task {
val s = streams.value
val cacheDir = s.cacheDirectory
val trgDir = (sourceManaged in Compile).value / "scalajs-ir-src"
val report = updateClassifiers.value
val scalaJSIRSourcesJar = report.select(
configuration = configurationFilter("sourcedeps"),
module = (_: ModuleID).name.startsWith("scalajs-ir_"),
artifact = artifactFilter(`type` = "src")).headOption.getOrElse {
sys.error(s"Could not fetch scalajs-ir sources")
}
FileFunction.cached(cacheDir / s"fetchScalaJSIRSource",
FilesInfo.lastModified, FilesInfo.exists) { dependencies =>
s.log.info(s"Unpacking scalajs-ir sources to $trgDir...")
if (trgDir.exists)
IO.delete(trgDir)
IO.createDirectory(trgDir)
IO.unzip(scalaJSIRSourcesJar, trgDir)
(trgDir ** "*.scala").get.toSet
} (Set(scalaJSIRSourcesJar)).toSeq
}.taskValue,
)
def runCompilerMain(repl: Boolean = false) = Def.inputTaskDyn {
val log = streams.value.log
val externalDeps = externalCompilerClasspathTask.value
val jars = packageAll.value
val scalaLib = findArtifactPath(externalDeps, "scala-library")
val dottyLib = jars("scala3-library")
val dottyCompiler = jars("scala3-compiler")
val args0: List[String] = spaceDelimited("<arg>").parsed.toList
val decompile = args0.contains("-decompile")
val printTasty = args0.contains("-print-tasty")
val debugFromTasty = args0.contains("-Ythrough-tasty")
val args = args0.filter(arg => arg != "-repl" && arg != "-decompile" &&
arg != "-with-compiler" && arg != "-Ythrough-tasty")
val main =
if (repl) "dotty.tools.repl.Main"
else if (decompile || printTasty) "dotty.tools.dotc.decompiler.Main"
else if (debugFromTasty) "dotty.tools.dotc.fromtasty.Debug"
else "dotty.tools.dotc.Main"
var extraClasspath = Seq(scalaLib, dottyLib)
if ((decompile || printTasty) && !args.contains("-classpath"))
extraClasspath ++= Seq(".")
if (args0.contains("-with-compiler")) {
if (scalaVersion.value == referenceVersion) {
log.error("-with-compiler should only be used with a bootstrapped compiler")
}
val dottyInterfaces = jars("scala3-interfaces")
val dottyStaging = jars("scala3-staging")
val dottyTastyInspector = jars("scala3-tasty-inspector")
val tastyCore = jars("tasty-core")
val asm = findArtifactPath(externalDeps, "scala-asm")
extraClasspath ++= Seq(dottyCompiler, dottyInterfaces, asm, dottyStaging, dottyTastyInspector, tastyCore)
}
val fullArgs = main :: insertClasspathInArgs(args, extraClasspath.mkString(File.pathSeparator))
(runMain in Compile).toTask(fullArgs.mkString(" ", " ", ""))
}
def insertClasspathInArgs(args: List[String], cp: String): List[String] = {
val (beforeCp, fromCp) = args.span(_ != "-classpath")
val classpath = fromCp.drop(1).headOption.fold(cp)(_ + File.pathSeparator + cp)
"-classpath" :: classpath :: beforeCp ::: fromCp.drop(2)
}
lazy val nonBootstrapedDottyCompilerSettings = commonDottyCompilerSettings ++ Seq(
// packageAll packages all and then returns a map with the abs location
packageAll := Def.taskDyn { // Use a dynamic task to avoid loops when loading the settings
Def.task {
Map(
"scala3-interfaces" -> packageBin.in(`scala3-interfaces`, Compile).value,
"scala3-compiler" -> packageBin.in(Compile).value,
"tasty-core" -> packageBin.in(`tasty-core`, Compile).value,
// NOTE: Using scala3-library-bootstrapped here is intentional: when
// running the compiler, we should always have the bootstrapped
// library on the compiler classpath since the non-bootstrapped one
// may not be binary-compatible.
"scala3-library" -> packageBin.in(`scala3-library-bootstrapped`, Compile).value
).mapValues(_.getAbsolutePath)
}
}.value,
testOptions in Test += Tests.Argument(
TestFrameworks.JUnit,
"--exclude-categories=dotty.BootstrappedOnlyTests",
),
// increase stack size for non-bootstrapped compiler, because some code
// is only tail-recursive after bootstrap
javaOptions in Test += "-Xss2m"
)
lazy val bootstrapedDottyCompilerSettings = commonDottyCompilerSettings ++ Seq(
javaOptions ++= {
val jars = packageAll.value
Seq(
"-Ddotty.tests.classes.dottyStaging=" + jars("scala3-staging"),
"-Ddotty.tests.classes.dottyTastyInspector=" + jars("scala3-tasty-inspector"),
)
},
packageAll := {
packageAll.in(`scala3-compiler`).value ++ Seq(
"scala3-compiler" -> packageBin.in(Compile).value.getAbsolutePath,
"scala3-staging" -> packageBin.in(LocalProject("scala3-staging"), Compile).value.getAbsolutePath,
"scala3-tasty-inspector" -> packageBin.in(LocalProject("scala3-tasty-inspector"), Compile).value.getAbsolutePath,
"tasty-core" -> packageBin.in(LocalProject("tasty-core-bootstrapped"), Compile).value.getAbsolutePath,
)
}
)
def dottyCompilerSettings(implicit mode: Mode): sbt.Def.SettingsDefinition =
if (mode == NonBootstrapped) nonBootstrapedDottyCompilerSettings else bootstrapedDottyCompilerSettings
lazy val `scala3-compiler` = project.in(file("compiler")).asDottyCompiler(NonBootstrapped)
lazy val `scala3-compiler-bootstrapped` = project.in(file("compiler")).asDottyCompiler(Bootstrapped)
def dottyCompiler(implicit mode: Mode): Project = mode match {
case NonBootstrapped => `scala3-compiler`
case Bootstrapped => `scala3-compiler-bootstrapped`
}
// Settings shared between scala3-library, scala3-library-bootstrapped and scala3-library-bootstrappedJS
lazy val dottyLibrarySettings = Seq(
scalacOptions in Compile ++= Seq(
// Needed so that the library sources are visible when `dotty.tools.dotc.core.Definitions#init` is called
"-sourcepath", (sourceDirectories in Compile).value.map(_.getAbsolutePath).distinct.mkString(File.pathSeparator),
// support declaration of scala.compiletime.erasedValue
"-Yerased-terms"
),
)
lazy val `scala3-library` = project.in(file("library")).asDottyLibrary(NonBootstrapped)
lazy val `scala3-library-bootstrapped`: Project = project.in(file("library")).asDottyLibrary(Bootstrapped)
def dottyLibrary(implicit mode: Mode): Project = mode match {
case NonBootstrapped => `scala3-library`
case Bootstrapped => `scala3-library-bootstrapped`
}
/** The dotty standard library compiled with the Scala.js back-end, to produce
* the corresponding .sjsir files.
*
* This artifact must be on the classpath on every "Dotty.js" project.
*
* Currently, only a very small fraction of the dotty library is actually
* included in this project, and hence available to Dotty.js projects. More
* will be added in the future as things are confirmed to be supported.
*/
lazy val `scala3-library-bootstrappedJS`: Project = project.in(file("library-js")).
asDottyLibrary(Bootstrapped).
enablePlugins(MyScalaJSPlugin).
settings(
libraryDependencies +=
("org.scala-js" %% "scalajs-library" % scalaJSVersion).withDottyCompat(scalaVersion.value),
unmanagedSourceDirectories in Compile :=
(unmanagedSourceDirectories in (`scala3-library-bootstrapped`, Compile)).value,
// Configure the source maps to point to GitHub for releases
scalacOptions ++= {
if (isRelease) {
val baseURI = (baseDirectory in LocalRootProject).value.toURI
val dottyVersion = version.value
Seq(s"-scalajs-mapSourceURI:$baseURI->$dottyGithubRawUserContentUrl/v$dottyVersion/")
} else {
Nil
}
},
// Make sure `scala3-bootstrapped/test` doesn't fail on this project for no reason
test in Test := {},
testOnly in Test := {},
)
lazy val tastyCoreSettings = Seq(
scalacOptions += "-source:3.0-migration"
)
lazy val `tasty-core` = project.in(file("tasty")).asTastyCore(NonBootstrapped)
lazy val `tasty-core-bootstrapped`: Project = project.in(file("tasty")).asTastyCore(Bootstrapped)
lazy val `tasty-core-scala2`: Project = project.in(file("tasty")).asTastyCoreScala2
def tastyCore(implicit mode: Mode): Project = mode match {
case NonBootstrapped => `tasty-core`
case Bootstrapped => `tasty-core-bootstrapped`
}
lazy val `scala3-staging` = project.in(file("staging")).
withCommonSettings(Bootstrapped).
// We want the compiler to be present in the compiler classpath when compiling this project but not
// when compiling a project that depends on scala3-staging (see sbt-dotty/sbt-test/sbt-dotty/quoted-example-project),
// but we always need it to be present on the JVM classpath at runtime.
dependsOn(dottyCompiler(Bootstrapped) % "provided; compile->runtime; test->test").
settings(commonBootstrappedSettings).
settings(
javaOptions := (javaOptions in `scala3-compiler-bootstrapped`).value
)
lazy val `scala3-tasty-inspector` = project.in(file("tasty-inspector")).
withCommonSettings(Bootstrapped).
// We want the compiler to be present in the compiler classpath when compiling this project but not
// when compiling a project that depends on scala3-tasty-inspector (see sbt-dotty/sbt-test/sbt-dotty/tasty-inspector-example-project),
// but we always need it to be present on the JVM classpath at runtime.
dependsOn(dottyCompiler(Bootstrapped) % "provided; compile->runtime; test->test").
settings(commonBootstrappedSettings).
settings(
javaOptions := (javaOptions in `scala3-compiler-bootstrapped`).value
)
/** Scala library compiled by dotty using the latest published sources of the library */
lazy val `stdlib-bootstrapped` = project.in(file("stdlib-bootstrapped")).
withCommonSettings(Bootstrapped).
dependsOn(dottyCompiler(Bootstrapped) % "provided; compile->runtime; test->test").
dependsOn(`scala3-tasty-inspector` % "test->test").
settings(commonBootstrappedSettings).
settings(
moduleName := "scala-library",
javaOptions := (javaOptions in `scala3-compiler-bootstrapped`).value,
scalacOptions -= "-Xfatal-warnings",
ivyConfigurations += SourceDeps.hide,
transitiveClassifiers := Seq("sources"),
libraryDependencies +=
("org.scala-lang" % "scala-library" % stdlibVersion(Bootstrapped) % "sourcedeps"),
sourceGenerators in Compile += Def.task {
val s = streams.value
val cacheDir = s.cacheDirectory
val trgDir = (sourceManaged in Compile).value / "scala-library-src"
val report = updateClassifiers.value
val scalaLibrarySourcesJar = report.select(
configuration = configurationFilter("sourcedeps"),
module = (_: ModuleID).name == "scala-library",
artifact = artifactFilter(`type` = "src")).headOption.getOrElse {
sys.error(s"Could not fetch scala-library sources")
}
FileFunction.cached(cacheDir / s"fetchScalaLibrarySrc",
FilesInfo.lastModified, FilesInfo.exists) { dependencies =>
s.log.info(s"Unpacking scala-library sources to $trgDir...")
if (trgDir.exists)
IO.delete(trgDir)
IO.createDirectory(trgDir)
IO.unzip(scalaLibrarySourcesJar, trgDir)
((trgDir ** "*.scala") +++ (trgDir ** "*.java")).get.toSet
} (Set(scalaLibrarySourcesJar)).toSeq
}.taskValue,
sources in Compile ~= (_.filterNot(file =>
// sources from https://github.com/scala/scala/tree/2.13.x/src/library-aux
file.getPath.endsWith("scala-library-src/scala/Any.scala") ||
file.getPath.endsWith("scala-library-src/scala/AnyVal.scala") ||
file.getPath.endsWith("scala-library-src/scala/AnyRef.scala") ||
file.getPath.endsWith("scala-library-src/scala/Nothing.scala") ||
file.getPath.endsWith("scala-library-src/scala/Null.scala") ||
file.getPath.endsWith("scala-library-src/scala/Singleton.scala"))),
managedClasspath in Test ~= {
_.filterNot(file => file.data.getName == s"scala-library-${stdlibVersion(Bootstrapped)}.jar")
},
)
/** Test the tasty generated by `stdlib-bootstrapped`
*
* The tests are run with the bootstrapped compiler and the tasty inpector on the classpath.
* The classpath has the default `scala-library` and not `stdlib-bootstrapped`.
*
* The jar of `stdlib-bootstrapped` is provided for to the tests.
* - inspector: test that we can load the contents of the jar using the tasty inspector
* - from-tasty: test that we can recompile the contents of the jar using `dotc -from-tasty`
*/
lazy val `stdlib-bootstrapped-tasty-tests` = project.in(file("stdlib-bootstrapped-tasty-tests")).
withCommonSettings(Bootstrapped).
dependsOn(`scala3-tasty-inspector` % "test->test").
settings(commonBootstrappedSettings).
settings(
javaOptions := (javaOptions in `scala3-compiler-bootstrapped`).value,
javaOptions += "-Ddotty.scala.library=" + packageBin.in(`stdlib-bootstrapped`, Compile).value.getAbsolutePath
)
lazy val `scala3-sbt-bridge` = project.in(file("sbt-bridge/src")).
// We cannot depend on any bootstrapped project to compile the bridge, since the
// bridge is needed to compile these projects.
dependsOn(dottyDoc(NonBootstrapped) % Provided).
settings(commonJavaSettings).
settings(
description := "sbt compiler bridge for Dotty",
sources in Test := Seq(),
scalaSource in Compile := baseDirectory.value,
javaSource in Compile := baseDirectory.value,
// Referring to the other project using a string avoids an infinite loop
// when sbt reads the settings.
test in Test := (test in (LocalProject("scala3-sbt-bridge-tests"), Test)).value,
libraryDependencies += Dependencies.`compiler-interface` % Provided
)
// We use a separate project for the bridge tests since they can only be run
// with the bootstrapped library on the classpath.
lazy val `scala3-sbt-bridge-tests` = project.in(file("sbt-bridge/test")).
dependsOn(dottyCompiler(Bootstrapped) % Test).
settings(commonBootstrappedSettings).
settings(
sources in Compile := Seq(),
scalaSource in Test := baseDirectory.value,
javaSource in Test := baseDirectory.value,
// Tests disabled until zinc-api-info cross-compiles with 2.13,
// alternatively we could just copy in sources the part of zinc-api-info we need.
sources in Test := Seq(),
// libraryDependencies += (Dependencies.`zinc-api-info` % Test).withDottyCompat(scalaVersion.value)
)
lazy val `scala3-language-server` = project.in(file("language-server")).
dependsOn(dottyCompiler(Bootstrapped)).
settings(commonBootstrappedSettings).
settings(
// Sources representing the shared configuration file used to communicate between the sbt-dotty
// plugin and the language server
unmanagedSourceDirectories in Compile += baseDirectory.value / "../sbt-dotty/src/dotty/tools/sbtplugin/config",
libraryDependencies ++= Seq(
"org.eclipse.lsp4j" % "org.eclipse.lsp4j" % "0.6.0",
Dependencies.`jackson-databind`
),
// Work around https://github.com/eclipse/lsp4j/issues/295
dependencyOverrides += "org.eclipse.xtend" % "org.eclipse.xtend.lib" % "2.16.0",
javaOptions := (javaOptions in `scala3-compiler-bootstrapped`).value,
run := Def.inputTaskDyn {
val inputArgs = spaceDelimited("<arg>").parsed
val mainClass = "dotty.tools.languageserver.Main"
val extensionPath = (baseDirectory in `vscode-dotty`).value.getAbsolutePath
val codeArgs =
s"--extensionDevelopmentPath=$extensionPath" +:
(if (inputArgs.isEmpty) List((baseDirectory.value / "..").getAbsolutePath) else inputArgs)
val clientCommand = prepareCommand(codeCommand.value ++ codeArgs)
val allArgs = "-client_command" +: clientCommand
runTask(Runtime, mainClass, allArgs: _*)
}.dependsOn(compile in (`vscode-dotty`, Compile)).evaluated
).
settings(
ideTestsCompilerVersion := (version in `scala3-compiler`).value,
ideTestsCompilerArguments := Seq(),
ideTestsDependencyClasspath := {
val dottyLib = (classDirectory in `scala3-library-bootstrapped` in Compile).value
val scalaLib =
(dependencyClasspath in `scala3-library-bootstrapped` in Compile)
.value
.map(_.data)
.filter(_.getName.matches("scala-library.*\\.jar"))
.toList
dottyLib :: scalaLib
},
buildInfoKeys in Test := Seq[BuildInfoKey](
ideTestsCompilerVersion,
ideTestsCompilerArguments,
ideTestsDependencyClasspath
),
buildInfoPackage in Test := "dotty.tools.languageserver.util.server",
BuildInfoPlugin.buildInfoScopedSettings(Test),
BuildInfoPlugin.buildInfoDefaultSettings
)
/** A sandbox to play with the Scala.js back-end of dotty.
*
* This sandbox is compiled with dotty with support for Scala.js. It can be
* used like any regular Scala.js project. In particular, `fastOptJS` will
* produce a .js file, and `run` will run the JavaScript code with a JS VM.
*