Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/backend/jvm/GenBCode.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import dotty.tools.backend.jvm.opt.*
import dotty.tools.dotc.{CompilationUnit, report}
import dotty.tools.dotc.core.Contexts.Context
import dotty.tools.dotc.core.Phases.Phase
import dotty.tools.io.JarArchive
import dotty.tools.io.JarDestination

import scala.annotation.stableNull

Expand Down Expand Up @@ -68,7 +68,7 @@ final class GenBCode extends Phase:
result
finally
ctx.settings.outputDir.value match
case jar: JarArchive =>
case jar: JarDestination =>
if (ctx.run.nn.suspendedUnits.nonEmpty)
// If we close the jar the next run will not be able to write on the jar.
// But if we do not close it we cannot use it as part of the macro classpath of the suspended files.
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/config/ScalaSettings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ trait CommonScalaSettings extends SettingGroup:
override def load(argValue: String, state: SettingsState): AbstractFile =
// TODO: use JAR compression level, Java output version
val path = Directory(argValue)
if path.ext.isJar then JarArchive.create(path) else new PlainDirectory(path)
if path.ext.isJar then JarArchive.output(path) else new PlainDirectory(path)
protected def FileContainerSetting(category: SettingCategory, name: String, allowsJar: Boolean, descr: String, default: AbstractFile, aliases: List[SettingAlias] = Nil, preferPrevious: Boolean = false, deprecation: Option[Deprecation] = None, ignoreInvalidArgs: Boolean = false): Setting[AbstractFile] =
publish(Setting(category, prependName(name), descr, default, if allowsJar then "directory or .jar file" else "directory", aliases = aliases, preferPrevious = preferPrevious, deprecation = deprecation, ignoreInvalidArgs = ignoreInvalidArgs, lazyLoader = Some(FileContainerLazyLoader)))

