Skip to content

Commit

Permalink
remain compatible with Zinc 1.3
Browse files Browse the repository at this point in the history
  • Loading branch information
bishabosha committed Jul 12, 2023
1 parent 34a5e45 commit 2458b8f
Show file tree
Hide file tree
Showing 18 changed files with 279 additions and 93 deletions.
13 changes: 5 additions & 8 deletions compiler/src/dotty/tools/backend/jvm/CodeGen.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import scala.tools.asm
import scala.tools.asm.tree._
import tpd._
import dotty.tools.io.AbstractFile
import dotty.tools.dotc.util.{NoSourcePosition, SourceFile}
import dotty.tools.dotc.util.NoSourcePosition


class CodeGen(val int: DottyBackendInterface, val primitives: DottyPrimitives)( val bTypes: BTypesFromSymbols[int.type]) { self =>
Expand Down Expand Up @@ -106,7 +106,7 @@ class CodeGen(val int: DottyBackendInterface, val primitives: DottyPrimitives)(
}

// Creates a callback that will be evaluated in PostProcessor after creating a file
private def onFileCreated(cls: ClassNode, claszSymbol: Symbol, sourceFile: SourceFile): AbstractFile => Unit = clsFile => {
private def onFileCreated(cls: ClassNode, claszSymbol: Symbol, sourceFile: interfaces.SourceFile): AbstractFile => Unit = clsFile => {
val (fullClassName, isLocal) = atPhase(sbtExtractDependenciesPhase) {
(ExtractDependencies.classNameAsString(claszSymbol), claszSymbol.isLocal)
}
Expand All @@ -115,12 +115,9 @@ class CodeGen(val int: DottyBackendInterface, val primitives: DottyPrimitives)(
if (ctx.compilerCallback != null)
ctx.compilerCallback.onClassGenerated(sourceFile, convertAbstractFile(clsFile), className)

if (ctx.sbtCallback != null) {
val jSourceFile = sourceFile.underlyingZincFile
val cb = ctx.sbtCallback
if (isLocal) cb.generatedLocalClass(jSourceFile, clsFile.jpath)
else cb.generatedNonLocalClass(jSourceFile, clsFile.jpath, className, fullClassName)
}
ctx.withIncCallback: cb =>
if (isLocal) cb.generatedLocalClass(sourceFile, clsFile.jpath)
else cb.generatedNonLocalClass(sourceFile, clsFile.jpath, className, fullClassName)
}

/** Convert a `dotty.tools.io.AbstractFile` into a
Expand Down
1 change: 0 additions & 1 deletion compiler/src/dotty/tools/dotc/config/ScalaSettings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,6 @@ private sealed trait YSettings:
val YdebugTypeError: Setting[Boolean] = BooleanSetting("-Ydebug-type-error", "Print the stack trace when a TypeError is caught", false)
val YdebugError: Setting[Boolean] = BooleanSetting("-Ydebug-error", "Print the stack trace when any error is caught.", false)
val YdebugUnpickling: Setting[Boolean] = BooleanSetting("-Ydebug-unpickling", "Print the stack trace when an error occurs when reading Tasty.", false)
val YdebugVirtualFiles: Setting[Boolean] = BooleanSetting("-Ydebug-virtual-files", "Debug usage of virtual files, e.g. remote cache in sbt", false)
val YtermConflict: Setting[String] = ChoiceSetting("-Yresolve-term-conflict", "strategy", "Resolve term conflicts", List("package", "object", "error"), "error")
val Ylog: Setting[List[String]] = PhasesSetting("-Ylog", "Log operations during")
val YlogClasspath: Setting[Boolean] = BooleanSetting("-Ylog-classpath", "Output information about what classpath is being applied.")
Expand Down
38 changes: 26 additions & 12 deletions compiler/src/dotty/tools/dotc/core/Contexts.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,17 @@ import scala.annotation.internal.sharable

import DenotTransformers.DenotTransformer
import dotty.tools.dotc.profile.Profiler
import dotty.tools.dotc.sbt.interfaces.IncrementalCallback
import util.Property.Key
import util.Store
import xsbti.AnalysisCallback
import plugins._
import java.util.concurrent.atomic.AtomicInteger
import java.util.Map as JMap
import java.nio.file.InvalidPathException


object Contexts {

private val (compilerCallbackLoc, store1) = Store.empty.newLocation[CompilerCallback]()
private val (sbtCallbackLoc, store2) = store1.newLocation[AnalysisCallback]()
private val (incCallbackLoc, store2) = store1.newLocation[IncrementalCallback | Null]()
private val (printerFnLoc, store3) = store2.newLocation[Context => Printer](new RefinedPrinter(_))
private val (settingsStateLoc, store4) = store3.newLocation[SettingsState]()
private val (compilationUnitLoc, store5) = store4.newLocation[CompilationUnit]()
Expand All @@ -55,7 +53,7 @@ object Contexts {
private val (notNullInfosLoc, store8) = store7.newLocation[List[NotNullInfo]]()
private val (importInfoLoc, store9) = store8.newLocation[ImportInfo | Null]()
private val (typeAssignerLoc, store10) = store9.newLocation[TypeAssigner](TypeAssigner)
private val (zincVirtualFilesLoc, store11) = store10.newLocation[JMap[String, xsbti.VirtualFile] | Null]()
private val (zincInitialFilesLoc, store11) = store10.newLocation[util.ReadOnlySet[AbstractFile] | Null]()

private val initialStore = store11

Expand Down Expand Up @@ -168,10 +166,18 @@ object Contexts {
def compilerCallback: CompilerCallback = store(compilerCallbackLoc)

/** The Zinc callback implementation if we are run from Zinc, null otherwise */
def sbtCallback: AnalysisCallback = store(sbtCallbackLoc)
def incCallback: IncrementalCallback | Null = store(incCallbackLoc)
def zincInitialFiles: util.ReadOnlySet[AbstractFile] | Null = store(zincInitialFilesLoc)

/** Run `op` if there exists an incremental callback */
inline def withIncCallback(inline op: IncrementalCallback => Unit): Unit =
val local = incCallback
if local != null then op(local)

/** A map from absolute path to VirtualFile if we are run from Zinc, null otherwise */
def zincVirtualFiles: JMap[String, xsbti.VirtualFile] | Null = store(zincVirtualFilesLoc)
def incrementalEnabled: Boolean =
val local = incCallback
if local != null then local.enabled
else false

/** The current plain printer */
def printerFn: Context => Printer = store(printerFnLoc)
Expand Down Expand Up @@ -240,7 +246,16 @@ object Contexts {
/** Sourcefile corresponding to given abstract file, memoized */
def getSource(file: AbstractFile, codec: => Codec = Codec(settings.encoding.value)) = {
util.Stats.record("Context.getSource")
base.sources.getOrElseUpdate(file, SourceFile(file, codec))
base.sources.getOrElseUpdate(file, {
val zincSources = zincInitialFiles
val cachedFile =
if zincSources != null then zincSources.lookup(file) match
case null => file
case cached => cached
else
file
SourceFile(cachedFile, codec)
})
}

/** SourceFile with given path name, memoized */
Expand Down Expand Up @@ -670,9 +685,8 @@ object Contexts {
}

def setCompilerCallback(callback: CompilerCallback): this.type = updateStore(compilerCallbackLoc, callback)
def setSbtCallback(callback: AnalysisCallback): this.type = updateStore(sbtCallbackLoc, callback)
def setZincVirtualFiles(map: JMap[String, xsbti.VirtualFile]): this.type =
updateStore(zincVirtualFilesLoc, map)
def setIncCallback(callback: IncrementalCallback): this.type = updateStore(incCallbackLoc, callback)
def setZincInitialFiles(zincInitialFiles: util.ReadOnlySet[AbstractFile]): this.type = updateStore(zincInitialFilesLoc, zincInitialFiles)
def setPrinterFn(printer: Context => Printer): this.type = updateStore(printerFnLoc, printer)
def setSettings(settingsState: SettingsState): this.type = updateStore(settingsStateLoc, settingsState)
def setRun(run: Run | Null): this.type = updateStore(runLoc, run)
Expand Down
4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/dotc/sbt/APIUtils.scala
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ object APIUtils {
* a dummy empty class can be registered instead, using this method.
*/
def registerDummyClass(classSym: ClassSymbol)(using Context): Unit = {
if (ctx.sbtCallback != null) {
ctx.withIncCallback { cb =>
val classLike = emptyClassLike(classSym)
ctx.sbtCallback.api(ctx.compilationUnit.source.underlyingZincFile, classLike)
cb.api(ctx.compilationUnit.source, classLike)
}
}

Expand Down
15 changes: 7 additions & 8 deletions compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class ExtractAPI extends Phase {

override def isRunnable(using Context): Boolean = {
def forceRun = ctx.settings.YdumpSbtInc.value || ctx.settings.YforceSbtPhases.value
super.isRunnable && (ctx.sbtCallback != null || forceRun)
super.isRunnable && (ctx.incrementalEnabled || forceRun)
}

// Check no needed. Does not transform trees
Expand All @@ -66,8 +66,8 @@ class ExtractAPI extends Phase {
override def run(using Context): Unit = {
val unit = ctx.compilationUnit
val sourceFile = unit.source
if (ctx.sbtCallback != null)
ctx.sbtCallback.startSource(sourceFile.underlyingZincFile)
ctx.withIncCallback: cb =>
cb.startSource(sourceFile)

val apiTraverser = new ExtractAPICollector
val classes = apiTraverser.apiSource(unit.tpdTree)
Expand All @@ -82,11 +82,10 @@ class ExtractAPI extends Phase {
} finally pw.close()
}

if ctx.sbtCallback != null &&
!ctx.compilationUnit.suspendedAtInliningPhase // already registered before this unit was suspended
then
classes.foreach(ctx.sbtCallback.api(sourceFile.underlyingZincFile, _))
mainClasses.foreach(ctx.sbtCallback.mainClass(sourceFile.underlyingZincFile, _))
ctx.withIncCallback: cb =>
if !ctx.compilationUnit.suspendedAtInliningPhase then // already registered before this unit was suspended
classes.foreach(cb.api(sourceFile, _))
mainClasses.foreach(cb.mainClass(sourceFile, _))
}
}

Expand Down
31 changes: 15 additions & 16 deletions compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import dotty.tools.dotc.core.Denotations.StaleSymbol
import dotty.tools.dotc.core.Types._
import dotty.tools.dotc.transform.SymUtils._
import dotty.tools.dotc.util.{SrcPos, NoSourcePosition}
import dotty.tools.uncheckedNN
import dotty.tools.io
import dotty.tools.io.{AbstractFile, PlainFile, ZipArchive}
import xsbti.UseScope
Expand Down Expand Up @@ -58,7 +57,7 @@ class ExtractDependencies extends Phase {

override def isRunnable(using Context): Boolean = {
def forceRun = ctx.settings.YdumpSbtInc.value || ctx.settings.YforceSbtPhases.value
super.isRunnable && (ctx.sbtCallback != null && ctx.sbtCallback.enabled() || forceRun)
super.isRunnable && (ctx.incrementalEnabled || forceRun)
}

// Check no needed. Does not transform trees
Expand Down Expand Up @@ -93,15 +92,16 @@ class ExtractDependencies extends Phase {
} finally pw.close()
}

if (ctx.sbtCallback != null && ctx.sbtCallback.enabled()) {
collector.usedNames.foreach {
case (clazz, usedNames) =>
val className = classNameAsString(clazz)
usedNames.names.foreach {
case (usedName, scopes) =>
ctx.sbtCallback.usedName(className, usedName.toString, scopes)
}
}
if (ctx.incrementalEnabled) {
ctx.withIncCallback: cb =>
collector.usedNames.foreach {
case (clazz, usedNames) =>
val className = classNameAsString(clazz)
usedNames.names.foreach {
case (usedName, scopes) =>
cb.usedName(className, usedName.toString, scopes)
}
}

collector.dependencies.foreach(recordDependency)
}
Expand All @@ -114,10 +114,10 @@ class ExtractDependencies extends Phase {
*/
def recordDependency(dep: ClassDependency)(using Context): Unit = {
val fromClassName = classNameAsString(dep.from)
val zincSourceFile = ctx.compilationUnit.source.underlyingZincFile
val sourceFile = ctx.compilationUnit.source

def binaryDependency(file: Path, binaryClassName: String) =
ctx.sbtCallback.binaryDependency(file, binaryClassName, fromClassName, zincSourceFile, dep.context)
ctx.withIncCallback(_.binaryDependency(file, binaryClassName, fromClassName, sourceFile, dep.context))

def processExternalDependency(depFile: AbstractFile, binaryClassName: String) = {
depFile match {
Expand All @@ -143,8 +143,7 @@ class ExtractDependencies extends Phase {
val depFile = dep.to.associatedFile
if (depFile != null) {
def depIsSameSource =
val depVF: xsbti.VirtualFile | Null = ctx.zincVirtualFiles.uncheckedNN.get(depFile.absolutePath)
depVF != null && depVF.id() == zincSourceFile.id()
depFile.absolutePath == sourceFile.file.absolutePath

// Cannot ignore inheritance relationship coming from the same source (see sbt/zinc#417)
def allowLocal = dep.context == DependencyByInheritance || dep.context == LocalDependencyByInheritance
Expand All @@ -158,7 +157,7 @@ class ExtractDependencies extends Phase {
// We cannot ignore dependencies coming from the same source file because
// the dependency info needs to propagate. See source-dependencies/trait-trait-211.
val toClassName = classNameAsString(dep.to)
ctx.sbtCallback.classDependency(toClassName, fromClassName, dep.context)
ctx.withIncCallback(_.classDependency(toClassName, fromClassName, dep.context))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package dotty.tools.dotc.sbt.interfaces;

import dotty.tools.dotc.interfaces.SourceFile;

import java.util.EnumSet;
import java.nio.file.Path;

/* User code should not implement this interface, it is intended to be a wrapper around xsbti.AnalysisCallback. */
public interface IncrementalCallback {
default void api(SourceFile sourceFile, xsbti.api.ClassLike classApi) {
}

default void startSource(SourceFile sourceFile) {
}

default void mainClass(SourceFile sourceFile, String className) {
}

default boolean enabled() {
return false;
}

default void usedName(String className, String name, EnumSet<xsbti.UseScope> useScopes) {
}

default void binaryDependency(Path onBinaryEntry, String onBinaryClassName, String fromClassName,
SourceFile fromSourceFile, xsbti.api.DependencyContext context) {
}

default void classDependency(String onClassName, String sourceClassName, xsbti.api.DependencyContext context) {
}

default void generatedLocalClass(SourceFile source, Path classFile) {
}

default void generatedNonLocalClass(SourceFile source, Path classFile, String binaryClassName,
String srcClassName) {
}
}
27 changes: 0 additions & 27 deletions compiler/src/dotty/tools/dotc/util/SourceFile.scala
Original file line number Diff line number Diff line change
Expand Up @@ -64,33 +64,6 @@ class SourceFile(val file: AbstractFile, computeContent: => Array[Char]) extends
import SourceFile._

private var myContent: Array[Char] | Null = null
private var myUnderlyingZincFile: xsbti.VirtualFile | Null = null

def underlyingZincFile(using Context): xsbti.VirtualFile =
val local = myUnderlyingZincFile
if local == null then
// usually without -sourcepath then the `underlying` will be set by Zinc.
val maybeUnderlying = file.underlying
val underlying0 =
if maybeUnderlying == null then
// When we have `-sourcepath` set then the file could come from the filesystem,
// rather than a zinc managed file, so then we need to check if we have a virtual file for it.
// TODO: we should consider in the future if there is a use case for sourcepath to possibly be
// made of virtual files.
val fromLookup = ctx.zincVirtualFiles.uncheckedNN.get(file.absolutePath)
if fromLookup != null then
fromLookup
else
sys.error(s"no underlying file for ${file.absolutePath}, possible paths = ${ctx.zincVirtualFiles.keySet}")
else maybeUnderlying
if ctx.settings.YdebugVirtualFiles.value then
val isVirtual = !underlying0.isInstanceOf[xsbti.PathBasedFile]
println(s"found underlying zinc file ${underlying0.id} for ${file.absolutePath} [virtual = $isVirtual]")

myUnderlyingZincFile = underlying0
underlying0
else
local

/** The contents of the original source file. Note that this can be empty, for example when
* the source is read from Tasty. */
Expand Down
3 changes: 0 additions & 3 deletions compiler/src/dotty/tools/io/AbstractFile.scala
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,6 @@ abstract class AbstractFile extends Iterable[AbstractFile] {
/** Returns the underlying Path if any and null otherwise. */
def jpath: JPath

/** Overridden in sbt-bridge ZincPlainFile and ZincVirtualFile */
def underlying: xsbti.VirtualFile | Null = null

/** An underlying source, if known. Mostly, a zip/jar file. */
def underlyingSource: Option[AbstractFile] = None

Expand Down
7 changes: 7 additions & 0 deletions sbt-bridge/src/dotty/tools/xsbt/AbstractZincFile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package dotty.tools.xsbt;

import xsbti.VirtualFile;

interface AbstractZincFile {
VirtualFile underlying();
}
Loading

0 comments on commit 2458b8f

Please sign in to comment.