-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Build.scala
1805 lines (1575 loc) · 78 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 com.typesafe.tools.mima.plugin.MimaPlugin.autoImport._
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
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._
import org.scalajs.linker.interface.ModuleInitializer
object DottyJSPlugin extends AutoPlugin {
import Build._
override def requires: Plugins = ScalaJSPlugin
override def projectSettings: Seq[Setting[_]] = Def.settings(
commonBootstrappedSettings,
/* #11709 Remove the dependency on scala3-library that ScalaJSPlugin adds.
* Instead, in this build, we use `.dependsOn` relationships to depend on
* the appropriate, locally-defined, scala3-library-bootstrappedJS.
*/
libraryDependencies ~= {
_.filter(!_.name.startsWith("scala3-library_sjs1"))
},
// 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").cross(CrossVersion.for3Use2_13),
// 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.1.2-RC1"
val baseVersion = "3.1.3-RC1"
// 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 sbtDottyVersion = "0.5.5"
/** Version against which we check binary compatibility.
*
* This must be the latest published release in the same versioning line.
* For example, if the next version is going to be 3.1.4, then this must be
* set to 3.1.3. If it is going to be 3.1.0, it must be set to the latest
* 3.0.x release.
*/
val previousDottyVersion = "3.1.1"
object CompatMode {
final val BinaryCompatible = 0
final val SourceAndBinaryCompatible = 1
}
val compatMode = {
val VersionRE = """^\d+\.(\d+).(\d+).*""".r
baseVersion match {
case VersionRE(_, "0") => CompatMode.BinaryCompatible
case _ => CompatMode.SourceAndBinaryCompatible
}
}
/** 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.8"
case Bootstrapped => "2.13.8"
}
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 = {
// Make sure sbt always computes the scalaBinaryVersion correctly
val bin = if (!dottyVersion.contains("-bin")) "-bin" else ""
dottyVersion + bin + "-nonbootstrapped"
}
val sbtCommunityBuildVersion = "0.1.0-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")
// 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")
val repl = taskKey[Unit]("spawns a repl with the correct classpath")
// Compiles the documentation and static site
val genDocs = inputKey[Unit]("run scaladoc to generate static documentation site")
// 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"
),
(Compile / compile / javacOptions) ++= Seq("-Xlint:unchecked", "-Xlint:deprecation"),
// Override `runCode` from DottyIDEPlugin to use the language-server and
// vscode extension from the source repository of dotty instead of a
// published version.
runCode := (`scala3-language-server` / run).toTask("").value,
// Avoid various sbt craziness involving classloaders and parallelism
run / fork := true,
Test / fork := true,
Test / parallelExecution := false,
outputStrategy := Some(StdoutOutput),
// enable verbose exception messages for JUnit
(Test / testOptions) += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s"),
)
// Settings shared globally (scoped in Global). Used in build.sbt
lazy val globalSettings = Def.settings(
onLoad := (Global / onLoad).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 =
// This is a legacy settings, we should reevalute generating javadocs
Compile / doc / sources := Seq()
lazy val commonSettings = publishSettings ++ Seq(
(Compile / scalaSource) := baseDirectory.value / "src",
(Test / scalaSource) := baseDirectory.value / "test",
(Compile / javaSource) := baseDirectory.value / "src",
(Test / javaSource) := baseDirectory.value / "test",
(Compile / resourceDirectory) := baseDirectory.value / "resources",
(Test / resourceDirectory) := 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,
// For compatibility with Java 9+ module system;
// without Automatic-Module-Name, the module name is derived from the jar file which is invalid because of the _3 suffix.
Compile / packageBin / packageOptions +=
Package.ManifestAttributes(
"Automatic-Module-Name" -> s"${dottyOrganization.replaceAll("-",".")}.${moduleName.value.replaceAll("-",".")}"
)
)
// 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,
classpathOptions ~= (old =>
old
.withAutoBoot(false) // no library on the compiler bootclasspath - we may need a more recent version
.withFilterLibrary(false) // ...instead, we put it on the compiler classpath
),
)
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(
(Compile / unmanagedSourceDirectories) += baseDirectory.value / "src-non-bootstrapped",
version := dottyNonBootstrappedVersion,
scalaVersion := referenceVersion,
excludeFromIDE := true,
disableDocSetting
)
private lazy val currentYear: String = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR).toString
def scalacOptionsDocSettings(includeExternalMappings: Boolean = true) = {
val extMap = Seq("-external-mappings:" +
(if (includeExternalMappings) ".*scala/.*::scaladoc3::https://dotty.epfl.ch/api/," else "") +
".*java/.*::javadoc::https://docs.oracle.com/javase/8/docs/api/")
Seq(
"-skip-by-regex:.+\\.internal($|\\..+)",
"-skip-by-regex:.+\\.impl($|\\..+)",
"-project-logo", "docs/logo.svg",
"-social-links:" +
"github::https://github.com/lampepfl/dotty," +
"discord::https://discord.com/invite/scala," +
"twitter::https://twitter.com/scala_lang",
// contains special definitions which are "transplanted" elsewhere
// and which therefore confuse Scaladoc when accessed from this pkg
"-skip-by-id:scala.runtime.stdLibPatches",
// MatchCase is a special type that represents match type cases,
// Reflect doesn't expect to see it as a standalone definition
// and therefore it's easier just not to document it
"-skip-by-id:scala.runtime.MatchCase",
"-project-footer", s"Copyright (c) 2002-$currentYear, LAMP/EPFL",
"-author",
"-groups",
"-default-template", "static-site-main"
) ++ extMap
}
// Settings used when compiling dotty with a non-bootstrapped dotty
lazy val commonBootstrappedSettings = commonDottySettings ++ NoBloopExport.settings ++ Seq(
bspEnabled := false,
(Compile / unmanagedSourceDirectories) += baseDirectory.value / "src-bootstrapped",
version := dottyVersion,
scalaVersion := dottyNonBootstrappedVersion,
scalaCompilerBridgeBinaryJar := {
Some((`scala3-sbt-bridge` / Compile / packageBin).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 externalLibraryDeps = (`scala3-library` / Compile / externalDependencyClasspath).value.map(_.data).toSet
val externalCompilerDeps = (`scala3-compiler` / Compile / externalDependencyClasspath).value.map(_.data).toSet
// 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 = (`tasty-core` / Compile / packageBin).value
val scala3Library = (`scala3-library` / Compile / packageBin).value
val scala3Interfaces = (`scala3-interfaces` / Compile / packageBin).value
val scala3Compiler = (`scala3-compiler` / Compile / packageBin).value
val libraryJars = Array(scala3Library) ++ externalLibraryDeps
val compilerJars = Seq(tastyCore, scala3Interfaces, scala3Compiler) ++ (externalCompilerDeps -- externalLibraryDeps)
Defaults.makeScalaInstance(
scalaVersion.value,
libraryJars = libraryJars,
allCompilerJars = compilerJars,
allDocJars = Seq.empty,
state.value,
scalaInstanceTopLoader.value
)
},
// We cannot include scaladoc in the regular `scalaInstance` task because
// it's a bootstrapped-only project, so we would run into a loop since we
// need the output of that task to compile scaladoc. But we can include it
// in the `scalaInstance` of the `doc` task which allows us to run
// `scala3-library-bootstrapped/doc` for example.
doc / scalaInstance := {
val externalDeps = (LocalProject("scaladoc") / Compile / externalDependencyClasspath).value.map(_.data)
val scalaDoc = (LocalProject("scaladoc") / Compile / packageBin).value
val docJars = Array(scalaDoc) ++ externalDeps
val base = scalaInstance.value
val docScalaInstance = Defaults.makeScalaInstance(
version = base.version,
libraryJars = base.libraryJars,
allCompilerJars = base.compilerJars,
allDocJars = docJars,
state.value,
scalaInstanceTopLoader.value
)
// assert that sbt reuses the same compiler class loader
assert(docScalaInstance.loaderCompilerOnly == base.loaderCompilerOnly)
docScalaInstance
},
Compile / doc / scalacOptions ++= scalacOptionsDocSettings()
)
lazy val commonBenchmarkSettings = Seq(
Jmh / bspEnabled := false,
Jmh / run / mainClass := Some("dotty.tools.benchmarks.Bench"), // custom main for jmh:run
javaOptions += "-DBENCH_COMPILER_CLASS_PATH=" + Attributed.data((`scala3-bootstrapped` / Compile / fullClasspath).value).mkString("", File.pathSeparator, ""),
javaOptions += "-DBENCH_CLASS_PATH=" + Attributed.data((`scala3-library-bootstrapped` / Compile / fullClasspath).value).mkString("", File.pathSeparator, "")
)
lazy val commonMiMaSettings = Def.settings(
mimaPreviousArtifacts += {
val thisProjectID = projectID.value
val crossedName = thisProjectID.crossVersion match {
case cv: Disabled => thisProjectID.name
case cv: Binary => s"${thisProjectID.name}_${cv.prefix}3${cv.suffix}"
}
(thisProjectID.organization % crossedName % previousDottyVersion)
},
mimaCheckDirection := (compatMode match {
case CompatMode.BinaryCompatible => "backward"
case CompatMode.SourceAndBinaryCompatible => "both"
}),
)
/** 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.
(dottyCompilerBootstrappedRef / Runtime / externalDependencyClasspath)
// 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).
settings(commonMiMaSettings).
settings(
versionScheme := Some("semver-spec")
)
/** 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(
// Generate compiler.properties, used by sbt
(Compile / resourceGenerators) += Def.task {
import java.util._
import java.text._
val file = (Compile / resourceManaged).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-$currentYear, 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" % "9.1.0-scala-1", // used by the backend
Dependencies.oldCompilerInterface, // we stick to the old version to avoid deprecation warnings
"org.jline" % "jline-reader" % "3.19.0", // used by the REPL
"org.jline" % "jline-terminal" % "3.19.0",
"org.jline" % "jline-terminal-jna" % "3.19.0", // needed for Windows
("io.get-coursier" %% "coursier" % "2.0.16" % Test).cross(CrossVersion.for3Use2_13),
),
// For convenience, change the baseDirectory when running the compiler
Compile / forkOptions := (Compile / forkOptions).value.withWorkingDirectory((ThisBuild / baseDirectory).value),
Compile / run / forkOptions := (Compile / run / forkOptions).value.withWorkingDirectory((ThisBuild / baseDirectory).value),
// And when running the tests
Test / forkOptions := (Test / forkOptions).value.withWorkingDirectory((ThisBuild / baseDirectory).value),
Test / test := {
// Exclude VulpixMetaTests
(Test / testOnly).toTask(" -- --exclude-categories=dotty.VulpixMetaTests").value
},
(Test / testOptions) += 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
(Compile / managedSources).value
(Compile / sourceManaged).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
)
(Test / testOnly).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 "")
(Test / testOnly).toTask(cmd)
}
}.evaluated,
Compile / mainClass := Some("dotty.tools.dotc.Main"),
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 := 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" && arg != "-print-tasty")
val main =
if (decompile) "dotty.tools.dotc.decompiler.Main"
else if (printTasty) "dotty.tools.dotc.core.tasty.TastyPrinter"
else if (debugFromTasty) "dotty.tools.dotc.fromtasty.Debug"
else "dotty.tools.dotc.Main"
var extraClasspath = Seq(scalaLib, dottyLib)
if (decompile && !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 :: (if (printTasty) args else insertClasspathInArgs(args, extraClasspath.mkString(File.pathSeparator)))
(Compile / runMain).toTask(fullArgs.mkString(" ", " ", ""))
}.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").cross(CrossVersion.for3Use2_13),
(Compile / sourceGenerators) += Def.task {
val s = streams.value
val cacheDir = s.cacheDirectory
val trgDir = (Compile / sourceManaged).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 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" -> (`scala3-interfaces` / Compile / packageBin).value,
"scala3-compiler" -> (Compile / packageBin).value,
"tasty-core" -> (`tasty-core` / Compile / packageBin).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" -> (`scala3-library-bootstrapped` / Compile / packageBin).value
).mapValues(_.getAbsolutePath)
}
}.value,
(Test / testOptions) += Tests.Argument(
TestFrameworks.JUnit,
"--exclude-categories=dotty.BootstrappedOnlyTests",
),
// increase stack size for non-bootstrapped compiler, because some code
// is only tail-recursive after bootstrap
(Test / javaOptions) += "-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 := {
(`scala3-compiler` / packageAll).value ++ Seq(
"scala3-compiler" -> (Compile / packageBin).value.getAbsolutePath,
"scala3-staging" -> (LocalProject("scala3-staging") / Compile / packageBin).value.getAbsolutePath,
"scala3-tasty-inspector" -> (LocalProject("scala3-tasty-inspector") / Compile / packageBin).value.getAbsolutePath,
"tasty-core" -> (LocalProject("tasty-core-bootstrapped") / Compile / packageBin).value.getAbsolutePath,
)
},
repl := (Compile / console).value,
Compile / console / scalacOptions := Nil, // reset so that we get stock REPL behaviour! E.g. avoid -unchecked being enabled
)
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 Scala3CompilerCoursierTest = config("scala3CompilerCoursierTest") extend Test
lazy val `scala3-compiler-bootstrapped` = project.in(file("compiler")).asDottyCompiler(Bootstrapped)
.configs(Scala3CompilerCoursierTest)
.settings(
inConfig(Scala3CompilerCoursierTest)(Defaults.testSettings),
Scala3CompilerCoursierTest / scalaSource := baseDirectory.value / "test-coursier",
Scala3CompilerCoursierTest / fork := true,
Scala3CompilerCoursierTest / envVars := Map("DOTTY_BOOTSTRAPPED_VERSION" -> dottyVersion),
Scala3CompilerCoursierTest / unmanagedClasspath += (Scala3CompilerCoursierTest / scalaSource).value,
Scala3CompilerCoursierTest / test := ((Scala3CompilerCoursierTest / test) dependsOn (
publishLocal, // Had to enumarate all deps since calling `scala3-bootstrap` / publishLocal will lead to recursive dependency => stack overflow
`scala3-interfaces` / publishLocal,
dottyLibrary(Bootstrapped) / publishLocal,
tastyCore(Bootstrapped) / publishLocal,
),
).value,
)
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(
(Compile / scalacOptions) ++= Seq(
// Needed so that the library sources are visible when `dotty.tools.dotc.core.Definitions#init` is called
"-sourcepath", (Compile / sourceDirectories).value.map(_.getAbsolutePath).distinct.mkString(File.pathSeparator),
"-Yexplicit-nulls",
),
)
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(DottyJSPlugin).
settings(
libraryDependencies +=
("org.scala-js" %% "scalajs-library" % scalaJSVersion).cross(CrossVersion.for3Use2_13),
Compile / unmanagedSourceDirectories ++=
(`scala3-library-bootstrapped` / Compile / unmanagedSourceDirectories).value,
// Configure the source maps to point to GitHub for releases
scalacOptions ++= {
if (isRelease) {
val baseURI = (LocalRootProject / baseDirectory).value.toURI
val dottyVersion = version.value
Seq(s"-scalajs-mapSourceURI:$baseURI->$dottyGithubRawUserContentUrl/$dottyVersion/")
} else {
Nil
}
},
// Make sure `scala3-bootstrapped/test` doesn't fail on this project for no reason
Test / test := {},
Test / testOnly := {},
)
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-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(
javaOptions := (`scala3-compiler-bootstrapped` / javaOptions).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-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(
javaOptions := (`scala3-compiler-bootstrapped` / javaOptions).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 := (`scala3-compiler-bootstrapped` / javaOptions).value,
Compile/scalacOptions += "-Yerased-terms",
Compile/scalacOptions ++= {
Seq(
"-sourcepath",
Seq(
(Compile/sourceManaged).value / "scala-library-src",
(Compile/sourceManaged).value / "dotty-library-src",
).mkString(File.pathSeparator),
)
},
Compile / doc / scalacOptions += "-Ydocument-synthetic-types",
scalacOptions -= "-Xfatal-warnings",
ivyConfigurations += SourceDeps.hide,
transitiveClassifiers := Seq("sources"),
libraryDependencies +=
("org.scala-lang" % "scala-library" % stdlibVersion(Bootstrapped) % "sourcedeps"),
(Compile / sourceGenerators) += Def.task {
val s = streams.value
val cacheDir = s.cacheDirectory
val trgDir = (Compile / sourceManaged).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,
(Compile / sourceGenerators) += Def.task {
val s = streams.value
val cacheDir = s.cacheDirectory
val trgDir = (Compile / sourceManaged).value / "dotty-library-src"
// NOTE `sourceDirectory` is used for actual copying,
// but `sources` are used as cache keys
val dottyLibSourceDirs = (`scala3-library-bootstrapped`/Compile/unmanagedSourceDirectories).value
def dottyLibSources = dottyLibSourceDirs.foldLeft(PathFinder.empty) { (pf, dir) =>
if (!dir.exists) pf else pf +++ (dir ** "*.scala") +++ (dir ** "*.java")
}
val cachedFun = FileFunction.cached(
cacheDir / s"copyDottyLibrarySrc",
FilesInfo.lastModified,
FilesInfo.exists,
) { _ =>
if (trgDir.exists) IO.delete(trgDir)
dottyLibSourceDirs.foreach { dir =>
if (dir.exists) {
s.log.info(s"Copying scala3-library sources from $dir to $trgDir...")
IO.copyDirectory(dir, trgDir)
}
}
((trgDir ** "*.scala") +++ (trgDir ** "*.java")).get.toSet
}
cachedFun(dottyLibSources.get.toSet).toSeq
}.taskValue,
(Compile / sources) ~= (_.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"))),
(Test / managedClasspath) ~= {
_.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 := (`scala3-compiler-bootstrapped` / javaOptions).value,
javaOptions += "-Ddotty.scala.library=" + (`stdlib-bootstrapped` / Compile / packageBin).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(`scala3-compiler` % Provided).
settings(commonJavaSettings).
settings(
description := "sbt compiler bridge for Dotty",
Test / sources := Seq(),
Compile / scalaSource := baseDirectory.value,
Compile / javaSource := baseDirectory.value,
Compile / resourceDirectory := baseDirectory.value.getParentFile / "resources",
// Referring to the other project using a string avoids an infinite loop
// when sbt reads the settings.