Expand Down
5 changes: 3 additions & 2 deletions compiler/src/dotty/tools/dotc/decompiler/Main.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import dotty.tools.io.AbstractFile
object Main extends dotc.Driver {
override protected def newCompiler(using Context): dotc.Compiler = {
assert(ctx.settings.fromTasty.value)
if (!ctx.settings.outputDir.isDefault)
Files.deleteIfExists(ctx.settings.outputDir.value.fileNamed("decompiled.scala").jpath)
if !ctx.settings.outputDir.isDefault then
val previous = ctx.settings.outputDir.value.lookupName("decompiled.scala", directory = false)
if previous != null then Files.deleteIfExists(previous.jpath)
new TASTYDecompiler
}

Expand Down
15 changes: 6 additions & 9 deletions compiler/src/dotty/tools/dotc/transform/Pickler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import collection.mutable
import util.concurrent.Executor

import compiletime.uninitialized
import dotty.tools.io.{AbstractFile, JarArchive, VirtualFile}
import dotty.tools.io.{AbstractFile, JarDestination, VirtualFile}
import dotty.tools.dotc.printing.OutlinePrinter

import scala.annotation.constructorOnly
Expand All @@ -34,7 +34,6 @@ import dotty.tools.dotc.util.chaining.*

import scala.concurrent.ExecutionContext
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
import java.nio.file.Files
import java.util.ConcurrentModificationException

object Pickler {
Expand Down Expand Up @@ -134,7 +133,7 @@ object Pickler {
// when we are done, i.e. no suspended units,
// we should close the file system so it can be read in the same JVM process.
earlyOut match
case Some(jar: JarArchive) => jar.close()
case Some(jar: JarDestination) => jar.close()
case _ =>
catch
case ex: Exception =>
Expand Down Expand Up @@ -557,12 +556,10 @@ class Pickler extends Phase {
.addMode(Mode.ReadPositions)
)
if ctx.isBestEffort then
val outpath =
ctx.settings.outputDir.value.jpath.nn.toAbsolutePath.normalize
.resolve("META-INF")
.resolve("best-effort")
Files.createDirectories(outpath)
BestEffortTastyWriter.write(outpath, result)
val out = ctx.settings.outputDir.value
if !out.ext.isJar || result.exists(_.pickled.nonEmpty) then
val outpath = out.subdirectoryNamed("META-INF").subdirectoryNamed("best-effort").jpath.nn
BestEffortTastyWriter.write(outpath, result)
result
}

Expand Down
24 changes: 15 additions & 9 deletions compiler/src/dotty/tools/io/FileWriters.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package dotty.tools.io

import dotty.tools.io.AbstractFile
import dotty.tools.io.JarArchive
import dotty.tools.initialize
import dotty.tools.io.PlainFile

import java.io.BufferedOutputStream
Expand Down Expand Up @@ -133,23 +133,26 @@ object FileWriters {

object FileWriter {
def apply(file: AbstractFile, jarManifest: Seq[(Attributes.Name, String)], jarCompressionLevel: Int = Deflater.DEFAULT_COMPRESSION): FileWriter = file match
case jar: JarArchive =>
val jarFile = jar.underlyingSource
assert(jar.iterator.isEmpty, s"Unsafe writing to non-empty JAR: $jarFile")
new JarEntryWriter(jarFile, jarManifest, jarCompressionLevel)
case jar: JarDestination =>
new JarEntryWriter(jar, jarManifest, jarCompressionLevel)
case _ if file.isVirtual => new VirtualFileWriter(file)
case _ if file.isDirectory => new DirEntryWriter(file.file.nn.toPath)
case _ => throw new IllegalStateException(s"don't know how to handle an output of $file [${file.getClass}]")
}

private final class JarEntryWriter(file: AbstractFile, extraManifest: Seq[(Attributes.Name, String)], compressionLevel: Int) extends FileWriter {
private final class JarEntryWriter(archive: JarDestination, extraManifest: Seq[(Attributes.Name, String)], compressionLevel: Int) extends FileWriter {
//keep these imports local - avoid confusion with scala naming
import java.util.jar.Attributes.Name.MANIFEST_VERSION
import java.util.jar.{JarOutputStream, Manifest}

private val storeOnly = compressionLevel == Deflater.NO_COMPRESSION

private val jarWriter: JarOutputStream = {
private var stream: JarOutputStream | Null = null

private def openStream(): JarOutputStream = {
val destination = archive.writableArchive
val file = destination.underlyingSource
assert(destination.iterator.isEmpty, s"Unsafe writing to non-empty JAR: $file")
import scala.util.Properties.*
val manifest = new Manifest
val attrs = manifest.getMainAttributes
Expand Down Expand Up @@ -179,6 +182,7 @@ object FileWriters {
crc.update(bytes)
entry.setCrc(crc.getValue)
}
val jarWriter = initialize(stream, stream = _, openStream())
jarWriter.putNextEntry(entry)
try jarWriter.write(bytes, 0, bytes.length)
finally jarWriter.flush()
Expand All @@ -188,10 +192,12 @@ object FileWriters {
val pathInJar =
if java.io.File.separatorChar == '/' then relativePath
else relativePath.replace('/', java.io.File.separatorChar)
PlainFile.toPlainFile(Paths.get(s"${file.path}!$pathInJar"))
PlainFile.toPlainFile(Paths.get(s"${archive.path}!$pathInJar"))
}

override def close(): Unit = this.synchronized(jarWriter.close())
override def close(): Unit = this.synchronized {
if stream != null then stream.nn.close()
}
}

private final class DirEntryWriter(base: Path) extends FileWriter {
Expand Down
31 changes: 30 additions & 1 deletion compiler/src/dotty/tools/io/JarArchive.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ import java.nio.file.{FileSystemAlreadyExistsException, FileSystems, InvalidPath
import java.util.jar.{Attributes, JarInputStream}
import scala.jdk.CollectionConverters.*

private[tools] sealed trait JarDestination extends AbstractFile {
private[io] def writableArchive: JarArchive
def close(): Unit
}

/**
* This class implements an [[AbstractFile]] backed by a jar
* that be can used as the compiler's output directory.
*/
class JarArchive private (underlying: Path, root: Directory) extends PlainDirectory(root) {
class JarArchive private (underlying: Path, root: Directory) extends PlainDirectory(root) with JarDestination {
private[io] def writableArchive: JarArchive = this
def close(): Unit = this.synchronized(jpath.getFileSystem().close())

override val path: String = underlying.path
Expand All @@ -22,6 +28,29 @@ class JarArchive private (underlying: Path, root: Directory) extends PlainDirect
}

object JarArchive {
private[tools] def output(path: Path): JarDestination = new Output(path)

private final class Output(target: Path) extends PlainDirectory(target.toDirectory) with JarDestination {
@volatile private var opened: JarArchive | Null = null

private[io] def writableArchive: JarArchive = synchronized {
dotty.tools.initialize(opened, opened = _, create(target))
}

override def iterator: Iterator[PlainFile] =
Option(opened).iterator.flatMap(_.iterator)

override def lookupName(name: String, directory: Boolean): AbstractFile | Null =
if opened == null then null else opened.nn.lookupName(name, directory)

override def fileNamed(name: String): AbstractFile = writableArchive.fileNamed(name)
override def subdirectoryNamed(name: String): AbstractFile = writableArchive.subdirectoryNamed(name)

def close(): Unit = synchronized {
if opened != null then opened.nn.close()
}
}

/** Create a new jar file. Overwrite if file already exists */
def create(path: Path): JarArchive = {
require(path.ext.isJar)
Expand Down
90 changes: 43 additions & 47 deletions compiler/test/dotty/tools/dotc/SettingsTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import PlainFile.*
import java.nio.file.*
import Files.*
import org.junit.Test
import org.junit.Assert.{assertEquals, assertFalse, assertNotEquals, assertTrue}
import org.junit.Assert.{assertArrayEquals, assertEquals, assertFalse, assertTrue}

import scala.util.Using

Expand Down Expand Up @@ -45,15 +45,39 @@ class SettingsTests:
assertEquals("'not_here' does not exist or is not a directory or .jar file", summary.errors.head)
assertEquals("missing argument for option -Vprint", summary.errors.last)

@Test def `output jar file is created eagerly`: Unit =
import TestConfiguration.basicClasspath
val source = "tests/pos/Foo.scala"
val out = Paths.get("out/jarredFoo.jar").normalize
if Files.exists(out) then Files.delete(out)
val args = List("-Xmain-class", "Jarred", "-classpath", basicClasspath, "-d", out.toString, source)
val summary = ScalaSettings.processArguments(args, processAll = true)
assertEquals(0, summary.errors.size)
assertTrue(Files.exists(out))
@Test def outputJarsAreWrittenOnFirstEntry(): Unit =
Using.resource(createTempDirectory("i27587")): dir =>
val source = Files.writeString(dir.resolve("Repro.scala"), "object A\n")
val early = dir.resolve("early.jar")
val out = dir.resolve("out.jar")
val args = List("-classpath", TestConfiguration.basicClasspath, "-Ypickle-write", early.toString, "-d", out.toString)
def compile(options: String*): Unit =
assertFalse(Main.process((args ++ options :+ source.toString).toArray).hasErrors)

compile("-Ystop-after:parser")
assertFalse(Files.exists(early))
assertFalse(Files.exists(out))

compile()
def entries(path: Path): Set[String] =
import scala.jdk.CollectionConverters.*
Using.resource(new java.util.jar.JarFile(path.toFile))(_.entries.asScala.map(_.getName).toSet)
assertTrue(entries(early).contains("A.tasty"))
assertTrue(entries(out).contains("A.class"))
val originalEarly = Files.readAllBytes(early)
val originalOut = Files.readAllBytes(out)
new interactive.InteractiveDriver(args, interactive.CachedLogicalPackage.none)
compile("-Ystop-after:parser")
Files.writeString(source, "")
compile()
assertArrayEquals(originalEarly, Files.readAllBytes(early))
assertArrayEquals(originalOut, Files.readAllBytes(out))

Files.writeString(source, "object B\n")
compile()
assertEquals(Set("META-INF/MANIFEST.MF", "B.tasty"), entries(early))
assertTrue(entries(out).contains("B.class"))
assertFalse(entries(out).contains("A.class"))

@Test def `t8124 Don't crash on missing argument`: Unit =
Using.resource(Files.createTempDirectory("testDir")): dir =>
Expand Down Expand Up @@ -294,44 +318,16 @@ class SettingsTests:
assertTrue("Nothing to see here", summary.warnings.isEmpty)
assertEquals(true, foo.value)

@Test def `Output setting is overriding existing jar`: Unit =
val result = Using.resource(Files.createTempFile("myfile", ".jar")): file =>
object Settings extends CommonScalaSettings:
val defaultDir = new PlainDirectory(Directory("."))
val testOutput = FileContainerSetting(RootSetting, "testOutput", true, "", defaultDir)

import Settings.*
Files.write(file, "test".getBytes())
val fileStateBefore = String(Files.readAllBytes(file))
val args = List(s"-testOutput:${file.toString}")
val summary = processArguments(args, processAll = true)

assertNotEquals(fileStateBefore, String(Files.readAllBytes(file)), "Jar should have been overridden")

@Test def `Output setting respects previous setting`: Unit =
val result = Using.resources(
Files.createTempFile("myfile", ".jar"), Files.createTempFile("myfile2", ".jar")
): (file1, file2) =>
object Settings extends CommonScalaSettings:
val defaultDir = new PlainDirectory(Directory("."))
val testOutput = FileContainerSetting(RootSetting, "testOutput", true, "", defaultDir, preferPrevious = true)

import Settings.*

Files.write(file1, "test1".getBytes())
Files.write(file2, "test2".getBytes())

val file1StateBefore = String(Files.readAllBytes(file1))
val file2StateBefore = String(Files.readAllBytes(file2))

val creationTime = Files.getLastModifiedTime(file1)
val args = List(s"-testOutput:${file1.toString}", s"-testOutput:${file2.toString}")
val summary = processArguments(args, processAll = true)

// The output is a new filesystem without information of original path
// We can't check the `testOutput.value` as in other tests.
assertNotEquals(file1StateBefore, String(Files.readAllBytes(file1)))
assertEquals(file2StateBefore, String(Files.readAllBytes(file2)))
Using.resource(createTempDirectory("earlyOutput")): dir =>
val first = dir.resolve("first.jar")
val second = dir.resolve("second.jar")
val args = List("-Ypickle-write", first.toString, "-Ypickle-write", second.toString)
val summary = ScalaSettings.processArguments(args, processAll = true)
withProcessedArgs(summary):
assertEquals(Some(first.toString), ScalaSettings.XearlyTastyOutput.value.map(_.path))
assertFalse(Files.exists(first))
assertFalse(Files.exists(second))

@Test def `Output side effect is not present when setting is deprecated`: Unit =
val result = Using.resource(Files.createTempFile("myfile", ".jar")): file =>
Expand Down
4 changes: 1 addition & 3 deletions sbt-bridge/test/xsbt/ScalaCompilerForUnitTesting.scala
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,7 @@ class ScalaCompilerForUnitTesting {
val testProgress = new TestCompileProgress
val classesOutput =
if (compileToJar) {
val jar = new File(temp, "classes.jar")
jar.createNewFile()
jar
new File(temp, "classes.jar")
} else {
val dir = new File(temp, "classes")
dir.mkdir()
Expand Down
Loading