From bd339f55734ad49aa9010c37d8505bd1e8297e2b Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Sun, 5 Jul 2020 12:35:48 +0200 Subject: [PATCH 01/10] Move importInfo to Context store Stats show that importInfo is updated about 10x less that Store. E.g. compiling Dotty: Total context creations: 5.6M Store creations: 68K Import info creations: 6.8K So this means we save 22.4M be removing importInfo as a field of contexts at a price of less than 600K for the added store creations. # Conflicts: # compiler/src/dotty/tools/dotc/core/Contexts.scala --- .../src/dotty/tools/dotc/core/Contexts.scala | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 551a2cf2037e..2e287a664af1 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -48,7 +48,9 @@ object Contexts { private val (runLoc, store6) = store5.newLocation[Run]() private val (profilerLoc, store7) = store6.newLocation[Profiler]() private val (notNullInfosLoc, store8) = store7.newLocation[List[NotNullInfo]]() - private val initialStore = store8 + private val (importInfoLoc, store9) = store8.newLocation[ImportInfo]() + + private val initialStore = store9 /** The current context */ inline def ctx(using ctx: Context): Context = ctx @@ -156,11 +158,6 @@ object Contexts { protected def typeAssigner_=(typeAssigner: TypeAssigner): Unit = _typeAssigner = typeAssigner final def typeAssigner: TypeAssigner = _typeAssigner - /** The currently active import info */ - private var _importInfo: ImportInfo = _ - protected def importInfo_=(importInfo: ImportInfo): Unit = _importInfo = importInfo - final def importInfo: ImportInfo = _importInfo - /** The current bounds in force for type parameters appearing in a GADT */ private var _gadt: GadtConstraint = _ protected def gadt_=(gadt: GadtConstraint): Unit = _gadt = gadt @@ -230,6 +227,9 @@ object Contexts { /** The paths currently known to be not null */ def notNullInfos = store(notNullInfosLoc) + /** The currently active import info */ + def importInfo = store(importInfoLoc) + /** The new implicit references that are introduced by this scope */ protected var implicitsCache: ContextualImplicits = null def implicits: ContextualImplicits = { @@ -351,7 +351,9 @@ object Contexts { /** Is this a context that introduces an import clause? */ def isImportContext: Boolean = - (this ne NoContext) && (this.importInfo ne outer.importInfo) + (this ne NoContext) + && (outer ne NoContext) + && (this.importInfo ne outer.importInfo) /** Is this a context that introduces a non-empty scope? */ def isNonEmptyScopeContext: Boolean = @@ -461,7 +463,6 @@ object Contexts { _scope = origin.scope _typerState = origin.typerState _typeAssigner = origin.typeAssigner - _importInfo = origin.importInfo _gadt = origin.gadt _searchHistory = origin.searchHistory _typeComparer = origin.typeComparer @@ -550,7 +551,6 @@ object Contexts { def setReporter(reporter: Reporter): this.type = setTyperState(typerState.fresh().setReporter(reporter)) def setTypeAssigner(typeAssigner: TypeAssigner): this.type = { this.typeAssigner = typeAssigner; this } def setTyper(typer: Typer): this.type = { this.scope = typer.scope; setTypeAssigner(typer) } - def setImportInfo(importInfo: ImportInfo): this.type = { this.importInfo = importInfo; this } def setGadt(gadt: GadtConstraint): this.type = { this.gadt = gadt; this } def setFreshGADTBounds: this.type = setGadt(gadt.fresh) def setSearchHistory(searchHistory: SearchHistory): this.type = { this.searchHistory = searchHistory; this } @@ -572,6 +572,7 @@ object Contexts { def setRun(run: Run): this.type = updateStore(runLoc, run) def setProfiler(profiler: Profiler): this.type = updateStore(profilerLoc, profiler) def setNotNullInfos(notNullInfos: List[NotNullInfo]): this.type = updateStore(notNullInfosLoc, notNullInfos) + def setImportInfo(importInfo: ImportInfo): this.type = updateStore(importInfoLoc, importInfo) def setProperty[T](key: Key[T], value: T): this.type = setMoreProperties(moreProperties.updated(key, value)) From 3715a10808a4e8bc1d83c26f465d1312e40425c0 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 16 Jul 2020 15:28:49 +0200 Subject: [PATCH 02/10] Change test logic. Use a freelist of unsused contexts instead of overwriting typerstate variables. Rename from `ctx.test` to `explore`. --- compiler/src/dotty/tools/dotc/Run.scala | 2 +- .../dotty/tools/dotc/core/Constraint.scala | 6 - .../src/dotty/tools/dotc/core/Contexts.scala | 114 ++++++++++++---- .../tools/dotc/core/OrderingConstraint.scala | 8 -- .../src/dotty/tools/dotc/core/Scopes.scala | 3 +- .../dotty/tools/dotc/core/TypeComparer.scala | 8 +- .../src/dotty/tools/dotc/core/TypeOps.scala | 1 + .../dotty/tools/dotc/core/TyperState.scala | 124 +++++++----------- .../tools/dotc/reporting/TestReporter.scala | 12 ++ .../dotty/tools/dotc/typer/Applications.scala | 12 +- .../dotty/tools/dotc/typer/Implicits.scala | 6 +- .../src/dotty/tools/dotc/typer/Namer.scala | 5 +- .../dotty/tools/dotc/typer/ProtoTypes.scala | 4 +- .../dotty/tools/dotc/typer/Synthesizer.scala | 2 +- 14 files changed, 174 insertions(+), 133 deletions(-) create mode 100644 compiler/src/dotty/tools/dotc/reporting/TestReporter.scala diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 222e63372c75..fb9b8144d5e0 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -72,7 +72,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint .setOwner(defn.RootClass) .setTyper(new Typer) .addMode(Mode.ImplicitsEnabled) - .setTyperState(new TyperState(ctx.typerState)) + .setTyperState(ctx.typerState.fresh(ctx.reporter)) ctx.initialize()(using start) // re-initialize the base context with start def addImport(ctx: Context, rootRef: ImportInfo.RootRef) = ctx.fresh.setImportInfo(ImportInfo.rootImport(rootRef)) diff --git a/compiler/src/dotty/tools/dotc/core/Constraint.scala b/compiler/src/dotty/tools/dotc/core/Constraint.scala index 1b0e36a24731..9c91232943e7 100644 --- a/compiler/src/dotty/tools/dotc/core/Constraint.scala +++ b/compiler/src/dotty/tools/dotc/core/Constraint.scala @@ -161,10 +161,4 @@ abstract class Constraint extends Showable { /** Check that constraint only refers to TypeParamRefs bound by itself */ def checkClosed()(using Context): Unit - - /** Constraint has not yet been retracted from a typer state */ - def isRetracted: Boolean - - /** Indicate that constraint has been retracted from a typer state */ - def markRetracted(): Unit } diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 2e287a664af1..46f4d436c2a6 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -286,7 +286,7 @@ object Contexts { * contexts are created only on request and cached in this array */ private var phasedCtx: Context = this - private var phasedCtxs: Array[Context] = _ + private var phasedCtxs: Array[Context] = null /** This context at given phase. * This method will always return a phase period equal to phaseId, thus will never return squashed phases @@ -340,11 +340,6 @@ object Contexts { /** The current reporter */ def reporter: Reporter = typerState.reporter - /** Run `op` as if it was run in a fresh explore typer state, but possibly - * optimized to re-use the current typer state. - */ - final def test[T](op: Context ?=> T): T = typerState.test(op)(using this) - /** Is this a context for the members of a class definition? */ def isClassDefContext: Boolean = owner.isClass && (owner ne outer.owner) @@ -453,15 +448,17 @@ object Contexts { /** Is the explicit nulls option set? */ def explicitNulls: Boolean = base.settings.YexplicitNulls.value - protected def init(outer: Context, origin: Context): this.type = { - util.Stats.record("Context.fresh") + /** Initialize all context fields, except typerState, which has to be set separately + * @param outer The outer context + * @param origin The context from which fields are copied + */ + private[Contexts] def init(outer: Context, origin: Context): this.type = { _outer = outer _period = origin.period _mode = origin.mode _owner = origin.owner _tree = origin.tree _scope = origin.scope - _typerState = origin.typerState _typeAssigner = origin.typeAssigner _gadt = origin.gadt _searchHistory = origin.searchHistory @@ -472,11 +469,19 @@ object Contexts { this } + def reuseIn(outer: Context): this.type = + implicitsCache = null + phasedCtxs = null + sourceCtx = null + init(outer, outer) + /** A fresh clone of this context embedded in this context. */ def fresh: FreshContext = freshOver(this) /** A fresh clone of this context embedded in the specified `outer` context. */ - def freshOver(outer: Context): FreshContext = new FreshContext(base).init(outer, this) + def freshOver(outer: Context): FreshContext = + util.Stats.record("Context.fresh") + FreshContext(base).init(outer, this).setTyperState(this.typerState) final def withOwner(owner: Symbol): Context = if (owner ne this.owner) fresh.setOwner(owner) else this @@ -539,25 +544,59 @@ object Contexts { * of its attributes using the with... methods. */ class FreshContext(base: ContextBase) extends Context(base) { - def setPeriod(period: Period): this.type = { this.period = period; this } - def setMode(mode: Mode): this.type = { this.mode = mode; this } - def setOwner(owner: Symbol): this.type = { assert(owner != NoSymbol); this.owner = owner; this } - def setTree(tree: Tree[? >: Untyped]): this.type = { this.tree = tree; this } + def setPeriod(period: Period): this.type = + util.Stats.record("Context.setPeriod") + this.period = period + this + def setMode(mode: Mode): this.type = + util.Stats.record("Context.setMode") + this.mode = mode + this + def setOwner(owner: Symbol): this.type = + util.Stats.record("Context.setOwner") + assert(owner != NoSymbol) + this.owner = owner + this + def setTree(tree: Tree[? >: Untyped]): this.type = + util.Stats.record("Context.setTree") + this.tree = tree + this def setScope(scope: Scope): this.type = { this.scope = scope; this } - def setNewScope: this.type = { this.scope = newScope; this } + def setNewScope: this.type = + util.Stats.record("Context.setScope") + this.scope = newScope + this def setTyperState(typerState: TyperState): this.type = { this.typerState = typerState; this } def setNewTyperState(): this.type = setTyperState(typerState.fresh().setCommittable(true)) def setExploreTyperState(): this.type = setTyperState(typerState.fresh().setCommittable(false)) def setReporter(reporter: Reporter): this.type = setTyperState(typerState.fresh().setReporter(reporter)) - def setTypeAssigner(typeAssigner: TypeAssigner): this.type = { this.typeAssigner = typeAssigner; this } + def setTypeAssigner(typeAssigner: TypeAssigner): this.type = + util.Stats.record("Context.setTypeAssigner") + this.typeAssigner = typeAssigner + this def setTyper(typer: Typer): this.type = { this.scope = typer.scope; setTypeAssigner(typer) } - def setGadt(gadt: GadtConstraint): this.type = { this.gadt = gadt; this } + def setGadt(gadt: GadtConstraint): this.type = + util.Stats.record("Context.setGadt") + this.gadt = gadt + this def setFreshGADTBounds: this.type = setGadt(gadt.fresh) - def setSearchHistory(searchHistory: SearchHistory): this.type = { this.searchHistory = searchHistory; this } - def setSource(source: SourceFile): this.type = { this.source = source; this } + def setSearchHistory(searchHistory: SearchHistory): this.type = + util.Stats.record("Context.setSearchHistory") + this.searchHistory = searchHistory + this + def setSource(source: SourceFile): this.type = + util.Stats.record("Context.setSource") + this.source = source + this def setTypeComparerFn(tcfn: Context => TypeComparer): this.type = { this.typeComparer = tcfn(this); this } - private def setMoreProperties(moreProperties: Map[Key[Any], Any]): this.type = { this.moreProperties = moreProperties; this } - private def setStore(store: Store): this.type = { this.store = store; this } + private def setMoreProperties(moreProperties: Map[Key[Any], Any]): this.type = + util.Stats.record("Context.setMoreProperties") + this.moreProperties = moreProperties + this + private def setStore(store: Store): this.type = + util.Stats.record("Context.setStore") + this.store = store + this def setImplicits(implicits: ContextualImplicits): this.type = { this.implicitsCache = implicits; this } def setCompilationUnit(compilationUnit: CompilationUnit): this.type = { @@ -632,6 +671,34 @@ object Contexts { final def retractMode(mode: Mode): c.type = c.setMode(c.mode &~ mode) } + /** Test `op` in a fresh context with a typerstate that is not committable. + * The passed context may not survive the operation. + */ + def explore[T](op: Context ?=> T)(using Context): T = + util.Stats.record("Context.test") + val base = ctx.base + import base._ + val nestedCtx = + if testsInUse < testContexts.size then + testContexts(testsInUse).reuseIn(ctx) + else + val ts = TyperState() + .setReporter(TestingReporter()) + .setCommittable(false) + val c = FreshContext(ctx.base).init(ctx, ctx).setTyperState(ts) + testContexts += c + c + testsInUse += 1 + val nestedTS = nestedCtx.typerState + nestedTS.init(ctx.typerState, ctx.typerState.constraint) + val result = + try op(using nestedCtx) + finally + nestedTS.reporter.asInstanceOf[TestingReporter].reset() + testsInUse -= 1 + result + end explore + /** A class defining the initial context with given context base * and set of possible settings. */ @@ -639,7 +706,7 @@ object Contexts { outer = NoContext period = InitialPeriod mode = Mode.None - typerState = new TyperState(null) + typerState = TyperState.initialState() owner = NoSymbol tree = untpd.EmptyTree typeAssigner = TypeAssigner @@ -785,6 +852,9 @@ object Contexts { protected[dotc] val indentTab: String = " " + private[dotc] val testContexts = new mutable.ArrayBuffer[FreshContext] + private[dotc] var testsInUse: Int = 0 + def reset(): Unit = { for ((_, set) <- uniqueSets) set.clear() errorTypeMsg.clear() diff --git a/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala b/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala index b25bfda84bf7..ebb6e7078acf 100644 --- a/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala +++ b/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala @@ -640,14 +640,6 @@ class OrderingConstraint(private val boundsMap: ParamBounds, upperMap.foreachBinding((_, paramss) => paramss.foreach(_.foreach(checkClosedType(_, "upper")))) end checkClosed -// ---------- Invalidation ------------------------------------------- - - private var retracted = false - - def isRetracted: Boolean = retracted - - def markRetracted(): Unit = retracted = true - // ---------- toText ----------------------------------------------------- override def toText(printer: Printer): Text = { diff --git a/compiler/src/dotty/tools/dotc/core/Scopes.scala b/compiler/src/dotty/tools/dotc/core/Scopes.scala index 289ca55eb91a..3e8c8fa7d163 100644 --- a/compiler/src/dotty/tools/dotc/core/Scopes.scala +++ b/compiler/src/dotty/tools/dotc/core/Scopes.scala @@ -192,10 +192,9 @@ object Scopes { extends Scope { /** Scope shares elements with `base` */ - protected[Scopes] def this(base: Scope)(using Context) = { + protected[Scopes] def this(base: Scope)(using Context) = this(base.lastEntry, base.size, base.nestingLevel + 1) ensureCapacity(MinHashedScopeSize) - } def this() = this(null, 0, 0) diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index c41ecd76dc27..969142e71ca4 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -1133,11 +1133,11 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w if (recCount >= Config.LogPendingSubTypesThreshold) monitored = true val result = if (monitored) monitoredIsSubType else firstTry recCount = recCount - 1 - if (!result) state.resetConstraintTo(saved) - else if (recCount == 0 && needsGc) { + if !result then + state.constraint = saved + else if recCount == 0 && needsGc then state.gc() needsGc = false - } if (Stats.monitored) recordStatistics(result, savedSuccessCount) result } @@ -1145,7 +1145,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w case NonFatal(ex) => if (ex.isInstanceOf[AssertionError]) showGoal(tp1, tp2) recCount -= 1 - state.resetConstraintTo(saved) + state.constraint = saved successCount = savedSuccessCount throw ex } diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index ef2e805ec77d..3eca986a973b 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -20,6 +20,7 @@ import typer.ProtoTypes._ import typer.ForceDegree import typer.Inferencing._ import typer.IfBottom +import reporting.TestingReporter import scala.annotation.internal.sharable import scala.annotation.threadUnsafe diff --git a/compiler/src/dotty/tools/dotc/core/TyperState.scala b/compiler/src/dotty/tools/dotc/core/TyperState.scala index c3e8db6b2db8..168e415b1d43 100644 --- a/compiler/src/dotty/tools/dotc/core/TyperState.scala +++ b/compiler/src/dotty/tools/dotc/core/TyperState.scala @@ -17,26 +17,28 @@ import scala.annotation.internal.sharable object TyperState { @sharable private var nextId: Int = 0 + def initialState() = + TyperState() + .init(null, OrderingConstraint.empty) + .setReporter(new ConsoleReporter()) + .setCommittable(true) } -class TyperState(private val previous: TyperState /* | Null */) { +class TyperState() { - Stats.record("typerState") + private var myId: Int = _ + def id: Int = myId - val id: Int = TyperState.nextId - TyperState.nextId += 1 + private var previous: TyperState = _ - private var myReporter = - if (previous == null) new ConsoleReporter() else previous.reporter + private var myReporter: Reporter = _ def reporter: Reporter = myReporter /** A fresh type state with the same constraint as this one and the given reporter */ def setReporter(reporter: Reporter): this.type = { myReporter = reporter; this } - private var myConstraint: Constraint = - if (previous == null) OrderingConstraint.empty - else previous.constraint + private var myConstraint: Constraint = _ def constraint: Constraint = myConstraint def constraint_=(c: Constraint)(using Context): Unit = { @@ -44,85 +46,64 @@ class TyperState(private val previous: TyperState /* | Null */) { myConstraint = c } - /** Reset constraint to `c` and mark current constraint as retracted if it differs from `c` */ - def resetConstraintTo(c: Constraint): Unit = { - if (c `ne` myConstraint) myConstraint.markRetracted() - myConstraint = c - } - - private val previousConstraint = - if (previous == null) constraint else previous.constraint + private var previousConstraint: Constraint = _ - private var myIsCommittable = true + private var myIsCommittable: Boolean = _ def isCommittable: Boolean = myIsCommittable - def setCommittable(committable: Boolean): this.type = { this.myIsCommittable = committable; this } + def setCommittable(committable: Boolean): this.type = + this.myIsCommittable = committable + this def isGlobalCommittable: Boolean = isCommittable && (previous == null || previous.isGlobalCommittable) - private var isShared = false + private var isCommitted: Boolean = _ - /** Mark typer state as shared (typically because it is the typer state of - * the creation context of a source definition that potentially still needs - * to be completed). Members of shared typer states are never overwritten in `test`. - */ - def markShared(): Unit = isShared = true + /** The set of uninstantiated type variables which have this state as their owning state */ + private var myOwnedVars: TypeVars = _ + def ownedVars: TypeVars = myOwnedVars + def ownedVars_=(vs: TypeVars): Unit = myOwnedVars = vs - private var isCommitted = false + /** Initializes all fields except reporter, isCommittable, which need to be + * set separately. + */ + private[core] def init(previous: TyperState, constraint: Constraint): this.type = + this.myId = TyperState.nextId + TyperState.nextId += 1 + this.previous = previous + this.myConstraint = constraint + this.previousConstraint = constraint + this.myOwnedVars = SimpleIdentitySet.empty + this.isCommitted = false + this + + def disable() = + previous = null + myConstraint = null + previousConstraint = null + myOwnedVars = null + isCommitted = false + myReporter = null + myIsCommittable = true /** A fresh typer state with the same constraint as this one. */ - def fresh(): TyperState = - new TyperState(this).setReporter(new StoreReporter(reporter)).setCommittable(isCommittable) + def fresh(reporter: Reporter = StoreReporter(this.reporter)): TyperState = + util.Stats.record("TyperState.fresh") + TyperState().init(this, this.constraint) + .setReporter(reporter) + .setCommittable(this.isCommittable) /** The uninstantiated variables */ def uninstVars: collection.Seq[TypeVar] = constraint.uninstVars - /** The set of uninstantiated type variables which have this state as their owning state */ - private var myOwnedVars: TypeVars = SimpleIdentitySet.empty - def ownedVars: TypeVars = myOwnedVars - def ownedVars_=(vs: TypeVars): Unit = myOwnedVars = vs - /** The closest ancestor of this typer state (including possibly this typer state itself) * which is not yet committed, or which does not have a parent. */ def uncommittedAncestor: TyperState = if (isCommitted) previous.uncommittedAncestor else this - private var testReporter: TestReporter = null - - /** Test using `op`. If current typerstate is shared, run `op` in a fresh exploration - * typerstate. If it is unshared, run `op` in current typerState, restoring typerState - * to previous state afterwards. - */ - def test[T](op: Context ?=> T)(using Context): T = - if (isShared) - op(using ctx.fresh.setExploreTyperState()) - else { - val savedConstraint = myConstraint - val savedReporter = myReporter - val savedCommittable = myIsCommittable - val savedCommitted = isCommitted - myIsCommittable = false - myReporter = { - if (testReporter == null || testReporter.inUse) - testReporter = new TestReporter(reporter) - else - testReporter.reset() - testReporter.inUse = true - testReporter - } - try op - finally { - testReporter.inUse = false - resetConstraintTo(savedConstraint) - myReporter = savedReporter - myIsCommittable = savedCommittable - isCommitted = savedCommitted - } - } - /** Commit typer state so that its information is copied into current typer state * In addition (1) the owning state of undetermined or temporarily instantiated * type variables changes from this typer state to the current one. (2) Variables @@ -190,14 +171,3 @@ class TyperState(private val previous: TyperState /* | Null */) { def stateChainStr: String = s"$this${if (previous == null) "" else previous.stateChainStr}" } - -/** Temporary, reusable reporter used in TyperState#test */ -private class TestReporter(outer: Reporter) extends StoreReporter(outer) { - /** Is this reporter currently used in a test? */ - var inUse: Boolean = false - - def reset(): Unit = { - assert(!inUse, s"Cannot reset reporter currently in use: $this") - infos = null - } -} diff --git a/compiler/src/dotty/tools/dotc/reporting/TestReporter.scala b/compiler/src/dotty/tools/dotc/reporting/TestReporter.scala new file mode 100644 index 000000000000..8ad5b525de5c --- /dev/null +++ b/compiler/src/dotty/tools/dotc/reporting/TestReporter.scala @@ -0,0 +1,12 @@ +package dotty.tools +package dotc +package reporting + +import collection.mutable +import Diagnostic._ + +/** A re-usable Reporter used in Contexts#test */ +class TestingReporter extends StoreReporter(null): + infos = new mutable.ListBuffer[Diagnostic] + override def hasUnreportedErrors: Boolean = infos.exists(_.isInstanceOf[Error]) + def reset(): Unit = infos.clear() diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index c97999f30da1..f823cc8a268c 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -1302,20 +1302,20 @@ trait Applications extends Compatibility { def isApplicableMethodRef(methRef: TermRef, args: List[Tree], resultType: Type, keepConstraint: Boolean)(using Context): Boolean = { def isApp(using Context): Boolean = new ApplicableToTrees(methRef, args, resultType).success - if (keepConstraint) isApp else ctx.test(isApp) + if (keepConstraint) isApp else explore(isApp) } /** Is given method reference applicable to argument trees `args` without inferring views? * @param resultType The expected result type of the application */ def isDirectlyApplicableMethodRef(methRef: TermRef, args: List[Tree], resultType: Type)(using Context): Boolean = - ctx.test(new ApplicableToTreesDirectly(methRef, args, resultType).success) + explore(new ApplicableToTreesDirectly(methRef, args, resultType).success) /** Is given method reference applicable to argument types `args`? * @param resultType The expected result type of the application */ def isApplicableMethodRef(methRef: TermRef, args: List[Type], resultType: Type)(using Context): Boolean = - ctx.test(new ApplicableToTypes(methRef, args, resultType).success) + explore(new ApplicableToTypes(methRef, args, resultType).success) /** Is given type applicable to argument trees `args`, possibly after inserting an `apply`? * @param resultType The expected result type of the application @@ -1474,7 +1474,7 @@ trait Applications extends Compatibility { case tp2: MethodType => true // (3a) case tp2: PolyType if tp2.resultType.isInstanceOf[MethodType] => true // (3a) case tp2: PolyType => // (3b) - ctx.test(isAsSpecificValueType(tp1, constrained(tp2).resultType)) + explore(isAsSpecificValueType(tp1, constrained(tp2).resultType)) case _ => // (3b) isAsSpecificValueType(tp1, tp2) } @@ -1658,9 +1658,9 @@ trait Applications extends Compatibility { * do they prune much, on average. */ def adaptByResult(chosen: TermRef, alts: List[TermRef]) = pt match { - case pt: FunProto if !ctx.test(resultConforms(chosen.symbol, chosen, pt.resultType)) => + case pt: FunProto if !explore(resultConforms(chosen.symbol, chosen, pt.resultType)) => val conformingAlts = alts.filter(alt => - (alt ne chosen) && ctx.test(resultConforms(alt.symbol, alt, pt.resultType))) + (alt ne chosen) && explore(resultConforms(alt.symbol, alt, pt.resultType))) conformingAlts match { case Nil => chosen case alt2 :: Nil => alt2 diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index 86ea09fdd3e2..8ff3603fc1d3 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -125,7 +125,7 @@ object Implicits { else if (mt.paramInfos.lengthCompare(1) == 0 && { var formal = widenSingleton(mt.paramInfos.head) if (approx) formal = wildApprox(formal) - ctx.test(argType relaxed_<:< formal.widenExpr) + explore(argType relaxed_<:< formal.widenExpr) }) Candidate.Conversion else @@ -242,7 +242,7 @@ object Implicits { val nestedCtx = ctx.fresh.addMode(Mode.TypevarsMissContext) def matchingCandidate(ref: ImplicitRef, extensionOnly: Boolean): Option[Candidate] = - var ckind = nestedCtx.test(candidateKind(ref.underlyingRef)) + var ckind = explore(candidateKind(ref.underlyingRef))(using nestedCtx) if extensionOnly then ckind &= Candidate.Extension if ckind == Candidate.None then None else Some(new Candidate(ref, ckind, level)) @@ -1131,7 +1131,7 @@ trait Implicits { self: Typer => def compareCandidate(prev: SearchSuccess, ref: TermRef, level: Int): Int = if (prev.ref eq ref) 0 else if (prev.level != level) prev.level - level - else nestedContext().test(compare(prev.ref, ref)) + else explore(compare(prev.ref, ref))(using nestedContext()) /** If `alt1` is also a search success, try to disambiguate as follows: * - If alt2 is preferred over alt1, pick alt2, otherwise return an diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index 67afb6dc8c83..97515593db91 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -24,6 +24,7 @@ import transform.ValueClasses._ import transform.TypeUtils._ import transform.SymUtils._ import reporting.messages._ +import reporting.TestingReporter import config.Feature.sourceVersion import config.SourceVersion._ @@ -816,7 +817,9 @@ class Namer { typer: Typer => /** The context with which this completer was created */ given creationContext as Context = ictx - ictx.typerState.markShared() + + // make sure testing contexts are not captured by completers + assert(!ictx.reporter.isInstanceOf[TestingReporter]) protected def typeSig(sym: Symbol): Type = original match { case original: ValDef => diff --git a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala index 22e1d10cb02d..c0ba833e585e 100644 --- a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala +++ b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala @@ -57,7 +57,7 @@ object ProtoTypes { normalizedCompatible(tp, pt, keepConstraint = false) case _ => testCompat } - else ctx.test(testCompat) + else explore(testCompat) } private def disregardProto(pt: Type)(using Context): Boolean = @@ -82,7 +82,7 @@ object ProtoTypes { case _ => true } - if (!res) ctx.typerState.resetConstraintTo(savedConstraint) + if !res then ctx.typerState.constraint = savedConstraint res } diff --git a/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala b/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala index 8d71ddb9d9f5..1ceb8d1a34cf 100644 --- a/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala @@ -178,7 +178,7 @@ class Synthesizer(typer: Typer)(using @constructorOnly c: Context): case args @ (arg1 :: arg2 :: Nil) => List(arg1, arg2).foreach(fullyDefinedType(_, "eq argument", span)) if canComparePredefined(arg1, arg2) - || !Implicits.strictEquality && ctx.test(validEqAnyArgs(arg1, arg2)) + || !Implicits.strictEquality && explore(validEqAnyArgs(arg1, arg2)) then ref(defn.Eql_eqlAny).appliedToTypes(args).withSpan(span) else EmptyTree case _ => EmptyTree From dd8a198973f2d6dfd2ac7e3d776dfdb189e5dc6f Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Tue, 7 Jul 2020 18:00:19 +0200 Subject: [PATCH 03/10] Stats recording for computing denotations --- compiler/src/dotty/tools/dotc/core/Symbols.scala | 4 ++++ compiler/src/dotty/tools/dotc/core/Types.scala | 2 ++ 2 files changed, 6 insertions(+) diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index ee64ef087ef1..ea019e3851d2 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -477,18 +477,21 @@ object Symbols { /** Set the denotation of this symbol */ private[core] def denot_=(d: SymDenotation): Unit = { + util.Stats.record("Symbol.denot_=") lastDenot = d checkedPeriod = Nowhere } /** The current denotation of this symbol */ final def denot(using Context): SymDenotation = { + util.Stats.record("Symbol.denot") val lastd = lastDenot if (checkedPeriod == ctx.period) lastd else computeDenot(lastd) } private def computeDenot(lastd: SymDenotation)(using Context): SymDenotation = { + util.Stats.record("Symbol.computeDenot") val now = ctx.period checkedPeriod = now if (lastd.validFor contains now) lastd else recomputeDenot(lastd) @@ -496,6 +499,7 @@ object Symbols { /** Overridden in NoSymbol */ protected def recomputeDenot(lastd: SymDenotation)(using Context): SymDenotation = { + util.Stats.record("Symbol.recomputeDenot") val newd = lastd.current.asInstanceOf[SymDenotation] lastDenot = newd newd diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index ed3ba9a562af..f08f2292bf60 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -1976,6 +1976,7 @@ object Types { /** The denotation currently denoted by this type */ final def denot(using Context): Denotation = { + util.Stats.record("NamedType.denot") val now = ctx.period // Even if checkedPeriod == now we still need to recheck lastDenotation.validFor // as it may have been mutated by SymDenotation#installAfter @@ -1987,6 +1988,7 @@ object Types { } private def computeDenot(using Context): Denotation = { + util.Stats.record("NamedType.computeDenot") def finish(d: Denotation) = { if (d.exists) From 7769a3c5f139b7dab6ea8cf3c5acec4191f00062 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 16 Jul 2020 10:54:42 +0200 Subject: [PATCH 04/10] Remove all mixin traits from Contexts Also: - Change functions from Context to context functions - Rename ctx.erasedTypes -> currentlyAfterErasure ctx.isAfterTyper -> currentlyAfterTyper - Add currentPhase, currentPeriod, ... utility methods - Replace `c.runId` by `currentRunId(using c)`. This can be changed back again if we end up not splitting period info from contexts - Add inMode, withMode, withoutMode utility wrappers - Move error messages directly into reporting: this avoids an annoying import --- bench/src/main/scala/Benchmarks.scala | 2 +- .../tools/backend/jvm/BCodeAsmCommon.scala | 3 +- .../tools/backend/jvm/BCodeBodyBuilder.scala | 13 +- .../tools/backend/jvm/BCodeHelpers.scala | 37 +- .../tools/backend/jvm/BCodeIdiomatic.scala | 3 +- .../tools/backend/jvm/BCodeSkelBuilder.scala | 15 +- .../tools/backend/jvm/BytecodeWriters.scala | 6 +- .../dotty/tools/backend/jvm/CoreBTypes.scala | 4 +- .../backend/jvm/DottyBackendInterface.scala | 14 +- .../dotty/tools/backend/jvm/GenBCode.scala | 12 +- .../tools/backend/jvm/scalaPrimitives.scala | 5 +- .../dotty/tools/backend/sjs/JSCodeGen.scala | 37 +- .../tools/backend/sjs/JSDefinitions.scala | 98 +- .../tools/backend/sjs/JSPrimitives.scala | 3 +- .../backend/sjs/JUnitBootstrappers.scala | 20 +- .../dotty/tools/dotc/CompilationUnit.scala | 6 +- compiler/src/dotty/tools/dotc/Driver.scala | 13 +- compiler/src/dotty/tools/dotc/Run.scala | 24 +- .../src/dotty/tools/dotc/ast/Desugar.scala | 47 +- .../dotty/tools/dotc/ast/DesugarEnums.scala | 2 +- .../dotty/tools/dotc/ast/MainProxies.scala | 10 +- .../tools/dotc/ast/TreeMapWithImplicits.scala | 19 +- .../dotty/tools/dotc/ast/TreeTypeMap.scala | 4 +- compiler/src/dotty/tools/dotc/ast/tpd.scala | 36 +- compiler/src/dotty/tools/dotc/ast/untpd.scala | 2 +- .../tools/dotc/config/CompilerCommand.scala | 12 +- .../src/dotty/tools/dotc/config/Feature.scala | 2 +- .../dotty/tools/dotc/core/Annotations.scala | 39 +- .../src/dotty/tools/dotc/core/Comments.scala | 4 +- .../tools/dotc/core/ConstraintHandling.scala | 6 +- .../dotty/tools/dotc/core/ContextOps.scala | 75 ++ .../src/dotty/tools/dotc/core/Contexts.scala | 82 +- .../dotty/tools/dotc/core/Definitions.scala | 461 ++++--- .../tools/dotc/core/DenotTransformers.scala | 4 +- .../dotty/tools/dotc/core/Denotations.scala | 165 ++- .../src/dotty/tools/dotc/core/NamerOps.scala | 60 + .../tools/dotc/core/OrderingConstraint.scala | 2 +- .../src/dotty/tools/dotc/core/Periods.scala | 39 +- .../src/dotty/tools/dotc/core/Phases.scala | 40 +- .../src/dotty/tools/dotc/core/Scopes.scala | 6 +- .../tools/dotc/core/SymDenotations.scala | 269 ++-- .../dotty/tools/dotc/core/SymbolLoaders.scala | 36 +- .../src/dotty/tools/dotc/core/Symbols.scala | 1196 +++++++++-------- .../tools/dotc/core/TypeApplications.scala | 4 +- .../dotty/tools/dotc/core/TypeComparer.scala | 39 +- .../dotty/tools/dotc/core/TypeErasure.scala | 4 +- .../dotty/tools/dotc/core/TypeErrors.scala | 5 +- .../src/dotty/tools/dotc/core/TypeOps.scala | 4 +- .../src/dotty/tools/dotc/core/Types.scala | 114 +- .../dotc/core/classfile/ClassfileParser.scala | 38 +- .../dotc/core/quoted/PickledQuotes.scala | 6 +- .../dotc/core/tasty/PositionPickler.scala | 2 +- .../tools/dotc/core/tasty/TreePickler.scala | 4 +- .../tools/dotc/core/tasty/TreeUnpickler.scala | 73 +- .../core/unpickleScala2/Scala2Unpickler.scala | 36 +- .../dotc/decompiler/IDEDecompilerDriver.scala | 2 +- .../tools/dotc/fromtasty/ReadTasty.scala | 9 +- .../tools/dotc/interactive/Interactive.scala | 3 +- .../dotc/interactive/InteractiveDriver.scala | 3 +- .../tools/dotc/parsing/JavaParsers.scala | 2 +- .../dotty/tools/dotc/parsing/Parsers.scala | 37 +- .../dotty/tools/dotc/parsing/Scanners.scala | 10 +- .../dotty/tools/dotc/plugins/Plugins.scala | 11 +- .../tools/dotc/printing/MessageLimiter.scala | 2 +- .../tools/dotc/printing/PlainPrinter.scala | 10 +- .../dotty/tools/dotc/printing/Printers.scala | 14 - compiler/src/dotty/tools/dotc/report.scala | 123 ++ .../dotty/tools/dotc/reporting/Message.scala | 2 - .../dotty/tools/dotc/reporting/Reporter.scala | 130 +- .../dotty/tools/dotc/reporting/messages.scala | 29 +- .../dotty/tools/dotc/reporting/trace.scala | 2 +- .../dotty/tools/dotc/rewrites/Rewrites.scala | 2 +- .../src/dotty/tools/dotc/sbt/ExtractAPI.scala | 6 +- .../tools/dotc/sbt/ExtractDependencies.scala | 4 +- .../tools/dotc/tastyreflect/FromSymbol.scala | 2 +- .../ReflectionCompilerInterface.scala | 28 +- .../tools/dotc/transform/AccessProxies.scala | 4 +- .../tools/dotc/transform/BetaReduce.scala | 4 +- .../dotty/tools/dotc/transform/Bridges.scala | 7 +- .../tools/dotc/transform/ByNameClosures.scala | 3 +- .../tools/dotc/transform/CapturedVars.scala | 6 +- .../tools/dotc/transform/CheckReentrant.scala | 11 +- .../tools/dotc/transform/CheckStatic.scala | 16 +- .../dotc/transform/CompleteJavaEnums.scala | 6 +- .../tools/dotc/transform/Constructors.scala | 2 +- .../transform/ContextFunctionResults.scala | 4 +- .../tools/dotc/transform/CookComments.scala | 1 + .../DropEmptyCompanions.scala.disabled | 2 +- .../dotc/transform/ElimErasedValueType.scala | 19 +- .../tools/dotc/transform/ElimRepeated.scala | 6 +- .../dotty/tools/dotc/transform/Erasure.scala | 34 +- .../tools/dotc/transform/ExpandSAMs.scala | 12 +- .../tools/dotc/transform/ExplicitOuter.scala | 13 +- .../tools/dotc/transform/ExplicitSelf.scala | 2 +- .../dotc/transform/ExtensionMethods.scala | 10 +- .../transform/FunctionXXLForwarders.scala | 2 +- .../dotc/transform/FunctionalInterfaces.scala | 2 +- .../tools/dotc/transform/HoistSuperArgs.scala | 4 +- .../tools/dotc/transform/InlinePatterns.scala | 2 +- .../dotc/transform/InterceptedMethods.scala | 2 +- .../IsInstanceOfEvaluator.scala.disabled | 10 +- .../tools/dotc/transform/LambdaLift.scala | 16 +- .../dotty/tools/dotc/transform/LazyVals.scala | 65 +- .../dotty/tools/dotc/transform/LiftTry.scala | 4 +- .../tools/dotc/transform/MacroTransform.scala | 2 +- .../tools/dotc/transform/MegaPhase.scala | 6 +- .../dotty/tools/dotc/transform/Memoize.scala | 6 +- .../dotty/tools/dotc/transform/Mixin.scala | 4 +- .../dotty/tools/dotc/transform/MixinOps.scala | 2 +- .../tools/dotc/transform/MoveStatics.scala | 2 +- .../dotc/transform/NonLocalReturns.scala | 6 +- .../dotc/transform/OverridingPairs.scala | 2 +- .../dotc/transform/PCPCheckAndHeal.scala | 12 +- .../dotc/transform/ParamForwarding.scala | 2 +- .../tools/dotc/transform/PatternMatcher.scala | 10 +- .../dotty/tools/dotc/transform/Pickler.scala | 10 +- .../tools/dotc/transform/PostTyper.scala | 14 +- .../dotc/transform/ProtectedAccessors.scala | 2 +- .../tools/dotc/transform/ReifyQuotes.scala | 2 +- .../tools/dotc/transform/ResolveSuper.scala | 8 +- .../dotty/tools/dotc/transform/Splicer.scala | 23 +- .../dotty/tools/dotc/transform/Staging.scala | 2 +- .../tools/dotc/transform/SuperAccessors.scala | 18 +- .../dotc/transform/SyntheticMembers.scala | 26 +- .../dotty/tools/dotc/transform/TailRec.scala | 38 +- .../dotc/transform/TransformByNameApply.scala | 2 +- .../tools/dotc/transform/TreeChecker.scala | 45 +- .../dotc/transform/TryCatchPatterns.scala | 2 +- .../dotc/transform/TupleOptimizations.scala | 4 +- .../tools/dotc/transform/TypeTestsCasts.scala | 13 +- .../tools/dotc/transform/TypeUtils.scala | 2 +- .../tools/dotc/transform/ValueClasses.scala | 4 +- .../dotc/transform/YCheckPositions.scala | 2 +- .../tools/dotc/transform/init/Checking.scala | 4 +- .../dotty/tools/dotc/transform/init/Env.scala | 2 +- .../tools/dotc/transform/init/Errors.scala | 13 +- .../localopt/StringInterpolatorOpt.scala | 5 +- .../tools/dotc/transform/patmat/Space.scala | 17 +- .../dotty/tools/dotc/typer/Applications.scala | 43 +- .../src/dotty/tools/dotc/typer/Checking.scala | 131 +- .../src/dotty/tools/dotc/typer/Deriving.scala | 14 +- .../dotty/tools/dotc/typer/Docstrings.scala | 2 +- .../src/dotty/tools/dotc/typer/Dynamic.scala | 2 +- .../tools/dotc/typer/ErrorReporting.scala | 9 +- .../dotty/tools/dotc/typer/EtaExpansion.scala | 4 +- .../src/dotty/tools/dotc/typer/FrontEnd.scala | 8 +- .../dotty/tools/dotc/typer/Implicits.scala | 29 +- .../dotty/tools/dotc/typer/Inferencing.scala | 2 +- .../src/dotty/tools/dotc/typer/Inliner.scala | 22 +- .../src/dotty/tools/dotc/typer/Namer.scala | 229 +--- .../dotty/tools/dotc/typer/Nullables.scala | 10 +- .../tools/dotc/typer/PrepareInlineable.scala | 18 +- .../dotty/tools/dotc/typer/ProtoTypes.scala | 2 +- .../tools/dotc/typer/QuotesAndSplices.scala | 51 +- .../src/dotty/tools/dotc/typer/ReTyper.scala | 10 +- .../dotty/tools/dotc/typer/RefChecks.scala | 64 +- .../dotty/tools/dotc/typer/Synthesizer.scala | 4 +- .../dotty/tools/dotc/typer/TypeAssigner.scala | 20 +- .../src/dotty/tools/dotc/typer/Typer.scala | 159 +-- .../tools/dotc/typer/VarianceChecker.scala | 18 +- .../dotty/tools/dotc/util/Signatures.scala | 29 +- .../src/dotty/tools/repl/ReplCompiler.scala | 2 +- .../src/dotty/tools/repl/ReplDriver.scala | 4 +- .../test/dotty/tools/AnnotationsTests.scala | 8 +- compiler/test/dotty/tools/SignatureTest.scala | 3 +- .../dotc/reporting/TestMessageLaziness.scala | 4 +- .../tools/dotc/reporting/TestReporter.scala | 1 - .../reporting/UserDefinedErrorMessages.scala | 1 - .../dotty/tools/vulpix/ParallelTesting.scala | 3 +- compiler/test/worksheets/sigtest.sc | 6 +- .../dotty/tools/dottydoc/DocCompiler.scala | 8 +- .../src/dotty/tools/dottydoc/DocDriver.scala | 7 +- .../core/AlternateConstructorsPhase.scala | 6 +- .../tools/dottydoc/core/ContextDottydoc.scala | 25 +- .../tools/dottydoc/core/DocASTPhase.scala | 13 +- .../dottydoc/core/DocImplicitsPhase.scala | 4 +- .../tools/dottydoc/core/DocstringPhase.scala | 22 +- .../dottydoc/core/LinkCompanionsPhase.scala | 14 +- .../dottydoc/core/PackageObjectsPhase.scala | 6 +- .../core/RemoveEmptyPackagesPhase.scala | 4 +- .../dottydoc/core/SortMembersPhase.scala | 12 +- .../tools/dottydoc/core/StatisticsPhase.scala | 10 +- .../dottydoc/core/TypeLinkingPhases.scala | 24 +- .../tools/dottydoc/core/UsecasePhase.scala | 6 +- .../dotty/tools/dottydoc/core/transform.scala | 42 +- .../dottydoc/model/comment/Comment.scala | 42 +- .../model/comment/CommentParser.scala | 6 +- .../dottydoc/model/comment/HtmlParsers.scala | 10 +- .../dottydoc/model/comment/WikiParser.scala | 2 +- .../tools/dottydoc/model/factories.scala | 22 +- .../tools/dottydoc/staticsite/BlogPost.scala | 4 +- .../tools/dottydoc/staticsite/Page.scala | 12 +- .../tools/dottydoc/staticsite/Site.scala | 26 +- .../tools/dottydoc/staticsite/Template.scala | 9 +- .../tools/dottydoc/staticsite/tags.scala | 14 +- .../dotty/tools/dottydoc/util/syntax.scala | 4 +- .../dotty/tools/dottydoc/DottyDocTest.scala | 2 +- docs/docs/contributing/debugging.md | 2 +- .../changed-features/compiler-plugins.md | 4 +- .../changed-features/numeric-literals.md | 3 +- .../languageserver/DottyLanguageServer.scala | 4 +- sbt-bridge/src/xsbt/DelegatingReporter.java | 1 - .../analyzer-plugin/plugin/Analyzer.scala | 8 +- .../compiler-plugin/plugin/DivideZero.scala | 2 +- .../scala/quoted/staging/QuoteCompiler.scala | 8 +- .../plugins/custom/analyzer/Analyzer_1.scala | 14 +- .../neg/divideZero-research/plugin_1.scala | 6 +- tests/plugins/neg/divideZero/plugin_1.scala | 6 +- 208 files changed, 2796 insertions(+), 2804 deletions(-) create mode 100644 compiler/src/dotty/tools/dotc/core/ContextOps.scala create mode 100644 compiler/src/dotty/tools/dotc/core/NamerOps.scala delete mode 100644 compiler/src/dotty/tools/dotc/printing/Printers.scala create mode 100644 compiler/src/dotty/tools/dotc/report.scala diff --git a/bench/src/main/scala/Benchmarks.scala b/bench/src/main/scala/Benchmarks.scala index 4c4ffca87810..677a95aa66cf 100644 --- a/bench/src/main/scala/Benchmarks.scala +++ b/bench/src/main/scala/Benchmarks.scala @@ -102,7 +102,7 @@ class Worker extends Driver { } catch { case ex: FatalError => - ctx.error(ex.getMessage) // signals that we should fail compilation. + report.error(ex.getMessage) // signals that we should fail compilation. ctx.reporter } else ctx.reporter diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala b/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala index 98627bfbec96..eb9481382b5b 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala @@ -4,6 +4,7 @@ package jvm import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Symbols._ +import dotty.tools.dotc.report /** * This trait contains code shared between GenBCode and GenASM that depends on types defined in @@ -89,7 +90,7 @@ final class BCodeAsmCommon[I <: DottyBackendInterface](val interface: I) { def enclosingMethodAttribute(classSym: Symbol, classDesc: Symbol => String, methodDesc: Symbol => String): Option[EnclosingMethodEntry] = { if (isAnonymousOrLocalClass(classSym)) { val methodOpt = enclosingMethodForEnclosingMethodAttribute(classSym) - ctx.debuglog(s"enclosing method for $classSym is $methodOpt (in ${methodOpt.map(_.enclosingClass)})") + report.debuglog(s"enclosing method for $classSym is $methodOpt (in ${methodOpt.map(_.enclosingClass)})") Some(EnclosingMethodEntry( classDesc(enclosingClassForEnclosingMethodAttribute(classSym)), methodOpt.map(_.javaSimpleName).orNull, diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala index 84cb98b8046f..df791164c5da 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala @@ -21,6 +21,7 @@ import dotty.tools.dotc.transform.SymUtils._ import dotty.tools.dotc.util.Spans._ import dotty.tools.dotc.core.Contexts.{inContext, atPhase} import dotty.tools.dotc.core.Phases._ +import dotty.tools.dotc.report /* * @@ -277,7 +278,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { tree match { case ValDef(nme.THIS, _, _) => - ctx.debuglog("skipping trivial assign to _$this: " + tree) + report.debuglog("skipping trivial assign to _$this: " + tree) case tree@ValDef(_, _, _) => val sym = tree.symbol @@ -326,9 +327,9 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { else { val arity = app.meth.tpe.widenDealias.firstParamTypes.size - env.size val returnsUnit = app.meth.tpe.widenDealias.resultType.classSymbol == defn.UnitClass - if (returnsUnit) ctx.requiredClass(("dotty.runtime.function.JProcedure" + arity)) - else if (arity <= 2) ctx.requiredClass(("dotty.runtime.function.JFunction" + arity)) - else ctx.requiredClass(("scala.Function" + arity)) + if (returnsUnit) requiredClass(("dotty.runtime.function.JProcedure" + arity)) + else if (arity <= 2) requiredClass(("dotty.runtime.function.JFunction" + arity)) + else requiredClass(("scala.Function" + arity)) } } val (fun, args) = call match { @@ -669,7 +670,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { var elemKind = arr.elementType val argsSize = args.length if (argsSize > dims) { - ctx.error(s"too many arguments for array constructor: found ${args.length} but array has only $dims dimension(s)", ctx.source.atSpan(app.span)) + report.error(s"too many arguments for array constructor: found ${args.length} but array has only $dims dimension(s)", ctx.source.atSpan(app.span)) } if (argsSize < dims) { /* In one step: @@ -1431,7 +1432,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { def genInvokeDynamicLambda(ctor: Symbol, lambdaTarget: Symbol, environmentSize: Int, functionalInterface: Symbol): BType = { import java.lang.invoke.LambdaMetafactory.FLAG_SERIALIZABLE - ctx.debuglog(s"Using invokedynamic rather than `new ${ctor.owner}`") + report.debuglog(s"Using invokedynamic rather than `new ${ctor.owner}`") val generatedType = classBTypeFromSymbol(functionalInterface) // Lambdas should be serializable if they implement a SAM that extends Serializable or if they // implement a scala.Function* class. diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index 46e403e72c8b..6516cbf95d73 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala @@ -27,6 +27,7 @@ import dotty.tools.dotc.core.Types._ import dotty.tools.dotc.core.TypeErasure import dotty.tools.dotc.transform.GenericSignatures import dotty.tools.io.AbstractFile +import dotty.tools.dotc.report import dotty.tools.backend.jvm.DottyBackendInterface.symExtensions @@ -52,11 +53,11 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { def ScalaATTRName: String = "Scala" def ScalaSignatureATTRName: String = "ScalaSig" - @threadUnsafe lazy val AnnotationRetentionAttr: ClassSymbol = ctx.requiredClass("java.lang.annotation.Retention") - @threadUnsafe lazy val AnnotationRetentionSourceAttr: TermSymbol = ctx.requiredClass("java.lang.annotation.RetentionPolicy").linkedClass.requiredValue("SOURCE") - @threadUnsafe lazy val AnnotationRetentionClassAttr: TermSymbol = ctx.requiredClass("java.lang.annotation.RetentionPolicy").linkedClass.requiredValue("CLASS") - @threadUnsafe lazy val AnnotationRetentionRuntimeAttr: TermSymbol = ctx.requiredClass("java.lang.annotation.RetentionPolicy").linkedClass.requiredValue("RUNTIME") - @threadUnsafe lazy val JavaAnnotationClass: ClassSymbol = ctx.requiredClass("java.lang.annotation.Annotation") + @threadUnsafe lazy val AnnotationRetentionAttr: ClassSymbol = requiredClass("java.lang.annotation.Retention") + @threadUnsafe lazy val AnnotationRetentionSourceAttr: TermSymbol = requiredClass("java.lang.annotation.RetentionPolicy").linkedClass.requiredValue("SOURCE") + @threadUnsafe lazy val AnnotationRetentionClassAttr: TermSymbol = requiredClass("java.lang.annotation.RetentionPolicy").linkedClass.requiredValue("CLASS") + @threadUnsafe lazy val AnnotationRetentionRuntimeAttr: TermSymbol = requiredClass("java.lang.annotation.RetentionPolicy").linkedClass.requiredValue("RUNTIME") + @threadUnsafe lazy val JavaAnnotationClass: ClassSymbol = requiredClass("java.lang.annotation.Annotation") val bCodeAsmCommon: BCodeAsmCommon[int.type] = new BCodeAsmCommon(int) import bCodeAsmCommon._ @@ -76,7 +77,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { outputDirectory } catch { case ex: Throwable => - ctx.error(s"Couldn't create file for class $cName\n${ex.getMessage}", ctx.source.atSpan(csym.span)) + report.error(s"Couldn't create file for class $cName\n${ex.getMessage}", ctx.source.atSpan(csym.span)) null } } @@ -425,7 +426,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { emitAssocs(nestedVisitor, assocs, bcodeStore)(innerClasesStore) case t => - ctx.error(ex"Annotation argument is not a constant", t.sourcePos) + report.error(ex"Annotation argument is not a constant", t.sourcePos) } } @@ -563,26 +564,26 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { */ def addForwarders(jclass: asm.ClassVisitor, jclassName: String, moduleClass: Symbol): Unit = { assert(moduleClass.is(ModuleClass), moduleClass) - ctx.debuglog(s"Dumping mirror class for object: $moduleClass") + report.debuglog(s"Dumping mirror class for object: $moduleClass") val linkedClass = moduleClass.companionClass lazy val conflictingNames: Set[Name] = { (linkedClass.info.allMembers.collect { case d if d.name.isTermName => d.name }).toSet } - ctx.debuglog(s"Potentially conflicting names for forwarders: $conflictingNames") + report.debuglog(s"Potentially conflicting names for forwarders: $conflictingNames") for (m0 <- sortedMembersBasedOnFlags(moduleClass.info, required = Method, excluded = ExcludedForwarder)) { val m = if (m0.is(Bridge)) m0.nextOverriddenSymbol else m0 if (m == NoSymbol) - ctx.log(s"$m0 is a bridge method that overrides nothing, something went wrong in a previous phase.") + report.log(s"$m0 is a bridge method that overrides nothing, something went wrong in a previous phase.") else if (m.isType || m.is(Deferred) || (m.owner eq defn.ObjectClass) || m.isConstructor || m.name.is(ExpandedName)) - ctx.debuglog(s"No forwarder for '$m' from $jclassName to '$moduleClass'") + report.debuglog(s"No forwarder for '$m' from $jclassName to '$moduleClass'") else if (conflictingNames(m.name)) - ctx.log(s"No forwarder for $m due to conflict with ${linkedClass.info.member(m.name)}") + report.log(s"No forwarder for $m due to conflict with ${linkedClass.info.member(m.name)}") else if (m.accessBoundary(defn.RootClass) ne defn.RootClass) - ctx.log(s"No forwarder for non-public member $m") + report.log(s"No forwarder for non-public member $m") else { - ctx.log(s"Adding static forwarder for '$m' from $jclassName to '$moduleClass'") + report.log(s"Adding static forwarder for '$m' from $jclassName to '$moduleClass'") addForwarder(jclass, moduleClass, m) } } @@ -822,7 +823,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { * The type in the AnnotationInfo is an AnnotatedTpe. Tested in jvm/annotations.scala. */ case a @ AnnotatedType(t, _) => - ctx.debuglog(s"typeKind of annotated type $a") + report.debuglog(s"typeKind of annotated type $a") typeToTypeKind(t)(ct)(storage) /* The cases below should probably never occur. They are kept for now to avoid introducing @@ -831,7 +832,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { */ case tp => - ctx.warning( + report.warning( s"an unexpected type representation reached the compiler backend while compiling ${ctx.compilationUnit}: $tp. " + "If possible, please file a bug on https://github.com/lampepfl/dotty/issues") @@ -871,7 +872,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { try body catch { case ex: Throwable => - ctx.error(i"""|compiler bug: created invalid generic signature for $sym in ${sym.denot.owner.showFullName} + report.error(i"""|compiler bug: created invalid generic signature for $sym in ${sym.denot.owner.showFullName} |signature: $sig |if this is reproducible, please report bug at https://github.com/lampepfl/dotty/issues """.trim, sym.sourcePos) @@ -922,7 +923,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { } def abort(msg: String): Nothing = { - ctx.error(msg) + report.error(msg) throw new RuntimeException(msg) } diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala b/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala index f763975663f5..6e2646c9e051 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala @@ -7,6 +7,7 @@ import scala.annotation.switch import scala.collection.mutable import Primitives.{NE, EQ, TestOp, ArithmeticOp} import scala.tools.asm.tree.MethodInsnNode +import dotty.tools.dotc.report /* * A high-level facade to the ASM API for bytecode generation. @@ -585,7 +586,7 @@ trait BCodeIdiomatic { } def abort(msg: String): Nothing = { - ctx.error(msg) + report.error(msg) throw new RuntimeException(msg) } diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala index 98fa9a22967e..8721b5a10828 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala @@ -18,6 +18,7 @@ import dotty.tools.dotc.core.StdNames.str import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Types.Type import dotty.tools.dotc.util.Spans._ +import dotty.tools.dotc.report /* * @@ -118,12 +119,12 @@ trait BCodeSkelBuilder extends BCodeHelpers { val optSerial: Option[Long] = claszSymbol.getAnnotation(defn.SerialVersionUIDAnnot).flatMap { annot => if (claszSymbol.is(Trait)) { - ctx.error("@SerialVersionUID does nothing on a trait", annot.tree.sourcePos) + report.error("@SerialVersionUID does nothing on a trait", annot.tree.sourcePos) None } else { val vuid = annot.argumentConstant(0).map(_.longValue) if (vuid.isEmpty) - ctx.error("The argument passed to @SerialVersionUID must be a constant", + report.error("The argument passed to @SerialVersionUID must be a constant", annot.argument(0).getOrElse(annot.tree).sourcePos) vuid } @@ -192,7 +193,7 @@ trait BCodeSkelBuilder extends BCodeHelpers { // it must be a top level class (name contains no $s) val isCandidateForForwarders = (lmoc.is(Module)) && lmoc.isStatic if (isCandidateForForwarders) { - ctx.log(s"Adding static forwarders from '$claszSymbol' to implementations in '$lmoc'") + report.log(s"Adding static forwarders from '$claszSymbol' to implementations in '$lmoc'") addForwarders(cnode, thisName, lmoc.moduleClass) } } @@ -388,7 +389,7 @@ trait BCodeSkelBuilder extends BCodeHelpers { */ def makeLocal(tk: BType, name: String, tpe: Type, pos: Span): Symbol = { - val locSym = ctx.newSymbol(methSymbol, name.toTermName, Synthetic, tpe, NoSymbol, pos) + val locSym = newSymbol(methSymbol, name.toTermName, Synthetic, tpe, NoSymbol, pos) makeLocal(locSym, tk) locSym } @@ -407,7 +408,7 @@ trait BCodeSkelBuilder extends BCodeHelpers { val loc = Local(tk, sym.javaSimpleName, nxtIdx, sym.is(Synthetic)) val existing = slots.put(sym, loc) if (existing.isDefined) - ctx.error("attempt to create duplicate local var.", ctx.source.atSpan(sym.span)) + report.error("attempt to create duplicate local var.", ctx.source.atSpan(sym.span)) assert(tk.size > 0, "makeLocal called for a symbol whose type is Unit.") nxtIdx += tk.size loc @@ -560,7 +561,7 @@ trait BCodeSkelBuilder extends BCodeHelpers { if (params.size > MaximumJvmParameters) { // SI-7324 - ctx.error(s"Platform restriction: a parameter list's length cannot exceed $MaximumJvmParameters.", ctx.source.atSpan(methSymbol.span)) + report.error(s"Platform restriction: a parameter list's length cannot exceed $MaximumJvmParameters.", ctx.source.atSpan(methSymbol.span)) return } @@ -587,7 +588,7 @@ trait BCodeSkelBuilder extends BCodeHelpers { case (_: Return) | Block(_, (_: Return)) => () case (_: Apply) | Block(_, (_: Apply)) if rhs.symbol eq defn.throwMethod => () case tpd.EmptyTree => - ctx.error("Concrete method has no definition: " + dd + ( + report.error("Concrete method has no definition: " + dd + ( if (ctx.settings.Ydebug.value) "(found: " + methSymbol.owner.info.decls.toList.mkString(", ") + ")" else ""), ctx.source.atSpan(NoSpan) diff --git a/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala b/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala index 1de8d54e3eff..77e3b6440713 100644 --- a/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala +++ b/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala @@ -4,6 +4,8 @@ package jvm import java.io.{ DataOutputStream, FileOutputStream, IOException, OutputStream, File => JFile } import dotty.tools.io._ +import dotty.tools.dotc.report + import java.util.jar.Attributes.Name import scala.language.postfixOps @@ -61,7 +63,7 @@ trait BytecodeWriters { try out.write(jclassBytes, 0, jclassBytes.length) finally out.flush() - ctx.informProgress("added " + label + path + " to jar") + report.informProgress("added " + label + path + " to jar") } override def close() = writer.close() } @@ -111,7 +113,7 @@ trait BytecodeWriters { try outstream.write(jclassBytes, 0, jclassBytes.length) finally outstream.close() - ctx.informProgress("wrote '" + label + "' to " + outfile) + report.informProgress("wrote '" + label + "' to " + outfile) } } diff --git a/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala b/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala index f9db89a9eea9..fae4e5d82bb8 100644 --- a/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala +++ b/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala @@ -114,8 +114,8 @@ class CoreBTypes[BTFS <: BTypesFromSymbols[_ <: DottyBackendInterface]](val bTyp * names of NothingClass and NullClass can't be emitted as-is. * TODO @lry Once there's a 2.11.3 starr, use the commented argument list. The current starr crashes on the type literal `scala.runtime.Nothing$` */ - lazy val RT_NOTHING : ClassBType = classBTypeFromSymbol(ctx.requiredClass("scala.runtime.Nothing$")) // (requiredClass[scala.runtime.Nothing$]) - lazy val RT_NULL : ClassBType = classBTypeFromSymbol(ctx.requiredClass("scala.runtime.Null$")) // (requiredClass[scala.runtime.Null$]) + lazy val RT_NOTHING : ClassBType = classBTypeFromSymbol(requiredClass("scala.runtime.Nothing$")) // (requiredClass[scala.runtime.Nothing$]) + lazy val RT_NULL : ClassBType = classBTypeFromSymbol(requiredClass("scala.runtime.Null$")) // (requiredClass[scala.runtime.Null$]) lazy val ObjectReference : ClassBType = classBTypeFromSymbol(defn.ObjectClass) lazy val objArrayReference : ArrayBType = ArrayBType(ObjectReference) diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index c363fe20de67..1e253df10d5f 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -23,6 +23,8 @@ import Phases._ import dotty.tools.dotc.util import dotty.tools.dotc.util.Spans +import dotty.tools.dotc.report + import Decorators._ import Constants._ import tpd._ @@ -81,7 +83,7 @@ class DottyBackendInterface(val outputDirectory: AbstractFile, val superCallsMap def _1: Type = field.tpe match { case JavaArrayType(elem) => elem case _ => - ctx.error(s"JavaSeqArray with type ${field.tpe} reached backend: $field", ctx.source.atSpan(field.span)) + report.error(s"JavaSeqArray with type ${field.tpe} reached backend: $field", ctx.source.atSpan(field.span)) UnspecifiedErrorType } def _2: List[Tree] = field.elems @@ -107,13 +109,19 @@ object DottyBackendInterface { else clazz.getName } + def requiredClass(str: String)(using Context): ClassSymbol = + Symbols.requiredClass(str) + def requiredClass[T](using evidence: ClassTag[T], ctx: Context): Symbol = - ctx.requiredClass(erasureString(evidence.runtimeClass)) + requiredClass(erasureString(evidence.runtimeClass)) + + def requiredModule(str: String)(using Context): Symbol = + Symbols.requiredModule(str) def requiredModule[T](using evidence: ClassTag[T], ctx: Context): Symbol = { val moduleName = erasureString(evidence.runtimeClass) val className = if (moduleName.endsWith("$")) moduleName.dropRight(1) else moduleName - ctx.requiredModule(className) + requiredModule(className) } given symExtensions as AnyRef: diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index b153fb5b0c2e..52138552bae4 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -9,6 +9,8 @@ import scala.collection.mutable import scala.collection.JavaConverters._ import dotty.tools.dotc.transform.SymUtils._ import dotty.tools.dotc.interfaces +import dotty.tools.dotc.report + import dotty.tools.dotc.util.SourceFile import java.util.Optional @@ -62,7 +64,7 @@ class GenBCode extends Phase { if (ctx.run.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. - ctx.error("Can not suspend and output to a jar at the same time. See suspension with -Xprint-suspension.") + report.error("Can not suspend and output to a jar at the same time. See suspension with -Xprint-suspension.") jar.close() case _ => } @@ -169,10 +171,10 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten val same = classSymbol.effectiveName.toString == dupClassSym.effectiveName.toString atPhase(typerPhase) { if (same) - summon[Context].warning( // FIXME: This should really be an error, but then FromTasty tests fail + report.warning( // FIXME: This should really be an error, but then FromTasty tests fail s"${cl1.show} and ${cl2.showLocated} produce classes that overwrite one another", cl1.sourcePos) else - summon[Context].warning(s"${cl1.show} differs only in case from ${cl2.showLocated}. " + + report.warning(s"${cl1.show} differs only in case from ${cl2.showLocated}. " + "Such classes will overwrite one another on case-insensitive filesystems.", cl1.sourcePos) } } @@ -212,7 +214,7 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten if (claszSymbol.companionClass == NoSymbol) { mirrorCodeGen.genMirrorClass(claszSymbol, cunit) } else { - ctx.log(s"No mirror class for module with linked class: ${claszSymbol.showFullName}") + report.log(s"No mirror class for module with linked class: ${claszSymbol.showFullName}") null } } else null @@ -264,7 +266,7 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten getFileForClassfile(outF, cls.name, ".class") } catch { case e: FileConflictException => - ctx.error(s"error writing ${cls.name}: ${e.getMessage}") + report.error(s"error writing ${cls.name}: ${e.getMessage}") null } } else null diff --git a/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala b/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala index eac57f1133fa..ff8d49945a48 100644 --- a/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala +++ b/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala @@ -8,6 +8,7 @@ import Contexts.{Context, ctx} import Names.TermName, StdNames._ import Types.{JavaArrayType, UnspecifiedErrorType, Type} import Symbols.{Symbol, NoSymbol} +import dotc.report import scala.annotation.threadUnsafe import scala.collection.immutable @@ -66,7 +67,7 @@ class DottyPrimitives(ictx: Context) { case defn.ArrayOf(el) => el case JavaArrayType(el) => el case _ => - ctx.error(s"expected Array $tpe") + report.error(s"expected Array $tpe") UnspecifiedErrorType } @@ -133,7 +134,7 @@ class DottyPrimitives(ictx: Context) { def addPrimitives(cls: Symbol, method: TermName, code: Int)(using Context): Unit = { val alts = cls.info.member(method).alternatives.map(_.symbol) if (alts.isEmpty) - ctx.error(s"Unknown primitive method $cls.$method") + report.error(s"Unknown primitive method $cls.$method") else alts foreach (s => addPrimitive(s, s.info.paramInfoss match { diff --git a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala index 3e5cebe508a1..d93160e72f12 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala @@ -27,6 +27,7 @@ import StdNames._ import dotty.tools.dotc.transform.Erasure import dotty.tools.dotc.util.SourcePosition import dotty.tools.dotc.util.Spans.Span +import dotty.tools.dotc.report import org.scalajs.ir import org.scalajs.ir.{ClassKind, Position, Trees => js, Types => jstpe} @@ -574,7 +575,7 @@ class JSCodeGen()(using genCtx: Context) { val resultType = toIRType(m.info.resultType) if (existingPublicStaticMethodNames.contains(methodIdent.name)) { - ctx.error( + report.error( "Unexpected situation: found existing public static method " + s"${methodIdent.name.nameString} in the companion class of " + s"${moduleClass.fullName}; cannot generate a static forwarder " + @@ -971,8 +972,8 @@ class JSCodeGen()(using genCtx: Context) { private def genStatOrExpr(tree: Tree, isStat: Boolean): js.Tree = { implicit val pos: SourcePosition = tree.sourcePos - ctx.debuglog(" " + tree) - ctx.debuglog("") + report.debuglog(" " + tree) + report.debuglog("") tree match { /** Local val or var declaration */ @@ -1791,7 +1792,7 @@ class JSCodeGen()(using genCtx: Context) { private lazy val externalEqualsNumNum: Symbol = defn.BoxesRunTimeModule.requiredMethod(nme.equalsNumNum) private lazy val externalEqualsNumChar: Symbol = - NoSymbol // ctx.requiredMethod(BoxesRunTimeTypeRef, nme.equalsNumChar) // this method is private + NoSymbol // requiredMethod(BoxesRunTimeTypeRef, nme.equalsNumChar) // this method is private private lazy val externalEqualsNumObject: Symbol = defn.BoxesRunTimeModule.requiredMethod(nme.equalsNumObject) private lazy val externalEquals: Symbol = @@ -1800,7 +1801,7 @@ class JSCodeGen()(using genCtx: Context) { /** Gen JS code for a call to Any.== */ private def genEqEqPrimitive(ltpe: Type, rtpe: Type, lsrc: js.Tree, rsrc: js.Tree)( implicit pos: SourcePosition): js.Tree = { - ctx.debuglog(s"$ltpe == $rtpe") + report.debuglog(s"$ltpe == $rtpe") val lsym = ltpe.widenDealias.typeSymbol.asClass val rsym = rtpe.widenDealias.typeSymbol.asClass @@ -1910,7 +1911,7 @@ class JSCodeGen()(using genCtx: Context) { case JavaArrayType(el) => el case tpe => val msg = ex"expected Array $tpe" - ctx.error(msg) + report.error(msg) ErrorType(msg) } @@ -2042,7 +2043,7 @@ class JSCodeGen()(using genCtx: Context) { def requireNotSuper(): Unit = { if (jsSuperClassValue.isDefined) - ctx.error("Illegal super call in Scala.js-defined JS class", tree.sourcePos) + report.error("Illegal super call in Scala.js-defined JS class", tree.sourcePos) } def requireNotSpread(arg: js.TreeOrJSSpread): js.Tree = @@ -2326,7 +2327,7 @@ class JSCodeGen()(using genCtx: Context) { } val closure = js.Closure(arrow = true, formalCaptures, formalParams, genBody, actualCaptures) - ctx.debuglog(closure.toString) + report.debuglog(closure.toString) val funInterfaceSym = functionalInterface.tpe.widenDealias.typeSymbol if (jsdefn.isJSFunctionClass(funInterfaceSym)) { @@ -2426,7 +2427,7 @@ class JSCodeGen()(using genCtx: Context) { js.BinaryOp(js.BinaryOp.!==, value, js.Null()) } else if (isJSType(sym)) { if (sym.is(Trait)) { - ctx.error( + report.error( s"isInstanceOf[${sym.fullName}] not supported because it is a JS trait", pos) js.BooleanLiteral(true) @@ -2542,7 +2543,7 @@ class JSCodeGen()(using genCtx: Context) { def resolveReifiedJSClassSym(arg: Tree): Symbol = { def fail(): Symbol = { - ctx.error( + report.error( tree.symbol.name.toString + " must be called with a constant " + "classOf[T] representing a class extending js.Any " + "(not a trait nor an object)", @@ -2625,7 +2626,7 @@ class JSCodeGen()(using genCtx: Context) { case JS_NATIVE => // js.native - ctx.error( + report.error( "js.native may only be used as stub implementation in facade types", tree.sourcePos) js.Undefined() @@ -2958,7 +2959,7 @@ class JSCodeGen()(using genCtx: Context) { * loaded as a value. */ private def reportErrorLoadGlobalScope()(implicit pos: SourcePosition): js.Tree = { - ctx.error( + report.error( "Loading the global scope as a value (anywhere but as the " + "left-hand-side of a `.`-selection) is not allowed." + GenericGlobalObjectInformationMsg, @@ -2988,14 +2989,14 @@ class JSCodeGen()(using genCtx: Context) { if (js.JSGlobalRef.isValidJSGlobalRefName(value)) { js.JSGlobalRef(value) } else if (js.JSGlobalRef.ReservedJSIdentifierNames.contains(value)) { - ctx.error( + report.error( "Invalid selection in the global scope of the reserved " + s"identifier name `$value`." + GenericGlobalObjectInformationMsg, pos) js.JSGlobalRef("erroneous") } else { - ctx.error( + report.error( "Selecting a field of the global scope whose name is " + "not a valid JavaScript identifier is not allowed." + GenericGlobalObjectInformationMsg, @@ -3004,7 +3005,7 @@ class JSCodeGen()(using genCtx: Context) { } case _ => - ctx.error( + report.error( "Selecting a field of the global scope with a dynamic " + "name is not allowed." + GenericGlobalObjectInformationMsg, @@ -3037,14 +3038,14 @@ class JSCodeGen()(using genCtx: Context) { if (js.JSGlobalRef.isValidJSGlobalRefName(value)) { js.JSFunctionApply(js.JSGlobalRef(value), args) } else if (js.JSGlobalRef.ReservedJSIdentifierNames.contains(value)) { - ctx.error( + report.error( "Invalid call in the global scope of the reserved " + s"identifier name `$value`." + GenericGlobalObjectInformationMsg, pos) js.Undefined() } else { - ctx.error( + report.error( "Calling a method of the global scope whose name is not " + "a valid JavaScript identifier is not allowed." + GenericGlobalObjectInformationMsg, @@ -3053,7 +3054,7 @@ class JSCodeGen()(using genCtx: Context) { } case _ => - ctx.error( + report.error( "Calling a method of the global scope with a dynamic " + "name is not allowed." + GenericGlobalObjectInformationMsg, diff --git a/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala b/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala index 2b0531cf0a51..21a5e67c45c6 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala @@ -20,15 +20,15 @@ object JSDefinitions { final class JSDefinitions()(using Context) { - @threadUnsafe lazy val InlineAnnotType: TypeRef = ctx.requiredClassRef("scala.inline") + @threadUnsafe lazy val InlineAnnotType: TypeRef = requiredClassRef("scala.inline") def InlineAnnot(using Context) = InlineAnnotType.symbol.asClass - @threadUnsafe lazy val NoinlineAnnotType: TypeRef = ctx.requiredClassRef("scala.noinline") + @threadUnsafe lazy val NoinlineAnnotType: TypeRef = requiredClassRef("scala.noinline") def NoinlineAnnot(using Context) = NoinlineAnnotType.symbol.asClass - @threadUnsafe lazy val JavaLangVoidType: TypeRef = ctx.requiredClassRef("java.lang.Void") + @threadUnsafe lazy val JavaLangVoidType: TypeRef = requiredClassRef("java.lang.Void") def JavaLangVoidClass(using Context) = JavaLangVoidType.symbol.asClass - @threadUnsafe lazy val ScalaJSJSPackageVal = ctx.requiredPackage("scala.scalajs.js") + @threadUnsafe lazy val ScalaJSJSPackageVal = requiredPackage("scala.scalajs.js") @threadUnsafe lazy val ScalaJSJSPackageClass = ScalaJSJSPackageVal.moduleClass.asClass @threadUnsafe lazy val JSPackage_typeOfR = ScalaJSJSPackageClass.requiredMethodRef("typeOf") def JSPackage_typeOf(using Context) = JSPackage_typeOfR.symbol @@ -37,60 +37,60 @@ final class JSDefinitions()(using Context) { @threadUnsafe lazy val JSPackage_nativeR = ScalaJSJSPackageClass.requiredMethodRef("native") def JSPackage_native(using Context) = JSPackage_nativeR.symbol - @threadUnsafe lazy val JSNativeAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.native") + @threadUnsafe lazy val JSNativeAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.native") def JSNativeAnnot(using Context) = JSNativeAnnotType.symbol.asClass - @threadUnsafe lazy val JSAnyType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.Any") + @threadUnsafe lazy val JSAnyType: TypeRef = requiredClassRef("scala.scalajs.js.Any") def JSAnyClass(using Context) = JSAnyType.symbol.asClass - @threadUnsafe lazy val JSObjectType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.Object") + @threadUnsafe lazy val JSObjectType: TypeRef = requiredClassRef("scala.scalajs.js.Object") def JSObjectClass(using Context) = JSObjectType.symbol.asClass - @threadUnsafe lazy val JSBaseThisFunctionType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.ThisFunction") + @threadUnsafe lazy val JSBaseThisFunctionType: TypeRef = requiredClassRef("scala.scalajs.js.ThisFunction") def JSBaseThisFunctionClass(using Context) = JSBaseThisFunctionType.symbol.asClass - @threadUnsafe lazy val JSArrayType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.Array") + @threadUnsafe lazy val JSArrayType: TypeRef = requiredClassRef("scala.scalajs.js.Array") def JSArrayClass(using Context) = JSArrayType.symbol.asClass - @threadUnsafe lazy val JSFunctionType = (0 to 22).map(n => ctx.requiredClassRef("scala.scalajs.js.Function" + n)).toArray + @threadUnsafe lazy val JSFunctionType = (0 to 22).map(n => requiredClassRef("scala.scalajs.js.Function" + n)).toArray def JSFunctionClass(n: Int)(using Context) = JSFunctionType(n).symbol.asClass - @threadUnsafe lazy val JSThisFunctionType = (0 to 21).map(n => ctx.requiredClassRef("scala.scalajs.js.ThisFunction" + n)).toArray + @threadUnsafe lazy val JSThisFunctionType = (0 to 21).map(n => requiredClassRef("scala.scalajs.js.ThisFunction" + n)).toArray def JSThisFunctionClass(n: Int)(using Context) = JSThisFunctionType(n).symbol.asClass - @threadUnsafe lazy val RuntimeExceptionType: TypeRef = ctx.requiredClassRef("java.lang.RuntimeException") + @threadUnsafe lazy val RuntimeExceptionType: TypeRef = requiredClassRef("java.lang.RuntimeException") def RuntimeExceptionClass(using Context) = RuntimeExceptionType.symbol.asClass - @threadUnsafe lazy val JavaScriptExceptionType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.JavaScriptException") + @threadUnsafe lazy val JavaScriptExceptionType: TypeRef = requiredClassRef("scala.scalajs.js.JavaScriptException") def JavaScriptExceptionClass(using Context) = JavaScriptExceptionType.symbol.asClass - @threadUnsafe lazy val JSGlobalScopeAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSGlobalScope") + @threadUnsafe lazy val JSGlobalScopeAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSGlobalScope") def JSGlobalScopeAnnot(using Context) = JSGlobalScopeAnnotType.symbol.asClass - @threadUnsafe lazy val JSNameAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSName") + @threadUnsafe lazy val JSNameAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSName") def JSNameAnnot(using Context) = JSNameAnnotType.symbol.asClass - @threadUnsafe lazy val JSFullNameAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSFullName") + @threadUnsafe lazy val JSFullNameAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSFullName") def JSFullNameAnnot(using Context) = JSFullNameAnnotType.symbol.asClass - @threadUnsafe lazy val JSBracketAccessAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSBracketAccess") + @threadUnsafe lazy val JSBracketAccessAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSBracketAccess") def JSBracketAccessAnnot(using Context) = JSBracketAccessAnnotType.symbol.asClass - @threadUnsafe lazy val JSBracketCallAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSBracketCall") + @threadUnsafe lazy val JSBracketCallAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSBracketCall") def JSBracketCallAnnot(using Context) = JSBracketCallAnnotType.symbol.asClass - @threadUnsafe lazy val JSExportAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExport") + @threadUnsafe lazy val JSExportAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSExport") def JSExportAnnot(using Context) = JSExportAnnotType.symbol.asClass - @threadUnsafe lazy val JSExportDescendentObjectsAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportDescendentObjects") + @threadUnsafe lazy val JSExportDescendentObjectsAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSExportDescendentObjects") def JSExportDescendentObjectsAnnot(using Context) = JSExportDescendentObjectsAnnotType.symbol.asClass - @threadUnsafe lazy val JSExportDescendentClassesAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportDescendentClasses") + @threadUnsafe lazy val JSExportDescendentClassesAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSExportDescendentClasses") def JSExportDescendentClassesAnnot(using Context) = JSExportDescendentClassesAnnotType.symbol.asClass - @threadUnsafe lazy val JSExportAllAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportAll") + @threadUnsafe lazy val JSExportAllAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSExportAll") def JSExportAllAnnot(using Context) = JSExportAllAnnotType.symbol.asClass - @threadUnsafe lazy val JSExportNamedAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportNamed") + @threadUnsafe lazy val JSExportNamedAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.JSExportNamed") def JSExportNamedAnnot(using Context) = JSExportNamedAnnotType.symbol.asClass - @threadUnsafe lazy val RawJSTypeAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.RawJSType") + @threadUnsafe lazy val RawJSTypeAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.RawJSType") def RawJSTypeAnnot(using Context) = RawJSTypeAnnotType.symbol.asClass - @threadUnsafe lazy val ExposedJSMemberAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.ExposedJSMember") + @threadUnsafe lazy val ExposedJSMemberAnnotType: TypeRef = requiredClassRef("scala.scalajs.js.annotation.ExposedJSMember") def ExposedJSMemberAnnot(using Context) = ExposedJSMemberAnnotType.symbol.asClass - @threadUnsafe lazy val JSAnyModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Any") + @threadUnsafe lazy val JSAnyModuleRef = requiredModuleRef("scala.scalajs.js.Any") def JSAnyModule(using Context) = JSAnyModuleRef.symbol @threadUnsafe lazy val JSAny_fromFunctionR = (0 to 22).map(n => JSAnyModule.requiredMethodRef("fromFunction" + n)).toArray def JSAny_fromFunction(n: Int)(using Context) = JSAny_fromFunctionR(n).symbol - @threadUnsafe lazy val JSDynamicModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Dynamic") + @threadUnsafe lazy val JSDynamicModuleRef = requiredModuleRef("scala.scalajs.js.Dynamic") def JSDynamicModule(using Context) = JSDynamicModuleRef.symbol @threadUnsafe lazy val JSDynamic_globalR = JSDynamicModule.requiredMethodRef("global") def JSDynamic_global(using Context) = JSDynamic_globalR.symbol @@ -104,25 +104,25 @@ final class JSDefinitions()(using Context) { @threadUnsafe lazy val JSDynamicLiteral_applyDynamicR = JSDynamicLiteralModule.requiredMethodRef("applyDynamic") def JSDynamicLiteral_applyDynamic(using Context) = JSDynamicLiteral_applyDynamicR.symbol - @threadUnsafe lazy val JSObjectModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Object") + @threadUnsafe lazy val JSObjectModuleRef = requiredModuleRef("scala.scalajs.js.Object") def JSObjectModule(using Context) = JSObjectModuleRef.symbol - @threadUnsafe lazy val JSArrayModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Array") + @threadUnsafe lazy val JSArrayModuleRef = requiredModuleRef("scala.scalajs.js.Array") def JSArrayModule(using Context) = JSArrayModuleRef.symbol @threadUnsafe lazy val JSArray_applyR = JSArrayModule.requiredMethodRef(nme.apply) def JSArray_apply(using Context) = JSArray_applyR.symbol - @threadUnsafe lazy val JSThisFunctionModuleRef = ctx.requiredModuleRef("scala.scalajs.js.ThisFunction") + @threadUnsafe lazy val JSThisFunctionModuleRef = requiredModuleRef("scala.scalajs.js.ThisFunction") def JSThisFunctionModule(using Context) = JSThisFunctionModuleRef.symbol @threadUnsafe lazy val JSThisFunction_fromFunctionR = (1 to 22).map(n => JSThisFunctionModule.requiredMethodRef("fromFunction" + n)).toArray def JSThisFunction_fromFunction(n: Int)(using Context) = JSThisFunction_fromFunctionR(n - 1).symbol - @threadUnsafe lazy val JSConstructorTagModuleRef = ctx.requiredModuleRef("scala.scalajs.js.ConstructorTag") + @threadUnsafe lazy val JSConstructorTagModuleRef = requiredModuleRef("scala.scalajs.js.ConstructorTag") def JSConstructorTagModule(using Context) = JSConstructorTagModuleRef.symbol @threadUnsafe lazy val JSConstructorTag_materializeR = JSConstructorTagModule.requiredMethodRef("materialize") def JSConstructorTag_materialize(using Context) = JSConstructorTag_materializeR.symbol - @threadUnsafe lazy val RuntimePackageVal = ctx.requiredPackage("scala.scalajs.runtime") + @threadUnsafe lazy val RuntimePackageVal = requiredPackage("scala.scalajs.runtime") @threadUnsafe lazy val RuntimePackageClass = RuntimePackageVal.moduleClass.asClass @threadUnsafe lazy val RuntimePackage_wrapJavaScriptExceptionR = RuntimePackageClass.requiredMethodRef("wrapJavaScriptException") def Runtime_wrapJavaScriptException(using Context) = RuntimePackage_wrapJavaScriptExceptionR.symbol @@ -139,7 +139,7 @@ final class JSDefinitions()(using Context) { @threadUnsafe lazy val Runtime_linkingInfoR = RuntimePackageClass.requiredMethodRef("linkingInfo") def Runtime_linkingInfo(using Context) = Runtime_linkingInfoR.symbol - @threadUnsafe lazy val SpecialPackageVal = ctx.requiredPackage("scala.scalajs.js.special") + @threadUnsafe lazy val SpecialPackageVal = requiredPackage("scala.scalajs.js.special") @threadUnsafe lazy val SpecialPackageClass = SpecialPackageVal.moduleClass.asClass @threadUnsafe lazy val Special_debuggerR = SpecialPackageClass.requiredMethodRef("debugger") def Special_debugger(using Context) = Special_debuggerR.symbol @@ -152,7 +152,7 @@ final class JSDefinitions()(using Context) { @threadUnsafe lazy val Special_instanceofR = SpecialPackageClass.requiredMethodRef("instanceof") def Special_instanceof(using Context) = Special_instanceofR.symbol - @threadUnsafe lazy val WrappedArrayType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.WrappedArray") + @threadUnsafe lazy val WrappedArrayType: TypeRef = requiredClassRef("scala.scalajs.js.WrappedArray") def WrappedArrayClass(using Context) = WrappedArrayType.symbol.asClass @threadUnsafe lazy val ScalaRunTime_isArrayR = defn.ScalaRuntimeModule.requiredMethodRef("isArray", List(???, ???)) @@ -163,10 +163,10 @@ final class JSDefinitions()(using Context) { @threadUnsafe lazy val BoxesRunTime_unboxToCharR = defn.BoxesRunTimeModule.requiredMethodRef("unboxToChar") def BoxesRunTime_unboxToChar(using Context): Symbol = BoxesRunTime_unboxToCharR.symbol - @threadUnsafe lazy val EnableReflectiveInstantiationAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.reflect.annotation.EnableReflectiveInstantiation") + @threadUnsafe lazy val EnableReflectiveInstantiationAnnotType: TypeRef = requiredClassRef("scala.scalajs.reflect.annotation.EnableReflectiveInstantiation") def EnableReflectiveInstantiationAnnot(using Context) = EnableReflectiveInstantiationAnnotType.symbol.asClass - @threadUnsafe lazy val ReflectModuleRef = ctx.requiredModuleRef("scala.scalajs.reflect.Reflect") + @threadUnsafe lazy val ReflectModuleRef = requiredModuleRef("scala.scalajs.reflect.Reflect") def ReflectModule(using Context) = ReflectModuleRef.symbol @threadUnsafe lazy val Reflect_registerLoadableModuleClassR = ReflectModule.requiredMethodRef("registerLoadableModuleClass") def Reflect_registerLoadableModuleClass(using Context) = Reflect_registerLoadableModuleClassR.symbol @@ -181,7 +181,7 @@ final class JSDefinitions()(using Context) { val fullNames = baseNames.flatMap { base => List(s"scala.runtime.${base}Ref", s"scala.runtime.Volatile${base}Ref") } - allRefClassesCache = fullNames.map(name => ctx.requiredClass(name)).toSet + allRefClassesCache = fullNames.map(name => requiredClass(name)).toSet } allRefClassesCache } @@ -209,37 +209,37 @@ final class JSDefinitions()(using Context) { /** Definitions related to the treatment of JUnit boostrappers. */ object junit { - @threadUnsafe lazy val TestAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Test") + @threadUnsafe lazy val TestAnnotType: TypeRef = requiredClassRef("org.junit.Test") def TestAnnotClass(using Context): ClassSymbol = TestAnnotType.symbol.asClass - @threadUnsafe lazy val BeforeAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Before") + @threadUnsafe lazy val BeforeAnnotType: TypeRef = requiredClassRef("org.junit.Before") def BeforeAnnotClass(using Context): ClassSymbol = BeforeAnnotType.symbol.asClass - @threadUnsafe lazy val AfterAnnotType: TypeRef = ctx.requiredClassRef("org.junit.After") + @threadUnsafe lazy val AfterAnnotType: TypeRef = requiredClassRef("org.junit.After") def AfterAnnotClass(using Context): ClassSymbol = AfterAnnotType.symbol.asClass - @threadUnsafe lazy val BeforeClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.BeforeClass") + @threadUnsafe lazy val BeforeClassAnnotType: TypeRef = requiredClassRef("org.junit.BeforeClass") def BeforeClassAnnotClass(using Context): ClassSymbol = BeforeClassAnnotType.symbol.asClass - @threadUnsafe lazy val AfterClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.AfterClass") + @threadUnsafe lazy val AfterClassAnnotType: TypeRef = requiredClassRef("org.junit.AfterClass") def AfterClassAnnotClass(using Context): ClassSymbol = AfterClassAnnotType.symbol.asClass - @threadUnsafe lazy val IgnoreAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Ignore") + @threadUnsafe lazy val IgnoreAnnotType: TypeRef = requiredClassRef("org.junit.Ignore") def IgnoreAnnotClass(using Context): ClassSymbol = IgnoreAnnotType.symbol.asClass - @threadUnsafe lazy val BootstrapperType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.Bootstrapper") + @threadUnsafe lazy val BootstrapperType: TypeRef = requiredClassRef("org.scalajs.junit.Bootstrapper") - @threadUnsafe lazy val TestMetadataType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.TestMetadata") + @threadUnsafe lazy val TestMetadataType: TypeRef = requiredClassRef("org.scalajs.junit.TestMetadata") - @threadUnsafe lazy val NoSuchMethodExceptionType: TypeRef = ctx.requiredClassRef("java.lang.NoSuchMethodException") + @threadUnsafe lazy val NoSuchMethodExceptionType: TypeRef = requiredClassRef("java.lang.NoSuchMethodException") - @threadUnsafe lazy val FutureType: TypeRef = ctx.requiredClassRef("scala.concurrent.Future") + @threadUnsafe lazy val FutureType: TypeRef = requiredClassRef("scala.concurrent.Future") def FutureClass(using Context): ClassSymbol = FutureType.symbol.asClass - @threadUnsafe private lazy val FutureModule_successfulR = ctx.requiredModule("scala.concurrent.Future").requiredMethodRef("successful") + @threadUnsafe private lazy val FutureModule_successfulR = requiredModule("scala.concurrent.Future").requiredMethodRef("successful") def FutureModule_successful(using Context): Symbol = FutureModule_successfulR.symbol - @threadUnsafe private lazy val SuccessModule_applyR = ctx.requiredModule("scala.util.Success").requiredMethodRef(nme.apply) + @threadUnsafe private lazy val SuccessModule_applyR = requiredModule("scala.util.Success").requiredMethodRef(nme.apply) def SuccessModule_apply(using Context): Symbol = SuccessModule_applyR.symbol } diff --git a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala index 56959c1d214d..56b3ca9da32e 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala @@ -9,6 +9,7 @@ import Symbols._ import dotty.tools.dotc.ast.tpd._ import dotty.tools.backend.jvm.DottyPrimitives +import dotty.tools.dotc.report import scala.collection.mutable @@ -76,7 +77,7 @@ class JSPrimitives(ictx: Context) extends DottyPrimitives(ictx) { def addPrimitives(cls: Symbol, method: TermName, code: Int)(using Context): Unit = { val alts = cls.info.member(method).alternatives.map(_.symbol) if (alts.isEmpty) { - ctx.error(s"Unknown primitive method $cls.$method") + report.error(s"Unknown primitive method $cls.$method") } else { for (s <- alts) addPrimitive(s, code) diff --git a/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala b/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala index 9f50aa97fda2..1c14780277d7 100644 --- a/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala +++ b/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala @@ -152,7 +152,7 @@ class JUnitBootstrappers extends MiniPhase { val bootstrapperName = (testClass.name ++ "$scalajs$junit$bootstrapper").toTermName val owner = testClass.owner - val moduleSym = ctx.newCompleteModuleSymbol(owner, bootstrapperName, + val moduleSym = newCompleteModuleSymbol(owner, bootstrapperName, Synthetic, Synthetic, List(defn.ObjectType, junitdefn.BootstrapperType), newScope, coord = testClass.span, assocFile = testClass.assocFile).entered @@ -178,7 +178,7 @@ class JUnitBootstrappers extends MiniPhase { } private def genConstructor(owner: ClassSymbol)(using Context): DefDef = { - val sym = ctx.newDefaultConstructor(owner).entered + val sym = newDefaultConstructor(owner).entered DefDef(sym, { Block( Super(This(owner), tpnme.EMPTY).select(defn.ObjectClass.primaryConstructor).appliedToNone :: Nil, @@ -188,7 +188,7 @@ class JUnitBootstrappers extends MiniPhase { } private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol)(using Context): DefDef = { - val sym = ctx.newSymbol(owner, name, Synthetic | Method, + val sym = newSymbol(owner, name, Synthetic | Method, MethodType(Nil, Nil, defn.UnitType)).entered DefDef(sym, { @@ -203,7 +203,7 @@ class JUnitBootstrappers extends MiniPhase { } private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: ClassSymbol, annot: Symbol)(using Context): DefDef = { - val sym = ctx.newSymbol(owner, name, Synthetic | Method, + val sym = newSymbol(owner, name, Synthetic | Method, MethodType(junitNme.instance :: Nil, defn.ObjectType :: Nil, defn.UnitType)).entered DefDef(sym, { (paramRefss: List[List[Tree]]) => @@ -217,7 +217,7 @@ class JUnitBootstrappers extends MiniPhase { private def genTests(owner: ClassSymbol, tests: List[Symbol])(using Context): DefDef = { val junitdefn = jsdefn.junit - val sym = ctx.newSymbol(owner, junitNme.tests, Synthetic | Method, + val sym = newSymbol(owner, junitNme.tests, Synthetic | Method, MethodType(Nil, defn.ArrayOf(junitdefn.TestMetadataType))).entered DefDef(sym, { @@ -238,7 +238,7 @@ class JUnitBootstrappers extends MiniPhase { case NamedArg(name, _) => name.show(using ctx) case other => other.show(using ctx) } - ctx.error(s"$shownName is an unsupported argument for the JUnit @Test annotation in this position", other.sourcePos) + report.error(s"$shownName is an unsupported argument for the JUnit @Test annotation in this position", other.sourcePos) None } } @@ -253,12 +253,12 @@ class JUnitBootstrappers extends MiniPhase { private def genInvokeTest(owner: ClassSymbol, testClass: ClassSymbol, tests: List[Symbol])(using Context): DefDef = { val junitdefn = jsdefn.junit - val sym = ctx.newSymbol(owner, junitNme.invokeTest, Synthetic | Method, + val sym = newSymbol(owner, junitNme.invokeTest, Synthetic | Method, MethodType(List(junitNme.instance, junitNme.name), List(defn.ObjectType, defn.StringType), junitdefn.FutureType)).entered DefDef(sym, { (paramRefss: List[List[Tree]]) => val List(List(instanceParamRef, nameParamRef)) = paramRefss - val castInstanceSym = ctx.newSymbol(sym, junitNme.castInstance, Synthetic, testClass.typeRef, coord = owner.span) + val castInstanceSym = newSymbol(sym, junitNme.castInstance, Synthetic, testClass.typeRef, coord = owner.span) Block( ValDef(castInstanceSym, instanceParamRef.cast(testClass.typeRef)) :: Nil, tests.foldRight[Tree] { @@ -287,13 +287,13 @@ class JUnitBootstrappers extends MiniPhase { instance.select(testMethod).appliedToNone } else { // We lie in the error message to not expose that we support async testing. - ctx.error("JUnit test must have Unit return type", testMethod.sourcePos) + report.error("JUnit test must have Unit return type", testMethod.sourcePos) EmptyTree } } private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol)(using Context): DefDef = { - val sym = ctx.newSymbol(owner, junitNme.newInstance, Synthetic | Method, + val sym = newSymbol(owner, junitNme.newInstance, Synthetic | Method, MethodType(Nil, defn.ObjectType)).entered DefDef(sym, New(testClass.typeRef, Nil)) diff --git a/compiler/src/dotty/tools/dotc/CompilationUnit.scala b/compiler/src/dotty/tools/dotc/CompilationUnit.scala index 02a303078082..58b4d97f131e 100644 --- a/compiler/src/dotty/tools/dotc/CompilationUnit.scala +++ b/compiler/src/dotty/tools/dotc/CompilationUnit.scala @@ -58,7 +58,7 @@ class CompilationUnit protected (val source: SourceFile) { assert(isSuspendable) if !suspended then if (ctx.settings.XprintSuspension.value) - ctx.echo(i"suspended: $this") + report.echo(i"suspended: $this") suspended = true ctx.run.suspendedUnits += this throw CompilationUnit.SuspendException() @@ -103,11 +103,11 @@ object CompilationUnit { if (!mustExist) source else if (source.file.isDirectory) { - ctx.error(s"expected file, received directory '${source.file.path}'") + report.error(s"expected file, received directory '${source.file.path}'") NoSource } else if (!source.file.exists) { - ctx.error(s"not found: ${source.file.path}") + report.error(s"not found: ${source.file.path}") NoSource } else source diff --git a/compiler/src/dotty/tools/dotc/Driver.scala b/compiler/src/dotty/tools/dotc/Driver.scala index 6271581d7526..9388f0f7bb75 100644 --- a/compiler/src/dotty/tools/dotc/Driver.scala +++ b/compiler/src/dotty/tools/dotc/Driver.scala @@ -42,7 +42,7 @@ class Driver { if !ctx.reporter.errorsReported && run.suspendedUnits.nonEmpty then val suspendedUnits = run.suspendedUnits.toList if (ctx.settings.XprintSuspension.value) - ctx.echo(i"compiling suspended $suspendedUnits%, %") + report.echo(i"compiling suspended $suspendedUnits%, %") val run1 = compiler.newRun for unit <- suspendedUnits do unit.suspended = false run1.compileUnits(suspendedUnits) @@ -51,7 +51,7 @@ class Driver { finish(run) catch case ex: FatalError => - ctx.error(ex.getMessage) // signals that we should fail compilation. + report.error(ex.getMessage) // signals that we should fail compilation. case ex: TypeError => println(s"${ex.toMessage} while compiling ${fileNames.mkString(", ")}") throw ex @@ -76,7 +76,7 @@ class Driver { if !ctx.settings.YdropComments.value || ctx.mode.is(Mode.ReadComments) then ictx.setProperty(ContextDoc, new ContextDocstrings) if Feature.enabledBySetting(nme.Scala2Compat) && false then // TODO: enable - ctx.warning("-language:Scala2Compat will go away; use -source 3.0-migration instead") + report.warning("-language:Scala2Compat will go away; use -source 3.0-migration instead") val fileNames = CompilerCommand.checkUsage(summary, sourcesRequired) fromTastySetup(fileNames, ctx) } @@ -84,7 +84,8 @@ class Driver { /** Setup extra classpath and figure out class names for tasty file inputs */ protected def fromTastySetup(fileNames0: List[String], ctx0: Context): (List[String], Context) = - if (ctx0.settings.fromTasty.value(using ctx0)) { + given Context = ctx0 + if (ctx0.settings.fromTasty.value) { // Resolve classpath and class names of tasty files val (classPaths, classNames) = fileNames0.flatMap { name => val path = Paths.get(name) @@ -99,11 +100,11 @@ class Driver { TastyFileUtil.getClassName(path) match { case Some(res) => res:: Nil case _ => - ctx0.error(s"Could not load classname from $name.") + report.error(s"Could not load classname from $name.") ("", name) :: Nil } else { - ctx0.error(s"File $name does not exist.") + report.error(s"File $name does not exist.") ("", name) :: Nil } }.unzip diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index fb9b8144d5e0..c5fc3719f991 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -10,7 +10,7 @@ import Scopes._ import typer.{ImportInfo, Typer} import Decorators._ import io.{AbstractFile, PlainFile} -import Phases.curPhases +import Phases.unfusedPhases import scala.io.Codec import util.{Set => _, _} @@ -85,7 +85,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint /** The context created for this run */ given runContext[Dummy_so_its_a_def] as Context = myCtx - assert(runContext.runId <= Periods.MaxPossibleRunId) + assert(currentRunId(using runContext) <= Periods.MaxPossibleRunId) private var myUnits: List[CompilationUnit] = _ private var myUnitsCached: List[CompilationUnit] = _ @@ -126,8 +126,8 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint } catch { case NonFatal(ex) => - if units != null then runContext.echo(i"exception occurred while compiling $units%, %") - else runContext.echo(s"exception occurred while compiling ${fileNames.mkString(", ")}") + if units != null then report.echo(i"exception occurred while compiling $units%, %") + else report.echo(s"exception occurred while compiling ${fileNames.mkString(", ")}") throw ex } @@ -165,7 +165,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint else ctx.settings.YstopAfter.value val pluginPlan = ctx.base.addPluginPhases(ctx.base.phasePlan) - val phases = ctx.base.squashPhases(pluginPlan, + val phases = ctx.base.fusePhases(pluginPlan, ctx.settings.Yskip.value, ctx.settings.YstopBefore.value, stopAfter, ctx.settings.Ycheck.value) ctx.base.usePhases(phases) @@ -184,7 +184,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint for (unit <- units) lastPrintedTree = printTree(lastPrintedTree)(using ctx.fresh.setPhase(phase.next).setCompilationUnit(unit)) - ctx.informTime(s"$phase ", start) + report.informTime(s"$phase ", start) Stats.record(s"total trees at end of $phase", ast.Trees.ntrees) for (unit <- units) Stats.record(s"retained typed trees at end of $phase", unit.tpdTree.treeSize) @@ -195,7 +195,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint val runCtx = ctx.fresh runCtx.setProfiler(Profiler()) - curPhases.foreach(_.initContext(runCtx)) + unfusedPhases.foreach(_.initContext(runCtx)) runPhases(using runCtx) if (!ctx.reporter.hasErrors) Rewrites.writeBack() while (finalizeActions.nonEmpty) { @@ -236,26 +236,26 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint private def printTree(last: PrintedTree)(using Context): PrintedTree = { val unit = ctx.compilationUnit - val prevPhase = ctx.phase.prev // can be a mini-phase + val prevPhase = currentPhase.prev // can be a mini-phase val squashedPhase = ctx.base.squashed(prevPhase) val treeString = unit.tpdTree.show(using ctx.withProperty(XprintMode, Some(()))) - ctx.echo(s"result of $unit after $squashedPhase:") + report.echo(s"result of $unit after $squashedPhase:") last match { case SomePrintedTree(phase, lastTreeSting) if lastTreeSting != treeString => val msg = if (!ctx.settings.XprintDiff.value && !ctx.settings.XprintDiffDel.value) treeString else DiffUtil.mkColoredCodeDiff(treeString, lastTreeSting, ctx.settings.XprintDiffDel.value) - ctx.echo(msg) + report.echo(msg) SomePrintedTree(squashedPhase.toString, treeString) case SomePrintedTree(phase, lastTreeSting) => - ctx.echo(" Unchanged since " + phase) + report.echo(" Unchanged since " + phase) last case NoPrintedTree => - ctx.echo(treeString) + report.echo(treeString) SomePrintedTree(squashedPhase.toString, treeString) } } diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index e17b85ee113f..7eca7b524bd2 100644 --- a/compiler/src/dotty/tools/dotc/ast/Desugar.scala +++ b/compiler/src/dotty/tools/dotc/ast/Desugar.scala @@ -4,7 +4,7 @@ package ast import core._ import util.Spans._, Types._, Contexts._, Constants._, Names._, NameOps._, Flags._ -import Symbols._, StdNames._, Trees._, Phases._ +import Symbols._, StdNames._, Trees._, Phases._, ContextOps._ import Decorators.{given _}, transform.SymUtils._ import NameKinds.{UniqueName, EvidenceParamName, DefaultGetterName} import typer.{FrontEnd, Namer} @@ -12,8 +12,7 @@ import util.{Property, SourceFile, SourcePosition} import config.Feature.{sourceVersion, migrateTo3, enabled} import config.SourceVersion._ import collection.mutable.ListBuffer -import reporting.messages._ -import reporting.trace +import reporting._ import annotation.constructorOnly import printing.Formatting.hl import config.Printers @@ -425,11 +424,11 @@ object desugar { val constrVparamss = if (originalVparamss.isEmpty) { // ensure parameter list is non-empty if (isCaseClass) - ctx.error(CaseClassMissingParamList(cdef), namePos) + report.error(CaseClassMissingParamList(cdef), namePos) ListOfNil } else if (isCaseClass && originalVparamss.head.exists(_.mods.isOneOf(GivenOrImplicit))) { - ctx.error(CaseClassMissingNonImplicitParamList(cdef), namePos) + report.error(CaseClassMissingNonImplicitParamList(cdef), namePos) ListOfNil } else originalVparamss.nestedMap(toDefParam(_, keepAnnotations = true, keepDefault = true)) @@ -476,7 +475,7 @@ object desugar { if (isEnum) { val (enumCases, enumStats) = stats.partition(DesugarEnums.isEnumCase) if (enumCases.isEmpty) - ctx.error(EnumerationsShouldNotBeEmpty(cdef), namePos) + report.error(EnumerationsShouldNotBeEmpty(cdef), namePos) val enumCompanionRef = TermRefTree() val enumImport = Import(enumCompanionRef, enumCases.flatMap(caseIds).map(ImportSelector(_))) @@ -533,7 +532,7 @@ object desugar { else if (originalTparams.isEmpty) appliedRef(enumClassRef) else { - ctx.error(TypedCaseDoesNotExplicitlyExtendTypedEnum(enumClass, cdef) + report.error(TypedCaseDoesNotExplicitlyExtendTypedEnum(enumClass, cdef) , cdef.sourcePos.startPos) appliedTypeTree(enumClassRef, constrTparams map (_ => anyRef)) } @@ -742,19 +741,19 @@ object desugar { if (!mods.isOneOf(GivenOrImplicit)) Nil else if (ctx.owner.is(Package)) { - ctx.error(TopLevelImplicitClass(cdef), cdef.sourcePos) + report.error(TopLevelImplicitClass(cdef), cdef.sourcePos) Nil } else if (mods.is(Trait)) { - ctx.error(TypesAndTraitsCantBeImplicit(), cdef.sourcePos) + report.error(TypesAndTraitsCantBeImplicit(), cdef.sourcePos) Nil } else if (isCaseClass) { - ctx.error(ImplicitCaseClass(cdef), cdef.sourcePos) + report.error(ImplicitCaseClass(cdef), cdef.sourcePos) Nil } else if (arity != 1 && !mods.is(Given)) { - ctx.error(ImplicitClassPrimaryConstructorArity(), cdef.sourcePos) + report.error(ImplicitClassPrimaryConstructorArity(), cdef.sourcePos) Nil } else { @@ -874,12 +873,12 @@ object desugar { def flagSourcePos(flag: FlagSet) = mods.mods.find(_.flags == flag).fold(mdef.sourcePos)(_.sourcePos) if (mods.is(Abstract)) - ctx.error(AbstractCannotBeUsedForObjects(mdef), flagSourcePos(Abstract)) + report.error(AbstractCannotBeUsedForObjects(mdef), flagSourcePos(Abstract)) if (mods.is(Sealed)) - ctx.error(ModifierRedundantForObjects(mdef, "sealed"), flagSourcePos(Sealed)) + report.error(ModifierRedundantForObjects(mdef, "sealed"), flagSourcePos(Sealed)) // Maybe this should be an error; see https://github.com/scala/bug/issues/11094. if (mods.is(Final) && !mods.is(Synthetic)) - ctx.warning(ModifierRedundantForObjects(mdef, "final"), flagSourcePos(Final)) + report.warning(ModifierRedundantForObjects(mdef, "final"), flagSourcePos(Final)) if (mods.is(Package)) packageModuleDef(mdef) @@ -896,7 +895,7 @@ object desugar { .withSpan(mdef.span.startPos) val ValDef(selfName, selfTpt, _) = impl.self val selfMods = impl.self.mods - if (!selfTpt.isEmpty) ctx.error(ObjectMayNotHaveSelfType(mdef), impl.self.sourcePos) + if (!selfTpt.isEmpty) report.error(ObjectMayNotHaveSelfType(mdef), impl.self.sourcePos) val clsSelf = ValDef(selfName, SingletonTypeTree(Ident(moduleName)), impl.self.rhs) .withMods(selfMods) .withSpan(impl.self.span.orElse(impl.span.startPos)) @@ -911,7 +910,7 @@ object desugar { def extMethods(ext: ExtMethods)(using Context): Tree = flatTree { for mdef <- ext.methods yield if mdef.tparams.nonEmpty then - ctx.error("extension method cannot have type parameters here, all type parameters go after `extension`", + report.error("extension method cannot have type parameters here, all type parameters go after `extension`", mdef.tparams.head.sourcePos) defDef( cpy.DefDef(mdef)( @@ -995,11 +994,11 @@ object desugar { def errPos = mdef.source.atSpan(mdef.nameSpan) if (ctx.owner == defn.ScalaPackageClass && defn.reservedScalaClassNames.contains(name.toTypeName)) { val kind = if (name.isTypeName) "class" else "object" - ctx.error(IllegalRedefinitionOfStandardKind(kind, name), errPos) + report.error(IllegalRedefinitionOfStandardKind(kind, name), errPos) name = name.errorName } if name.isExtensionName && !mdef.mods.is(Extension) then - ctx.error(em"illegal method name: $name may not start with `extension_`", errPos) + report.error(em"illegal method name: $name may not start with `extension_`", errPos) name } @@ -1016,7 +1015,7 @@ object desugar { case Some(DefDef(name, _, (vparam :: _) :: _, _, _)) => s"extension_${name}_${inventTypeName(vparam.tpt)}" case _ => - ctx.error(AnonymousInstanceCannotBeEmpty(impl), impl.sourcePos) + report.error(AnonymousInstanceCannotBeEmpty(impl), impl.sourcePos) nme.ERROR.toString else impl.parents.map(inventTypeName(_)).mkString("given_", "_", "") @@ -1190,7 +1189,7 @@ object desugar { var tested: MemberDef = tree def checkApplicable(flag: Flag, test: MemberDefTest): Unit = if (tested.mods.is(flag) && !test.applyOrElse(tree, (md: MemberDef) => false)) { - ctx.error(ModifierNotAllowedForDefinition(flag), tree.sourcePos) + report.error(ModifierNotAllowedForDefinition(flag), tree.sourcePos) tested = tested.withMods(tested.mods.withoutFlags(flag)) } checkApplicable(Opaque, legalOpaque) @@ -1409,7 +1408,7 @@ object desugar { Select(qual, name.toTermName)) Select(prefix, parts.last.toTypeName) case _ => - TypeTree(ctx.requiredClass(fullName).typeRef) + TypeTree(requiredClass(fullName).typeRef) } Annotated(tree, New(ttree, Nil)) } @@ -1693,7 +1692,7 @@ object desugar { else { assert(ctx.mode.isExpr || ctx.reporter.errorsReported || ctx.mode.is(Mode.Interactive), ctx.mode) if (!enabled(nme.postfixOps)) { - ctx.error( + report.error( s"""postfix operator `${op.name}` needs to be enabled |by making the implicit value scala.language.postfixOps visible. |---- @@ -1820,7 +1819,7 @@ object desugar { elems foreach collect case Alternative(trees) => for (tree <- trees; (vble, _) <- getVariables(tree)) - ctx.error(IllegalVariableInPatternAlternative(), vble.sourcePos) + report.error(IllegalVariableInPatternAlternative(), vble.sourcePos) case Annotated(arg, _) => collect(arg) case InterpolatedString(_, segments) => @@ -1843,7 +1842,7 @@ object desugar { def traverse(tree: untpd.Tree)(using Context): Unit = tree match { case Splice(expr) => collect(expr) case TypSplice(expr) => - ctx.error(TypeSpliceInValPattern(expr), tree.sourcePos) + report.error(TypeSpliceInValPattern(expr), tree.sourcePos) case _ => traverseChildren(tree) } }.traverse(expr) diff --git a/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala b/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala index 328562431042..790c8d5ad710 100644 --- a/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala +++ b/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala @@ -217,7 +217,7 @@ object DesugarEnums { case Ident(name) => val matches = tparamNames.contains(name) if (matches && (caseTypeParams.nonEmpty || vparamss.isEmpty)) - ctx.error(i"illegal reference to type parameter $name from enum case", tree.sourcePos) + report.error(i"illegal reference to type parameter $name from enum case", tree.sourcePos) matches case LambdaTypeTree(lambdaParams, body) => underBinders(lambdaParams, foldOver(x, tree)) diff --git a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala index f68ae53cecfe..486b27826c08 100644 --- a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala +++ b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala @@ -47,7 +47,7 @@ object MainProxies { def addArgs(call: untpd.Tree, mt: MethodType, idx: Int): untpd.Tree = if (mt.isImplicitMethod) { - ctx.error(s"@main method cannot have implicit parameters", pos) + report.error(s"@main method cannot have implicit parameters", pos) call } else { @@ -65,7 +65,7 @@ object MainProxies { mt.resType match { case restpe: MethodType => if (mt.paramInfos.lastOption.getOrElse(NoType).isRepeatedParam) - ctx.error(s"varargs parameter of @main method must come last", pos) + report.error(s"varargs parameter of @main method must come last", pos) addArgs(call1, restpe, idx + args.length) case _ => call1 @@ -74,7 +74,7 @@ object MainProxies { var result: List[TypeDef] = Nil if (!mainFun.owner.isStaticOwner) - ctx.error(s"@main method is not statically accessible", pos) + report.error(s"@main method is not statically accessible", pos) else { var call = ref(mainFun.termRef) mainFun.info match { @@ -82,9 +82,9 @@ object MainProxies { case mt: MethodType => call = addArgs(call, mt, 0) case _: PolyType => - ctx.error(s"@main method cannot have type parameters", pos) + report.error(s"@main method cannot have type parameters", pos) case _ => - ctx.error(s"@main can only annotate a method", pos) + report.error(s"@main can only annotate a method", pos) } val errVar = Ident(nme.error) val handler = CaseDef( diff --git a/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala b/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala index c677ecd46be8..ce782262ec24 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala @@ -1,10 +1,12 @@ -package dotty.tools.dotc.ast +package dotty.tools.dotc +package ast -import dotty.tools.dotc.ast.Trees._ -import dotty.tools.dotc.core.Contexts._ -import dotty.tools.dotc.core.Flags._ -import dotty.tools.dotc.core.Symbols._ -import dotty.tools.dotc.core.TypeError +import Trees._ +import core.Contexts._ +import core.ContextOps.enter +import core.Flags._ +import core.Symbols._ +import core.TypeError import scala.annotation.tailrec @@ -72,7 +74,8 @@ class TreeMapWithImplicits extends tpd.TreeMap { new TreeTraverser { def traverse(tree: Tree)(using Context): Unit = { tree match { - case d: DefTree if d.symbol.isOneOf(GivenOrImplicit) => nestedCtx.enter(d.symbol) + case d: DefTree if d.symbol.isOneOf(GivenOrImplicit) => + nestedCtx.enter(d.symbol) case _ => } traverseChildren(tree) @@ -118,7 +121,7 @@ class TreeMapWithImplicits extends tpd.TreeMap { } catch { case ex: TypeError => - ctx.error(ex, tree.sourcePos) + report.error(ex, tree.sourcePos) tree } } diff --git a/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala b/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala index 2a4e5a40f107..6bbf253d3b80 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala @@ -177,7 +177,7 @@ class TreeTypeMap( * between original and mapped symbols. */ def withMappedSyms(syms: List[Symbol], mapAlways: Boolean = false): TreeTypeMap = - withMappedSyms(syms, ctx.mapSymbols(syms, this, mapAlways)) + withMappedSyms(syms, mapSymbols(syms, this, mapAlways)) /** The tree map with the substitution between originals `syms` * and mapped symbols `mapped`. Also goes into mapped classes @@ -188,7 +188,7 @@ class TreeTypeMap( val substMap = withSubstitution(syms, mapped) val fullMap = mapped.filter(_.isClass).foldLeft(substMap) { (tmap, cls) => val origDcls = cls.info.decls.toList - val mappedDcls = ctx.mapSymbols(origDcls, tmap) + val mappedDcls = mapSymbols(origDcls, tmap) val tmap1 = tmap.withMappedSyms(origDcls, mappedDcls) if (symsChanged) origDcls.lazyZip(mappedDcls).foreach(cls.asClass.replace) diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index efcbc5c8900d..708d4ecc2ded 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -121,7 +121,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** A closure whole anonymous function has the given method type */ def Lambda(tpe: MethodType, rhsFn: List[Tree] => Tree)(using Context): Block = { - val meth = ctx.newSymbol(ctx.owner, nme.ANON_FUN, Synthetic | Method, tpe) + val meth = newSymbol(ctx.owner, nme.ANON_FUN, Synthetic | Method, tpe) Closure(meth, tss => rhsFn(tss.head).changeOwner(ctx.owner, meth)) } @@ -204,7 +204,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { ta.assignType(untpd.ValDef(sym.name, TypeTree(sym.info), rhs), sym) def SyntheticValDef(name: TermName, rhs: Tree)(using Context): ValDef = - ValDef(ctx.newSymbol(ctx.owner, name, Synthetic, rhs.tpe.widen, coord = rhs.span), rhs) + ValDef(newSymbol(ctx.owner, name, Synthetic, rhs.tpe.widen, coord = rhs.span), rhs) def DefDef(sym: TermSymbol, tparams: List[TypeSymbol], vparamss: List[List[TermSymbol]], resultType: Type, rhs: Tree)(using Context): DefDef = @@ -239,7 +239,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { assert(tparams.hasSameLengthAs(tp.paramNames) && tparams.head.isType) (tparams.asInstanceOf[List[TypeSymbol]], vparamss) case _ => - (ctx.newTypeParams(sym, tp.paramNames, EmptyFlags, tp.instantiateParamInfos(_)), Nil) + (newTypeParams(sym, tp.paramNames, EmptyFlags, tp.instantiateParamInfos(_)), Nil) (tparams, existingParamss, tp.instantiate(tparams map (_.typeRef))) case tp => (Nil, sym.rawParamss, tp) } @@ -256,7 +256,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { else EmptyFlags val maybeErased = if (tp.isErasedMethod) Erased else EmptyFlags - def makeSym(info: Type) = ctx.newSymbol(sym, name, TermParam | maybeImplicit | maybeErased, info, coord = sym.coord) + def makeSym(info: Type) = newSymbol(sym, name, TermParam | maybeImplicit | maybeErased, info, coord = sym.coord) if (isParamDependent) { val sym = makeSym(origInfo.substParams(tp, previousParamRefs.toList)) @@ -311,7 +311,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { def ClassDefWithParents(cls: ClassSymbol, constr: DefDef, parents: List[Tree], body: List[Tree])(using Context): TypeDef = { val selfType = - if (cls.classInfo.selfInfo ne NoType) ValDef(ctx.newSelfSym(cls)) + if (cls.classInfo.selfInfo ne NoType) ValDef(newSelfSym(cls)) else EmptyValDef def isOwnTypeParam(stat: Tree) = stat.symbol.is(TypeParam) && stat.symbol.owner == cls @@ -321,7 +321,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { yield TypeDef(tparam) val findLocalDummy = FindLocalDummyAccumulator(cls) val localDummy = body.foldLeft(NoSymbol: Symbol)(findLocalDummy.apply) - .orElse(ctx.newLocalDummy(cls)) + .orElse(newLocalDummy(cls)) val impl = untpd.Template(constr, parents, Nil, selfType, newTypeParams ++ body) .withType(localDummy.termRef) ta.assignType(untpd.TypeDef(cls.name, impl), cls) @@ -345,9 +345,9 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { if (head.isRef(defn.AnyClass)) defn.AnyRefType :: parents else head :: parents } else parents - val cls = ctx.newNormalizedClassSymbol(owner, tpnme.ANON_CLASS, Synthetic | Final, parents1, + val cls = newNormalizedClassSymbol(owner, tpnme.ANON_CLASS, Synthetic | Final, parents1, coord = fns.map(_.span).reduceLeft(_ union _)) - val constr = ctx.newConstructor(cls, Synthetic, Nil, Nil).entered + val constr = newConstructor(cls, Synthetic, Nil, Nil).entered def forwarder(fn: TermSymbol, name: TermName) = { val fwdMeth = fn.copy(cls, name, Synthetic | Method | Final).entered.asTerm if (fwdMeth.allOverriddenSymbols.exists(!_.is(Deferred))) fwdMeth.setFlag(Override) @@ -359,7 +359,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } def Import(expr: Tree, selectors: List[untpd.ImportSelector])(using Context): Import = - ta.assignType(untpd.Import(expr, selectors), ctx.newImportSymbol(ctx.owner, expr)) + ta.assignType(untpd.Import(expr, selectors), newImportSymbol(ctx.owner, expr)) def PackageDef(pid: RefTree, stats: List[Tree])(using Context): PackageDef = ta.assignType(untpd.PackageDef(pid, stats), pid) @@ -414,7 +414,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { ref(NamedType(sym.owner.thisType, sym.name, sym.denot)) private def followOuterLinks(t: Tree)(using Context) = t match { - case t: This if ctx.erasedTypes && !(t.symbol == ctx.owner.enclosingClass || t.symbol.isStaticOwner) => + case t: This if currentlyAfterErasure && !(t.symbol == ctx.owner.enclosingClass || t.symbol.isStaticOwner) => // after erasure outer paths should be respected ExplicitOuter.OuterOps(ctx).path(toCls = t.tpe.widen.classSymbol) case t => @@ -444,7 +444,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { case _ => EmptyTree } recur(tp).orElse { - ctx.error(em"$tp is not an addressable singleton type") + report.error(em"$tp is not an addressable singleton type") TypeTree(tp) } } @@ -458,7 +458,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { def newArr = ref(defn.DottyArraysModule).select(defn.newArrayMethod).withSpan(span) - if (!ctx.erasedTypes) { + if (!currentlyAfterErasure) { assert(!TypeErasure.isGeneric(elemTpe), elemTpe) //needs to be done during typer. See Applications.convertNewGenericArray newArr.appliedToTypeTrees(TypeTree(returnTpe) :: Nil).appliedToArgs(clsOf(elemTpe) :: clsOf(returnTpe) :: dims :: Nil).withSpan(span) } @@ -528,7 +528,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { */ def ModuleDef(sym: TermSymbol, body: List[Tree])(using Context): tpd.Thicket = { val modcls = sym.moduleClass.asClass - val constrSym = modcls.primaryConstructor orElse ctx.newDefaultConstructor(modcls).entered + val constrSym = modcls.primaryConstructor orElse newDefaultConstructor(modcls).entered val constr = DefDef(constrSym.asTerm, EmptyTree) val clsdef = ClassDef(modcls, constr, body) val valdef = ValDef(sym, New(modcls.typeRef).select(constrSym).appliedToNone) @@ -828,7 +828,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * owner by `from` to `to`. */ def changeOwnerAfter(from: Symbol, to: Symbol, trans: DenotTransformer)(using Context): ThisTree = - if (ctx.phase == trans.next) { + if (currentPhase == trans.next) { val traverser = new TreeTraverser { def traverse(tree: Tree)(using Context) = tree match { case tree: DefTree => @@ -962,7 +962,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** cast tree to `tp`, assuming no exception is raised, i.e the operation is pure */ def cast(tp: Type)(using Context): Tree = { assert(tp.isValueType, i"bad cast: $tree.asInstanceOf[$tp]") - tree.select(if (ctx.erasedTypes) defn.Any_asInstanceOf else defn.Any_typeCast) + tree.select(if (currentlyAfterErasure) defn.Any_asInstanceOf else defn.Any_typeCast) .appliedToType(tp) } @@ -972,7 +972,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { */ def ensureConforms(tp: Type)(using Context): Tree = if (tree.tpe <:< tp) tree - else if (!ctx.erasedTypes) cast(tp) + else if (!currentlyAfterErasure) cast(tp) else Erasure.Boxing.adaptToType(tree, tp) /** `tree ne null` (might need a cast to be type correct) */ @@ -1149,14 +1149,14 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { else if (tree.tpe.widen isRef numericCls) tree else { - ctx.warning(i"conversion from ${tree.tpe.widen} to ${numericCls.typeRef} will always fail at runtime.") + report.warning(i"conversion from ${tree.tpe.widen} to ${numericCls.typeRef} will always fail at runtime.") Throw(New(defn.ClassCastExceptionClass.typeRef, Nil)).withSpan(tree.span) } } /** A tree that corresponds to `Predef.classOf[$tp]` in source */ def clsOf(tp: Type)(using Context): Tree = - if ctx.erasedTypes then + if currentlyAfterErasure then def TYPE(module: TermSymbol) = ref(module).select(nme.TYPE_) defn.scalaClassName(tp) match case tpnme.Boolean => TYPE(defn.BoxedBooleanModule) diff --git a/compiler/src/dotty/tools/dotc/ast/untpd.scala b/compiler/src/dotty/tools/dotc/ast/untpd.scala index ee0ceff4f537..ef9b4359bd49 100644 --- a/compiler/src/dotty/tools/dotc/ast/untpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/untpd.scala @@ -260,7 +260,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { else if compatible(this.flags, flags) then this | flags else val what = if flags.isTermFlags then "values" else "types" - ctx.error(em"${(flags & ModifierFlags).flagsString} $what cannot be ${this.flags.flagsString}", ctx.source.atSpan(span)) + report.error(em"${(flags & ModifierFlags).flagsString} $what cannot be ${this.flags.flagsString}", ctx.source.atSpan(span)) Modifiers(flags) /** Modifiers with given list of Mods. It is checked that diff --git a/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala b/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala index 75155d967e61..82a5dead7d02 100644 --- a/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala +++ b/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala @@ -133,23 +133,23 @@ object CompilerCommand { } // Print all warnings encountered during arguments parsing - summary.warnings.foreach(ctx.warning(_)) + summary.warnings.foreach(report.warning(_)) if (summary.errors.nonEmpty) { - summary.errors foreach (ctx.error(_)) - ctx.echo(" dotc -help gives more information") + summary.errors foreach (report.error(_)) + report.echo(" dotc -help gives more information") Nil } else if (settings.version.value) { - ctx.echo(versionMsg) + report.echo(versionMsg) Nil } else if (shouldStopWithInfo) { - ctx.echo(infoMessage) + report.echo(infoMessage) Nil } else { - if (sourcesRequired && summary.arguments.isEmpty) ctx.echo(usageMessage) + if (sourcesRequired && summary.arguments.isEmpty) report.echo(usageMessage) summary.arguments } } diff --git a/compiler/src/dotty/tools/dotc/config/Feature.scala b/compiler/src/dotty/tools/dotc/config/Feature.scala index 46f80ce1287b..dd513e32c81b 100644 --- a/compiler/src/dotty/tools/dotc/config/Feature.scala +++ b/compiler/src/dotty/tools/dotc/config/Feature.scala @@ -81,7 +81,7 @@ object Feature: if sourceVersion.isMigrating && sourceVersion.stable == version || version == `3.0` && migrateTo3 then - ctx.migrationWarning(msg, pos) + report.migrationWarning(msg, pos) true else false diff --git a/compiler/src/dotty/tools/dotc/core/Annotations.scala b/compiler/src/dotty/tools/dotc/core/Annotations.scala index 8aa1fb3ed94d..eefdd5c64bd0 100644 --- a/compiler/src/dotty/tools/dotc/core/Annotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Annotations.scala @@ -51,36 +51,27 @@ object Annotations { def tree(using Context): Tree = t } - /** The context to use to evaluate an annotation */ - private def annotCtx(using Context): Context = - // We should always produce the same annotation tree, no matter when the - // annotation is evaluated. Setting the phase to a pre-transformation phase - // seems to be enough to ensure this (note that after erasure, `ctx.typer` - // will be the Erasure typer, but that doesn't seem to affect the annotation - // trees we create, so we leave it as is) - ctx.withPhaseNoLater(picklerPhase) - abstract class LazyAnnotation extends Annotation { - protected var mySym: Symbol | (Context => Symbol) + protected var mySym: Symbol | (Context ?=> Symbol) override def symbol(using parentCtx: Context): Symbol = assert(mySym != null) mySym match { - case symFn: (Context => Symbol) @unchecked => + case symFn: (Context ?=> Symbol) @unchecked => mySym = null - mySym = symFn(annotCtx) - case sym: Symbol if sym.defRunId != parentCtx.runId => + mySym = atPhaseNoLater(picklerPhase)(symFn) + case sym: Symbol if sym.defRunId != currentRunId(using parentCtx) => mySym = sym.denot.current.symbol case _ => } mySym.asInstanceOf[Symbol] - protected var myTree: Tree | (Context => Tree) + protected var myTree: Tree | (Context ?=> Tree) def tree(using Context): Tree = assert(myTree != null) myTree match { - case treeFn: (Context => Tree) @unchecked => + case treeFn: (Context ?=> Tree) @unchecked => myTree = null - myTree = treeFn(annotCtx) + myTree = atPhaseNoLater(picklerPhase)(treeFn) case _ => } myTree.asInstanceOf[Tree] @@ -107,13 +98,13 @@ object Annotations { abstract class LazyBodyAnnotation extends BodyAnnotation { // Copy-pasted from LazyAnnotation to avoid having to turn it into a trait - protected var myTree: Tree | (Context => Tree) + protected var myTree: Tree | (Context ?=> Tree) def tree(using Context): Tree = assert(myTree != null) myTree match { - case treeFn: (Context => Tree) @unchecked => + case treeFn: (Context ?=> Tree) @unchecked => myTree = null - myTree = treeFn(annotCtx) + myTree = atPhaseNoLater(picklerPhase)(treeFn) case _ => } myTree.asInstanceOf[Tree] @@ -125,7 +116,7 @@ object Annotations { object LazyBodyAnnotation { def apply(bodyFn: Context ?=> Tree): LazyBodyAnnotation = new LazyBodyAnnotation: - protected var myTree: Tree | (Context => Tree) = ctx => bodyFn(using ctx) + protected var myTree: Tree | (Context ?=> Tree) = (using ctx) => bodyFn(using ctx) } object Annotation { @@ -156,15 +147,15 @@ object Annotations { /** Create an annotation where the tree is computed lazily. */ def deferred(sym: Symbol)(treeFn: Context ?=> Tree)(using Context): Annotation = new LazyAnnotation { - protected var myTree: Tree | (Context => Tree) = ctx => treeFn(using ctx) - protected var mySym: Symbol | (Context => Symbol) = sym + protected var myTree: Tree | (Context ?=> Tree) = (using ctx) => treeFn(using ctx) + protected var mySym: Symbol | (Context ?=> Symbol) = sym } /** Create an annotation where the symbol and the tree are computed lazily. */ def deferredSymAndTree(symFn: Context ?=> Symbol)(treeFn: Context ?=> Tree)(using Context): Annotation = new LazyAnnotation { - protected var mySym: Symbol | (Context => Symbol) = ctx => symFn(using ctx) - protected var myTree: Tree | (Context => Tree) = ctx => treeFn(using ctx) + protected var mySym: Symbol | (Context ?=> Symbol) = (using ctx) => symFn(using ctx) + protected var myTree: Tree | (Context ?=> Tree) = (using ctx) => treeFn(using ctx) } def deferred(atp: Type, args: List[Tree])(using Context): Annotation = diff --git a/compiler/src/dotty/tools/dotc/core/Comments.scala b/compiler/src/dotty/tools/dotc/core/Comments.scala index 90700ac2e46b..71037e19bc6e 100644 --- a/compiler/src/dotty/tools/dotc/core/Comments.scala +++ b/compiler/src/dotty/tools/dotc/core/Comments.scala @@ -9,7 +9,7 @@ import util.Spans._ import util.CommentParsing._ import util.Property.Key import parsing.Parsers.Parser -import reporting.messages.ProperDefinitionNotFound +import reporting.ProperDefinitionNotFound object Comments { val ContextDoc: Key[ContextDocstrings] = new Key[ContextDocstrings] @@ -123,7 +123,7 @@ object Comments { val newName = ctx.compilationUnit.freshNames.newName(tree.name, NameKinds.DocArtifactName) untpd.cpy.DefDef(tree)(name = newName) case _ => - ctx.error(ProperDefinitionNotFound(), ctx.source.atSpan(codePos)) + report.error(ProperDefinitionNotFound(), ctx.source.atSpan(codePos)) tree } } diff --git a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala index c1d65385008d..86df2e10120a 100644 --- a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala +++ b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala @@ -9,7 +9,7 @@ import Decorators._ import Flags._ import config.Config import config.Printers.typr -import dotty.tools.dotc.reporting.trace +import reporting.trace /** Methods for adding constraints and solving them. * @@ -164,7 +164,7 @@ trait ConstraintHandling[AbstractContext] { def msg = i"!!! instantiated to Nothing: $param, constraint = $constraint" if Config.failOnInstantiationToNothing then assert(false, msg) - else ctx.log(msg) + else report.log(msg) def others = if isUpper then constraint.lower(param) else constraint.upper(param) val bound = adjust(rawBound) bound.exists @@ -237,7 +237,7 @@ trait ConstraintHandling[AbstractContext] { constraint.forallParams { param => val TypeBounds(lo, hi) = constraint.entry(param) isSubType(lo, hi) || { - ctx.log(i"sub fail $lo <:< $hi") + report.log(i"sub fail $lo <:< $hi") false } } diff --git a/compiler/src/dotty/tools/dotc/core/ContextOps.scala b/compiler/src/dotty/tools/dotc/core/ContextOps.scala new file mode 100644 index 000000000000..9101b4b40981 --- /dev/null +++ b/compiler/src/dotty/tools/dotc/core/ContextOps.scala @@ -0,0 +1,75 @@ +package dotty.tools.dotc +package core + +import Contexts._, Symbols._, Types._, Flags._, Scopes._, Decorators._, NameOps._ +import Denotations._ +import SymDenotations.LazyType, Names.Name, StdNames.nme +import ast.untpd + +/** Extension methods for contexts where we want to keep the ctx. syntax */ +object ContextOps: + + extension (ctx: Context): + + /** Enter symbol into current class, if current class is owner of current context, + * or into current scope, if not. Should always be called instead of scope.enter + * in order to make sure that updates to class members are reflected in + * finger prints. + */ + def enter(sym: Symbol): Symbol = inContext(ctx) { + ctx.owner match + case cls: ClassSymbol => cls.classDenot.enter(sym) + case _ => scope.openForMutations.enter(sym) + sym + } + + /** The denotation with the given `name` and all `required` flags in current context + */ + def denotNamed(name: Name, required: FlagSet = EmptyFlags): Denotation = inContext(ctx) { + if (owner.isClass) + if (outer.owner == owner) { // inner class scope; check whether we are referring to self + if (scope.size == 1) { + val elem = scope.lastEntry + if (elem.name == name) return elem.sym.denot // return self + } + val pre = owner.thisType + pre.findMember(name, pre, required, EmptyFlags) + } + else // we are in the outermost context belonging to a class; self is invisible here. See inClassContext. + owner.findMember(name, owner.thisType, required, EmptyFlags) + else + scope.denotsNamed(name).filterWithFlags(required, EmptyFlags).toDenot(NoPrefix) + } + + /** A fresh local context with given tree and owner. + * Owner might not exist (can happen for self valdefs), in which case + * no owner is set in result context + */ + def localContext(tree: untpd.Tree, owner: Symbol): FreshContext = inContext(ctx) { + val freshCtx = fresh.setTree(tree) + if (owner.exists) freshCtx.setOwner(owner) else freshCtx + } + + /** Context where `sym` is defined, assuming we are in a nested context. */ + def defContext(sym: Symbol): Context = inContext(ctx) { + outersIterator + .dropWhile(_.owner != sym) + .dropWhile(_.owner == sym) + .next() + } + + /** A new context for the interior of a class */ + def inClassContext(selfInfo: TypeOrSymbol): Context = inContext(ctx) { + val localCtx: Context = fresh.setNewScope + selfInfo match { + case sym: Symbol if sym.exists && sym.name != nme.WILDCARD => localCtx.scope.openForMutations.enter(sym) + case _ => + } + localCtx + } + + def packageContext(tree: untpd.PackageDef, pkg: Symbol): Context = inContext(ctx) { + if (pkg.is(Package)) fresh.setOwner(pkg.moduleClass).setTree(tree) + else ctx + } +end ContextOps \ No newline at end of file diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 46f4d436c2a6..f43a38881368 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -15,7 +15,7 @@ import ast.Trees._ import ast.untpd import Flags.GivenOrImplicit import util.{NoSource, SimpleIdentityMap, SourceFile} -import typer.{Implicits, ImportInfo, Inliner, NamerContextOps, SearchHistory, SearchRoot, TypeAssigner, Typer, Nullables} +import typer.{Implicits, ImportInfo, Inliner, SearchHistory, SearchRoot, TypeAssigner, Typer, Nullables} import Nullables.{NotNullInfo, given _} import Implicits.ContextualImplicits import config.Settings._ @@ -72,10 +72,35 @@ object Contexts { atPhase(phase.id)(op) inline def atNextPhase[T](inline op: Context ?=> T)(using Context): T = - atPhase(ctx.phase.next)(op) + atPhase(currentPhase.next)(op) - inline def atPhaseNotLaterThan[T](limit: Phase)(inline op: Context ?=> T)(using Context): T = - op(using if !limit.exists || ctx.phase <= limit then ctx else ctx.withPhase(limit)) + inline def atPhaseNoLater[T](limit: Phase)(inline op: Context ?=> T)(using Context): T = + op(using if !limit.exists || currentPhase <= limit then ctx else ctx.withPhase(limit)) + + inline def atPhaseNoEarlier[T](limit: Phase)(inline op: Context ?=> T)(using Context): T = + op(using if !limit.exists || limit <= currentPhase then ctx else ctx.withPhase(limit)) + + inline def currentPeriod(using ctx: Context): Period = ctx.period + + inline def currentPhase(using ctx: Context): Phase = ctx.base.phases(ctx.period.firstPhaseId) + + inline def currentRunId(using ctx: Context): Int = ctx.period.runId + + inline def currentPhaseId(using ctx: Context): Int = ctx.period.phaseId + + def currentlyAfterTyper(using Context): Boolean = ctx.base.isAfterTyper(currentPhase) + + /** Does current phase use an erased types interpretation? */ + def currentlyAfterErasure(using Context): Boolean = currentPhase.erasedTypes + + inline def inMode[T](mode: Mode)(inline op: Context ?=> T)(using ctx: Context): T = + op(using if mode != ctx.mode then ctx.fresh.setMode(mode) else ctx) + + inline def withMode[T](mode: Mode)(inline op: Context ?=> T)(using ctx: Context): T = + inMode(ctx.mode | mode)(op) + + inline def withoutMode[T](mode: Mode)(inline op: Context ?=> T)(using ctx: Context): T = + inMode(ctx.mode &~ mode)(op) /** A context is passed basically everywhere in dotc. * This is convenient but carries the risk of captured contexts in @@ -96,15 +121,7 @@ object Contexts { * of all class fields of type context; allow them only in whitelisted * classes (which should be short-lived). */ - abstract class Context(val base: ContextBase) - extends Periods - with Phases - with Printers - with Symbols - with SymDenotations - with Reporting - with NamerContextOps - with Cloneable { thiscontext => + abstract class Context(val base: ContextBase) { thiscontext => given Context = this @@ -212,6 +229,11 @@ object Contexts { /** The current plain printer */ def printerFn: Context => Printer = store(printerFnLoc) + /** A function creating a printer */ + def printer: Printer = + val pr = printerFn(this) + if this.settings.YplainPrinter.value then pr.plain else pr + /** The current settings values */ def settingsState: SettingsState = store(settingsStateLoc) @@ -255,6 +277,13 @@ object Contexts { implicitsCache } + /** Either the current scope, or, if the current context owner is a class, + * the declarations of the current class. + */ + def effectiveScope(using Context): Scope = + if owner != null && owner.isClass then owner.asClass.unforcedDecls + else scope + /** Sourcefile corresponding to given abstract file, memoized */ def getSource(file: AbstractFile, codec: => Codec = Codec(settings.encoding.value)) = { util.Stats.record("getSource") @@ -272,7 +301,7 @@ object Contexts { src } catch { case ex: InvalidPathException => - ctx.error(s"invalid file path: ${ex.getMessage}") + report.error(s"invalid file path: ${ex.getMessage}") NoSource } } @@ -292,8 +321,8 @@ object Contexts { * This method will always return a phase period equal to phaseId, thus will never return squashed phases */ final def withPhase(phaseId: PhaseId): Context = - if (this.phaseId == phaseId) this - else if (phasedCtx.phaseId == phaseId) phasedCtx + if (this.period.phaseId == phaseId) this + else if (phasedCtx.period.phaseId == phaseId) phasedCtx else if (phasedCtxs != null && phasedCtxs(phaseId) != null) phasedCtxs(phaseId) else { val ctx1 = fresh.setPhase(phaseId) @@ -309,10 +338,10 @@ object Contexts { withPhase(phase.id) final def withPhaseNoLater(phase: Phase): Context = - if (phase.exists && this.phase.id > phase.id) withPhase(phase) else this + if (phase.exists && period.phaseId > phase.id) withPhase(phase) else this final def withPhaseNoEarlier(phase: Phase): Context = - if (phase.exists && this.phase.id < phase.id) withPhase(phase) else this + if (phase.exists && period.phaseId < phase.id) withPhase(phase) else this // `creationTrace`-related code. To enable, uncomment the code below and the // call to `setCreationTrace()` in this file. @@ -432,9 +461,6 @@ object Contexts { fresh.setImportInfo(ImportInfo(sym, imp.selectors, impNameOpt)) } - /** Does current phase use an erased types interpretation? */ - def erasedTypes: Boolean = phase.erasedTypes - /** Is the debug option set? */ def debug: Boolean = base.settings.Ydebug.value @@ -516,6 +542,11 @@ object Contexts { case None => fresh.dropProperty(key) } + def typer: Typer = this.typeAssigner match { + case typer: Typer => typer + case _ => new Typer + } + override def toString: String = { def iinfo(using Context) = if (ctx.importInfo == null) "" else i"${ctx.importInfo.selectors}%, %" "Context(\n" + @@ -634,8 +665,8 @@ object Contexts { def updateStore[T](loc: Store.Location[T], value: T): this.type = setStore(store.updated(loc, value)) - def setPhase(pid: PhaseId): this.type = setPeriod(Period(runId, pid)) - def setPhase(phase: Phase): this.type = setPeriod(Period(runId, phase.start, phase.end)) + def setPhase(pid: PhaseId): this.type = setPeriod(Period(period.runId, pid)) + def setPhase(phase: Phase): this.type = setPeriod(Period(period.runId, phase.start, phase.end)) def setSetting[T](setting: Setting[T], value: T): this.type = setSettings(setting.updateIn(settingsState, value)) @@ -661,13 +692,11 @@ object Contexts { if (mode != c.mode) c.fresh.setMode(mode) else c final def addMode(mode: Mode): Context = withModeBits(c.mode | mode) - final def maskMode(mode: Mode): Context = withModeBits(c.mode & mode) final def retractMode(mode: Mode): Context = withModeBits(c.mode &~ mode) } implicit class FreshModeChanges(val c: FreshContext) extends AnyVal { final def addMode(mode: Mode): c.type = c.setMode(c.mode | mode) - final def maskMode(mode: Mode): c.type = c.setMode(c.mode & mode) final def retractMode(mode: Mode): c.type = c.setMode(c.mode &~ mode) } @@ -729,7 +758,6 @@ object Contexts { * compiler run. */ class ContextBase extends ContextState - with Denotations.DenotationsBase with Phases.PhasesBase with Plugins { @@ -840,7 +868,7 @@ object Contexts { private[dotc] var phases: Array[Phase] = _ /** Phases with consecutive Transforms grouped into a single phase, Empty array if squashing is disabled */ - private[core] var squashedPhases: Array[Phase] = Array.empty[Phase] + private[core] var fusedPhases: Array[Phase] = Array.empty[Phase] /** Next denotation transformer id */ private[core] var nextDenotTransformerId: Array[Int] = _ diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index f125773aa16a..6db6eeeb54bc 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -40,17 +40,17 @@ class Definitions { private var initCtx: Context = _ private given currentContext[Dummy_so_its_a_def] as Context = initCtx - private def newSymbol[N <: Name](owner: Symbol, name: N, flags: FlagSet, info: Type) = - ctx.newSymbol(owner, name, flags | Permanent, info) + private def newPermanentSymbol[N <: Name](owner: Symbol, name: N, flags: FlagSet, info: Type) = + newSymbol(owner, name, flags | Permanent, info) - private def newClassSymbol(owner: Symbol, name: TypeName, flags: FlagSet, infoFn: ClassSymbol => Type) = - ctx.newClassSymbol(owner, name, flags | Permanent | NoInits | Open, infoFn) + private def newPermanentClassSymbol(owner: Symbol, name: TypeName, flags: FlagSet, infoFn: ClassSymbol => Type) = + newClassSymbol(owner, name, flags | Permanent | NoInits | Open, infoFn) private def enterCompleteClassSymbol(owner: Symbol, name: TypeName, flags: FlagSet, parents: List[TypeRef], decls: Scope = newScope) = - ctx.newCompleteClassSymbol(owner, name, flags | Permanent | NoInits | Open, parents, decls).entered + newCompleteClassSymbol(owner, name, flags | Permanent | NoInits | Open, parents, decls).entered private def enterTypeField(cls: ClassSymbol, name: TypeName, flags: FlagSet, scope: MutableScope) = - scope.enter(newSymbol(cls, name, flags, TypeBounds.empty)) + scope.enter(newPermanentSymbol(cls, name, flags, TypeBounds.empty)) private def enterTypeParam(cls: ClassSymbol, name: TypeName, flags: FlagSet, scope: MutableScope) = enterTypeField(cls, name, flags | ClassTypeParamCreationFlags, scope) @@ -74,7 +74,7 @@ class Definitions { denot.info = ClassInfo(ScalaPackageClass.thisType, cls, parents, paramDecls) } } - newClassSymbol(ScalaPackageClass, name, Artifact, completer).entered + newPermanentClassSymbol(ScalaPackageClass, name, Artifact, completer).entered } /** The trait FunctionN, ContextFunctionN, ErasedFunctionN or ErasedContextFunction, for some N @@ -133,17 +133,17 @@ class Definitions { } val flags0 = Trait | NoInits val flags = if (name.isContextFunction) flags0 | Final else flags0 - newClassSymbol(ScalaPackageClass, name, flags, completer) + newPermanentClassSymbol(ScalaPackageClass, name, flags, completer) } private def newMethod(cls: ClassSymbol, name: TermName, info: Type, flags: FlagSet = EmptyFlags): TermSymbol = - newSymbol(cls, name, flags | Method, info).asTerm + newPermanentSymbol(cls, name, flags | Method, info).asTerm private def enterMethod(cls: ClassSymbol, name: TermName, info: Type, flags: FlagSet = EmptyFlags): TermSymbol = newMethod(cls, name, info, flags).entered private def enterAliasType(name: TypeName, tpe: Type, flags: FlagSet = EmptyFlags): TypeSymbol = { - val sym = newSymbol(ScalaPackageClass, name, flags, TypeAlias(tpe)) + val sym = newPermanentSymbol(ScalaPackageClass, name, flags, TypeAlias(tpe)) ScalaPackageClass.currentPackageDecls.enter(sym) sym } @@ -176,7 +176,7 @@ class Definitions { private def mkArityArray(name: String, arity: Int, countFrom: Int): Array[TypeRef] = { val arr = new Array[TypeRef](arity + 1) - for (i <- countFrom to arity) arr(i) = ctx.requiredClassRef(name + i) + for (i <- countFrom to arity) arr(i) = requiredClassRef(name + i) arr } @@ -186,62 +186,62 @@ class Definitions { cls } - @tu lazy val RootClass: ClassSymbol = ctx.newPackageSymbol( + @tu lazy val RootClass: ClassSymbol = newPackageSymbol( NoSymbol, nme.ROOT, (root, rootcls) => ctx.base.rootLoader(root)).moduleClass.asClass - @tu lazy val RootPackage: TermSymbol = ctx.newSymbol( + @tu lazy val RootPackage: TermSymbol = newSymbol( NoSymbol, nme.ROOTPKG, PackageCreationFlags, TypeRef(NoPrefix, RootClass)) - @tu lazy val EmptyPackageVal: TermSymbol = ctx.newPackageSymbol( + @tu lazy val EmptyPackageVal: TermSymbol = newPackageSymbol( RootClass, nme.EMPTY_PACKAGE, (emptypkg, emptycls) => ctx.base.rootLoader(emptypkg)).entered @tu lazy val EmptyPackageClass: ClassSymbol = EmptyPackageVal.moduleClass.asClass /** A package in which we can place all methods that are interpreted specially by the compiler */ - @tu lazy val OpsPackageVal: TermSymbol = ctx.newCompletePackageSymbol(RootClass, nme.OPS_PACKAGE).entered + @tu lazy val OpsPackageVal: TermSymbol = newCompletePackageSymbol(RootClass, nme.OPS_PACKAGE).entered @tu lazy val OpsPackageClass: ClassSymbol = OpsPackageVal.moduleClass.asClass - @tu lazy val ScalaPackageVal: TermSymbol = ctx.requiredPackage(nme.scala) - @tu lazy val ScalaMathPackageVal: TermSymbol = ctx.requiredPackage("scala.math") + @tu lazy val ScalaPackageVal: TermSymbol = requiredPackage(nme.scala) + @tu lazy val ScalaMathPackageVal: TermSymbol = requiredPackage("scala.math") @tu lazy val ScalaPackageClass: ClassSymbol = { val cls = ScalaPackageVal.moduleClass.asClass cls.info.decls.openForMutations.useSynthesizer( - name => ctx => + name => if (name.isTypeName && name.isSyntheticFunction) newFunctionNTrait(name.asTypeName) else NoSymbol) cls } - @tu lazy val ScalaPackageObject: Symbol = ctx.requiredModule("scala.package") - @tu lazy val JavaPackageVal: TermSymbol = ctx.requiredPackage(nme.java) + @tu lazy val ScalaPackageObject: Symbol = requiredModule("scala.package") + @tu lazy val JavaPackageVal: TermSymbol = requiredPackage(nme.java) @tu lazy val JavaPackageClass: ClassSymbol = JavaPackageVal.moduleClass.asClass - @tu lazy val JavaLangPackageVal: TermSymbol = ctx.requiredPackage(jnme.JavaLang) + @tu lazy val JavaLangPackageVal: TermSymbol = requiredPackage(jnme.JavaLang) @tu lazy val JavaLangPackageClass: ClassSymbol = JavaLangPackageVal.moduleClass.asClass // fundamental modules - @tu lazy val SysPackage : Symbol = ctx.requiredModule("scala.sys.package") + @tu lazy val SysPackage : Symbol = requiredModule("scala.sys.package") @tu lazy val Sys_error: Symbol = SysPackage.moduleClass.requiredMethod(nme.error) - @tu lazy val ScalaXmlPackageClass: Symbol = ctx.getPackageClassIfDefined("scala.xml") + @tu lazy val ScalaXmlPackageClass: Symbol = getPackageClassIfDefined("scala.xml") - @tu lazy val CompiletimePackageObject: Symbol = ctx.requiredModule("scala.compiletime.package") + @tu lazy val CompiletimePackageObject: Symbol = requiredModule("scala.compiletime.package") @tu lazy val Compiletime_erasedValue : Symbol = CompiletimePackageObject.requiredMethod("erasedValue") @tu lazy val Compiletime_error : Symbol = CompiletimePackageObject.requiredMethod(nme.error) @tu lazy val Compiletime_constValue : Symbol = CompiletimePackageObject.requiredMethod("constValue") @tu lazy val Compiletime_constValueOpt: Symbol = CompiletimePackageObject.requiredMethod("constValueOpt") @tu lazy val Compiletime_code : Symbol = CompiletimePackageObject.requiredMethod("extension_code") @tu lazy val Compiletime_summonFrom : Symbol = CompiletimePackageObject.requiredMethod("summonFrom") - @tu lazy val CompiletimeTestingPackageObject: Symbol = ctx.requiredModule("scala.compiletime.testing.package") + @tu lazy val CompiletimeTestingPackageObject: Symbol = requiredModule("scala.compiletime.testing.package") @tu lazy val CompiletimeTesting_typeChecks: Symbol = CompiletimeTestingPackageObject.requiredMethod("typeChecks") @tu lazy val CompiletimeTesting_typeCheckErrors: Symbol = CompiletimeTestingPackageObject.requiredMethod("typeCheckErrors") - @tu lazy val CompiletimeTesting_ErrorClass: ClassSymbol = ctx.requiredClass("scala.compiletime.testing.Error") - @tu lazy val CompiletimeTesting_Error: Symbol = ctx.requiredModule("scala.compiletime.testing.Error") + @tu lazy val CompiletimeTesting_ErrorClass: ClassSymbol = requiredClass("scala.compiletime.testing.Error") + @tu lazy val CompiletimeTesting_Error: Symbol = requiredModule("scala.compiletime.testing.Error") @tu lazy val CompiletimeTesting_Error_apply = CompiletimeTesting_Error.requiredMethod(nme.apply) - @tu lazy val CompiletimeTesting_ErrorKind: Symbol = ctx.requiredModule("scala.compiletime.testing.ErrorKind") + @tu lazy val CompiletimeTesting_ErrorKind: Symbol = requiredModule("scala.compiletime.testing.ErrorKind") @tu lazy val CompiletimeTesting_ErrorKind_Parser: Symbol = CompiletimeTesting_ErrorKind.requiredMethod("Parser") @tu lazy val CompiletimeTesting_ErrorKind_Typer: Symbol = CompiletimeTesting_ErrorKind.requiredMethod("Typer") - @tu lazy val CompiletimeOpsPackageObject: Symbol = ctx.requiredModule("scala.compiletime.ops.package") - @tu lazy val CompiletimeOpsPackageObjectAny: Symbol = ctx.requiredModule("scala.compiletime.ops.package.any") - @tu lazy val CompiletimeOpsPackageObjectInt: Symbol = ctx.requiredModule("scala.compiletime.ops.package.int") - @tu lazy val CompiletimeOpsPackageObjectString: Symbol = ctx.requiredModule("scala.compiletime.ops.package.string") - @tu lazy val CompiletimeOpsPackageObjectBoolean: Symbol = ctx.requiredModule("scala.compiletime.ops.package.boolean") + @tu lazy val CompiletimeOpsPackageObject: Symbol = requiredModule("scala.compiletime.ops.package") + @tu lazy val CompiletimeOpsPackageObjectAny: Symbol = requiredModule("scala.compiletime.ops.package.any") + @tu lazy val CompiletimeOpsPackageObjectInt: Symbol = requiredModule("scala.compiletime.ops.package.int") + @tu lazy val CompiletimeOpsPackageObjectString: Symbol = requiredModule("scala.compiletime.ops.package.string") + @tu lazy val CompiletimeOpsPackageObjectBoolean: Symbol = requiredModule("scala.compiletime.ops.package.boolean") /** The `scalaShadowing` package is used to safely modify classes and * objects in scala so that they can be used from dotty. They will @@ -250,7 +250,7 @@ class Definitions { * in `scalaShadowing` so they don't clash with the same-named `scala` * members at runtime. */ - @tu lazy val ScalaShadowingPackage: TermSymbol = ctx.requiredPackage(nme.scalaShadowing) + @tu lazy val ScalaShadowingPackage: TermSymbol = requiredPackage(nme.scalaShadowing) /** Note: We cannot have same named methods defined in Object and Any (and AnyVal, for that matter) * because after erasure the Any and AnyVal references get remapped to the Object methods @@ -292,7 +292,7 @@ class Definitions { Any_toString, Any_##, Any_getClass, Any_isInstanceOf, Any_asInstanceOf, Any_typeTest, Any_typeCast) @tu lazy val ObjectClass: ClassSymbol = { - val cls = ctx.requiredClass("java.lang.Object") + val cls = requiredClass("java.lang.Object") assert(!cls.isCompleted, "race for completing java.lang.Object") cls.info = ClassInfo(cls.owner.thisType, cls, AnyClass.typeRef :: Nil, newScope) cls.setFlag(NoInits | JavaDefined) @@ -331,7 +331,7 @@ class Definitions { Any_toString, Any_##, Any_getClass, Any_isInstanceOf, Any_typeTest, Object_eq, Object_ne) @tu lazy val AnyKindClass: ClassSymbol = { - val cls = ctx.newCompleteClassSymbol(ScalaPackageClass, tpnme.AnyKind, AbstractFinal | Permanent, Nil) + val cls = newCompleteClassSymbol(ScalaPackageClass, tpnme.AnyKind, AbstractFinal | Permanent, Nil) if (!ctx.settings.YnoKindPolymorphism.value) // Enable kind-polymorphism by exposing scala.AnyKind cls.entered @@ -378,29 +378,29 @@ class Definitions { def UncheckedNullAliasType: TypeRef = UncheckedNullAlias.typeRef @tu lazy val ImplicitScrutineeTypeSym = - newSymbol(ScalaPackageClass, tpnme.IMPLICITkw, EmptyFlags, TypeBounds.empty).entered + newPermanentSymbol(ScalaPackageClass, tpnme.IMPLICITkw, EmptyFlags, TypeBounds.empty).entered def ImplicitScrutineeTypeRef: TypeRef = ImplicitScrutineeTypeSym.typeRef - @tu lazy val ScalaPredefModule: Symbol = ctx.requiredModule("scala.Predef") + @tu lazy val ScalaPredefModule: Symbol = requiredModule("scala.Predef") @tu lazy val Predef_conforms : Symbol = ScalaPredefModule.requiredMethod(nme.conforms_) @tu lazy val Predef_classOf : Symbol = ScalaPredefModule.requiredMethod(nme.classOf) @tu lazy val Predef_identity : Symbol = ScalaPredefModule.requiredMethod(nme.identity) @tu lazy val Predef_undefined: Symbol = ScalaPredefModule.requiredMethod(nme.???) - def SubTypeClass(using Context): ClassSymbol = ctx.requiredClass("scala.<:<") + def SubTypeClass(using Context): ClassSymbol = requiredClass("scala.<:<") @tu lazy val SubType_refl: Symbol = SubTypeClass.companionModule.requiredMethod(nme.refl) - def DummyImplicitClass(using Context): ClassSymbol = ctx.requiredClass("scala.DummyImplicit") + def DummyImplicitClass(using Context): ClassSymbol = requiredClass("scala.DummyImplicit") - @tu lazy val ScalaRuntimeModule: Symbol = ctx.requiredModule("scala.runtime.ScalaRunTime") + @tu lazy val ScalaRuntimeModule: Symbol = requiredModule("scala.runtime.ScalaRunTime") def runtimeMethodRef(name: PreName): TermRef = ScalaRuntimeModule.requiredMethodRef(name) def ScalaRuntime_drop: Symbol = runtimeMethodRef(nme.drop).symbol @tu lazy val ScalaRuntime__hashCode: Symbol = ScalaRuntimeModule.requiredMethod(nme._hashCode_) - @tu lazy val BoxesRunTimeModule: Symbol = ctx.requiredModule("scala.runtime.BoxesRunTime") + @tu lazy val BoxesRunTimeModule: Symbol = requiredModule("scala.runtime.BoxesRunTime") @tu lazy val BoxesRunTimeModule_externalEquals: Symbol = BoxesRunTimeModule.info.decl(nme.equals_).suchThat(toDenot(_).info.firstParamTypes.size == 2).symbol - @tu lazy val ScalaStaticsModule: Symbol = ctx.requiredModule("scala.runtime.Statics") + @tu lazy val ScalaStaticsModule: Symbol = requiredModule("scala.runtime.Statics") def staticsMethodRef(name: PreName): TermRef = ScalaStaticsModule.requiredMethodRef(name) def staticsMethod(name: PreName): TermSymbol = ScalaStaticsModule.requiredMethod(name) @@ -408,27 +408,27 @@ class Definitions { // will return "null" when called recursively, see #1856. def DottyPredefModule: Symbol = { if (myDottyPredefModule == null) { - myDottyPredefModule = ctx.requiredModule("dotty.DottyPredef") + myDottyPredefModule = requiredModule("dotty.DottyPredef") assert(myDottyPredefModule != null) } myDottyPredefModule } private var myDottyPredefModule: Symbol = _ - @tu lazy val DottyArraysModule: Symbol = ctx.requiredModule("dotty.runtime.Arrays") + @tu lazy val DottyArraysModule: Symbol = requiredModule("dotty.runtime.Arrays") def newGenericArrayMethod(using Context): TermSymbol = DottyArraysModule.requiredMethod("newGenericArray") def newArrayMethod(using Context): TermSymbol = DottyArraysModule.requiredMethod("newArray") def getWrapVarargsArrayModule: Symbol = ScalaRuntimeModule // The set of all wrap{X, Ref}Array methods, where X is a value type - val WrapArrayMethods: PerRun[collection.Set[Symbol]] = new PerRun({ implicit ctx => + val WrapArrayMethods: PerRun[collection.Set[Symbol]] = new PerRun({ val methodNames = ScalaValueTypes.map(ast.tpd.wrapArrayMethodName) `union` Set(nme.wrapRefArray) methodNames.map(getWrapVarargsArrayModule.requiredMethod(_)) }) - @tu lazy val ListModule: Symbol = ctx.requiredModule("scala.collection.immutable.List") - @tu lazy val NilModule: Symbol = ctx.requiredModule("scala.collection.immutable.Nil") + @tu lazy val ListModule: Symbol = requiredModule("scala.collection.immutable.List") + @tu lazy val NilModule: Symbol = requiredModule("scala.collection.immutable.Nil") @tu lazy val SingletonClass: ClassSymbol = // needed as a synthetic class because Scala 2.x refers to it in classfiles @@ -438,8 +438,8 @@ class Definitions { List(AnyClass.typeRef), EmptyScope) @tu lazy val SingletonType: TypeRef = SingletonClass.typeRef - @tu lazy val CollectionSeqType: TypeRef = ctx.requiredClassRef("scala.collection.Seq") - @tu lazy val SeqType: TypeRef = ctx.requiredClassRef("scala.collection.immutable.Seq") + @tu lazy val CollectionSeqType: TypeRef = requiredClassRef("scala.collection.Seq") + @tu lazy val SeqType: TypeRef = requiredClassRef("scala.collection.immutable.Seq") def SeqClass(using Context): ClassSymbol = SeqType.symbol.asClass @tu lazy val Seq_apply : Symbol = SeqClass.requiredMethod(nme.apply) @tu lazy val Seq_head : Symbol = SeqClass.requiredMethod(nme.head) @@ -448,7 +448,7 @@ class Definitions { @tu lazy val Seq_length : Symbol = SeqClass.requiredMethod(nme.length) @tu lazy val Seq_toSeq : Symbol = SeqClass.requiredMethod(nme.toSeq) - @tu lazy val ArrayType: TypeRef = ctx.requiredClassRef("scala.Array") + @tu lazy val ArrayType: TypeRef = requiredClassRef("scala.Array") def ArrayClass(using Context): ClassSymbol = ArrayType.symbol.asClass @tu lazy val Array_apply : Symbol = ArrayClass.requiredMethod(nme.apply) @tu lazy val Array_update : Symbol = ArrayClass.requiredMethod(nme.update) @@ -456,7 +456,7 @@ class Definitions { @tu lazy val Array_clone : Symbol = ArrayClass.requiredMethod(nme.clone_) @tu lazy val ArrayConstructor: Symbol = ArrayClass.requiredMethod(nme.CONSTRUCTOR) - @tu lazy val ArrayModule: Symbol = ctx.requiredModule("scala.Array") + @tu lazy val ArrayModule: Symbol = requiredModule("scala.Array") @tu lazy val UnitType: TypeRef = valueTypeRef("scala.Unit", java.lang.Void.TYPE, UnitEnc, nme.specializedTypeNames.Void) def UnitClass(using Context): ClassSymbol = UnitType.symbol.asClass @@ -503,35 +503,35 @@ class Definitions { @tu lazy val DoubleType: TypeRef = valueTypeRef("scala.Double", java.lang.Double.TYPE, DoubleEnc, nme.specializedTypeNames.Double) def DoubleClass(using Context): ClassSymbol = DoubleType.symbol.asClass - @tu lazy val BoxedUnitClass: ClassSymbol = ctx.requiredClass("scala.runtime.BoxedUnit") + @tu lazy val BoxedUnitClass: ClassSymbol = requiredClass("scala.runtime.BoxedUnit") def BoxedUnit_UNIT(using Context): TermSymbol = BoxedUnitClass.linkedClass.requiredValue("UNIT") def BoxedUnit_TYPE(using Context): TermSymbol = BoxedUnitClass.linkedClass.requiredValue("TYPE") - @tu lazy val BoxedBooleanClass: ClassSymbol = ctx.requiredClass("java.lang.Boolean") - @tu lazy val BoxedByteClass : ClassSymbol = ctx.requiredClass("java.lang.Byte") - @tu lazy val BoxedShortClass : ClassSymbol = ctx.requiredClass("java.lang.Short") - @tu lazy val BoxedCharClass : ClassSymbol = ctx.requiredClass("java.lang.Character") - @tu lazy val BoxedIntClass : ClassSymbol = ctx.requiredClass("java.lang.Integer") - @tu lazy val BoxedLongClass : ClassSymbol = ctx.requiredClass("java.lang.Long") - @tu lazy val BoxedFloatClass : ClassSymbol = ctx.requiredClass("java.lang.Float") - @tu lazy val BoxedDoubleClass : ClassSymbol = ctx.requiredClass("java.lang.Double") - - @tu lazy val BoxedBooleanModule: TermSymbol = ctx.requiredModule("java.lang.Boolean") - @tu lazy val BoxedByteModule : TermSymbol = ctx.requiredModule("java.lang.Byte") - @tu lazy val BoxedShortModule : TermSymbol = ctx.requiredModule("java.lang.Short") - @tu lazy val BoxedCharModule : TermSymbol = ctx.requiredModule("java.lang.Character") - @tu lazy val BoxedIntModule : TermSymbol = ctx.requiredModule("java.lang.Integer") - @tu lazy val BoxedLongModule : TermSymbol = ctx.requiredModule("java.lang.Long") - @tu lazy val BoxedFloatModule : TermSymbol = ctx.requiredModule("java.lang.Float") - @tu lazy val BoxedDoubleModule : TermSymbol = ctx.requiredModule("java.lang.Double") - @tu lazy val BoxedUnitModule : TermSymbol = ctx.requiredModule("java.lang.Void") + @tu lazy val BoxedBooleanClass: ClassSymbol = requiredClass("java.lang.Boolean") + @tu lazy val BoxedByteClass : ClassSymbol = requiredClass("java.lang.Byte") + @tu lazy val BoxedShortClass : ClassSymbol = requiredClass("java.lang.Short") + @tu lazy val BoxedCharClass : ClassSymbol = requiredClass("java.lang.Character") + @tu lazy val BoxedIntClass : ClassSymbol = requiredClass("java.lang.Integer") + @tu lazy val BoxedLongClass : ClassSymbol = requiredClass("java.lang.Long") + @tu lazy val BoxedFloatClass : ClassSymbol = requiredClass("java.lang.Float") + @tu lazy val BoxedDoubleClass : ClassSymbol = requiredClass("java.lang.Double") + + @tu lazy val BoxedBooleanModule: TermSymbol = requiredModule("java.lang.Boolean") + @tu lazy val BoxedByteModule : TermSymbol = requiredModule("java.lang.Byte") + @tu lazy val BoxedShortModule : TermSymbol = requiredModule("java.lang.Short") + @tu lazy val BoxedCharModule : TermSymbol = requiredModule("java.lang.Character") + @tu lazy val BoxedIntModule : TermSymbol = requiredModule("java.lang.Integer") + @tu lazy val BoxedLongModule : TermSymbol = requiredModule("java.lang.Long") + @tu lazy val BoxedFloatModule : TermSymbol = requiredModule("java.lang.Float") + @tu lazy val BoxedDoubleModule : TermSymbol = requiredModule("java.lang.Double") + @tu lazy val BoxedUnitModule : TermSymbol = requiredModule("java.lang.Void") @tu lazy val ByNameParamClass2x: ClassSymbol = enterSpecialPolyClass(tpnme.BYNAME_PARAM_CLASS, Covariant, Seq(AnyType)) @tu lazy val RepeatedParamClass: ClassSymbol = enterSpecialPolyClass(tpnme.REPEATED_PARAM_CLASS, Covariant, Seq(ObjectType, SeqType)) // fundamental classes - @tu lazy val StringClass: ClassSymbol = ctx.requiredClass("java.lang.String") + @tu lazy val StringClass: ClassSymbol = requiredClass("java.lang.String") def StringType: Type = StringClass.typeRef @tu lazy val StringModule: Symbol = StringClass.linkedClass @tu lazy val String_+ : TermSymbol = enterMethod(StringClass, nme.raw.PLUS, methOfAny(StringType), Final) @@ -540,19 +540,19 @@ class Definitions { case _ => false }).symbol - @tu lazy val JavaCloneableClass: ClassSymbol = ctx.requiredClass("java.lang.Cloneable") - @tu lazy val NullPointerExceptionClass: ClassSymbol = ctx.requiredClass("java.lang.NullPointerException") - @tu lazy val IndexOutOfBoundsException: ClassSymbol = ctx.requiredClass("java.lang.IndexOutOfBoundsException") - @tu lazy val ClassClass: ClassSymbol = ctx.requiredClass("java.lang.Class") - @tu lazy val BoxedNumberClass: ClassSymbol = ctx.requiredClass("java.lang.Number") - @tu lazy val ClassCastExceptionClass: ClassSymbol = ctx.requiredClass("java.lang.ClassCastException") + @tu lazy val JavaCloneableClass: ClassSymbol = requiredClass("java.lang.Cloneable") + @tu lazy val NullPointerExceptionClass: ClassSymbol = requiredClass("java.lang.NullPointerException") + @tu lazy val IndexOutOfBoundsException: ClassSymbol = requiredClass("java.lang.IndexOutOfBoundsException") + @tu lazy val ClassClass: ClassSymbol = requiredClass("java.lang.Class") + @tu lazy val BoxedNumberClass: ClassSymbol = requiredClass("java.lang.Number") + @tu lazy val ClassCastExceptionClass: ClassSymbol = requiredClass("java.lang.ClassCastException") @tu lazy val ClassCastExceptionClass_stringConstructor: TermSymbol = ClassCastExceptionClass.info.member(nme.CONSTRUCTOR).suchThat(_.info.firstParamTypes match { case List(pt) => val pt1 = if (ctx.explicitNulls) pt.stripNull() else pt pt1.isRef(StringClass) case _ => false }).symbol.asTerm - @tu lazy val ArithmeticExceptionClass: ClassSymbol = ctx.requiredClass("java.lang.ArithmeticException") + @tu lazy val ArithmeticExceptionClass: ClassSymbol = requiredClass("java.lang.ArithmeticException") @tu lazy val ArithmeticExceptionClass_stringConstructor: TermSymbol = ArithmeticExceptionClass.info.member(nme.CONSTRUCTOR).suchThat(_.info.firstParamTypes match { case List(pt) => val pt1 = if (ctx.explicitNulls) pt.stripNull() else pt @@ -560,27 +560,27 @@ class Definitions { case _ => false }).symbol.asTerm - @tu lazy val JavaSerializableClass: ClassSymbol = ctx.requiredClass("java.io.Serializable") + @tu lazy val JavaSerializableClass: ClassSymbol = requiredClass("java.io.Serializable") - @tu lazy val ComparableClass: ClassSymbol = ctx.requiredClass("java.lang.Comparable") + @tu lazy val ComparableClass: ClassSymbol = requiredClass("java.lang.Comparable") - @tu lazy val SystemClass: ClassSymbol = ctx.requiredClass("java.lang.System") + @tu lazy val SystemClass: ClassSymbol = requiredClass("java.lang.System") @tu lazy val SystemModule: Symbol = SystemClass.linkedClass - @tu lazy val NoSuchElementExceptionClass = ctx.requiredClass("java.util.NoSuchElementException") + @tu lazy val NoSuchElementExceptionClass = requiredClass("java.util.NoSuchElementException") def NoSuchElementExceptionType = NoSuchElementExceptionClass.typeRef - @tu lazy val IllegalArgumentExceptionClass = ctx.requiredClass("java.lang.IllegalArgumentException") + @tu lazy val IllegalArgumentExceptionClass = requiredClass("java.lang.IllegalArgumentException") def IllegalArgumentExceptionType = IllegalArgumentExceptionClass.typeRef // in scalac modified to have Any as parent - @tu lazy val ThrowableType: TypeRef = ctx.requiredClassRef("java.lang.Throwable") + @tu lazy val ThrowableType: TypeRef = requiredClassRef("java.lang.Throwable") def ThrowableClass(using Context): ClassSymbol = ThrowableType.symbol.asClass @tu lazy val SerializableType: TypeRef = JavaSerializableClass.typeRef def SerializableClass(using Context): ClassSymbol = SerializableType.symbol.asClass @tu lazy val JavaEnumClass: ClassSymbol = { - val cls = ctx.requiredClass("java.lang.Enum") + val cls = requiredClass("java.lang.Enum") cls.infoOrCompleter match { case completer: ClassfileLoader => cls.info = new ClassfileLoader(completer.classfile) { @@ -605,14 +605,14 @@ class Definitions { } def JavaEnumType = JavaEnumClass.typeRef - @tu lazy val StringBuilderClass: ClassSymbol = ctx.requiredClass("scala.collection.mutable.StringBuilder") - @tu lazy val MatchErrorClass : ClassSymbol = ctx.requiredClass("scala.MatchError") - @tu lazy val ConversionClass : ClassSymbol = ctx.requiredClass("scala.Conversion").typeRef.symbol.asClass + @tu lazy val StringBuilderClass: ClassSymbol = requiredClass("scala.collection.mutable.StringBuilder") + @tu lazy val MatchErrorClass : ClassSymbol = requiredClass("scala.MatchError") + @tu lazy val ConversionClass : ClassSymbol = requiredClass("scala.Conversion").typeRef.symbol.asClass - @tu lazy val StringAddClass : ClassSymbol = ctx.requiredClass("scala.runtime.StringAdd") + @tu lazy val StringAddClass : ClassSymbol = requiredClass("scala.runtime.StringAdd") @tu lazy val StringAdd_+ : Symbol = StringAddClass.requiredMethod(nme.raw.PLUS) - @tu lazy val StringContextClass: ClassSymbol = ctx.requiredClass("scala.StringContext") + @tu lazy val StringContextClass: ClassSymbol = requiredClass("scala.StringContext") @tu lazy val StringContext_s : Symbol = StringContextClass.requiredMethod(nme.s) @tu lazy val StringContext_raw: Symbol = StringContextClass.requiredMethod(nme.raw_) @tu lazy val StringContext_f : Symbol = StringContextClass.requiredMethod(nme.f) @@ -622,63 +622,63 @@ class Definitions { @tu lazy val StringContextModule_standardInterpolator: Symbol = StringContextModule.requiredMethod(nme.standardInterpolator) @tu lazy val StringContextModule_processEscapes: Symbol = StringContextModule.requiredMethod(nme.processEscapes) - @tu lazy val InternalStringContextMacroModule: Symbol = ctx.requiredModule("dotty.internal.StringContextMacro") + @tu lazy val InternalStringContextMacroModule: Symbol = requiredModule("dotty.internal.StringContextMacro") @tu lazy val InternalStringContextMacroModule_f: Symbol = InternalStringContextMacroModule.requiredMethod(nme.f) - @tu lazy val PartialFunctionClass: ClassSymbol = ctx.requiredClass("scala.PartialFunction") + @tu lazy val PartialFunctionClass: ClassSymbol = requiredClass("scala.PartialFunction") @tu lazy val PartialFunction_isDefinedAt: Symbol = PartialFunctionClass.requiredMethod(nme.isDefinedAt) @tu lazy val PartialFunction_applyOrElse: Symbol = PartialFunctionClass.requiredMethod(nme.applyOrElse) - @tu lazy val AbstractPartialFunctionClass: ClassSymbol = ctx.requiredClass("scala.runtime.AbstractPartialFunction") - @tu lazy val FunctionXXLClass: ClassSymbol = ctx.requiredClass("scala.FunctionXXL") - @tu lazy val ScalaSymbolClass: ClassSymbol = ctx.requiredClass("scala.Symbol") - @tu lazy val DynamicClass: ClassSymbol = ctx.requiredClass("scala.Dynamic") - @tu lazy val OptionClass: ClassSymbol = ctx.requiredClass("scala.Option") - @tu lazy val SomeClass: ClassSymbol = ctx.requiredClass("scala.Some") - @tu lazy val NoneModule: Symbol = ctx.requiredModule("scala.None") + @tu lazy val AbstractPartialFunctionClass: ClassSymbol = requiredClass("scala.runtime.AbstractPartialFunction") + @tu lazy val FunctionXXLClass: ClassSymbol = requiredClass("scala.FunctionXXL") + @tu lazy val ScalaSymbolClass: ClassSymbol = requiredClass("scala.Symbol") + @tu lazy val DynamicClass: ClassSymbol = requiredClass("scala.Dynamic") + @tu lazy val OptionClass: ClassSymbol = requiredClass("scala.Option") + @tu lazy val SomeClass: ClassSymbol = requiredClass("scala.Some") + @tu lazy val NoneModule: Symbol = requiredModule("scala.None") - @tu lazy val EnumClass: ClassSymbol = ctx.requiredClass("scala.Enum") + @tu lazy val EnumClass: ClassSymbol = requiredClass("scala.Enum") @tu lazy val Enum_ordinal: Symbol = EnumClass.requiredMethod(nme.ordinal) - @tu lazy val EnumValuesClass: ClassSymbol = ctx.requiredClass("scala.runtime.EnumValues") - @tu lazy val ProductClass: ClassSymbol = ctx.requiredClass("scala.Product") + @tu lazy val EnumValuesClass: ClassSymbol = requiredClass("scala.runtime.EnumValues") + @tu lazy val ProductClass: ClassSymbol = requiredClass("scala.Product") @tu lazy val Product_canEqual : Symbol = ProductClass.requiredMethod(nme.canEqual_) @tu lazy val Product_productArity : Symbol = ProductClass.requiredMethod(nme.productArity) @tu lazy val Product_productElement : Symbol = ProductClass.requiredMethod(nme.productElement) @tu lazy val Product_productElementName: Symbol = ProductClass.requiredMethod(nme.productElementName) @tu lazy val Product_productPrefix : Symbol = ProductClass.requiredMethod(nme.productPrefix) - @tu lazy val IteratorClass: ClassSymbol = ctx.requiredClass("scala.collection.Iterator") + @tu lazy val IteratorClass: ClassSymbol = requiredClass("scala.collection.Iterator") def IteratorModule(using Context): Symbol = IteratorClass.companionModule - @tu lazy val ModuleSerializationProxyClass: ClassSymbol = ctx.requiredClass("scala.runtime.ModuleSerializationProxy") + @tu lazy val ModuleSerializationProxyClass: ClassSymbol = requiredClass("scala.runtime.ModuleSerializationProxy") @tu lazy val ModuleSerializationProxyConstructor: TermSymbol = ModuleSerializationProxyClass.requiredMethod(nme.CONSTRUCTOR, List(ClassType(TypeBounds.empty))) - @tu lazy val MirrorClass: ClassSymbol = ctx.requiredClass("scala.deriving.Mirror") - @tu lazy val Mirror_ProductClass: ClassSymbol = ctx.requiredClass("scala.deriving.Mirror.Product") + @tu lazy val MirrorClass: ClassSymbol = requiredClass("scala.deriving.Mirror") + @tu lazy val Mirror_ProductClass: ClassSymbol = requiredClass("scala.deriving.Mirror.Product") @tu lazy val Mirror_Product_fromProduct: Symbol = Mirror_ProductClass.requiredMethod(nme.fromProduct) - @tu lazy val Mirror_SumClass: ClassSymbol = ctx.requiredClass("scala.deriving.Mirror.Sum") - @tu lazy val Mirror_SingletonClass: ClassSymbol = ctx.requiredClass("scala.deriving.Mirror.Singleton") - @tu lazy val Mirror_SingletonProxyClass: ClassSymbol = ctx.requiredClass("scala.deriving.Mirror.SingletonProxy") + @tu lazy val Mirror_SumClass: ClassSymbol = requiredClass("scala.deriving.Mirror.Sum") + @tu lazy val Mirror_SingletonClass: ClassSymbol = requiredClass("scala.deriving.Mirror.Singleton") + @tu lazy val Mirror_SingletonProxyClass: ClassSymbol = requiredClass("scala.deriving.Mirror.SingletonProxy") - @tu lazy val LanguageModule: Symbol = ctx.requiredModule("scala.language") - @tu lazy val LanguageExperimentalModule: Symbol = ctx.requiredModule("scala.language.experimental") - @tu lazy val NonLocalReturnControlClass: ClassSymbol = ctx.requiredClass("scala.runtime.NonLocalReturnControl") - @tu lazy val SelectableClass: ClassSymbol = ctx.requiredClass("scala.Selectable") + @tu lazy val LanguageModule: Symbol = requiredModule("scala.language") + @tu lazy val LanguageExperimentalModule: Symbol = requiredModule("scala.language.experimental") + @tu lazy val NonLocalReturnControlClass: ClassSymbol = requiredClass("scala.runtime.NonLocalReturnControl") + @tu lazy val SelectableClass: ClassSymbol = requiredClass("scala.Selectable") - @tu lazy val ClassTagClass: ClassSymbol = ctx.requiredClass("scala.reflect.ClassTag") + @tu lazy val ClassTagClass: ClassSymbol = requiredClass("scala.reflect.ClassTag") @tu lazy val ClassTagModule: Symbol = ClassTagClass.companionModule @tu lazy val ClassTagModule_apply: Symbol = ClassTagModule.requiredMethod(nme.apply) - @tu lazy val QuotedExprClass: ClassSymbol = ctx.requiredClass("scala.quoted.Expr") + @tu lazy val QuotedExprClass: ClassSymbol = requiredClass("scala.quoted.Expr") @tu lazy val QuotedExprModule: Symbol = QuotedExprClass.companionModule @tu lazy val QuotedExprModule_nullExpr: Symbol = QuotedExprModule.requiredMethod(nme.nullExpr) @tu lazy val QuotedExprModule_unitExpr: Symbol = QuotedExprModule.requiredMethod(nme.unitExpr) - @tu lazy val QuoteContextClass: ClassSymbol = ctx.requiredClass("scala.quoted.QuoteContext") + @tu lazy val QuoteContextClass: ClassSymbol = requiredClass("scala.quoted.QuoteContext") - @tu lazy val LiftableModule: Symbol = ctx.requiredModule("scala.quoted.Liftable") + @tu lazy val LiftableModule: Symbol = requiredModule("scala.quoted.Liftable") @tu lazy val LiftableModule_BooleanIsLiftable: Symbol = LiftableModule.requiredMethod("BooleanIsLiftable") @tu lazy val LiftableModule_ByteIsLiftable: Symbol = LiftableModule.requiredMethod("ByteIsLiftable") @tu lazy val LiftableModule_ShortIsLiftable: Symbol = LiftableModule.requiredMethod("ShortIsLiftable") @@ -689,78 +689,78 @@ class Definitions { @tu lazy val LiftableModule_CharIsLiftable: Symbol = LiftableModule.requiredMethod("CharIsLiftable") @tu lazy val LiftableModule_StringIsLiftable: Symbol = LiftableModule.requiredMethod("StringIsLiftable") - @tu lazy val InternalQuotedModule: Symbol = ctx.requiredModule("scala.internal.quoted.CompileTime") + @tu lazy val InternalQuotedModule: Symbol = requiredModule("scala.internal.quoted.CompileTime") @tu lazy val InternalQuoted_exprQuote : Symbol = InternalQuotedModule.requiredMethod("exprQuote") @tu lazy val InternalQuoted_exprSplice : Symbol = InternalQuotedModule.requiredMethod("exprSplice") @tu lazy val InternalQuoted_exprNestedSplice : Symbol = InternalQuotedModule.requiredMethod("exprNestedSplice") @tu lazy val InternalQuoted_typeQuote : Symbol = InternalQuotedModule.requiredMethod("typeQuote") @tu lazy val InternalQuoted_QuoteTypeTagAnnot: ClassSymbol = InternalQuotedModule.requiredClass("quoteTypeTag") - @tu lazy val InternalQuotedMatcher: Symbol = ctx.requiredModule("scala.internal.quoted.Matcher") + @tu lazy val InternalQuotedMatcher: Symbol = requiredModule("scala.internal.quoted.Matcher") @tu lazy val InternalQuotedMatcher_patternHole: Symbol = InternalQuotedMatcher.requiredMethod("patternHole") @tu lazy val InternalQuotedMatcher_patternHigherOrderHole: Symbol = InternalQuotedMatcher.requiredMethod("patternHigherOrderHole") @tu lazy val InternalQuotedMatcher_higherOrderHole: Symbol = InternalQuotedMatcher.requiredMethod("higherOrderHole") @tu lazy val InternalQuotedMatcher_patternTypeAnnot: ClassSymbol = InternalQuotedMatcher.requiredClass("patternType") @tu lazy val InternalQuotedMatcher_fromAboveAnnot: ClassSymbol = InternalQuotedMatcher.requiredClass("fromAbove") - @tu lazy val InternalQuotedExprModule: Symbol = ctx.requiredModule("scala.internal.quoted.Expr") + @tu lazy val InternalQuotedExprModule: Symbol = requiredModule("scala.internal.quoted.Expr") @tu lazy val InternalQuotedExpr_unapply: Symbol = InternalQuotedExprModule.requiredMethod(nme.unapply) - @tu lazy val InternalQuotedTypeModule: Symbol = ctx.requiredModule("scala.internal.quoted.Type") + @tu lazy val InternalQuotedTypeModule: Symbol = requiredModule("scala.internal.quoted.Type") @tu lazy val InternalQuotedType_unapply: Symbol = InternalQuotedTypeModule.requiredMethod(nme.unapply) - @tu lazy val QuotedTypeClass: ClassSymbol = ctx.requiredClass("scala.quoted.Type") + @tu lazy val QuotedTypeClass: ClassSymbol = requiredClass("scala.quoted.Type") @tu lazy val QuotedType_splice: Symbol = QuotedTypeClass.requiredType(tpnme.spliceType) @tu lazy val QuotedTypeModule: Symbol = QuotedTypeClass.companionModule - @tu lazy val TastyReflectionClass: ClassSymbol = ctx.requiredClass("scala.tasty.Reflection") + @tu lazy val TastyReflectionClass: ClassSymbol = requiredClass("scala.tasty.Reflection") - @tu lazy val Unpickler_unpickleExpr: Symbol = ctx.requiredMethod("scala.internal.quoted.Unpickler.unpickleExpr") - @tu lazy val Unpickler_unpickleType: Symbol = ctx.requiredMethod("scala.internal.quoted.Unpickler.unpickleType") + @tu lazy val Unpickler_unpickleExpr: Symbol = requiredMethod("scala.internal.quoted.Unpickler.unpickleExpr") + @tu lazy val Unpickler_unpickleType: Symbol = requiredMethod("scala.internal.quoted.Unpickler.unpickleType") - @tu lazy val EqlClass: ClassSymbol = ctx.requiredClass("scala.Eql") + @tu lazy val EqlClass: ClassSymbol = requiredClass("scala.Eql") def Eql_eqlAny(using Context): TermSymbol = EqlClass.companionModule.requiredMethod(nme.eqlAny) - @tu lazy val TypeBoxClass: ClassSymbol = ctx.requiredClass("scala.internal.TypeBox") + @tu lazy val TypeBoxClass: ClassSymbol = requiredClass("scala.internal.TypeBox") @tu lazy val TypeBox_CAP: TypeSymbol = TypeBoxClass.requiredType(tpnme.CAP) - @tu lazy val MatchCaseClass: ClassSymbol = ctx.requiredClass("scala.internal.MatchCase") - @tu lazy val NotClass: ClassSymbol = ctx.requiredClass("scala.implicits.Not") + @tu lazy val MatchCaseClass: ClassSymbol = requiredClass("scala.internal.MatchCase") + @tu lazy val NotClass: ClassSymbol = requiredClass("scala.implicits.Not") @tu lazy val Not_value: Symbol = NotClass.companionModule.requiredMethod(nme.value) - @tu lazy val ValueOfClass: ClassSymbol = ctx.requiredClass("scala.ValueOf") - @tu lazy val StatsModule: Symbol = ctx.requiredModule("dotty.tools.dotc.util.Stats") + @tu lazy val ValueOfClass: ClassSymbol = requiredClass("scala.ValueOf") + @tu lazy val StatsModule: Symbol = requiredModule("dotty.tools.dotc.util.Stats") @tu lazy val Stats_doRecord: Symbol = StatsModule.requiredMethod("doRecord") - @tu lazy val FromDigitsClass: ClassSymbol = ctx.requiredClass("scala.util.FromDigits") - @tu lazy val FromDigits_WithRadixClass: ClassSymbol = ctx.requiredClass("scala.util.FromDigits.WithRadix") - @tu lazy val FromDigits_DecimalClass: ClassSymbol = ctx.requiredClass("scala.util.FromDigits.Decimal") - @tu lazy val FromDigits_FloatingClass: ClassSymbol = ctx.requiredClass("scala.util.FromDigits.Floating") + @tu lazy val FromDigitsClass: ClassSymbol = requiredClass("scala.util.FromDigits") + @tu lazy val FromDigits_WithRadixClass: ClassSymbol = requiredClass("scala.util.FromDigits.WithRadix") + @tu lazy val FromDigits_DecimalClass: ClassSymbol = requiredClass("scala.util.FromDigits.Decimal") + @tu lazy val FromDigits_FloatingClass: ClassSymbol = requiredClass("scala.util.FromDigits.Floating") - @tu lazy val XMLTopScopeModule: Symbol = ctx.requiredModule("scala.xml.TopScope") + @tu lazy val XMLTopScopeModule: Symbol = requiredModule("scala.xml.TopScope") - @tu lazy val CommandLineParserModule: Symbol = ctx.requiredModule("scala.util.CommandLineParser") + @tu lazy val CommandLineParserModule: Symbol = requiredModule("scala.util.CommandLineParser") @tu lazy val CLP_ParseError: ClassSymbol = CommandLineParserModule.requiredClass("ParseError").typeRef.symbol.asClass @tu lazy val CLP_parseArgument: Symbol = CommandLineParserModule.requiredMethod("parseArgument") @tu lazy val CLP_parseRemainingArguments: Symbol = CommandLineParserModule.requiredMethod("parseRemainingArguments") @tu lazy val CLP_showError: Symbol = CommandLineParserModule.requiredMethod("showError") - @tu lazy val TupleTypeRef: TypeRef = ctx.requiredClassRef("scala.Tuple") + @tu lazy val TupleTypeRef: TypeRef = requiredClassRef("scala.Tuple") def TupleClass(using Context): ClassSymbol = TupleTypeRef.symbol.asClass @tu lazy val Tuple_cons: Symbol = TupleClass.requiredMethod("*:") - @tu lazy val EmptyTupleModule: Symbol = ctx.requiredModule("scala.EmptyTuple") - @tu lazy val NonEmptyTupleTypeRef: TypeRef = ctx.requiredClassRef("scala.NonEmptyTuple") + @tu lazy val EmptyTupleModule: Symbol = requiredModule("scala.EmptyTuple") + @tu lazy val NonEmptyTupleTypeRef: TypeRef = requiredClassRef("scala.NonEmptyTuple") def NonEmptyTupleClass(using Context): ClassSymbol = NonEmptyTupleTypeRef.symbol.asClass lazy val NonEmptyTuple_tail: Symbol = NonEmptyTupleClass.requiredMethod("tail") - @tu lazy val PairClass: ClassSymbol = ctx.requiredClass("scala.*:") + @tu lazy val PairClass: ClassSymbol = requiredClass("scala.*:") - @tu lazy val TupleXXLClass: ClassSymbol = ctx.requiredClass("scala.runtime.TupleXXL") + @tu lazy val TupleXXLClass: ClassSymbol = requiredClass("scala.runtime.TupleXXL") def TupleXXLModule(using Context): Symbol = TupleXXLClass.companionModule def TupleXXL_fromIterator(using Context): Symbol = TupleXXLModule.requiredMethod("fromIterator") - @tu lazy val RuntimeTupleModule: Symbol = ctx.requiredModule("scala.runtime.Tuple") + @tu lazy val RuntimeTupleModule: Symbol = requiredModule("scala.runtime.Tuple") @tu lazy val RuntimeTupleModuleClass: Symbol = RuntimeTupleModule.moduleClass lazy val RuntimeTuple_consIterator: Symbol = RuntimeTupleModule.requiredMethod("consIterator") lazy val RuntimeTuple_concatIterator: Symbol = RuntimeTupleModule.requiredMethod("concatIterator") @@ -775,68 +775,68 @@ class Definitions { lazy val RuntimeTuple_isInstanceOfEmptyTuple: Symbol = RuntimeTupleModule.requiredMethod("isInstanceOfEmptyTuple") lazy val RuntimeTuple_isInstanceOfNonEmptyTuple: Symbol = RuntimeTupleModule.requiredMethod("isInstanceOfNonEmptyTuple") - @tu lazy val TupledFunctionTypeRef: TypeRef = ctx.requiredClassRef("scala.TupledFunction") + @tu lazy val TupledFunctionTypeRef: TypeRef = requiredClassRef("scala.TupledFunction") def TupledFunctionClass(using Context): ClassSymbol = TupledFunctionTypeRef.symbol.asClass - @tu lazy val InternalTupledFunctionTypeRef: TypeRef = ctx.requiredClassRef("scala.internal.TupledFunction") + @tu lazy val InternalTupledFunctionTypeRef: TypeRef = requiredClassRef("scala.internal.TupledFunction") def InternalTupleFunctionClass(using Context): ClassSymbol = InternalTupledFunctionTypeRef.symbol.asClass - def InternalTupleFunctionModule(using Context): Symbol = ctx.requiredModule("scala.internal.TupledFunction") + def InternalTupleFunctionModule(using Context): Symbol = requiredModule("scala.internal.TupledFunction") // Annotation base classes - @tu lazy val AnnotationClass: ClassSymbol = ctx.requiredClass("scala.annotation.Annotation") - @tu lazy val ClassfileAnnotationClass: ClassSymbol = ctx.requiredClass("scala.annotation.ClassfileAnnotation") - @tu lazy val StaticAnnotationClass: ClassSymbol = ctx.requiredClass("scala.annotation.StaticAnnotation") - @tu lazy val RefiningAnnotationClass: ClassSymbol = ctx.requiredClass("scala.annotation.RefiningAnnotation") + @tu lazy val AnnotationClass: ClassSymbol = requiredClass("scala.annotation.Annotation") + @tu lazy val ClassfileAnnotationClass: ClassSymbol = requiredClass("scala.annotation.ClassfileAnnotation") + @tu lazy val StaticAnnotationClass: ClassSymbol = requiredClass("scala.annotation.StaticAnnotation") + @tu lazy val RefiningAnnotationClass: ClassSymbol = requiredClass("scala.annotation.RefiningAnnotation") // Annotation classes - @tu lazy val AnnotationDefaultAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.AnnotationDefault") - @tu lazy val BodyAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.Body") - @tu lazy val ChildAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.Child") - @tu lazy val ContextResultCountAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.ContextResultCount") - @tu lazy val DeprecatedAnnot: ClassSymbol = ctx.requiredClass("scala.deprecated") - @tu lazy val ImplicitAmbiguousAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.implicitAmbiguous") - @tu lazy val ImplicitNotFoundAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.implicitNotFound") - @tu lazy val InlineParamAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.InlineParam") - @tu lazy val InvariantBetweenAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.InvariantBetween") - @tu lazy val MainAnnot: ClassSymbol = ctx.requiredClass("scala.main") - @tu lazy val MigrationAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.migration") - @tu lazy val NativeAnnot: ClassSymbol = ctx.requiredClass("scala.native") - @tu lazy val RepeatedAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.Repeated") - @tu lazy val SourceFileAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.SourceFile") - @tu lazy val ScalaSignatureAnnot: ClassSymbol = ctx.requiredClass("scala.reflect.ScalaSignature") - @tu lazy val ScalaLongSignatureAnnot: ClassSymbol = ctx.requiredClass("scala.reflect.ScalaLongSignature") - @tu lazy val ScalaStrictFPAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.strictfp") - @tu lazy val ScalaStaticAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.static") - @tu lazy val SerialVersionUIDAnnot: ClassSymbol = ctx.requiredClass("scala.SerialVersionUID") - @tu lazy val SuperTraitAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.superTrait") - @tu lazy val TASTYSignatureAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.TASTYSignature") - @tu lazy val TASTYLongSignatureAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.internal.TASTYLongSignature") - @tu lazy val TailrecAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.tailrec") - @tu lazy val ThreadUnsafeAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.threadUnsafe") - @tu lazy val ConstructorOnlyAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.constructorOnly") - @tu lazy val CompileTimeOnlyAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.compileTimeOnly") - @tu lazy val SwitchAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.switch") - @tu lazy val ThrowsAnnot: ClassSymbol = ctx.requiredClass("scala.throws") - @tu lazy val TransientAnnot: ClassSymbol = ctx.requiredClass("scala.transient") - @tu lazy val UncheckedAnnot: ClassSymbol = ctx.requiredClass("scala.unchecked") - @tu lazy val UncheckedStableAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.unchecked.uncheckedStable") - @tu lazy val UncheckedVarianceAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.unchecked.uncheckedVariance") - @tu lazy val VolatileAnnot: ClassSymbol = ctx.requiredClass("scala.volatile") - @tu lazy val FieldMetaAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.meta.field") - @tu lazy val GetterMetaAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.meta.getter") - @tu lazy val SetterMetaAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.meta.setter") - @tu lazy val ShowAsInfixAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.showAsInfix") - @tu lazy val FunctionalInterfaceAnnot: ClassSymbol = ctx.requiredClass("java.lang.FunctionalInterface") - @tu lazy val InfixAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.infix") - @tu lazy val AlphaAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.alpha") - @tu lazy val VarargsAnnot: ClassSymbol = ctx.requiredClass("scala.annotation.varargs") + @tu lazy val AnnotationDefaultAnnot: ClassSymbol = requiredClass("scala.annotation.internal.AnnotationDefault") + @tu lazy val BodyAnnot: ClassSymbol = requiredClass("scala.annotation.internal.Body") + @tu lazy val ChildAnnot: ClassSymbol = requiredClass("scala.annotation.internal.Child") + @tu lazy val ContextResultCountAnnot: ClassSymbol = requiredClass("scala.annotation.internal.ContextResultCount") + @tu lazy val DeprecatedAnnot: ClassSymbol = requiredClass("scala.deprecated") + @tu lazy val ImplicitAmbiguousAnnot: ClassSymbol = requiredClass("scala.annotation.implicitAmbiguous") + @tu lazy val ImplicitNotFoundAnnot: ClassSymbol = requiredClass("scala.annotation.implicitNotFound") + @tu lazy val InlineParamAnnot: ClassSymbol = requiredClass("scala.annotation.internal.InlineParam") + @tu lazy val InvariantBetweenAnnot: ClassSymbol = requiredClass("scala.annotation.internal.InvariantBetween") + @tu lazy val MainAnnot: ClassSymbol = requiredClass("scala.main") + @tu lazy val MigrationAnnot: ClassSymbol = requiredClass("scala.annotation.migration") + @tu lazy val NativeAnnot: ClassSymbol = requiredClass("scala.native") + @tu lazy val RepeatedAnnot: ClassSymbol = requiredClass("scala.annotation.internal.Repeated") + @tu lazy val SourceFileAnnot: ClassSymbol = requiredClass("scala.annotation.internal.SourceFile") + @tu lazy val ScalaSignatureAnnot: ClassSymbol = requiredClass("scala.reflect.ScalaSignature") + @tu lazy val ScalaLongSignatureAnnot: ClassSymbol = requiredClass("scala.reflect.ScalaLongSignature") + @tu lazy val ScalaStrictFPAnnot: ClassSymbol = requiredClass("scala.annotation.strictfp") + @tu lazy val ScalaStaticAnnot: ClassSymbol = requiredClass("scala.annotation.static") + @tu lazy val SerialVersionUIDAnnot: ClassSymbol = requiredClass("scala.SerialVersionUID") + @tu lazy val SuperTraitAnnot: ClassSymbol = requiredClass("scala.annotation.superTrait") + @tu lazy val TASTYSignatureAnnot: ClassSymbol = requiredClass("scala.annotation.internal.TASTYSignature") + @tu lazy val TASTYLongSignatureAnnot: ClassSymbol = requiredClass("scala.annotation.internal.TASTYLongSignature") + @tu lazy val TailrecAnnot: ClassSymbol = requiredClass("scala.annotation.tailrec") + @tu lazy val ThreadUnsafeAnnot: ClassSymbol = requiredClass("scala.annotation.threadUnsafe") + @tu lazy val ConstructorOnlyAnnot: ClassSymbol = requiredClass("scala.annotation.constructorOnly") + @tu lazy val CompileTimeOnlyAnnot: ClassSymbol = requiredClass("scala.annotation.compileTimeOnly") + @tu lazy val SwitchAnnot: ClassSymbol = requiredClass("scala.annotation.switch") + @tu lazy val ThrowsAnnot: ClassSymbol = requiredClass("scala.throws") + @tu lazy val TransientAnnot: ClassSymbol = requiredClass("scala.transient") + @tu lazy val UncheckedAnnot: ClassSymbol = requiredClass("scala.unchecked") + @tu lazy val UncheckedStableAnnot: ClassSymbol = requiredClass("scala.annotation.unchecked.uncheckedStable") + @tu lazy val UncheckedVarianceAnnot: ClassSymbol = requiredClass("scala.annotation.unchecked.uncheckedVariance") + @tu lazy val VolatileAnnot: ClassSymbol = requiredClass("scala.volatile") + @tu lazy val FieldMetaAnnot: ClassSymbol = requiredClass("scala.annotation.meta.field") + @tu lazy val GetterMetaAnnot: ClassSymbol = requiredClass("scala.annotation.meta.getter") + @tu lazy val SetterMetaAnnot: ClassSymbol = requiredClass("scala.annotation.meta.setter") + @tu lazy val ShowAsInfixAnnot: ClassSymbol = requiredClass("scala.annotation.showAsInfix") + @tu lazy val FunctionalInterfaceAnnot: ClassSymbol = requiredClass("java.lang.FunctionalInterface") + @tu lazy val InfixAnnot: ClassSymbol = requiredClass("scala.annotation.infix") + @tu lazy val AlphaAnnot: ClassSymbol = requiredClass("scala.annotation.alpha") + @tu lazy val VarargsAnnot: ClassSymbol = requiredClass("scala.annotation.varargs") // A list of annotations that are commonly used to indicate that a field/method argument or return // type is not null. These annotations are used by the nullification logic in JavaNullInterop to // improve the precision of type nullification. // We don't require that any of these annotations be present in the class path, but we want to // create Symbols for the ones that are present, so they can be checked during nullification. - @tu lazy val NotNullAnnots: List[ClassSymbol] = ctx.getClassesIfDefined( + @tu lazy val NotNullAnnots: List[ClassSymbol] = getClassesIfDefined( "javax.annotation.Nonnull" :: "javax.validation.constraints.NotNull" :: "androidx.annotation.NonNull" :: @@ -867,7 +867,7 @@ class Definitions { def ClassType(arg: Type)(using Context): Type = { val ctype = ClassClass.typeRef - if (ctx.phase.erasedTypes) ctype else ctype.appliedTo(arg) + if (currentPhase.erasedTypes) ctype else ctype.appliedTo(arg) } /** The enumeration type, goven a value of the enumeration */ @@ -905,7 +905,7 @@ class Definitions { object ArrayOf { def apply(elem: Type)(using Context): Type = - if (ctx.erasedTypes) JavaArrayType(elem) + if (currentlyAfterErasure) JavaArrayType(elem) else ArrayType.appliedTo(elem :: Nil) def unapply(tp: Type)(using Context): Option[Type] = tp.dealias match { case AppliedType(at, arg :: Nil) if at.isRef(ArrayType.symbol) => Some(arg) @@ -983,13 +983,13 @@ class Definitions { // ----- Symbol sets --------------------------------------------------- @tu lazy val AbstractFunctionType: Array[TypeRef] = mkArityArray("scala.runtime.AbstractFunction", MaxImplementedFunctionArity, 0) - val AbstractFunctionClassPerRun: PerRun[Array[Symbol]] = new PerRun(implicit ctx => AbstractFunctionType.map(_.symbol.asClass)) + val AbstractFunctionClassPerRun: PerRun[Array[Symbol]] = new PerRun(AbstractFunctionType.map(_.symbol.asClass)) def AbstractFunctionClass(n: Int)(using Context): Symbol = AbstractFunctionClassPerRun()(using ctx)(n) @tu private lazy val ImplementedFunctionType = mkArityArray("scala.Function", MaxImplementedFunctionArity, 0) - def FunctionClassPerRun: PerRun[Array[Symbol]] = new PerRun(implicit ctx => ImplementedFunctionType.map(_.symbol.asClass)) + def FunctionClassPerRun: PerRun[Array[Symbol]] = new PerRun(ImplementedFunctionType.map(_.symbol.asClass)) - val LazyHolder: PerRun[Map[Symbol, Symbol]] = new PerRun({ implicit ctx => - def holderImpl(holderType: String) = ctx.requiredClass("scala.runtime." + holderType) + val LazyHolder: PerRun[Map[Symbol, Symbol]] = new PerRun({ + def holderImpl(holderType: String) = requiredClass("scala.runtime." + holderType) Map[Symbol, Symbol]( IntClass -> holderImpl("LazyInt"), LongClass -> holderImpl("LazyLong"), @@ -1007,23 +1007,23 @@ class Definitions { def FunctionClass(n: Int, isContextual: Boolean = false, isErased: Boolean = false)(using Context): Symbol = if (isContextual && isErased) - ctx.requiredClass("scala.ErasedContextFunction" + n.toString) + requiredClass("scala.ErasedContextFunction" + n.toString) else if (isContextual) - ctx.requiredClass("scala.ContextFunction" + n.toString) + requiredClass("scala.ContextFunction" + n.toString) else if (isErased) - ctx.requiredClass("scala.ErasedFunction" + n.toString) + requiredClass("scala.ErasedFunction" + n.toString) else if (n <= MaxImplementedFunctionArity) FunctionClassPerRun()(n) else - ctx.requiredClass("scala.Function" + n.toString) + requiredClass("scala.Function" + n.toString) @tu lazy val Function0_apply: Symbol = ImplementedFunctionType(0).symbol.requiredMethod(nme.apply) def FunctionType(n: Int, isContextual: Boolean = false, isErased: Boolean = false)(using Context): TypeRef = - if (n <= MaxImplementedFunctionArity && (!isContextual || ctx.erasedTypes) && !isErased) ImplementedFunctionType(n) + if (n <= MaxImplementedFunctionArity && (!isContextual || currentlyAfterErasure) && !isErased) ImplementedFunctionType(n) else FunctionClass(n, isContextual, isErased).typeRef - lazy val PolyFunctionClass = ctx.requiredClass("scala.PolyFunction") + lazy val PolyFunctionClass = requiredClass("scala.PolyFunction") def PolyFunctionType = PolyFunctionClass.typeRef /** If `cls` is a class in the scala package, its name, otherwise EmptyTypeName */ @@ -1041,13 +1041,13 @@ class Definitions { name.drop(prefix.length).forall(_.isDigit)) def isBottomClass(cls: Symbol): Boolean = - if (ctx.explicitNulls && !ctx.phase.erasedTypes) cls == NothingClass + if (ctx.explicitNulls && !currentPhase.erasedTypes) cls == NothingClass else isBottomClassAfterErasure(cls) def isBottomClassAfterErasure(cls: Symbol): Boolean = cls == NothingClass || cls == NullClass def isBottomType(tp: Type): Boolean = - if (ctx.explicitNulls && !ctx.phase.erasedTypes) tp.derivesFrom(NothingClass) + if (ctx.explicitNulls && !currentPhase.erasedTypes) tp.derivesFrom(NothingClass) else isBottomTypeAfterErasure(tp) def isBottomTypeAfterErasure(tp: Type): Boolean = @@ -1233,15 +1233,15 @@ class Definitions { Function1SpecializedReturnTypes @tu lazy val Function1SpecializedParamClasses: PerRun[collection.Set[Symbol]] = - new PerRun(implicit ctx => Function1SpecializedParamTypes.map(_.symbol)) + new PerRun(Function1SpecializedParamTypes.map(_.symbol)) @tu lazy val Function2SpecializedParamClasses: PerRun[collection.Set[Symbol]] = - new PerRun(implicit ctx => Function2SpecializedParamTypes.map(_.symbol)) + new PerRun(Function2SpecializedParamTypes.map(_.symbol)) @tu lazy val Function0SpecializedReturnClasses: PerRun[collection.Set[Symbol]] = - new PerRun(implicit ctx => Function0SpecializedReturnTypes.map(_.symbol)) + new PerRun(Function0SpecializedReturnTypes.map(_.symbol)) @tu lazy val Function1SpecializedReturnClasses: PerRun[collection.Set[Symbol]] = - new PerRun(implicit ctx => Function1SpecializedReturnTypes.map(_.symbol)) + new PerRun(Function1SpecializedReturnTypes.map(_.symbol)) @tu lazy val Function2SpecializedReturnClasses: PerRun[collection.Set[Symbol]] = - new PerRun(implicit ctx => Function2SpecializedReturnTypes.map(_.symbol)) + new PerRun(Function2SpecializedReturnTypes.map(_.symbol)) def isSpecializableFunction(cls: ClassSymbol, paramTypes: List[Type], retType: Type)(using Context): Boolean = paramTypes.length <= 2 && cls.derivesFrom(FunctionClass(paramTypes.length)) && (paramTypes match { @@ -1285,7 +1285,7 @@ class Definitions { */ object ContextFunctionType: def unapply(tp: Type)(using Context): Option[(List[Type], Type, Boolean)] = - if ctx.erasedTypes then + if currentlyAfterErasure then atPhase(erasurePhase)(unapply(tp)) else val tp1 = tp.dealias @@ -1339,27 +1339,26 @@ class Definitions { Set(ComparableClass, ProductClass, SerializableClass, // add these for now, until we had a chance to retrofit 2.13 stdlib // we should do a more through sweep through it then. - ctx.requiredClass("scala.collection.SortedOps"), - ctx.requiredClass("scala.collection.StrictOptimizedSortedSetOps"), - ctx.requiredClass("scala.collection.generic.DefaultSerializable"), - ctx.requiredClass("scala.collection.generic.IsIterable"), - ctx.requiredClass("scala.collection.generic.IsIterableOnce"), - ctx.requiredClass("scala.collection.generic.IsMap"), - ctx.requiredClass("scala.collection.generic.IsSeq"), - ctx.requiredClass("scala.collection.generic.Subtractable"), - ctx.requiredClass("scala.collection.immutable.StrictOptimizedSeqOps") + requiredClass("scala.collection.SortedOps"), + requiredClass("scala.collection.StrictOptimizedSortedSetOps"), + requiredClass("scala.collection.generic.DefaultSerializable"), + requiredClass("scala.collection.generic.IsIterable"), + requiredClass("scala.collection.generic.IsIterableOnce"), + requiredClass("scala.collection.generic.IsMap"), + requiredClass("scala.collection.generic.IsSeq"), + requiredClass("scala.collection.generic.Subtractable"), + requiredClass("scala.collection.immutable.StrictOptimizedSeqOps") ) // ----- primitive value class machinery ------------------------------------------ - /** This class would also be obviated by the implicit function type design */ - class PerRun[T](generate: Context => T) { + class PerRun[T](generate: Context ?=> T) { private var current: RunId = NoRunId private var cached: T = _ def apply()(using Context): T = { - if (current != ctx.runId) { - cached = generate(ctx) - current = ctx.runId + if (current != currentRunId) { + cached = generate + current = currentRunId } cached } @@ -1371,10 +1370,10 @@ class Definitions { @tu private lazy val ScalaNumericValueTypes: collection.Set[TypeRef] = ScalaNumericValueTypeList.toSet @tu private lazy val ScalaValueTypes: collection.Set[TypeRef] = ScalaNumericValueTypes `union` Set(UnitType, BooleanType) - val ScalaNumericValueClasses: PerRun[collection.Set[Symbol]] = new PerRun(implicit ctx => ScalaNumericValueTypes.map(_.symbol)) - val ScalaValueClasses: PerRun[collection.Set[Symbol]] = new PerRun(implicit ctx => ScalaValueTypes.map(_.symbol)) + val ScalaNumericValueClasses: PerRun[collection.Set[Symbol]] = new PerRun(ScalaNumericValueTypes.map(_.symbol)) + val ScalaValueClasses: PerRun[collection.Set[Symbol]] = new PerRun(ScalaValueTypes.map(_.symbol)) - val ScalaBoxedClasses: PerRun[collection.Set[Symbol]] = new PerRun(implicit ctx => + val ScalaBoxedClasses: PerRun[collection.Set[Symbol]] = new PerRun( Set(BoxedByteClass, BoxedShortClass, BoxedCharClass, BoxedIntClass, BoxedLongClass, BoxedFloatClass, BoxedDoubleClass, BoxedUnitClass, BoxedBooleanClass) ) @@ -1386,7 +1385,7 @@ class Definitions { // private val valueTypeNamesToJavaType = mutable.Map[TypeName, Class[?]]() private def valueTypeRef(name: String, jtype: Class[?], enc: Int, tag: Name): TypeRef = { - val vcls = ctx.requiredClassRef(name) + val vcls = requiredClassRef(name) valueTypeEnc(vcls.name) = enc typeTags(vcls.name) = tag // unboxedTypeRef(boxed.name) = vcls diff --git a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala index 4b08c9442102..0cb6432df952 100644 --- a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala +++ b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala @@ -24,7 +24,7 @@ object DenotTransformers { /** The validity period of the transformed denotations in the given context */ def validFor(using Context): Period = - Period(ctx.runId, id + 1, lastPhaseId) + Period(currentRunId, id + 1, lastPhaseId) /** The transformation method */ def transform(ref: SingleDenotation)(using Context): SingleDenotation @@ -43,7 +43,7 @@ object DenotTransformers { if (info1 eq ref.info) ref else ref match { case ref: SymDenotation => - ref.copySymDenotation(info = info1).copyCaches(ref, ctx.phase.next) + ref.copySymDenotation(info = info1).copyCaches(ref, currentPhase.next) case _ => ref.derivedSingleDenotation(ref.symbol, info1) } diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index cf417ed032bb..cb0da1a65b39 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package core -import SymDenotations.{ SymDenotation, ClassDenotation, NoDenotation, LazyType } +import SymDenotations.{ SymDenotation, ClassDenotation, NoDenotation, LazyType, stillValid, acceptStale, traceInvalid } import Contexts._ import Names._ import NameKinds._ @@ -131,10 +131,10 @@ object Denotations { /** The denotation with info(s) as seen from prefix type */ final def asSeenFrom(pre: Type)(using Context): AsSeenFromResult = if (Config.cacheAsSeenFrom) { - if ((cachedPrefix ne pre) || ctx.period != validAsSeenFrom) { + if ((cachedPrefix ne pre) || currentPeriod != validAsSeenFrom) { cachedAsSeenFrom = computeAsSeenFrom(pre) cachedPrefix = pre - validAsSeenFrom = if (pre.isProvisional) Nowhere else ctx.period + validAsSeenFrom = if (pre.isProvisional) Nowhere else currentPeriod } cachedAsSeenFrom } @@ -298,7 +298,7 @@ object Denotations { case m @ MissingRef(ownerd, name) => if (generateStubs) { if (ctx.settings.YdebugMissingRefs.value) m.ex.printStackTrace() - ctx.newStubSymbol(ownerd.symbol, name, source) + newStubSymbol(ownerd.symbol, name, source) } else NoSymbol case NoDenotation | _: NoQualifyingRef => @@ -586,7 +586,7 @@ object Denotations { try info.signature catch { // !!! DEBUG case scala.util.control.NonFatal(ex) => - ctx.echo(s"cannot take signature of ${info.show}") + report.echo(s"cannot take signature of ${info.show}") throw ex } case _ => Signature.NotAMethod @@ -686,14 +686,14 @@ object Denotations { private def updateValidity()(using Context): this.type = { assert( - ctx.runId >= validFor.runId + currentRunId >= validFor.runId || ctx.settings.YtestPickler.value // mixing test pickler with debug printing can travel back in time || ctx.mode.is(Mode.Printing) // no use to be picky when printing error messages || symbol.isOneOf(ValidForeverFlags), - s"denotation $this invalid in run ${ctx.runId}. ValidFor: $validFor") + s"denotation $this invalid in run ${currentRunId}. ValidFor: $validFor") var d: SingleDenotation = this while ({ - d.validFor = Period(ctx.period.runId, d.validFor.firstPhaseId, d.validFor.lastPhaseId) + d.validFor = Period(currentPeriod.runId, d.validFor.firstPhaseId, d.validFor.lastPhaseId) d.invalidateInheritedInfo() d = d.nextInRun d ne this @@ -706,7 +706,7 @@ object Denotations { * if denotation is no longer valid. * However, StaleSymbol error is not thrown in the following situations: * - * - If ctx.acceptStale returns true (e.g. because we are in the IDE), + * - If acceptStale returns true (e.g. because we are in the IDE), * update the symbol to the new version if it exists, or return * the old version otherwise. * - If the symbol did not have a denotation that was defined at the current phase @@ -715,13 +715,13 @@ object Denotations { private def bringForward()(using Context): SingleDenotation = { this match { case symd: SymDenotation => - if (ctx.stillValid(symd)) return updateValidity() - if (ctx.acceptStale(symd)) return symd.currentSymbol.denot.orElse(symd).updateValidity() + if (stillValid(symd)) return updateValidity() + if (acceptStale(symd)) return symd.currentSymbol.denot.orElse(symd).updateValidity() case _ => } if (!symbol.exists) return updateValidity() - if (!coveredInterval.containsPhaseId(ctx.phaseId)) return NoDenotation - if (ctx.debug) ctx.traceInvalid(this) + if (!coveredInterval.containsPhaseId(currentPhaseId)) return NoDenotation + if (ctx.debug) traceInvalid(this) staleSymbolError } @@ -746,7 +746,7 @@ object Denotations { if (myValidFor.code <= 0) nextDefined else this /** Produce a denotation that is valid for the given context. - * Usually called when !(validFor contains ctx.period) + * Usually called when !(validFor contains currentPeriod) * (even though this is not a precondition). * If the runId of the context is the same as runId of this denotation, * the right flock member is located, or, if it does not exist yet, @@ -758,7 +758,7 @@ object Denotations { * the symbol is stale, which constitutes an internal error. */ def current(using Context): SingleDenotation = { - val currentPeriod = ctx.period + val currentPeriod = Contexts.currentPeriod val valid = myValidFor if (valid.code <= 0) { // can happen if we sit on a stale denotation which has been replaced @@ -808,7 +808,7 @@ object Denotations { else { next match { case next: ClassDenotation => - assert(!next.is(Package), s"illegal transformation of package denotation by transformer ${ctx.withPhase(transformer).phase}") + assert(!next.is(Package), s"illegal transformation of package denotation by transformer $transformer") case _ => } next.insertAfter(cur) @@ -842,7 +842,7 @@ object Denotations { } private def demandOutsideDefinedMsg(using Context): String = - s"demanding denotation of $this at phase ${ctx.phase}(${ctx.phaseId}) outside defined interval: defined periods are${definedPeriodsString}" + s"demanding denotation of $this at phase ${currentPhase}(${currentPhaseId}) outside defined interval: defined periods are${definedPeriodsString}" /** Install this denotation to be the result of the given denotation transformer. * This is the implementation of the same-named method in SymDenotations. @@ -851,16 +851,16 @@ object Denotations { */ protected def installAfter(phase: DenotTransformer)(using Context): Unit = { val targetId = phase.next.id - if (ctx.phaseId != targetId) atPhase(phase.next)(installAfter(phase)) + if (currentPhaseId != targetId) atPhase(phase.next)(installAfter(phase)) else { val current = symbol.current // println(s"installing $this after $phase/${phase.id}, valid = ${current.validFor}") // printPeriods(current) - this.validFor = Period(ctx.runId, targetId, current.validFor.lastPhaseId) + this.validFor = Period(currentRunId, targetId, current.validFor.lastPhaseId) if (current.validFor.firstPhaseId >= targetId) current.replaceWith(this) else { - current.validFor = Period(ctx.runId, current.validFor.firstPhaseId, targetId - 1) + current.validFor = Period(currentRunId, current.validFor.firstPhaseId, targetId - 1) insertAfter(current) } } @@ -919,7 +919,7 @@ object Denotations { case denot: SymDenotation => s"in ${denot.owner}" case _ => "" } - s"stale symbol; $this#${symbol.id} $ownerMsg, defined in ${myValidFor}, is referred to in run ${ctx.period}" + s"stale symbol; $this#${symbol.id} $ownerMsg, defined in ${myValidFor}, is referred to in run ${currentPeriod}" } /** The period (interval of phases) for which there exists @@ -977,10 +977,10 @@ object Denotations { true case MethodNotAMethodMatch => // Java allows defining both a field and a zero-parameter method with the same name - !ctx.erasedTypes && !(symbol.is(JavaDefined) && other.symbol.is(JavaDefined)) + !currentlyAfterErasure && !(symbol.is(JavaDefined) && other.symbol.is(JavaDefined)) case ParamMatch => // The signatures do not tell us enough to be sure about matching - !ctx.erasedTypes && info.matches(other.info) + !currentlyAfterErasure && info.matches(other.info) case noMatch => false end matches @@ -1071,7 +1071,7 @@ object Denotations { class ErrorDenotation(using Context) extends NonSymSingleDenotation(NoSymbol, NoType, NoType) { override def exists: Boolean = false override def hasUniqueSym: Boolean = false - validFor = Period.allInRun(ctx.runId) + validFor = Period.allInRun(currentRunId) protected def newLikeThis(s: Symbol, i: Type, pre: Type): SingleDenotation = this } @@ -1189,72 +1189,67 @@ object Denotations { s"multi-denotation with alternatives $alternatives does not implement operation $op") } - // --------------- Context Base Trait ------------------------------- - - trait DenotationsBase { this: ContextBase => - - /** The current denotation of the static reference given by path, - * or a MissingRef or NoQualifyingRef instance, if it does not exist. - * if generateStubs is set, generates stubs for missing top-level symbols - */ - def staticRef(path: Name, generateStubs: Boolean = true, isPackage: Boolean = false)(using Context): Denotation = { - def select(prefix: Denotation, selector: Name): Denotation = { - val owner = prefix.disambiguate(_.info.isParameterless) - def isPackageFromCoreLibMissing: Boolean = - owner.symbol == defn.RootClass && - ( - selector == nme.scala || // if the scala package is missing, the stdlib must be missing - selector == nme.scalaShadowing // if the scalaShadowing package is missing, the dotty library must be missing - ) - if (owner.exists) { - val result = if (isPackage) owner.info.decl(selector) else owner.info.member(selector) - if (result.exists) result - else if (isPackageFromCoreLibMissing) throw new MissingCoreLibraryException(selector.toString) - else { - val alt = - if (generateStubs) missingHook(owner.symbol.moduleClass, selector) - else NoSymbol - if (alt.exists) alt.denot - else MissingRef(owner, selector) - } + /** The current denotation of the static reference given by path, + * or a MissingRef or NoQualifyingRef instance, if it does not exist. + * if generateStubs is set, generates stubs for missing top-level symbols + */ + def staticRef(path: Name, generateStubs: Boolean = true, isPackage: Boolean = false)(using Context): Denotation = { + def select(prefix: Denotation, selector: Name): Denotation = { + val owner = prefix.disambiguate(_.info.isParameterless) + def isPackageFromCoreLibMissing: Boolean = + owner.symbol == defn.RootClass && + ( + selector == nme.scala || // if the scala package is missing, the stdlib must be missing + selector == nme.scalaShadowing // if the scalaShadowing package is missing, the dotty library must be missing + ) + if (owner.exists) { + val result = if (isPackage) owner.info.decl(selector) else owner.info.member(selector) + if (result.exists) result + else if (isPackageFromCoreLibMissing) throw new MissingCoreLibraryException(selector.toString) + else { + val alt = + if (generateStubs) missingHook(owner.symbol.moduleClass, selector) + else NoSymbol + if (alt.exists) alt.denot + else MissingRef(owner, selector) } - else owner } - def recur(path: Name, wrap: TermName => Name = identity): Denotation = path match { - case path: TypeName => - recur(path.toTermName, n => n.toTypeName) - case ModuleClassName(underlying) => - recur(underlying, n => wrap(ModuleClassName(n))) - case QualifiedName(prefix, selector) => - select(recur(prefix), wrap(selector)) - case qn @ AnyQualifiedName(prefix, _) => - recur(prefix, n => wrap(qn.info.mkString(n).toTermName)) - case path: SimpleName => - def recurSimple(len: Int, wrap: TermName => Name): Denotation = { - val point = path.lastIndexOf('.', len - 1) - val selector = wrap(path.slice(point + 1, len).asTermName) - val prefix = - if (point > 0) recurSimple(point, identity) - else if (selector.isTermName) defn.RootClass.denot - else defn.EmptyPackageClass.denot - select(prefix, selector) - } - recurSimple(path.length, wrap) - } - recur(path) + else owner } - - /** If we are looking for a non-existing term name in a package, - * assume it is a package for which we do not have a directory and - * enter it. - */ - def missingHook(owner: Symbol, name: Name)(using Context): Symbol = - if (owner.is(Package) && name.isTermName) - ctx.newCompletePackageSymbol(owner, name.asTermName).entered - else - NoSymbol + def recur(path: Name, wrap: TermName => Name = identity): Denotation = path match { + case path: TypeName => + recur(path.toTermName, n => n.toTypeName) + case ModuleClassName(underlying) => + recur(underlying, n => wrap(ModuleClassName(n))) + case QualifiedName(prefix, selector) => + select(recur(prefix), wrap(selector)) + case qn @ AnyQualifiedName(prefix, _) => + recur(prefix, n => wrap(qn.info.mkString(n).toTermName)) + case path: SimpleName => + def recurSimple(len: Int, wrap: TermName => Name): Denotation = { + val point = path.lastIndexOf('.', len - 1) + val selector = wrap(path.slice(point + 1, len).asTermName) + val prefix = + if (point > 0) recurSimple(point, identity) + else if (selector.isTermName) defn.RootClass.denot + else defn.EmptyPackageClass.denot + select(prefix, selector) + } + recurSimple(path.length, wrap) + } + recur(path) } + /** If we are looking for a non-existing term name in a package, + * assume it is a package for which we do not have a directory and + * enter it. + */ + def missingHook(owner: Symbol, name: Name)(using Context): Symbol = + if (owner.is(Package) && name.isTermName) + newCompletePackageSymbol(owner, name.asTermName).entered + else + NoSymbol + /** An exception for accessing symbols that are no longer valid in current run */ class StaleSymbol(msg: => String) extends Exception { util.Stats.record("stale symbol") diff --git a/compiler/src/dotty/tools/dotc/core/NamerOps.scala b/compiler/src/dotty/tools/dotc/core/NamerOps.scala new file mode 100644 index 000000000000..2131c509ed7e --- /dev/null +++ b/compiler/src/dotty/tools/dotc/core/NamerOps.scala @@ -0,0 +1,60 @@ +package dotty.tools.dotc +package core + +import Contexts._, Symbols._, Types._, Flags._, Scopes._, Decorators._, NameOps._ +import Denotations._ +import SymDenotations.LazyType, Names.Name, StdNames.nme + +/** Operations that are shared between Namer and TreeUnpickler */ +object NamerOps: + + /** The given type, unless `sym` is a constructor, in which case the + * type of the constructed instance is returned + */ + def effectiveResultType(sym: Symbol, typeParams: List[Symbol], givenTp: Type)(using Context): Type = + if (sym.name == nme.CONSTRUCTOR) sym.owner.typeRef.appliedTo(typeParams.map(_.typeRef)) + else givenTp + + /** if isConstructor, make sure it has one non-implicit parameter list */ + def normalizeIfConstructor(termParamss: List[List[Symbol]], isConstructor: Boolean)(using Context): List[List[Symbol]] = + if (isConstructor && + (termParamss.isEmpty || termParamss.head.nonEmpty && termParamss.head.head.isOneOf(GivenOrImplicit))) + Nil :: termParamss + else + termParamss + + /** The method type corresponding to given parameters and result type */ + def methodType(typeParams: List[Symbol], valueParamss: List[List[Symbol]], resultType: Type, isJava: Boolean = false)(using Context): Type = + val monotpe = + valueParamss.foldRight(resultType) { (params, resultType) => + val (isContextual, isImplicit, isErased) = + if params.isEmpty then (false, false, false) + else (params.head.is(Given), params.head.is(Implicit), params.head.is(Erased)) + val make = MethodType.companion(isJava = isJava, isContextual = isContextual, isImplicit = isImplicit, isErased = isErased) + if isJava then + for param <- params do + if param.info.isDirectRef(defn.ObjectClass) then param.info = defn.AnyType + make.fromSymbols(params, resultType) + } + if typeParams.nonEmpty then PolyType.fromParams(typeParams.asInstanceOf[List[TypeSymbol]], monotpe) + else if valueParamss.isEmpty then ExprType(monotpe) + else monotpe + + /** Add moduleClass or sourceModule functionality to completer + * for a module or module class + */ + def adjustModuleCompleter(completer: LazyType, name: Name)(using Context): LazyType = + val scope = ctx.effectiveScope + if name.isTermName then + completer.withModuleClass(findModuleBuddy(name.moduleClassName, scope)) + else + completer.withSourceModule(findModuleBuddy(name.sourceModuleName, scope)) + + /** Find moduleClass/sourceModule in effective scope */ + private def findModuleBuddy(name: Name, scope: Scope)(using Context) = { + val it = scope.lookupAll(name).filter(_.is(Module)) + if (it.hasNext) it.next() + else NoSymbol.assertingErrorsReported(s"no companion $name in $scope") + } + +end NamerOps \ No newline at end of file diff --git a/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala b/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala index ebb6e7078acf..98797b01eadd 100644 --- a/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala +++ b/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala @@ -537,7 +537,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, // HKLambdas are hash-consed, need to create an artificial difference by adding // a LazyRef to a bound. val TypeBounds(lo, hi) :: pinfos1 = tl.paramInfos - paramInfos = TypeBounds(lo, LazyRef(_ => hi)) :: pinfos1 + paramInfos = TypeBounds(lo, LazyRef(hi)) :: pinfos1 } ensureFresh(tl.newLikeThis(tl.paramNames, paramInfos, tl.resultType)) } diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index c6de89ba9399..ae59500d8a1d 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -1,46 +1,29 @@ package dotty.tools.dotc.core import Contexts._ -import Phases.curPhases +import Phases.unfusedPhases -/** Periods are the central "clock" of the compiler - * A period consists of a run id and a phase id. - * run ids represent compiler runs - * phase ids represent compiler phases - */ -abstract class Periods { thisCtx: Context => - import Periods._ - - /** The current phase identifier */ - def phaseId: Int = period.phaseId - - /** The current run identifier */ - def runId: Int = period.runId +object Periods { /** The period containing the current period where denotations do not change. * We compute this by taking as first phase the first phase less or equal to * the current phase that has the same "nextTransformerId". As last phase * we take the next transformer id following the current phase. */ - def stablePeriod: Period = { - var first = phaseId - val nxTrans = thisCtx.base.nextDenotTransformerId(first) - while (first - 1 > NoPhaseId && (thisCtx.base.nextDenotTransformerId(first - 1) == nxTrans)) + def currentStablePeriod(using Context): Period = + var first = currentPhaseId + val nxTrans = ctx.base.nextDenotTransformerId(first) + while (first - 1 > NoPhaseId && (ctx.base.nextDenotTransformerId(first - 1) == nxTrans)) first -= 1 - Period(runId, first, nxTrans) - } + Period(currentRunId, first, nxTrans) /** Are all base types in the current period guaranteed to be the same as in period `p`? */ - def hasSameBaseTypesAs(p: Period): Boolean = { - val period = thisCtx.period + def currentHasSameBaseTypesAs(p: Period)(using Context): Boolean = + val period = currentPeriod period == p || period.runId == p.runId && - curPhases(period.phaseId).sameBaseTypesStartId == - curPhases(p.phaseId).sameBaseTypesStartId - } -} - -object Periods { + unfusedPhases(period.phaseId).sameBaseTypesStartId == + unfusedPhases(p.phaseId).sameBaseTypesStartId /** A period is a contiguous sequence of phase ids in some run. * It is coded as follows: diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index 7513d19109fb..f35dae303e23 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -16,30 +16,16 @@ import Periods._ import typer.{FrontEnd, RefChecks} import ast.tpd -trait Phases { - self: Context => - - import Phases._ - - def phase: Phase = base.phases(period.firstPhaseId) - - def phasesStack: List[Phase] = - if ((this eq NoContext) || !phase.exists) Nil - else { - val rest = outersIterator.dropWhile(_.phase == phase) - phase :: (if (rest.hasNext) rest.next().phasesStack else Nil) - } - - def isAfterTyper: Boolean = base.isAfterTyper(phase) -} - object Phases { + inline def phaseOf(id: PhaseId)(using Context): Phase = + ctx.base.phases(id) + trait PhasesBase { this: ContextBase => // drop NoPhase at beginning - def allPhases: Array[Phase] = (if (squashedPhases.nonEmpty) squashedPhases else phases).tail + def allPhases: Array[Phase] = (if (fusedPhases.nonEmpty) fusedPhases else phases).tail object NoPhase extends Phase { override def exists: Boolean = false @@ -69,12 +55,12 @@ object Phases { * Each TreeTransform gets own period, * whereas a combined TreeTransformer gets period equal to union of periods of it's TreeTransforms */ - final def squashPhases(phasess: List[List[Phase]], + final def fusePhases(phasess: List[List[Phase]], phasesToSkip: List[String], stopBeforePhases: List[String], stopAfterPhases: List[String], YCheckAfter: List[String])(using Context): List[Phase] = { - val squashedPhases = ListBuffer[Phase]() + val fusedPhases = ListBuffer[Phase]() var prevPhases: Set[String] = Set.empty val YCheckAll = YCheckAfter.contains("all") @@ -117,17 +103,17 @@ object Phases { prevPhases += phase.phaseName phase } - squashedPhases += phaseToAdd + fusedPhases += phaseToAdd val shouldAddYCheck = YCheckAfter.containsPhase(phaseToAdd) || YCheckAll if (shouldAddYCheck) { val checker = new TreeChecker - squashedPhases += checker + fusedPhases += checker } } i += 1 } - squashedPhases.toList + fusedPhases.toList } /** Use the following phases in the order they are given. @@ -198,9 +184,9 @@ object Phases { } if (squash) - this.squashedPhases = (NoPhase :: phasess).toArray + this.fusedPhases = (NoPhase :: phasess).toArray else - this.squashedPhases = this.phases + this.fusedPhases = this.phases config.println(s"Phases = ${phases.toList}") config.println(s"nextDenotTransformerId = ${nextDenotTransformerId.toList}") @@ -322,7 +308,7 @@ object Phases { /** Is this phase the standard typerphase? True for FrontEnd, but * not for other first phases (such as FromTasty). The predicate * is tested in some places that perform checks and corrections. It's - * different from isAfterTyper (and cheaper to test). + * different from currentlyAfterTyper (and cheaper to test). */ def isTyper: Boolean = false @@ -427,7 +413,7 @@ object Phases { def flattenPhase(using Context): Phase = ctx.base.flattenPhase def genBCodePhase(using Context): Phase = ctx.base.genBCodePhase - def curPhases(using Context): Array[Phase] = ctx.base.phases + def unfusedPhases(using Context): Array[Phase] = ctx.base.phases /** Replace all instances of `oldPhaseClass` in `current` phases * by the result of `newPhases` applied to the old phase. diff --git a/compiler/src/dotty/tools/dotc/core/Scopes.scala b/compiler/src/dotty/tools/dotc/core/Scopes.scala index 3e8c8fa7d163..b9f80c918049 100644 --- a/compiler/src/dotty/tools/dotc/core/Scopes.scala +++ b/compiler/src/dotty/tools/dotc/core/Scopes.scala @@ -42,7 +42,7 @@ object Scopes { * the given name in the given context. Returns `NoSymbol` if the * no symbol should be synthesized for the given name. */ - type SymbolSynthesizer = Name => Context => Symbol + type SymbolSynthesizer = Name => Context ?=> Symbol class ScopeEntry private[Scopes] (val name: Name, _sym: Symbol, val owner: Scope) { @@ -265,7 +265,7 @@ object Scopes { /** enter a symbol in this scope. */ final def enter[T <: Symbol](sym: T)(using Context): T = { - if (sym.isType && ctx.phaseId <= typerPhase.id) + if (sym.isType && currentPhaseId <= typerPhase.id) assert(lookup(sym.name) == NoSymbol, s"duplicate ${sym.debugString}; previous was ${lookup(sym.name).debugString}") // !!! DEBUG newScopeEntry(sym) @@ -369,7 +369,7 @@ object Scopes { e = e.prev } if ((e eq null) && (synthesize != null)) { - val sym = synthesize(name)(ctx) + val sym = synthesize(name) if (sym.exists) newScopeEntry(sym) else e } else e diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index 051b904897fa..c71c81eaed1b 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -4,8 +4,8 @@ package core import Periods._, Contexts._, Symbols._, Denotations._, Names._, NameOps._, Annotations._ import Types._, Flags._, Decorators._, DenotTransformers._, StdNames._, Scopes._ -import NameOps._, NameKinds._, Phases._ -import Phases.typerPhase +import NameOps._, NameKinds._ +import Phases.{Phase, typerPhase, unfusedPhases} import Constants.Constant import TypeApplications.TypeParamInfo import Scopes.Scope @@ -21,106 +21,12 @@ import util.Stats import java.util.WeakHashMap import scala.util.control.NonFatal import config.Config -import reporting.{Message, trace} -import reporting.messages.BadSymbolicReference +import reporting._ import collection.mutable import transform.TypeUtils._ import scala.annotation.internal.sharable -trait SymDenotations { thisCtx: Context => - import SymDenotations._ - - /** Factory method for SymDenotion creation. All creations - * should be done via this method. - */ - def SymDenotation( - symbol: Symbol, - owner: Symbol, - name: Name, - initFlags: FlagSet, - initInfo: Type, - initPrivateWithin: Symbol = NoSymbol)(using Context): SymDenotation = { - val result = - if (symbol.isClass) - if (initFlags.is(Package)) new PackageClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) - else new ClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) - else new SymDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) - result.validFor = stablePeriod - result - } - - def stillValid(denot: SymDenotation): Boolean = - if (denot.isOneOf(ValidForeverFlags) || denot.isRefinementClass || denot.isImport) true - else { - val initial = denot.initial - val firstPhaseId = initial.validFor.firstPhaseId.max(typerPhase.id) - if ((initial ne denot) || thisCtx.phaseId != firstPhaseId) - thisCtx.withPhase(firstPhaseId).stillValidInOwner(initial) - else - stillValidInOwner(denot) - } - - private[SymDenotations] def stillValidInOwner(denot: SymDenotation): Boolean = try { - val owner = denot.owner.denot - stillValid(owner) && ( - !owner.isClass - || owner.isRefinementClass - || owner.is(Scala2x) - || (owner.unforcedDecls.lookupAll(denot.name) contains denot.symbol) - || denot.isSelfSym - || denot.isLocalDummy) - } - catch { - case ex: StaleSymbol => false - } - - /** Explain why symbol is invalid; used for debugging only */ - def traceInvalid(denot: Denotation): Boolean = { - def show(d: Denotation) = s"$d#${d.symbol.id}" - def explain(msg: String) = { - println(s"${show(denot)} is invalid at ${thisCtx.period} because $msg") - false - } - denot match { - case denot: SymDenotation => - def explainSym(msg: String) = explain(s"$msg\ndefined = ${denot.definedPeriodsString}") - if (denot.isOneOf(ValidForeverFlags) || denot.isRefinementClass) true - else inContext(thisCtx) { - val initial = denot.initial - if ((initial ne denot) || ctx.phaseId != initial.validFor.firstPhaseId) - ctx.withPhase(initial.validFor.firstPhaseId).traceInvalid(initial) - else try { - val owner = denot.owner.denot - if (!traceInvalid(owner)) explainSym("owner is invalid") - else if (!owner.isClass || owner.isRefinementClass || denot.isSelfSym) true - else if (owner.unforcedDecls.lookupAll(denot.name) contains denot.symbol) true - else explainSym(s"decls of ${show(owner)} are ${owner.unforcedDecls.lookupAll(denot.name).toList}, do not contain ${denot.symbol}") - } - catch { - case ex: StaleSymbol => explainSym(s"$ex was thrown") - } - } - case _ => - explain("denotation is not a SymDenotation") - } - } - - /** Configurable: Accept stale symbol with warning if in IDE - * Always accept stale symbols when testing pickling. - */ - def staleOK: Boolean = - Config.ignoreStaleInIDE && mode.is(Mode.Interactive) || - settings.YtestPickler.value - - /** Possibly accept stale symbol with warning if in IDE */ - def acceptStale(denot: SingleDenotation): Boolean = - staleOK && { - thisCtx.debugwarn(denot.staleSymbolMsg) - true - } -} - object SymDenotations { /** A sym-denotation represents the contents of a definition @@ -407,7 +313,7 @@ object SymDenotations { def recurWithoutParamss(info: Type): List[List[Symbol]] = info match case info: LambdaType => val params = info.paramNames.lazyZip(info.paramInfos).map((pname, ptype) => - ctx.newSymbol(symbol, pname, SyntheticParam, ptype)) + newSymbol(symbol, pname, SyntheticParam, ptype)) val prefs = params.map(_.namedType) for param <- params do param.info = param.info.substParams(info, prefs) @@ -856,7 +762,7 @@ object SymDenotations { /** Is this symbol a class of which `null` is a value? */ final def isNullableClass(using Context): Boolean = - if (ctx.explicitNulls && !ctx.phase.erasedTypes) symbol == defn.NullClass || symbol == defn.AnyClass + if (ctx.explicitNulls && !currentPhase.erasedTypes) symbol == defn.NullClass || symbol == defn.AnyClass else isNullableClassAfterErasure /** Is this symbol a class of which `null` is a value after erasure? @@ -943,7 +849,7 @@ object SymDenotations { || this.is(Protected) && ( superAccess || pre.isInstanceOf[ThisType] - || ctx.phase.erasedTypes + || currentPhase.erasedTypes || isProtectedAccessOK ) ) @@ -956,7 +862,7 @@ object SymDenotations { def membersNeedAsSeenFrom(pre: Type)(using Context): Boolean = !( this.isTerm || this.isStaticOwner && !this.seesOpaques - || ctx.erasedTypes + || currentlyAfterErasure || (pre eq NoPrefix) || (pre eq thisType) ) @@ -969,7 +875,7 @@ object SymDenotations { * Default parameters are recognized until erasure. */ def hasDefaultParams(using Context): Boolean = - if ctx.erasedTypes then false + if currentlyAfterErasure then false else if is(HasDefaultParams) then true else if is(NoDefaultParams) then false else @@ -1419,7 +1325,7 @@ object SymDenotations { final def accessBoundary(base: Symbol)(using Context): Symbol = if (this.is(Private)) owner else if (this.isAllOf(StaticProtected)) defn.RootClass - else if (privateWithin.exists && !ctx.phase.erasedTypes) privateWithin + else if (privateWithin.exists && !currentPhase.erasedTypes) privateWithin else if (this.is(Protected)) base else defn.RootClass @@ -1544,12 +1450,12 @@ object SymDenotations { // simulate default parameters, while also passing implicit context ctx to the default values val initFlags1 = (if (initFlags != UndefinedFlags) initFlags else this.flags) val info1 = if (info != null) info else this.info - if (ctx.isAfterTyper && changedClassParents(info, info1, completersMatter = false)) - assert(ctx.phase.changesParents, i"undeclared parent change at ${ctx.phase} for $this, was: $info, now: $info1") + if (currentlyAfterTyper && changedClassParents(info, info1, completersMatter = false)) + assert(currentPhase.changesParents, i"undeclared parent change at ${currentPhase} for $this, was: $info, now: $info1") val privateWithin1 = if (privateWithin != null) privateWithin else this.privateWithin val annotations1 = if (annotations != null) annotations else this.annotations val rawParamss1 = if rawParamss != null then rawParamss else this.rawParamss - val d = ctx.SymDenotation(symbol, owner, name, initFlags1, info1, privateWithin1) + val d = SymDenotation(symbol, owner, name, initFlags1, info1, privateWithin1) d.annotations = annotations1 d.rawParamss = rawParamss1 d.registeredCompanion = registeredCompanion @@ -1661,18 +1567,17 @@ object SymDenotations { private var memberNamesCache: MemberNames = MemberNames.None private def memberCache(using Context): LRUCache[Name, PreDenotation] = { - if (myMemberCachePeriod != ctx.period) { + if (myMemberCachePeriod != currentPeriod) { myMemberCache = new LRUCache - myMemberCachePeriod = ctx.period + myMemberCachePeriod = currentPeriod } myMemberCache } private def baseTypeCache(using Context): BaseTypeMap = { - if (!ctx.hasSameBaseTypesAs(myBaseTypeCachePeriod)) { + if !currentHasSameBaseTypesAs(myBaseTypeCachePeriod) then myBaseTypeCache = new BaseTypeMap - myBaseTypeCachePeriod = ctx.period - } + myBaseTypeCachePeriod = currentPeriod myBaseTypeCache } @@ -1736,7 +1641,7 @@ object SymDenotations { override final def typeParams(using Context): List[TypeSymbol] = { if (myTypeParams == null) myTypeParams = - if (ctx.erasedTypes || is(Module)) Nil // fast return for modules to avoid scanning package decls + if (currentlyAfterErasure || is(Module)) Nil // fast return for modules to avoid scanning package decls else { val di = initial if (this ne di) di.typeParams @@ -1824,7 +1729,7 @@ object SymDenotations { def computeBaseData(implicit onBehalf: BaseData, ctx: Context): (List[ClassSymbol], BaseClassSet) = { def emptyParentsExpected = - is(Package) || (symbol == defn.AnyClass) || ctx.erasedTypes && (symbol == defn.ObjectClass) + is(Package) || (symbol == defn.AnyClass) || currentlyAfterErasure && (symbol == defn.ObjectClass) if (classParents.isEmpty && !emptyParentsExpected) onBehalf.signalProvisional() val builder = new BaseDataBuilder @@ -1920,7 +1825,7 @@ object SymDenotations { */ def ensureTypeParamsInCorrectOrder()(using Context): Unit = { val tparams = typeParams - if (!ctx.erasedTypes && !typeParamsFromDecls.corresponds(tparams)(_.name == _.name)) { + if (!currentlyAfterErasure && !typeParamsFromDecls.corresponds(tparams)(_.name == _.name)) { val decls = info.decls val decls1 = newScope for (tparam <- typeParams) decls1.enter(decls.lookup(tparam.name)) @@ -2199,7 +2104,7 @@ object SymDenotations { * `phase.next`, install a new denotation with a cloned scope in `phase.next`. */ def ensureFreshScopeAfter(phase: DenotTransformer)(using Context): Unit = - if (ctx.phaseId != phase.next.id) atPhase(phase.next)(ensureFreshScopeAfter(phase)) + if (currentPhaseId != phase.next.id) atPhase(phase.next)(ensureFreshScopeAfter(phase)) else { val prevClassInfo = atPhase(phase) { current.asInstanceOf[ClassDenotation].classInfo @@ -2249,8 +2154,8 @@ object SymDenotations { /** The package objects in this class */ def packageObjs(using Context): List[ClassDenotation] = { - if (packageObjsRunId != ctx.runId) { - packageObjsRunId = ctx.runId + if (packageObjsRunId != currentRunId) { + packageObjsRunId = currentRunId packageObjsCache = Nil // break cycle in case we are looking for package object itself packageObjsCache = { val pkgObjBuf = new mutable.ListBuffer[ClassDenotation] @@ -2346,7 +2251,7 @@ object SymDenotations { try f.container == chosen.container catch case NonFatal(ex) => true if !ambiguityWarningIssued then for conflicting <- assocFiles.find(!sameContainer(_)) do - ctx.warning(i"""${ambiguousFilesMsg(conflicting)} + report.warning(i"""${ambiguousFilesMsg(conflicting)} |Keeping only the definition in $chosen""") ambiguityWarningIssued = true multi.filterWithPredicate(_.symbol.associatedFile == chosen) @@ -2391,7 +2296,7 @@ object SymDenotations { for (sym <- scope.toList.iterator) // We need to be careful to not force the denotation of `sym` here, // otherwise it will be brought forward to the current run. - if (sym.defRunId != ctx.runId && sym.isClass && sym.asClass.assocFile == file) + if (sym.defRunId != currentRunId && sym.isClass && sym.asClass.assocFile == file) scope.unlink(sym, sym.lastKnownDenotation.name) } } @@ -2419,7 +2324,95 @@ object SymDenotations { def canBeLocal(name: Name, flags: FlagSet)(using Context) = !name.isConstructorName && !flags.is(Param) && !flags.is(ParamAccessor) - // ---- Completion -------------------------------------------------------- + /** Factory method for SymDenotion creation. All creations + * should be done via this method. + */ + def SymDenotation( + symbol: Symbol, + owner: Symbol, + name: Name, + initFlags: FlagSet, + initInfo: Type, + initPrivateWithin: Symbol = NoSymbol)(using Context): SymDenotation = { + val result = + if (symbol.isClass) + if (initFlags.is(Package)) new PackageClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) + else new ClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) + else new SymDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) + result.validFor = currentStablePeriod + result + } + + def stillValid(denot: SymDenotation)(using Context): Boolean = + if (denot.isOneOf(ValidForeverFlags) || denot.isRefinementClass || denot.isImport) true + else { + val initial = denot.initial + val firstPhaseId = initial.validFor.firstPhaseId.max(typerPhase.id) + if ((initial ne denot) || currentPhaseId != firstPhaseId) + atPhase(firstPhaseId)(stillValidInOwner(initial)) + else + stillValidInOwner(denot) + } + + private[SymDenotations] def stillValidInOwner(denot: SymDenotation)(using Context): Boolean = try { + val owner = denot.owner.denot + stillValid(owner) && ( + !owner.isClass + || owner.isRefinementClass + || owner.is(Scala2x) + || (owner.unforcedDecls.lookupAll(denot.name) contains denot.symbol) + || denot.isSelfSym + || denot.isLocalDummy) + } + catch { + case ex: StaleSymbol => false + } + + /** Explain why symbol is invalid; used for debugging only */ + def traceInvalid(denot: Denotation)(using Context): Boolean = { + def show(d: Denotation) = s"$d#${d.symbol.id}" + def explain(msg: String) = { + println(s"${show(denot)} is invalid at ${currentPeriod} because $msg") + false + } + denot match { + case denot: SymDenotation => + def explainSym(msg: String) = explain(s"$msg\ndefined = ${denot.definedPeriodsString}") + if (denot.isOneOf(ValidForeverFlags) || denot.isRefinementClass) true + else + val initial = denot.initial + if ((initial ne denot) || currentPhaseId != initial.validFor.firstPhaseId) + atPhase(initial.validFor.firstPhaseId)(traceInvalid(initial)) + else try { + val owner = denot.owner.denot + if (!traceInvalid(owner)) explainSym("owner is invalid") + else if (!owner.isClass || owner.isRefinementClass || denot.isSelfSym) true + else if (owner.unforcedDecls.lookupAll(denot.name) contains denot.symbol) true + else explainSym(s"decls of ${show(owner)} are ${owner.unforcedDecls.lookupAll(denot.name).toList}, do not contain ${denot.symbol}") + } + catch { + case ex: StaleSymbol => explainSym(s"$ex was thrown") + } + case _ => + explain("denotation is not a SymDenotation") + } + } + + /** Configurable: Accept stale symbol with warning if in IDE + * Always accept stale symbols when testing pickling. + */ + def staleOK(using Context): Boolean = + Config.ignoreStaleInIDE && ctx.mode.is(Mode.Interactive) + || ctx.settings.YtestPickler.value + + /** Possibly accept stale symbol with warning if in IDE */ + def acceptStale(denot: SingleDenotation)(using Context): Boolean = + staleOK && { + report.debugwarn(denot.staleSymbolMsg) + true + } + +// ---- Completion -------------------------------------------------------- /** Instances of LazyType are carried by uncompleted symbols. * Note: LazyTypes double up as (constant) functions from Symbol and @@ -2437,10 +2430,9 @@ object SymDenotations { def apply(sym: Symbol): LazyType = this def apply(module: TermSymbol, modcls: ClassSymbol): LazyType = this - private val NoSymbolFn = (_: Context) => NoSymbol private var myDecls: Scope = EmptyScope - private var mySourceModuleFn: Context => Symbol = NoSymbolFn - private var myModuleClassFn: Context => Symbol = NoSymbolFn + private var mySourceModuleFn: Context ?=> Symbol = LazyType.NoSymbolFn + private var myModuleClassFn: Context ?=> Symbol = LazyType.NoSymbolFn /** The type parameters computed by the completer before completion has finished */ def completerTypeParams(sym: Symbol)(using Context): List[TypeParamInfo] = @@ -2448,16 +2440,19 @@ object SymDenotations { else sym.info.typeParams def decls: Scope = myDecls - def sourceModule(using Context): Symbol = mySourceModuleFn(ctx) - def moduleClass(using Context): Symbol = myModuleClassFn(ctx) + def sourceModule(using Context): Symbol = mySourceModuleFn + def moduleClass(using Context): Symbol = myModuleClassFn def withDecls(decls: Scope): this.type = { myDecls = decls; this } - def withSourceModule(sourceModuleFn: Context => Symbol): this.type = { mySourceModuleFn = sourceModuleFn; this } - def withModuleClass(moduleClassFn: Context => Symbol): this.type = { myModuleClassFn = moduleClassFn; this } + def withSourceModule(sourceModuleFn: Context ?=> Symbol): this.type = { mySourceModuleFn = sourceModuleFn; this } + def withModuleClass(moduleClassFn: Context ?=> Symbol): this.type = { myModuleClassFn = moduleClassFn; this } override def toString: String = getClass.toString } + object LazyType: + private val NoSymbolFn = (using _: Context) => NoSymbol + /** A subtrait of LazyTypes where completerTypeParams yields a List[TypeSymbol], which * should be completed independently of the info. */ @@ -2509,7 +2504,7 @@ object SymDenotations { def complete(denot: SymDenotation)(using Context): Unit = { val sym = denot.symbol val errMsg = BadSymbolicReference(denot) - ctx.error(errMsg, sym.sourcePos) + report.error(errMsg, sym.sourcePos) if (ctx.debug) throw new scala.Error() initializeToDefaults(denot, errMsg) } @@ -2540,7 +2535,7 @@ object SymDenotations { implicit val None: MemberNames = new InvalidCache with MemberNames { def apply(keepOnly: NameFilter, clsd: ClassDenotation)(implicit onBehalf: MemberNames, ctx: Context) = ??? } - def newCache()(using Context): MemberNames = new MemberNamesImpl(ctx.period) + def newCache()(using Context): MemberNames = new MemberNamesImpl(currentPeriod) } /** A cache for baseclasses, as a sequence in linearization order and as a set that @@ -2557,7 +2552,7 @@ object SymDenotations { def apply(clsd: ClassDenotation)(implicit onBehalf: BaseData, ctx: Context) = ??? def signalProvisional() = () } - def newCache()(using Context): BaseData = new BaseDataImpl(ctx.period) + def newCache()(using Context): BaseData = new BaseDataImpl(currentPeriod) } private abstract class InheritedCacheImpl(val createdAt: Period) extends InheritedCache { @@ -2580,11 +2575,11 @@ object SymDenotations { } def isValidAt(phase: Phase)(using Context) = - checkedPeriod == ctx.period || - createdAt.runId == ctx.runId && - createdAt.phaseId < curPhases.length && - sameGroup(curPhases(createdAt.phaseId), phase) && - { checkedPeriod = ctx.period; true } + checkedPeriod == currentPeriod || + createdAt.runId == currentRunId && + createdAt.phaseId < unfusedPhases.length && + sameGroup(unfusedPhases(createdAt.phaseId), phase) && + { checkedPeriod = currentPeriod; true } } private class InvalidCache extends InheritedCache { @@ -2597,7 +2592,7 @@ object SymDenotations { private var cache: SimpleIdentityMap[NameFilter, Set[Name]] = SimpleIdentityMap.Empty final def isValid(using Context): Boolean = - cache != null && isValidAt(ctx.phase) + cache != null && isValidAt(currentPhase) private var locked = false @@ -2639,7 +2634,7 @@ object SymDenotations { private var locked = false private var provisional = false - final def isValid(using Context): Boolean = valid && isValidAt(ctx.phase) + final def isValid(using Context): Boolean = valid && isValidAt(currentPhase) def invalidate(): Unit = if (valid && !locked) { diff --git a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala index 8409ce080360..0755b3ae5fc0 100644 --- a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala +++ b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala @@ -46,7 +46,7 @@ object SymbolLoaders { def enterClass( owner: Symbol, name: PreName, completer: SymbolLoader, flags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(using Context): Symbol = { - val cls = ctx.newClassSymbol(owner, name.toTypeName.unmangleClassName.decode, flags, completer, assocFile = completer.sourceFileOrNull) + val cls = newClassSymbol(owner, name.toTypeName.unmangleClassName.decode, flags, completer, assocFile = completer.sourceFileOrNull) enterNew(owner, cls, completer, scope) } @@ -55,9 +55,9 @@ object SymbolLoaders { def enterModule( owner: Symbol, name: PreName, completer: SymbolLoader, modFlags: FlagSet = EmptyFlags, clsFlags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(using Context): Symbol = { - val module = ctx.newModuleSymbol( + val module = newModuleSymbol( owner, name.toTermName.decode, modFlags, clsFlags, - (module, _) => completer.proxy withDecls newScope withSourceModule (_ => module), + (module, _) => completer.proxy.withDecls(newScope).withSourceModule(module), assocFile = completer.sourceFileOrNull) enterNew(owner, module, completer, scope) enterNew(owner, module.moduleClass, completer, scope) @@ -75,12 +75,12 @@ object SymbolLoaders { // This was motivated by the desire to use YourKit probes, which // require yjp.jar at runtime. See SI-2089. if (ctx.settings.YtermConflict.value == "package" || ctx.mode.is(Mode.Interactive)) { - ctx.warning( + report.warning( s"Resolving package/object name conflict in favor of package ${preExisting.fullName}. The object will be inaccessible.") owner.asClass.delete(preExisting) } else if (ctx.settings.YtermConflict.value == "object") { - ctx.warning( + report.warning( s"Resolving package/object name conflict in favor of object ${preExisting.fullName}. The package will be inaccessible.") return NoSymbol } @@ -88,7 +88,7 @@ object SymbolLoaders { throw new TypeError( i"""$owner contains object and package with same name: $pname |one of them needs to be removed from classpath""") - ctx.newModuleSymbol(owner, pname, PackageCreationFlags, PackageCreationFlags, + newModuleSymbol(owner, pname, PackageCreationFlags, PackageCreationFlags, completer).entered } @@ -130,7 +130,7 @@ object SymbolLoaders { def checkPathMatches(path: List[TermName], what: String, tree: NameTree): Boolean = { val ok = filePath == path if (!ok) - ctx.warning(i"""$what ${tree.name} is in the wrong directory. + report.warning(i"""$what ${tree.name} is in the wrong directory. |It was declared to be in package ${path.reverse.mkString(".")} |But it is found in directory ${filePath.reverse.mkString(File.separator)}""", tree.sourcePos.focus) @@ -186,10 +186,10 @@ object SymbolLoaders { def initializeFromClassPath(owner: Symbol, classRep: ClassRepresentation)(using Context): Unit = ((classRep.binary, classRep.source): @unchecked) match { case (Some(bin), Some(src)) if needCompile(bin, src) && !binaryOnly(owner, classRep.name) => - if (ctx.settings.verbose.value) ctx.inform("[symloader] picked up newer source file for " + src.path) + if (ctx.settings.verbose.value) report.inform("[symloader] picked up newer source file for " + src.path) enterToplevelsFromSource(owner, classRep.name, src) case (None, Some(src)) => - if (ctx.settings.verbose.value) ctx.inform("[symloader] no class, picked up source file for " + src.path) + if (ctx.settings.verbose.value) report.inform("[symloader] no class, picked up source file for " + src.path) enterToplevelsFromSource(owner, classRep.name, src) case (Some(bin), _) => enterClassAndModule(owner, classRep.name, ctx.platform.newClassLoader(bin)) @@ -206,7 +206,7 @@ object SymbolLoaders { override def sourceModule(using Context): TermSymbol = _sourceModule def description(using Context): String = "package loader " + sourceModule.fullName - private var enterFlatClasses: Option[Context => Unit] = None + private var enterFlatClasses: Option[() => Context ?=> Unit] = None Stats.record("package scopes") @@ -226,14 +226,14 @@ object SymbolLoaders { if (e != null) e else if (isFlatName(mangled.toSimpleName) && enterFlatClasses.isDefined) { Stats.record("package scopes with flatnames entered") - enterFlatClasses.get(ctx) + enterFlatClasses.get() lookupEntry(name) } else e } override def ensureComplete()(using Context): Unit = - for (enter <- enterFlatClasses) enter(ctx) + for (enter <- enterFlatClasses) enter() override def newScopeLikeThis(): PackageScope = new PackageScope } @@ -283,7 +283,7 @@ object SymbolLoaders { val packageName = if (root.isEffectiveRoot) "" else root.symbol.javaClassName - enterFlatClasses = Some { ctx => + enterFlatClasses = Some { () => enterFlatClasses = None inContext(ctx){enterClasses(root, packageName, flat = true)} } @@ -328,7 +328,7 @@ abstract class SymbolLoader extends LazyType { self => def signalError(ex: Exception): Unit = { if (ctx.debug) ex.printStackTrace() val msg = ex.getMessage() - ctx.error( + report.error( if (msg eq null) "i/o error while loading " + root.name else "error while loading " + root.name + ",\n" + msg) } @@ -340,7 +340,7 @@ abstract class SymbolLoader extends LazyType { self => } else doComplete(root) - ctx.informTime("loaded " + description, start) + report.informTime("loaded " + description, start) } catch { case ex: IOException => @@ -373,13 +373,13 @@ abstract class SymbolLoader extends LazyType { self => // An example for this situation is scala.reflect.Manifest, which exists // as a class in scala.reflect and as a val in scala.reflect.package. if (rootDenot.is(ModuleClass)) - ctx.newClassSymbol( + newClassSymbol( rootDenot.owner, rootDenot.name.stripModuleClassSuffix.asTypeName, Synthetic, _ => NoType).classDenot else - ctx.newModuleSymbol( + newModuleSymbol( rootDenot.owner, rootDenot.name.toTermName, Synthetic, Synthetic, - (module, _) => NoLoader().withDecls(newScope).withSourceModule(_ => module)) + (module, _) => NoLoader().withDecls(newScope).withSourceModule(module)) .moduleClass.denot.asClass } if (rootDenot.is(ModuleClass)) (linkedDenot, rootDenot) diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index ea019e3851d2..bb484de1951c 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -11,6 +11,7 @@ import Symbols._ import Contexts._ import Phases._ import SymDenotations._ +import Denotations._ import printing.Texts._ import printing.Printer import Types._ @@ -34,391 +35,6 @@ import scala.collection.JavaConverters._ import scala.annotation.internal.sharable import config.Printers.typr -/** Creation methods for symbols */ -trait Symbols { thisCtx: Context => - -// ---- Factory methods for symbol creation ---------------------- -// -// All symbol creations should be done via the next two methods. - - /** Create a symbol without a denotation. - * Note this uses a cast instead of a direct type refinement because - * it's debug-friendlier not to create an anonymous class here. - */ - def newNakedSymbol[N <: Name](coord: Coord = NoCoord)(using Context): Symbol { type ThisName = N } = - new Symbol(coord, ctx.base.nextSymId).asInstanceOf[Symbol { type ThisName = N }] - - /** Create a class symbol without a denotation. */ - def newNakedClassSymbol(coord: Coord = NoCoord, assocFile: AbstractFile = null)(using Context): ClassSymbol = - new ClassSymbol(coord, assocFile, ctx.base.nextSymId) - -// ---- Symbol creation methods ---------------------------------- - - /** Create a symbol from its fields (info may be lazy) */ - def newSymbol[N <: Name]( - owner: Symbol, - name: N, - flags: FlagSet, - info: Type, - privateWithin: Symbol = NoSymbol, - coord: Coord = NoCoord): Symbol { type ThisName = N } = { - val sym = newNakedSymbol[N](coord) - val denot = SymDenotation(sym, owner, name, flags, info, privateWithin) - sym.denot = denot - sym - } - - /** Create a class symbol from a function producing its denotation */ - def newClassSymbolDenoting(denotFn: ClassSymbol => SymDenotation, coord: Coord = NoCoord, assocFile: AbstractFile = null): ClassSymbol = { - val cls = newNakedClassSymbol(coord, assocFile) - cls.denot = denotFn(cls) - cls - } - - /** Create a class symbol from its non-info fields and a function - * producing its info (the produced info may be lazy). - */ - def newClassSymbol( - owner: Symbol, - name: TypeName, - flags: FlagSet, - infoFn: ClassSymbol => Type, - privateWithin: Symbol = NoSymbol, - coord: Coord = NoCoord, - assocFile: AbstractFile = null): ClassSymbol - = { - val cls = newNakedClassSymbol(coord, assocFile) - val denot = SymDenotation(cls, owner, name, flags, infoFn(cls), privateWithin) - cls.denot = denot - cls - } - - /** Create a class symbol from its non-info fields and the fields of its info. */ - def newCompleteClassSymbol( - owner: Symbol, - name: TypeName, - flags: FlagSet, - parents: List[TypeRef], - decls: Scope = newScope, - selfInfo: Type = NoType, - privateWithin: Symbol = NoSymbol, - coord: Coord = NoCoord, - assocFile: AbstractFile = null): ClassSymbol = - newClassSymbol( - owner, name, flags, - ClassInfo(owner.thisType, _, parents, decls, selfInfo), - privateWithin, coord, assocFile) - - /** Same as `newCompleteClassSymbol` except that `parents` can be a list of arbitrary - * types which get normalized into type refs and parameter bindings. - */ - def newNormalizedClassSymbol( - owner: Symbol, - name: TypeName, - flags: FlagSet, - parentTypes: List[Type], - decls: Scope = newScope, - selfInfo: Type = NoType, - privateWithin: Symbol = NoSymbol, - coord: Coord = NoCoord, - assocFile: AbstractFile = null): ClassSymbol = { - def completer = new LazyType { - def complete(denot: SymDenotation)(using Context): Unit = { - val cls = denot.asClass.classSymbol - val decls = newScope - denot.info = ClassInfo(owner.thisType, cls, parentTypes.map(_.dealias), decls) - } - } - newClassSymbol(owner, name, flags, completer, privateWithin, coord, assocFile) - } - - def newRefinedClassSymbol(coord: Coord = NoCoord): ClassSymbol = - newCompleteClassSymbol(thisCtx.owner, tpnme.REFINE_CLASS, NonMember, parents = Nil, coord = coord) - - /** Create a module symbol with associated module class - * from its non-info fields and a function producing the info - * of the module class (this info may be lazy). - */ - def newModuleSymbol( - owner: Symbol, - name: TermName, - modFlags: FlagSet, - clsFlags: FlagSet, - infoFn: (TermSymbol, ClassSymbol) => Type, // typically a ModuleClassCompleterWithDecls - privateWithin: Symbol = NoSymbol, - coord: Coord = NoCoord, - assocFile: AbstractFile = null): TermSymbol - = { - val base = owner.thisType - val module = newNakedSymbol[TermName](coord) - val modcls = newNakedClassSymbol(coord, assocFile) - val modclsFlags = clsFlags | ModuleClassCreationFlags - val modclsName = name.toTypeName.adjustIfModuleClass(modclsFlags) - val cdenot = SymDenotation( - modcls, owner, modclsName, modclsFlags, - infoFn(module, modcls), privateWithin) - val mdenot = SymDenotation( - module, owner, name, modFlags | ModuleValCreationFlags, - if (cdenot.isCompleted) TypeRef(owner.thisType, modcls) - else new ModuleCompleter(modcls)) - module.denot = mdenot - modcls.denot = cdenot - module - } - - /** Create a module symbol with associated module class - * from its non-info fields and the fields of the module class info. - * @param flags The combined flags of the module and the module class - * These are masked with RetainedModuleValFlags/RetainedModuleClassFlags. - */ - def newCompleteModuleSymbol( - owner: Symbol, - name: TermName, - modFlags: FlagSet, - clsFlags: FlagSet, - parents: List[TypeRef], - decls: Scope, - privateWithin: Symbol = NoSymbol, - coord: Coord = NoCoord, - assocFile: AbstractFile = null): TermSymbol = - newModuleSymbol( - owner, name, modFlags, clsFlags, - (module, modcls) => ClassInfo( - owner.thisType, modcls, parents, decls, TermRef(owner.thisType, module)), - privateWithin, coord, assocFile) - - val companionMethodFlags: FlagSet = Flags.Synthetic | Flags.Private | Flags.Method - - /** Create a package symbol with associated package class - * from its non-info fields and a lazy type for loading the package's members. - */ - def newPackageSymbol( - owner: Symbol, - name: TermName, - infoFn: (TermSymbol, ClassSymbol) => LazyType): TermSymbol = - newModuleSymbol(owner, name, PackageCreationFlags, PackageCreationFlags, infoFn) - - /** Create a package symbol with associated package class - * from its non-info fields its member scope. - */ - def newCompletePackageSymbol( - owner: Symbol, - name: TermName, - modFlags: FlagSet = EmptyFlags, - clsFlags: FlagSet = EmptyFlags, - decls: Scope = newScope): TermSymbol = - newCompleteModuleSymbol( - owner, name, - modFlags | PackageCreationFlags, clsFlags | PackageCreationFlags, - Nil, decls) - - /** Define a new symbol associated with a Bind or pattern wildcard and, by default, make it gadt narrowable. */ - def newPatternBoundSymbol(name: Name, info: Type, span: Span, addToGadt: Boolean = true, flags: FlagSet = EmptyFlags): Symbol = { - val sym = newSymbol(owner, name, Case | flags, info, coord = span) - if (addToGadt && name.isTypeName) gadt.addToConstraint(sym) - sym - } - - /** Create a stub symbol that will issue a missing reference error - * when attempted to be completed. - */ - def newStubSymbol(owner: Symbol, name: Name, file: AbstractFile = null): Symbol = { - def stubCompleter = new StubInfo() - val normalizedOwner = if (owner.is(ModuleVal)) owner.moduleClass else owner - typr.println(s"creating stub for ${name.show}, owner = ${normalizedOwner.denot.debugString}, file = $file") - typr.println(s"decls = ${normalizedOwner.unforcedDecls.toList.map(_.debugString).mkString("\n ")}") // !!! DEBUG - //if (base.settings.debug.value) throw new Error() - val stub = name match { - case name: TermName => - newModuleSymbol(normalizedOwner, name, EmptyFlags, EmptyFlags, stubCompleter, assocFile = file) - case name: TypeName => - newClassSymbol(normalizedOwner, name, EmptyFlags, stubCompleter, assocFile = file) - } - stub - } - - /** Create the local template dummy of given class `cls`. - * In a template - * - * trait T { val fld: Int; { val x: int = 2 }; val fld2 = { val y = 2; y }} - * - * the owner of `x` is the local dummy of the template. The owner of the local - * dummy is then the class of the template itself. By contrast, the owner of `y` - * would be `fld2`. There is a single local dummy per template. - */ - def newLocalDummy(cls: Symbol, coord: Coord = NoCoord): TermSymbol = - newSymbol(cls, nme.localDummyName(cls), NonMember, NoType) - - /** Create an import symbol pointing back to given qualifier `expr`. */ - def newImportSymbol(owner: Symbol, expr: Tree, coord: Coord = NoCoord): TermSymbol = - newImportSymbol(owner, ImportType(expr), coord = coord) - - /** Create an import symbol with given `info`. */ - def newImportSymbol(owner: Symbol, info: Type, coord: Coord): TermSymbol = - newSymbol(owner, nme.IMPORT, Synthetic | NonMember, info, coord = coord) - - /** Create a class constructor symbol for given class `cls`. */ - def newConstructor(cls: ClassSymbol, flags: FlagSet, paramNames: List[TermName], paramTypes: List[Type], privateWithin: Symbol = NoSymbol, coord: Coord = NoCoord): TermSymbol = - newSymbol(cls, nme.CONSTRUCTOR, flags | Method, MethodType(paramNames, paramTypes, cls.typeRef), privateWithin, coord) - - /** Create an empty default constructor symbol for given class `cls`. */ - def newDefaultConstructor(cls: ClassSymbol): TermSymbol = - newConstructor(cls, EmptyFlags, Nil, Nil) - - def newLazyImplicit(info: Type, coord: Coord = NoCoord): TermSymbol = - newSymbol(owner, LazyImplicitName.fresh(), EmptyFlags, info, coord = coord) - - /** Create a symbol representing a selftype declaration for class `cls`. */ - def newSelfSym(cls: ClassSymbol, name: TermName = nme.WILDCARD, selfInfo: Type = NoType): TermSymbol = - newSymbol(cls, name, SelfSymFlags, selfInfo orElse cls.classInfo.selfType, coord = cls.coord) - - /** Create new type parameters with given owner, names, and flags. - * @param boundsFn A function that, given type refs to the newly created - * parameters returns a list of their bounds. - */ - def newTypeParams( - owner: Symbol, - names: List[TypeName], - flags: FlagSet, - boundsFn: List[TypeRef] => List[Type]): List[TypeSymbol] = { - - val tparamBuf = new mutable.ListBuffer[TypeSymbol] - val trefBuf = new mutable.ListBuffer[TypeRef] - for (name <- names) { - val tparam = newSymbol( - owner, name, flags | owner.typeParamCreationFlags, NoType, coord = owner.coord) - tparamBuf += tparam - trefBuf += TypeRef(owner.thisType, tparam) - } - val tparams = tparamBuf.toList - val bounds = boundsFn(trefBuf.toList) - for (tparam, bound) <- tparams.lazyZip(bounds) do - tparam.info = bound - tparams - } - - /** Create a new skolem symbol. This is not the same as SkolemType, even though the - * motivation (create a singleton referencing to a type) is similar. - */ - def newSkolem(tp: Type): TermSymbol = newSymbol(defn.RootClass, nme.SKOLEM, SyntheticArtifact | NonMember | Permanent, tp) - - def newErrorSymbol(owner: Symbol, name: Name, msg: Message): Symbol = { - val errType = ErrorType(msg) - newSymbol(owner, name, SyntheticArtifact, - if (name.isTypeName) TypeAlias(errType) else errType) - } - - /** Map given symbols, subjecting their attributes to the mappings - * defined in the given TreeTypeMap `ttmap`. - * Cross symbol references are brought over from originals to copies. - * Do not copy any symbols if all attributes of all symbols stay the same. - */ - def mapSymbols(originals: List[Symbol], ttmap: TreeTypeMap, mapAlways: Boolean = false): List[Symbol] = - if (originals.forall(sym => - (ttmap.mapType(sym.info) eq sym.info) && - !(ttmap.oldOwners contains sym.owner)) && !mapAlways) - originals - else { - val copies: List[Symbol] = for (original <- originals) yield - original match { - case original: ClassSymbol => - newNakedClassSymbol(original.coord, original.assocFile) - case _ => - newNakedSymbol[original.ThisName](original.coord) - } - val ttmap1 = ttmap.withSubstitution(originals, copies) - originals.lazyZip(copies) foreach { (original, copy) => - val odenot = original.denot - val oinfo = original.info match { - case ClassInfo(pre, _, parents, decls, selfInfo) => - assert(original.isClass) - ClassInfo(pre, copy.asClass, parents, decls.cloneScope, selfInfo) - case oinfo => oinfo - } - - val completer = new LazyType { - def complete(denot: SymDenotation)(using Context): Unit = { - denot.info = oinfo // needed as otherwise we won't be able to go from Sym -> parents & etc - // Note that this is a hack, but hack commonly used in Dotty - // The same thing is done by other completers all the time - denot.info = ttmap1.mapType(oinfo) - denot.annotations = odenot.annotations.mapConserve(ttmap1.apply) - } - } - - copy.denot = odenot.copySymDenotation( - symbol = copy, - owner = ttmap1.mapOwner(odenot.owner), - initFlags = odenot.flags &~ Touched, - info = completer, - privateWithin = ttmap1.mapOwner(odenot.privateWithin), // since this refers to outer symbols, need not include copies (from->to) in ownermap here. - annotations = odenot.annotations) - copy.registeredCompanion = - copy.registeredCompanion.subst(originals, copies) - } - - copies.foreach(_.ensureCompleted()) // avoid memory leak - copies - } - -// ----- Locating predefined symbols ---------------------------------------- - - def requiredPackage(path: PreName): TermSymbol = { - val name = path.toTermName - base.staticRef(name, isPackage = true).requiredSymbol("package", name)(_.is(Package)).asTerm - } - - def requiredPackageRef(path: PreName): TermRef = requiredPackage(path).termRef - - def requiredClass(path: PreName): ClassSymbol = { - val name = path.toTypeName - base.staticRef(name).requiredSymbol("class", name)(_.isClass) match { - case cls: ClassSymbol => cls - case sym => defn.AnyClass - } - } - - def requiredClassRef(path: PreName): TypeRef = requiredClass(path).typeRef - - /** Get ClassSymbol if class is either defined in current compilation run - * or present on classpath. - * Returns NoSymbol otherwise. */ - def getClassIfDefined(path: PreName): Symbol = { - val name = path.toTypeName - base.staticRef(name, generateStubs = false) - .requiredSymbol("class", name, generateStubs = false)(_.isClass) - } - - /** Get a List of ClassSymbols which are either defined in current compilation - * run or present on classpath. - */ - def getClassesIfDefined(paths: List[PreName]): List[ClassSymbol] = - paths.map(getClassIfDefined).filter(_.exists).map(_.asInstanceOf[ClassSymbol]) - - /** Get ClassSymbol if package is either defined in current compilation run - * or present on classpath. - * Returns NoSymbol otherwise. */ - def getPackageClassIfDefined(path: PreName): Symbol = { - val name = path.toTypeName - base.staticRef(name, isPackage = true, generateStubs = false) - .requiredSymbol("package", name, generateStubs = false)(_ is PackageClass) - } - - def requiredModule(path: PreName): TermSymbol = { - val name = path.toTermName - base.staticRef(name).requiredSymbol("object", name)(_.is(Module)).asTerm - } - - def requiredModuleRef(path: PreName): TermRef = requiredModule(path).termRef - - def requiredMethod(path: PreName): TermSymbol = { - val name = path.toTermName - base.staticRef(name).requiredSymbol("method", name)(_.is(Method)).asTerm - } - - def requiredMethodRef(path: PreName): TermRef = requiredMethod(path).termRef -} - object Symbols { implicit def eqSymbol: Eql[Symbol, Symbol] = Eql.derived @@ -486,13 +102,13 @@ object Symbols { final def denot(using Context): SymDenotation = { util.Stats.record("Symbol.denot") val lastd = lastDenot - if (checkedPeriod == ctx.period) lastd + if (checkedPeriod == currentPeriod) lastd else computeDenot(lastd) } private def computeDenot(lastd: SymDenotation)(using Context): SymDenotation = { util.Stats.record("Symbol.computeDenot") - val now = ctx.period + val now = currentPeriod checkedPeriod = now if (lastd.validFor contains now) lastd else recomputeDenot(lastd) } @@ -518,14 +134,14 @@ object Symbols { /** Does this symbol come from a currently compiled source file? */ final def isDefinedInCurrentRun(using Context): Boolean = - span.exists && defRunId == ctx.runId && { + span.exists && defRunId == currentRunId && { val file = associatedFile file != null && ctx.run.files.contains(file) } /** Is symbol valid in current run? */ final def isValidInCurrentRun(using Context): Boolean = - (lastDenot.validFor.runId == ctx.runId || ctx.stillValid(lastDenot)) && + (lastDenot.validFor.runId == currentRunId || stillValid(lastDenot)) && (lastDenot.symbol eq this) // the last condition is needed because under ctx.staleOK overwritten // members keep denotations pointing to the new symbol, so the validity @@ -533,9 +149,9 @@ object Symbols { // valid. If the option would be removed, the check would be no longer needed. final def isTerm(using Context): Boolean = - (if (defRunId == ctx.runId) lastDenot else denot).isTerm + (if (defRunId == currentRunId) lastDenot else denot).isTerm final def isType(using Context): Boolean = - (if (defRunId == ctx.runId) lastDenot else denot).isType + (if (defRunId == currentRunId) lastDenot else denot).isType final def asTerm(using Context): TermSymbol = { assert(isTerm, s"asTerm called on not-a-Term $this" ); asInstanceOf[TermSymbol] @@ -588,7 +204,7 @@ object Symbols { * @pre Symbol is a class member */ def enteredAfter(phase: DenotTransformer)(using Context): this.type = - if ctx.phaseId != phase.next.id then + if currentPhaseId != phase.next.id then atPhase(phase.next)(enteredAfter(phase)) else this.owner match { case owner: ClassSymbol => @@ -613,7 +229,7 @@ object Symbols { * @pre Symbol is a class member */ def dropAfter(phase: DenotTransformer)(using Context): Unit = - if ctx.phaseId != phase.next.id then + if currentPhaseId != phase.next.id then atPhase(phase.next)(dropAfter(phase)) else { assert (!this.owner.is(Package)) @@ -675,258 +291,652 @@ object Symbols { } } - /** A symbol related to `sym` that is defined in source code. - * - * @see enclosingSourceSymbols - */ - @annotation.tailrec final def sourceSymbol(using Context): Symbol = - if (!denot.exists) - this - else if (denot.is(ModuleVal)) - this.moduleClass.sourceSymbol // The module val always has a zero-extent position - else if (denot.is(Synthetic)) { - val linked = denot.linkedClass - if (linked.exists && !linked.is(Synthetic)) - linked - else - denot.owner.sourceSymbol - } - else if (denot.isPrimaryConstructor) - denot.owner.sourceSymbol - else this + /** A symbol related to `sym` that is defined in source code. + * + * @see enclosingSourceSymbols + */ + @annotation.tailrec final def sourceSymbol(using Context): Symbol = + if (!denot.exists) + this + else if (denot.is(ModuleVal)) + this.moduleClass.sourceSymbol // The module val always has a zero-extent position + else if (denot.is(Synthetic)) { + val linked = denot.linkedClass + if (linked.exists && !linked.is(Synthetic)) + linked + else + denot.owner.sourceSymbol + } + else if (denot.isPrimaryConstructor) + denot.owner.sourceSymbol + else this + + /** The position of this symbol, or NoSpan if the symbol was not loaded + * from source or from TASTY. This is always a zero-extent position. + */ + final def span: Span = if (coord.isSpan) coord.toSpan else NoSpan + + final def sourcePos(using Context): SourcePosition = { + val src = source + (if (src.exists) src else ctx.source).atSpan(span) + } + + // ParamInfo types and methods + def isTypeParam(using Context): Boolean = denot.is(TypeParam) + def paramName(using Context): ThisName = name.asInstanceOf[ThisName] + def paramInfo(using Context): Type = denot.info + def paramInfoAsSeenFrom(pre: Type)(using Context): Type = pre.memberInfo(this) + def paramInfoOrCompleter(using Context): Type = denot.infoOrCompleter + def paramVariance(using Context): Variance = denot.variance + def paramRef(using Context): TypeRef = denot.typeRef + +// -------- Printing -------------------------------------------------------- + + /** The prefix string to be used when displaying this symbol without denotation */ + protected def prefixString: String = "Symbol" + + override def toString: String = + if (lastDenot == null) s"Naked$prefixString#$id" + else lastDenot.toString// + "#" + id // !!! DEBUG + + def toText(printer: Printer): Text = printer.toText(this) + + def showLocated(using Context): String = ctx.printer.locatedText(this).show + def showExtendedLocation(using Context): String = ctx.printer.extendedLocationText(this).show + def showDcl(using Context): String = ctx.printer.dclText(this).show + def showKind(using Context): String = ctx.printer.kindString(this) + def showName(using Context): String = ctx.printer.nameString(this) + def showFullName(using Context): String = ctx.printer.fullNameString(this) + + override def hashCode(): Int = id // for debugging. + } + + type TermSymbol = Symbol { type ThisName = TermName } + type TypeSymbol = Symbol { type ThisName = TypeName } + + class ClassSymbol private[Symbols] (coord: Coord, val assocFile: AbstractFile, id: Int) + extends Symbol(coord, id) { + + type ThisName = TypeName + + type TreeOrProvider = tpd.TreeProvider | tpd.Tree + + private var myTree: TreeOrProvider = tpd.EmptyTree + + /** If this is a top-level class and `-Yretain-trees` (or `-from-tasty`) is set. + * Returns the TypeDef tree (possibly wrapped inside PackageDefs) for this class, otherwise EmptyTree. + * This will force the info of the class. + */ + def rootTree(using Context): Tree = rootTreeContaining("") + + /** Same as `tree` but load tree only if `id == ""` or the tree might contain `id`. + * For Tasty trees this means consulting whether the name table defines `id`. + * For already loaded trees, we maintain the referenced ids in an attachment. + */ + def rootTreeContaining(id: String)(using Context): Tree = { + denot.infoOrCompleter match { + case _: NoCompleter => + case _ => denot.ensureCompleted() + } + myTree match { + case fn: TreeProvider => + if (id.isEmpty || fn.mightContain(id)) { + val tree = fn.tree + myTree = tree + tree + } + else tpd.EmptyTree + case tree: Tree @ unchecked => + if (id.isEmpty || mightContain(tree, id)) tree else tpd.EmptyTree + } + } + + def rootTreeOrProvider: TreeOrProvider = myTree + + private[dotc] def rootTreeOrProvider_=(t: TreeOrProvider)(using Context): Unit = + myTree = t + + private def mightContain(tree: Tree, id: String)(using Context): Boolean = { + val ids = tree.getAttachment(Ids) match { + case Some(ids) => ids + case None => + val idSet = mutable.SortedSet[String]() + tree.foreachSubTree { + case tree: tpd.NameTree if tree.name.toTermName.isInstanceOf[SimpleName] => + idSet += tree.name.toString + case _ => + } + val ids = idSet.toArray + tree.putAttachment(Ids, ids) + ids + } + ids.binarySearch(id) >= 0 + } + + /** The source or class file from which this class was generated, null if not applicable. */ + override def associatedFile(using Context): AbstractFile = + if (assocFile != null || this.owner.is(PackageClass) || this.isEffectiveRoot) assocFile + else super.associatedFile + + private var mySource: SourceFile = NoSource + + final def sourceOfClass(using Context): SourceFile = { + if (!mySource.exists && !denot.is(Package)) + // this allows sources to be added in annotations after `sourceOfClass` is first called + mySource = { + val file = associatedFile + if (file != null && file.extension != "class") ctx.getSource(file) + else { + def sourceFromTopLevel(using Context) = + denot.topLevelClass.unforcedAnnotation(defn.SourceFileAnnot) match { + case Some(sourceAnnot) => sourceAnnot.argumentConstant(0) match { + case Some(Constant(path: String)) => ctx.getSource(path) + case none => NoSource + } + case none => NoSource + } + atPhaseNoLater(flattenPhase)(sourceFromTopLevel) + } + } + mySource + } + + final def classDenot(using Context): ClassDenotation = + denot.asInstanceOf[ClassDenotation] + + override protected def prefixString: String = "ClassSymbol" + } + + @sharable object NoSymbol extends Symbol(NoCoord, 0) { + override def associatedFile(using Context): AbstractFile = NoSource.file + override def recomputeDenot(lastd: SymDenotation)(using Context): SymDenotation = NoDenotation + } + + NoDenotation // force it in order to set `denot` field of NoSymbol + + implicit class Copier[N <: Name](sym: Symbol { type ThisName = N })(using Context) { + /** Copy a symbol, overriding selective fields. + * Note that `coord` and `associatedFile` will be set from the fields in `owner`, not + * the fields in `sym`. + */ + def copy( + owner: Symbol = sym.owner, + name: N = sym.name, + flags: FlagSet = sym.flags, + info: Type = sym.info, + privateWithin: Symbol = sym.privateWithin, + coord: Coord = NoCoord, // Can be `= owner.coord` once we boostrap + associatedFile: AbstractFile = null // Can be `= owner.associatedFile` once we boostrap + ): Symbol = { + val coord1 = if (coord == NoCoord) owner.coord else coord + val associatedFile1 = if (associatedFile == null) owner.associatedFile else associatedFile + + if (sym.isClass) + newClassSymbol(owner, name.asTypeName, flags, _ => info, privateWithin, coord1, associatedFile1) + else + newSymbol(owner, name, flags, info, privateWithin, coord1) + } + } + + /** Makes all denotation operations available on symbols */ + implicit def toDenot(sym: Symbol)(using Context): SymDenotation = sym.denot + + /** Makes all class denotation operations available on class symbols */ + implicit def toClassDenot(cls: ClassSymbol)(using Context): ClassDenotation = cls.classDenot + + /** The Definitions object */ + def defn(using Context): Definitions = ctx.definitions + + /** The current class */ + def currentClass(using Context): ClassSymbol = ctx.owner.enclosingClass.asClass + + /* Mutable map from symbols any T */ + class MutableSymbolMap[T](private[Symbols] val value: java.util.IdentityHashMap[Symbol, T]) extends AnyVal { + + def apply(sym: Symbol): T = value.get(sym) + + def get(sym: Symbol): Option[T] = Option(value.get(sym)) + + def getOrElse[U >: T](sym: Symbol, default: => U): U = { + val v = value.get(sym) + if (v != null) v else default + } + + def getOrElseUpdate(sym: Symbol, op: => T): T = { + val v = value.get(sym) + if (v != null) v + else { + val v = op + assert(v != null) + value.put(sym, v) + v + } + } + + def update(sym: Symbol, x: T): Unit = { + assert(x != null) + value.put(sym, x) + } + def put(sym: Symbol, x: T): T = { + assert(x != null) + value.put(sym, x) + } - /** The position of this symbol, or NoSpan if the symbol was not loaded - * from source or from TASTY. This is always a zero-extent position. - */ - final def span: Span = if (coord.isSpan) coord.toSpan else NoSpan + def -=(sym: Symbol): Unit = value.remove(sym) + def remove(sym: Symbol): Option[T] = Option(value.remove(sym)) - final def sourcePos(using Context): SourcePosition = { - val src = source - (if (src.exists) src else ctx.source).atSpan(span) - } + def contains(sym: Symbol): Boolean = value.containsKey(sym) - // ParamInfo types and methods - def isTypeParam(using Context): Boolean = denot.is(TypeParam) - def paramName(using Context): ThisName = name.asInstanceOf[ThisName] - def paramInfo(using Context): Type = denot.info - def paramInfoAsSeenFrom(pre: Type)(using Context): Type = pre.memberInfo(this) - def paramInfoOrCompleter(using Context): Type = denot.infoOrCompleter - def paramVariance(using Context): Variance = denot.variance - def paramRef(using Context): TypeRef = denot.typeRef + def isEmpty: Boolean = value.isEmpty -// -------- Printing -------------------------------------------------------- + def clear(): Unit = value.clear() - /** The prefix string to be used when displaying this symbol without denotation */ - protected def prefixString: String = "Symbol" + def filter(p: ((Symbol, T)) => Boolean): Map[Symbol, T] = + value.asScala.toMap.filter(p) - override def toString: String = - if (lastDenot == null) s"Naked$prefixString#$id" - else lastDenot.toString// + "#" + id // !!! DEBUG + def iterator: Iterator[(Symbol, T)] = value.asScala.iterator - def toText(printer: Printer): Text = printer.toText(this) + def keysIterator: Iterator[Symbol] = value.keySet().asScala.iterator - def showLocated(using Context): String = ctx.printer.locatedText(this).show - def showExtendedLocation(using Context): String = ctx.printer.extendedLocationText(this).show - def showDcl(using Context): String = ctx.printer.dclText(this).show - def showKind(using Context): String = ctx.printer.kindString(this) - def showName(using Context): String = ctx.printer.nameString(this) - def showFullName(using Context): String = ctx.printer.fullNameString(this) + def toMap: Map[Symbol, T] = value.asScala.toMap - override def hashCode(): Int = id // for debugging. + override def toString: String = value.asScala.toString() } - type TermSymbol = Symbol { type ThisName = TermName } - type TypeSymbol = Symbol { type ThisName = TypeName } + inline def newMutableSymbolMap[T]: MutableSymbolMap[T] = + new MutableSymbolMap(new java.util.IdentityHashMap[Symbol, T]()) - class ClassSymbol private[Symbols] (coord: Coord, val assocFile: AbstractFile, id: Int) - extends Symbol(coord, id) { +// ---- Factory methods for symbol creation ---------------------- +// +// All symbol creations should be done via the next two methods. - type ThisName = TypeName + /** Create a symbol without a denotation. + * Note this uses a cast instead of a direct type refinement because + * it's debug-friendlier not to create an anonymous class here. + */ + def newNakedSymbol[N <: Name](coord: Coord = NoCoord)(using Context): Symbol { type ThisName = N } = + new Symbol(coord, ctx.base.nextSymId).asInstanceOf[Symbol { type ThisName = N }] - type TreeOrProvider = tpd.TreeProvider | tpd.Tree + /** Create a class symbol without a denotation. */ + def newNakedClassSymbol(coord: Coord = NoCoord, assocFile: AbstractFile = null)(using Context): ClassSymbol = + new ClassSymbol(coord, assocFile, ctx.base.nextSymId) - private var myTree: TreeOrProvider = tpd.EmptyTree +// ---- Symbol creation methods ---------------------------------- - /** If this is a top-level class and `-Yretain-trees` (or `-from-tasty`) is set. - * Returns the TypeDef tree (possibly wrapped inside PackageDefs) for this class, otherwise EmptyTree. - * This will force the info of the class. - */ - def rootTree(using Context): Tree = rootTreeContaining("") + /** Create a symbol from its fields (info may be lazy) */ + def newSymbol[N <: Name]( + owner: Symbol, + name: N, + flags: FlagSet, + info: Type, + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord)(using Context): Symbol { type ThisName = N } = { + val sym = newNakedSymbol[N](coord) + val denot = SymDenotation(sym, owner, name, flags, info, privateWithin) + sym.denot = denot + sym + } - /** Same as `tree` but load tree only if `id == ""` or the tree might contain `id`. - * For Tasty trees this means consulting whether the name table defines `id`. - * For already loaded trees, we maintain the referenced ids in an attachment. - */ - def rootTreeContaining(id: String)(using Context): Tree = { - denot.infoOrCompleter match { - case _: NoCompleter => - case _ => denot.ensureCompleted() - } - myTree match { - case fn: TreeProvider => - if (id.isEmpty || fn.mightContain(id)) { - val tree = fn.tree - myTree = tree - tree - } - else tpd.EmptyTree - case tree: Tree @ unchecked => - if (id.isEmpty || mightContain(tree, id)) tree else tpd.EmptyTree + /** Create a class symbol from a function producing its denotation */ + def newClassSymbolDenoting(denotFn: ClassSymbol => SymDenotation, + coord: Coord = NoCoord, assocFile: AbstractFile = null)(using Context): ClassSymbol = { + val cls = newNakedClassSymbol(coord, assocFile) + cls.denot = denotFn(cls) + cls + } + + /** Create a class symbol from its non-info fields and a function + * producing its info (the produced info may be lazy). + */ + def newClassSymbol( + owner: Symbol, + name: TypeName, + flags: FlagSet, + infoFn: ClassSymbol => Type, + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord, + assocFile: AbstractFile = null)(using Context): ClassSymbol + = { + val cls = newNakedClassSymbol(coord, assocFile) + val denot = SymDenotation(cls, owner, name, flags, infoFn(cls), privateWithin) + cls.denot = denot + cls + } + + /** Create a class symbol from its non-info fields and the fields of its info. */ + def newCompleteClassSymbol( + owner: Symbol, + name: TypeName, + flags: FlagSet, + parents: List[TypeRef], + decls: Scope = newScope, + selfInfo: Type = NoType, + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord, + assocFile: AbstractFile = null)(using Context): ClassSymbol = + newClassSymbol( + owner, name, flags, + ClassInfo(owner.thisType, _, parents, decls, selfInfo), + privateWithin, coord, assocFile) + + /** Same as `newCompleteClassSymbol` except that `parents` can be a list of arbitrary + * types which get normalized into type refs and parameter bindings. + */ + def newNormalizedClassSymbol( + owner: Symbol, + name: TypeName, + flags: FlagSet, + parentTypes: List[Type], + decls: Scope = newScope, + selfInfo: Type = NoType, + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord, + assocFile: AbstractFile = null)(using Context): ClassSymbol = { + def completer = new LazyType { + def complete(denot: SymDenotation)(using Context): Unit = { + val cls = denot.asClass.classSymbol + val decls = newScope + denot.info = ClassInfo(owner.thisType, cls, parentTypes.map(_.dealias), decls) } } + newClassSymbol(owner, name, flags, completer, privateWithin, coord, assocFile) + } - def rootTreeOrProvider: TreeOrProvider = myTree + def newRefinedClassSymbol(coord: Coord = NoCoord)(using Context): ClassSymbol = + newCompleteClassSymbol(ctx.owner, tpnme.REFINE_CLASS, NonMember, parents = Nil, coord = coord) - private[dotc] def rootTreeOrProvider_=(t: TreeOrProvider)(using Context): Unit = - myTree = t + /** Create a module symbol with associated module class + * from its non-info fields and a function producing the info + * of the module class (this info may be lazy). + */ + def newModuleSymbol( + owner: Symbol, + name: TermName, + modFlags: FlagSet, + clsFlags: FlagSet, + infoFn: (TermSymbol, ClassSymbol) => Type, // typically a ModuleClassCompleterWithDecls + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord, + assocFile: AbstractFile = null)(using Context): TermSymbol + = { + val base = owner.thisType + val module = newNakedSymbol[TermName](coord) + val modcls = newNakedClassSymbol(coord, assocFile) + val modclsFlags = clsFlags | ModuleClassCreationFlags + val modclsName = name.toTypeName.adjustIfModuleClass(modclsFlags) + val cdenot = SymDenotation( + modcls, owner, modclsName, modclsFlags, + infoFn(module, modcls), privateWithin) + val mdenot = SymDenotation( + module, owner, name, modFlags | ModuleValCreationFlags, + if (cdenot.isCompleted) TypeRef(owner.thisType, modcls) + else new ModuleCompleter(modcls)) + module.denot = mdenot + modcls.denot = cdenot + module + } + + /** Create a module symbol with associated module class + * from its non-info fields and the fields of the module class info. + * @param flags The combined flags of the module and the module class + * These are masked with RetainedModuleValFlags/RetainedModuleClassFlags. + */ + def newCompleteModuleSymbol( + owner: Symbol, + name: TermName, + modFlags: FlagSet, + clsFlags: FlagSet, + parents: List[TypeRef], + decls: Scope, + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord, + assocFile: AbstractFile = null)(using Context): TermSymbol = + newModuleSymbol( + owner, name, modFlags, clsFlags, + (module, modcls) => ClassInfo( + owner.thisType, modcls, parents, decls, TermRef(owner.thisType, module)), + privateWithin, coord, assocFile) + + /** Create a package symbol with associated package class + * from its non-info fields and a lazy type for loading the package's members. + */ + def newPackageSymbol( + owner: Symbol, + name: TermName, + infoFn: (TermSymbol, ClassSymbol) => LazyType)(using Context): TermSymbol = + newModuleSymbol(owner, name, PackageCreationFlags, PackageCreationFlags, infoFn) + /** Create a package symbol with associated package class + * from its non-info fields its member scope. + */ + def newCompletePackageSymbol( + owner: Symbol, + name: TermName, + modFlags: FlagSet = EmptyFlags, + clsFlags: FlagSet = EmptyFlags, + decls: Scope = newScope)(using Context): TermSymbol = + newCompleteModuleSymbol( + owner, name, + modFlags | PackageCreationFlags, clsFlags | PackageCreationFlags, + Nil, decls) + + /** Define a new symbol associated with a Bind or pattern wildcard and, by default, make it gadt narrowable. */ + def newPatternBoundSymbol( + name: Name, + info: Type, + span: Span, + addToGadt: Boolean = true, + flags: FlagSet = EmptyFlags)(using Context): Symbol = { + val sym = newSymbol(ctx.owner, name, Case | flags, info, coord = span) + if (addToGadt && name.isTypeName) ctx.gadt.addToConstraint(sym) + sym + } - private def mightContain(tree: Tree, id: String)(using Context): Boolean = { - val ids = tree.getAttachment(Ids) match { - case Some(ids) => ids - case None => - val idSet = mutable.SortedSet[String]() - tree.foreachSubTree { - case tree: tpd.NameTree if tree.name.toTermName.isInstanceOf[SimpleName] => - idSet += tree.name.toString - case _ => - } - val ids = idSet.toArray - tree.putAttachment(Ids, ids) - ids - } - ids.binarySearch(id) >= 0 + /** Create a stub symbol that will issue a missing reference error + * when attempted to be completed. + */ + def newStubSymbol(owner: Symbol, name: Name, file: AbstractFile = null)(using Context): Symbol = { + def stubCompleter = new StubInfo() + val normalizedOwner = if (owner.is(ModuleVal)) owner.moduleClass else owner + typr.println(s"creating stub for ${name.show}, owner = ${normalizedOwner.denot.debugString}, file = $file") + typr.println(s"decls = ${normalizedOwner.unforcedDecls.toList.map(_.debugString).mkString("\n ")}") // !!! DEBUG + //if (base.settings.debug.value) throw new Error() + val stub = name match { + case name: TermName => + newModuleSymbol(normalizedOwner, name, EmptyFlags, EmptyFlags, stubCompleter, assocFile = file) + case name: TypeName => + newClassSymbol(normalizedOwner, name, EmptyFlags, stubCompleter, assocFile = file) } + stub + } - /** The source or class file from which this class was generated, null if not applicable. */ - override def associatedFile(using Context): AbstractFile = - if (assocFile != null || this.owner.is(PackageClass) || this.isEffectiveRoot) assocFile - else super.associatedFile + /** Create the local template dummy of given class `cls`. + * In a template + * + * trait T { val fld: Int; { val x: int = 2 }; val fld2 = { val y = 2; y }} + * + * the owner of `x` is the local dummy of the template. The owner of the local + * dummy is then the class of the template itself. By contrast, the owner of `y` + * would be `fld2`. There is a single local dummy per template. + */ + def newLocalDummy(cls: Symbol, coord: Coord = NoCoord)(using Context): TermSymbol = + newSymbol(cls, nme.localDummyName(cls), NonMember, NoType) - private var mySource: SourceFile = NoSource + /** Create an import symbol pointing back to given qualifier `expr`. */ + def newImportSymbol(owner: Symbol, expr: Tree, coord: Coord = NoCoord)(using Context): TermSymbol = + newImportSymbol(owner, ImportType(expr), coord = coord) - final def sourceOfClass(using Context): SourceFile = { - if (!mySource.exists && !denot.is(Package)) - // this allows sources to be added in annotations after `sourceOfClass` is first called - mySource = { - val file = associatedFile - if (file != null && file.extension != "class") ctx.getSource(file) - else { - def sourceFromTopLevel(using Context) = - denot.topLevelClass.unforcedAnnotation(defn.SourceFileAnnot) match { - case Some(sourceAnnot) => sourceAnnot.argumentConstant(0) match { - case Some(Constant(path: String)) => ctx.getSource(path) - case none => NoSource - } - case none => NoSource - } - sourceFromTopLevel(using ctx.withPhaseNoLater(flattenPhase)) - } - } - mySource - } + /** Create an import symbol with given `info`. */ + def newImportSymbol(owner: Symbol, info: Type, coord: Coord)(using Context): TermSymbol = + newSymbol(owner, nme.IMPORT, Synthetic | NonMember, info, coord = coord) - final def classDenot(using Context): ClassDenotation = - denot.asInstanceOf[ClassDenotation] + /** Create a class constructor symbol for given class `cls`. */ + def newConstructor( + cls: ClassSymbol, + flags: FlagSet, + paramNames: List[TermName], + paramTypes: List[Type], + privateWithin: Symbol = NoSymbol, + coord: Coord = NoCoord)(using Context): TermSymbol = + newSymbol(cls, nme.CONSTRUCTOR, flags | Method, MethodType(paramNames, paramTypes, cls.typeRef), privateWithin, coord) - override protected def prefixString: String = "ClassSymbol" - } + /** Create an empty default constructor symbol for given class `cls`. */ + def newDefaultConstructor(cls: ClassSymbol)(using Context): TermSymbol = + newConstructor(cls, EmptyFlags, Nil, Nil) - @sharable object NoSymbol extends Symbol(NoCoord, 0) { - override def associatedFile(using Context): AbstractFile = NoSource.file - override def recomputeDenot(lastd: SymDenotation)(using Context): SymDenotation = NoDenotation - } + def newLazyImplicit(info: Type, coord: Coord = NoCoord)(using Context): TermSymbol = + newSymbol(ctx.owner, LazyImplicitName.fresh(), EmptyFlags, info, coord = coord) - NoDenotation // force it in order to set `denot` field of NoSymbol + /** Create a symbol representing a selftype declaration for class `cls`. */ + def newSelfSym( + cls: ClassSymbol, + name: TermName = nme.WILDCARD, + selfInfo: Type = NoType)(using Context): TermSymbol = + newSymbol(cls, name, SelfSymFlags, selfInfo orElse cls.classInfo.selfType, coord = cls.coord) - implicit class Copier[N <: Name](sym: Symbol { type ThisName = N })(using Context) { - /** Copy a symbol, overriding selective fields. - * Note that `coord` and `associatedFile` will be set from the fields in `owner`, not - * the fields in `sym`. - */ - def copy( - owner: Symbol = sym.owner, - name: N = sym.name, - flags: FlagSet = sym.flags, - info: Type = sym.info, - privateWithin: Symbol = sym.privateWithin, - coord: Coord = NoCoord, // Can be `= owner.coord` once we boostrap - associatedFile: AbstractFile = null // Can be `= owner.associatedFile` once we boostrap - ): Symbol = { - val coord1 = if (coord == NoCoord) owner.coord else coord - val associatedFile1 = if (associatedFile == null) owner.associatedFile else associatedFile + /** Create new type parameters with given owner, names, and flags. + * @param boundsFn A function that, given type refs to the newly created + * parameters returns a list of their bounds. + */ + def newTypeParams( + owner: Symbol, + names: List[TypeName], + flags: FlagSet, + boundsFn: List[TypeRef] => List[Type])(using Context): List[TypeSymbol] = { - if (sym.isClass) - ctx.newClassSymbol(owner, name.asTypeName, flags, _ => info, privateWithin, coord1, associatedFile1) - else - ctx.newSymbol(owner, name, flags, info, privateWithin, coord1) + val tparamBuf = new mutable.ListBuffer[TypeSymbol] + val trefBuf = new mutable.ListBuffer[TypeRef] + for (name <- names) { + val tparam = newSymbol( + owner, name, flags | owner.typeParamCreationFlags, NoType, coord = owner.coord) + tparamBuf += tparam + trefBuf += TypeRef(owner.thisType, tparam) } + val tparams = tparamBuf.toList + val bounds = boundsFn(trefBuf.toList) + for (tparam, bound) <- tparams.lazyZip(bounds) do + tparam.info = bound + tparams } - /** Makes all denotation operations available on symbols */ - implicit def toDenot(sym: Symbol)(using Context): SymDenotation = sym.denot - - /** Makes all class denotation operations available on class symbols */ - implicit def toClassDenot(cls: ClassSymbol)(using Context): ClassDenotation = cls.classDenot - - /** The Definitions object */ - def defn(using Context): Definitions = ctx.definitions + /** Create a new skolem symbol. This is not the same as SkolemType, even though the + * motivation (create a singleton referencing to a type) is similar. + */ + def newSkolem(tp: Type)(using Context): TermSymbol = + newSymbol(defn.RootClass, nme.SKOLEM, SyntheticArtifact | NonMember | Permanent, tp) - /** The current class */ - def currentClass(using Context): ClassSymbol = ctx.owner.enclosingClass.asClass + def newErrorSymbol(owner: Symbol, name: Name, msg: Message)(using Context): Symbol = { + val errType = ErrorType(msg) + newSymbol(owner, name, SyntheticArtifact, + if (name.isTypeName) TypeAlias(errType) else errType) + } - /* Mutable map from symbols any T */ - class MutableSymbolMap[T](private[Symbols] val value: java.util.IdentityHashMap[Symbol, T]) extends AnyVal { + /** Map given symbols, subjecting their attributes to the mappings + * defined in the given TreeTypeMap `ttmap`. + * Cross symbol references are brought over from originals to copies. + * Do not copy any symbols if all attributes of all symbols stay the same. + */ + def mapSymbols(originals: List[Symbol], ttmap: TreeTypeMap, mapAlways: Boolean = false)(using Context): List[Symbol] = + if (originals.forall(sym => + (ttmap.mapType(sym.info) eq sym.info) && + !(ttmap.oldOwners contains sym.owner)) && !mapAlways) + originals + else { + val copies: List[Symbol] = for (original <- originals) yield + original match { + case original: ClassSymbol => + newNakedClassSymbol(original.coord, original.assocFile) + case _ => + newNakedSymbol[original.ThisName](original.coord) + } + val ttmap1 = ttmap.withSubstitution(originals, copies) + originals.lazyZip(copies) foreach { (original, copy) => + val odenot = original.denot + val oinfo = original.info match { + case ClassInfo(pre, _, parents, decls, selfInfo) => + assert(original.isClass) + ClassInfo(pre, copy.asClass, parents, decls.cloneScope, selfInfo) + case oinfo => oinfo + } - def apply(sym: Symbol): T = value.get(sym) + val completer = new LazyType { + def complete(denot: SymDenotation)(using Context): Unit = { + denot.info = oinfo // needed as otherwise we won't be able to go from Sym -> parents & etc + // Note that this is a hack, but hack commonly used in Dotty + // The same thing is done by other completers all the time + denot.info = ttmap1.mapType(oinfo) + denot.annotations = odenot.annotations.mapConserve(ttmap1.apply) + } + } - def get(sym: Symbol): Option[T] = Option(value.get(sym)) + copy.denot = odenot.copySymDenotation( + symbol = copy, + owner = ttmap1.mapOwner(odenot.owner), + initFlags = odenot.flags &~ Touched, + info = completer, + privateWithin = ttmap1.mapOwner(odenot.privateWithin), // since this refers to outer symbols, need not include copies (from->to) in ownermap here. + annotations = odenot.annotations) + copy.registeredCompanion = + copy.registeredCompanion.subst(originals, copies) + } - def getOrElse[U >: T](sym: Symbol, default: => U): U = { - val v = value.get(sym) - if (v != null) v else default + copies.foreach(_.ensureCompleted()) // avoid memory leak + copies } - def getOrElseUpdate(sym: Symbol, op: => T): T = { - val v = value.get(sym) - if (v != null) v - else { - val v = op - assert(v != null) - value.put(sym, v) - v - } - } +// ----- Locating predefined symbols ---------------------------------------- - def update(sym: Symbol, x: T): Unit = { - assert(x != null) - value.put(sym, x) - } - def put(sym: Symbol, x: T): T = { - assert(x != null) - value.put(sym, x) - } + def requiredPackage(path: PreName)(using Context): TermSymbol = { + val name = path.toTermName + staticRef(name, isPackage = true).requiredSymbol("package", name)(_.is(Package)).asTerm + } - def -=(sym: Symbol): Unit = value.remove(sym) - def remove(sym: Symbol): Option[T] = Option(value.remove(sym)) + def requiredPackageRef(path: PreName)(using Context): TermRef = requiredPackage(path).termRef - def contains(sym: Symbol): Boolean = value.containsKey(sym) + def requiredClass(path: PreName)(using Context): ClassSymbol = { + val name = path.toTypeName + staticRef(name).requiredSymbol("class", name)(_.isClass) match { + case cls: ClassSymbol => cls + case sym => defn.AnyClass + } + } - def isEmpty: Boolean = value.isEmpty + def requiredClassRef(path: PreName)(using Context): TypeRef = requiredClass(path).typeRef - def clear(): Unit = value.clear() + /** Get ClassSymbol if class is either defined in current compilation run + * or present on classpath. + * Returns NoSymbol otherwise. */ + def getClassIfDefined(path: PreName)(using Context): Symbol = { + val name = path.toTypeName + staticRef(name, generateStubs = false) + .requiredSymbol("class", name, generateStubs = false)(_.isClass) + } - def filter(p: ((Symbol, T)) => Boolean): Map[Symbol, T] = - value.asScala.toMap.filter(p) + /** Get a List of ClassSymbols which are either defined in current compilation + * run or present on classpath. + */ + def getClassesIfDefined(paths: List[PreName])(using Context): List[ClassSymbol] = + paths.map(getClassIfDefined).filter(_.exists).map(_.asInstanceOf[ClassSymbol]) - def iterator: Iterator[(Symbol, T)] = value.asScala.iterator + /** Get ClassSymbol if package is either defined in current compilation run + * or present on classpath. + * Returns NoSymbol otherwise. */ + def getPackageClassIfDefined(path: PreName)(using Context): Symbol = { + val name = path.toTypeName + staticRef(name, isPackage = true, generateStubs = false) + .requiredSymbol("package", name, generateStubs = false)(_ is PackageClass) + } - def keysIterator: Iterator[Symbol] = value.keySet().asScala.iterator + def requiredModule(path: PreName)(using Context): TermSymbol = { + val name = path.toTermName + staticRef(name).requiredSymbol("object", name)(_.is(Module)).asTerm + } - def toMap: Map[Symbol, T] = value.asScala.toMap + def requiredModuleRef(path: PreName)(using Context): TermRef = requiredModule(path).termRef - override def toString: String = value.asScala.toString() + def requiredMethod(path: PreName)(using Context): TermSymbol = { + val name = path.toTermName + staticRef(name).requiredSymbol("method", name)(_.is(Method)).asTerm } - inline def newMutableSymbolMap[T]: MutableSymbolMap[T] = - new MutableSymbolMap(new java.util.IdentityHashMap[Symbol, T]()) + def requiredMethodRef(path: PreName)(using Context): TermRef = requiredMethod(path).termRef } diff --git a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala index d8d195781482..24c2a294f5ea 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala @@ -287,7 +287,7 @@ class TypeApplications(val self: Type) extends AnyVal { val typParams = self.typeParams val stripped = self.stripTypeVar val dealiased = stripped.safeDealias - if (args.isEmpty || ctx.erasedTypes) self + if (args.isEmpty || currentlyAfterErasure) self else dealiased match { case dealiased: HKTypeLambda => def tryReduce = @@ -337,7 +337,7 @@ class TypeApplications(val self: Type) extends AnyVal { case dealiased: TypeBounds => dealiased.derivedTypeBounds(dealiased.lo.appliedTo(args), dealiased.hi.appliedTo(args)) case dealiased: LazyRef => - LazyRef(c => dealiased.ref(using c).appliedTo(args)(using c)) + LazyRef(dealiased.ref.appliedTo(args)) case dealiased: WildcardType => WildcardType(dealiased.optBounds.orElse(TypeBounds.empty).appliedTo(args).bounds) case dealiased: TypeRef if dealiased.symbol == defn.NothingClass => diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index 969142e71ca4..9f25389e310c 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -3,7 +3,8 @@ package dotc package core import Types._, Contexts._, Symbols._, Flags._, Names._, NameOps._, Denotations._ -import Decorators._, Phases._ +import Decorators._ +import Phases.gettersPhase import StdNames.nme import TypeOps.refineUsingParent import collection.mutable @@ -196,14 +197,14 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w def monitoredIsSubType = { if (pendingSubTypes == null) { pendingSubTypes = new mutable.HashSet[(Type, Type)] - ctx.log(s"!!! deep subtype recursion involving ${tp1.show} <:< ${tp2.show}, constraint = ${state.constraint.show}") - ctx.log(s"!!! constraint = ${constraint.show}") + report.log(s"!!! deep subtype recursion involving ${tp1.show} <:< ${tp2.show}, constraint = ${state.constraint.show}") + report.log(s"!!! constraint = ${constraint.show}") //if (ctx.settings.YnoDeepSubtypes.value) { // new Error("deep subtype").printStackTrace() //} assert(!ctx.settings.YnoDeepSubtypes.value) if (Config.traceDeepSubTypeRecursions && !this.isInstanceOf[ExplainingTypeComparer]) - ctx.log(TypeComparer.explained(summon[Context].typeComparer.isSubType(tp1, tp2, approx))) + report.log(TypeComparer.explained(summon[Context].typeComparer.isSubType(tp1, tp2, approx))) } // Eliminate LazyRefs before checking whether we have seen a type before val normalize = new TypeMap { @@ -260,7 +261,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w // This is safe because X$ self-type is X.type sym1 = sym1.companionModule if ((sym1 ne NoSymbol) && (sym1 eq sym2)) - ctx.erasedTypes || + currentlyAfterErasure || sym1.isStaticOwner || isSubPrefix(tp1.prefix, tp2.prefix) || thirdTryNamed(tp2) @@ -363,7 +364,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w if (!frozenConstraint && tp2.isRef(NothingClass) && state.isGlobalCommittable) { def msg = s"!!! instantiated to Nothing: $tp1, constraint = ${constraint.show}" if (Config.failOnInstantiationToNothing) assert(false, msg) - else ctx.log(msg) + else report.log(msg) } true } @@ -387,7 +388,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } case tp1: SkolemType => tp2 match { - case tp2: SkolemType if !ctx.phase.isTyper && recur(tp1.info, tp2.info) => true + case tp2: SkolemType if !currentPhase.isTyper && recur(tp1.info, tp2.info) => true case _ => thirdTry } case tp1: TypeVar => @@ -807,7 +808,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w case _ => tp2.isAnyRef } compareJavaArray - case tp1: ExprType if ctx.phase.id > gettersPhase.id => + case tp1: ExprType if currentPhase.id > gettersPhase.id => // getters might have converted T to => T, need to compensate. recur(tp1.widenExpr, tp2) case _ => @@ -1232,7 +1233,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * for equality would give the wrong result, so we should not use the sets * for comparisons. */ - def canCompare(ts: Set[Type]) = ctx.phase.isTyper || { + def canCompare(ts: Set[Type]) = currentPhase.isTyper || { val hasSkolems = new ExistsAccumulator(_.isInstanceOf[SkolemType]) { override def stopAtStatic = true } @@ -1311,7 +1312,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w */ def compareCaptured(arg1: TypeBounds, arg2: Type) = tparam match { case tparam: Symbol => - if (leftRoot.isStable || (ctx.isAfterTyper || ctx.mode.is(Mode.TypevarsMissContext)) + if (leftRoot.isStable || (currentlyAfterTyper || ctx.mode.is(Mode.TypevarsMissContext)) && leftRoot.member(tparam.name).exists) { val captured = TypeRef(leftRoot, tparam) try isSubArg(captured, arg2) @@ -1861,7 +1862,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w final def glb(tps: List[Type]): Type = tps.foldLeft(AnyType: Type)(glb) def widenInUnions(using Context): Boolean = - migrateTo3 || ctx.erasedTypes + migrateTo3 || currentlyAfterErasure /** The least upper bound of two types * @param canConstrain If true, new constraints might be added to simplify the lub. @@ -2020,7 +2021,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } private def andTypeGen(tp1: Type, tp2: Type, op: (Type, Type) => Type, - original: (Type, Type) => Type = _ & _, isErased: Boolean = ctx.erasedTypes): Type = trace(s"glb(${tp1.show}, ${tp2.show})", subtyping, show = true) { + original: (Type, Type) => Type = _ & _, isErased: Boolean = currentlyAfterErasure): Type = trace(s"glb(${tp1.show}, ${tp2.show})", subtyping, show = true) { val t1 = distributeAnd(tp1, tp2) if (t1.exists) t1 else { @@ -2048,7 +2049,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * Finally, refined types with the same refined name are * opportunistically merged. */ - final def andType(tp1: Type, tp2: Type, isErased: Boolean = ctx.erasedTypes): Type = + final def andType(tp1: Type, tp2: Type, isErased: Boolean = currentlyAfterErasure): Type = andTypeGen(tp1, tp2, AndType(_, _), isErased = isErased) final def simplifyAndTypeWithFallback(tp1: Type, tp2: Type, fallback: Type): Type = @@ -2063,7 +2064,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * @param isErased Apply erasure semantics. If erased is true, instead of creating * an OrType, the lub will be computed using TypeCreator#erasedLub. */ - final def orType(tp1: Type, tp2: Type, isErased: Boolean = ctx.erasedTypes): Type = { + final def orType(tp1: Type, tp2: Type, isErased: Boolean = currentlyAfterErasure): Type = { val t1 = distributeOr(tp1, tp2) if (t1.exists) t1 else { @@ -2232,12 +2233,12 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w /** Show subtype goal that led to an assertion failure */ def showGoal(tp1: Type, tp2: Type)(using Context): Unit = { - ctx.echo(i"assertion failure for ${show(tp1)} <:< ${show(tp2)}, frozen = $frozenConstraint") + report.echo(i"assertion failure for ${show(tp1)} <:< ${show(tp2)}, frozen = $frozenConstraint") def explainPoly(tp: Type) = tp match { - case tp: TypeParamRef => ctx.echo(s"TypeParamRef ${tp.show} found in ${tp.binder.show}") - case tp: TypeRef if tp.symbol.exists => ctx.echo(s"typeref ${tp.show} found in ${tp.symbol.owner.show}") - case tp: TypeVar => ctx.echo(s"typevar ${tp.show}, origin = ${tp.origin}") - case _ => ctx.echo(s"${tp.show} is a ${tp.getClass}") + case tp: TypeParamRef => report.echo(s"TypeParamRef ${tp.show} found in ${tp.binder.show}") + case tp: TypeRef if tp.symbol.exists => report.echo(s"typeref ${tp.show} found in ${tp.symbol.owner.show}") + case tp: TypeVar => report.echo(s"typevar ${tp.show}, origin = ${tp.origin}") + case _ => report.echo(s"${tp.show} is a ${tp.getClass}") } if (Config.verboseExplainSubtype) { explainPoly(tp1) diff --git a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala index ecc5b14a2536..ddf0272a1d9d 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala @@ -132,7 +132,7 @@ object TypeErasure { /** The current context with a phase no later than erasure */ def preErasureCtx(using Context) = - if (ctx.erasedTypes) ctx.withPhase(erasurePhase) else ctx + if (currentlyAfterErasure) ctx.withPhase(erasurePhase) else ctx /** The standard erasure of a Scala type. Value classes are erased as normal classes. * @@ -608,7 +608,7 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean else val cls = normalizeClass(sym.asClass) val fullName = - if !ctx.erasedTypes then + if !currentlyAfterErasure then // It's important to use the initial symbol to compute the full name // because the current symbol might have a different name or owner // and signatures are required to be stable before erasure. diff --git a/compiler/src/dotty/tools/dotc/core/TypeErrors.scala b/compiler/src/dotty/tools/dotc/core/TypeErrors.scala index 60548db38006..950963497fbc 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeErrors.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeErrors.scala @@ -10,15 +10,14 @@ import Contexts._ import SymDenotations._ import Denotations._ import Decorators._ -import reporting.{Message, NoExplanation} -import reporting.messages._ +import reporting._ import ast.untpd import config.Printers.cyclicErrors class TypeError(msg: String) extends Exception(msg) { def this() = this("") final def toMessage(using Context): Message = - produceMessage(using ctx.addMode(Mode.Printing)) + withMode(Mode.Printing)(produceMessage) def produceMessage(using Context): Message = super.getMessage override def getMessage: String = super.getMessage } diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index 3eca986a973b..47f3aadf6c7b 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -122,7 +122,7 @@ object TypeOps: } def isLegalPrefix(pre: Type)(using Context): Boolean = - pre.isStable || !ctx.phase.isTyper + pre.isStable || !currentPhase.isTyper /** Implementation of Types#simplified */ def simplify(tp: Type, theMap: SimplifyMap)(using Context): Type = { @@ -193,7 +193,7 @@ object TypeOps: val accu1 = if (accu exists (_ derivesFrom c)) accu else c :: accu if (cs == c.baseClasses) accu1 else dominators(rest, accu1) case Nil => // this case can happen because after erasure we do not have a top class anymore - assert(ctx.erasedTypes || ctx.reporter.errorsReported) + assert(currentlyAfterErasure || ctx.reporter.errorsReported) defn.ObjectClass :: Nil } diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index f08f2292bf60..2166b565cc6a 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -539,7 +539,7 @@ object Types { case tp: TypeProxy => tp.underlying.findDecl(name, excluded) case err: ErrorType => - ctx.newErrorSymbol(classSymbol orElse defn.RootClass, name, err.msg) + newErrorSymbol(classSymbol orElse defn.RootClass, name, err.msg) case _ => NoDenotation } @@ -620,7 +620,7 @@ object Types { case tp: JavaArrayType => defn.ObjectType.findMember(name, pre, required, excluded) case err: ErrorType => - ctx.newErrorSymbol(pre.classSymbol orElse defn.RootClass, name, err.msg) + newErrorSymbol(pre.classSymbol orElse defn.RootClass, name, err.msg) case _ => NoDenotation } @@ -677,7 +677,7 @@ object Types { } else val joint = pdenot.meet( - new JointRefDenotation(NoSymbol, rinfo, Period.allInRun(ctx.runId), pre), + new JointRefDenotation(NoSymbol, rinfo, Period.allInRun(currentRunId), pre), pre, safeIntersection = ctx.base.pendingMemberSearches.contains(name)) joint match @@ -980,7 +980,7 @@ object Types { */ def matches(that: Type)(using Context): Boolean = { record("matches") - ctx.typeComparer.matchesType(this, that, relaxed = !ctx.phase.erasedTypes) + ctx.typeComparer.matchesType(this, that, relaxed = !currentPhase.erasedTypes) } /** This is the same as `matches` except that it also matches => T with T and @@ -1209,7 +1209,7 @@ object Types { case Atoms.Unknown => Atoms.Unknown case _ => Atoms.Unknown - private def dealias1(keep: AnnotatedType => Context => Boolean)(using Context): Type = this match { + private def dealias1(keep: AnnotatedType => Context ?=> Boolean)(using Context): Type = this match { case tp: TypeRef => if (tp.symbol.isClass) tp else tp.info match { @@ -1225,7 +1225,7 @@ object Types { if (tp1.exists) tp1.dealias1(keep) else tp case tp: AnnotatedType => val tp1 = tp.parent.dealias1(keep) - if (keep(tp)(ctx)) tp.derivedAnnotatedType(tp1, tp.annot) else tp1 + if keep(tp) then tp.derivedAnnotatedType(tp1, tp.annot) else tp1 case tp: LazyRef => tp.ref.dealias1(keep) case _ => this @@ -1260,7 +1260,7 @@ object Types { */ def tryNormalize(using Context): Type = NoType - private def widenDealias1(keep: AnnotatedType => Context => Boolean)(using Context): Type = { + private def widenDealias1(keep: AnnotatedType => Context ?=> Boolean)(using Context): Type = { val res = this.widen.dealias1(keep) if (res eq this) res else res.widenDealias1(keep) } @@ -1334,7 +1334,7 @@ object Types { * that has the given type as info. */ def narrow(using Context): TermRef = - TermRef(NoPrefix, ctx.newSkolem(this)) + TermRef(NoPrefix, newSkolem(this)) /** Useful for diagnostics: The underlying type if this type is a type proxy, * otherwise NoType @@ -1413,7 +1413,7 @@ object Types { TermRef(this, name, member(name)) def select(name: TermName, sig: Signature)(using Context): TermRef = - TermRef(this, name, member(name).atSignature(sig, relaxed = !ctx.erasedTypes)) + TermRef(this, name, member(name).atSignature(sig, relaxed = !currentlyAfterErasure)) // ----- Access to parts -------------------------------------------- @@ -1601,8 +1601,8 @@ object Types { def toFunctionType(dropLast: Int = 0)(using Context): Type = this match { case mt: MethodType if !mt.isParamDependent => val formals1 = if (dropLast == 0) mt.paramInfos else mt.paramInfos dropRight dropLast - val isContextual = mt.isContextualMethod && !ctx.erasedTypes - val isErased = mt.isErasedMethod && !ctx.erasedTypes + val isContextual = mt.isContextualMethod && !currentlyAfterErasure + val isErased = mt.isErasedMethod && !currentlyAfterErasure val result1 = mt.nonDependentResultApprox match { case res: MethodType => res.toFunctionType() case res => res @@ -1904,7 +1904,7 @@ object Types { protected[dotc] def computeSignature(using Context): Signature = val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) - else if ctx.erasedTypes then atPhase(erasurePhase)(computeSignature) + else if currentlyAfterErasure then atPhase(erasurePhase)(computeSignature) else symbol.asSeenFrom(prefix).signature /** The signature computed from the current denotation with `sigFromDenot` if it is @@ -1914,11 +1914,11 @@ object Types { * some symbols change their signature at erasure. */ private def currentSignature(using Context): Signature = - if ctx.runId == mySignatureRunId then mySignature + if currentRunId == mySignatureRunId then mySignature else val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) - else if ctx.erasedTypes then atPhase(erasurePhase)(currentSignature) + else if currentlyAfterErasure then atPhase(erasurePhase)(currentSignature) else val sym = currentSymbol if sym.exists then sym.asSeenFrom(prefix).signature @@ -1934,7 +1934,7 @@ object Types { final def symbol(using Context): Symbol = // We can rely on checkedPeriod (unlike in the definition of `denot` below) // because SymDenotation#installAfter never changes the symbol - if (checkedPeriod == ctx.period) lastSymbol else computeSymbol + if (checkedPeriod == currentPeriod) lastSymbol else computeSymbol private def computeSymbol(using Context): Symbol = designator match { @@ -1948,7 +1948,7 @@ object Types { * current run. */ def denotationIsCurrent(using Context): Boolean = - lastDenotation != null && lastDenotation.validFor.runId == ctx.runId + lastDenotation != null && lastDenotation.validFor.runId == currentRunId /** If the reference is symbolic or the denotation is current, its symbol, otherwise NoDenotation. * @@ -1969,7 +1969,7 @@ object Types { * Used to get the class underlying a ThisType. */ private[Types] def stableInRunSymbol(using Context): Symbol = - if (checkedPeriod.runId == ctx.runId) lastSymbol + if (checkedPeriod.runId == currentRunId) lastSymbol else symbol def info(using Context): Type = denot.info @@ -1977,7 +1977,7 @@ object Types { /** The denotation currently denoted by this type */ final def denot(using Context): Denotation = { util.Stats.record("NamedType.denot") - val now = ctx.period + val now = currentPeriod // Even if checkedPeriod == now we still need to recheck lastDenotation.validFor // as it may have been mutated by SymDenotation#installAfter if (checkedPeriod != Nowhere && lastDenotation.validFor.contains(now)) { @@ -2008,7 +2008,7 @@ object Types { finish(memberDenot(name, allowPrivate)) case sym: Symbol => val symd = sym.lastKnownDenotation - if (symd.validFor.runId != ctx.runId && !ctx.stillValid(symd)) + if (symd.validFor.runId != currentRunId && !stillValid(symd)) finish(memberDenot(symd.initial.name, allowPrivate = false)) else if (prefix.isArgPrefixOf(symd)) finish(argDenot(sym.asType)) @@ -2021,10 +2021,10 @@ object Types { lastDenotation match { case lastd0: SingleDenotation => val lastd = lastd0.skipRemoved - if (lastd.validFor.runId == ctx.runId && (checkedPeriod != Nowhere)) finish(lastd.current) + if (lastd.validFor.runId == currentRunId && (checkedPeriod != Nowhere)) finish(lastd.current) else lastd match { case lastd: SymDenotation => - if (ctx.stillValid(lastd) && (checkedPeriod != Nowhere)) finish(lastd.current) + if (stillValid(lastd) && (checkedPeriod != Nowhere)) finish(lastd.current) else finish(memberDenot(lastd.initial.name, allowPrivate = false)) case _ => fromDesignator @@ -2038,7 +2038,7 @@ object Types { private def disambiguate(d: Denotation, sig: Signature)(using Context): Denotation = if (sig != null) - d.atSignature(sig, relaxed = !ctx.erasedTypes) match { + d.atSignature(sig, relaxed = !currentlyAfterErasure) match { case d1: SingleDenotation => d1 case d1 => d1.atSignature(sig, relaxed = false) match { @@ -2053,9 +2053,9 @@ object Types { if (!d.exists && !allowPrivate && ctx.mode.is(Mode.Interactive)) // In the IDE we might change a public symbol to private, and would still expect to find it. d = memberDenot(prefix, name, true) - if (!d.exists && ctx.phaseId > FirstPhaseId && lastDenotation.isInstanceOf[SymDenotation]) + if (!d.exists && currentPhaseId > FirstPhaseId && lastDenotation.isInstanceOf[SymDenotation]) // name has changed; try load in earlier phase and make current - d = atPhase(ctx.phaseId - 1)(memberDenot(name, allowPrivate)).current + d = atPhase(currentPhaseId - 1)(memberDenot(name, allowPrivate)).current if (d.isOverloaded) d = disambiguate(d) d @@ -2094,7 +2094,7 @@ object Types { else { if (!ctx.reporter.errorsReported) throw new TypeError( - i"""bad parameter reference $this at ${ctx.phase} + i"""bad parameter reference $this at ${currentPhase} |the parameter is ${param.showLocated} but the prefix $prefix |does not define any corresponding arguments.""") NoDenotation @@ -2114,7 +2114,7 @@ object Types { lastDenotation = denot lastSymbol = denot.symbol - checkedPeriod = if (prefix.isProvisional) Nowhere else ctx.period + checkedPeriod = if (prefix.isProvisional) Nowhere else currentPeriod designator match { case sym: Symbol if designator ne lastSymbol => designator = lastSymbol.asInstanceOf[Designator{ type ThisName = self.ThisName }] @@ -2155,7 +2155,7 @@ object Types { s"""data race? overwriting $lastSymbol with $sym in type $this, |last sym id = ${lastSymbol.id}, new sym id = ${sym.id}, |last owner = ${lastSymbol.owner}, new owner = ${sym.owner}, - |period = ${ctx.phase} at run ${ctx.runId}""") + |period = ${currentPhase} at run ${currentRunId}""") } /** A reference with the initial symbol in `symd` has an info that @@ -2451,11 +2451,11 @@ object Types { * based tests. */ def canDropAlias(using Context) = - if myCanDropAliasPeriod != ctx.period then + if myCanDropAliasPeriod != currentPeriod then myCanDropAlias = !symbol.canMatchInheritedSymbols || !prefix.baseClasses.exists(_.info.decls.lookup(name).is(Deferred)) - myCanDropAliasPeriod = ctx.period + myCanDropAliasPeriod = currentPeriod myCanDropAlias override def designator: Designator = myDesignator @@ -2489,7 +2489,7 @@ object Types { /** Assert current phase does not have erasure semantics */ private def assertUnerased()(using Context) = - if (Config.checkUnerased) assert(!ctx.phase.erasedTypes) + if (Config.checkUnerased) assert(!currentPhase.erasedTypes) /** The designator to be used for a named type creation with given prefix, name, and denotation. * This is the denotation's symbol, if it exists and the prefix is not the this type @@ -2561,7 +2561,7 @@ object Types { } override def underlying(using Context): Type = - if (ctx.erasedTypes) tref + if (currentlyAfterErasure) tref else cls.info match { case cinfo: ClassInfo => cinfo.selfType case _: ErrorType | NoType if ctx.mode.is(Mode.Interactive) => cls.info @@ -2629,7 +2629,7 @@ object Types { } } - case class LazyRef(private var refFn: Context => Type, reportCycles: Boolean = false) extends UncachedProxyType with ValueType { + case class LazyRef(private var refFn: Context ?=> Type, reportCycles: Boolean = false) extends UncachedProxyType with ValueType { private var myRef: Type = null private var computed = false @@ -2642,7 +2642,7 @@ object Types { throw CyclicReference(NoDenotation) else computed = true - val result = refFn(ctx) + val result = refFn refFn = null if result != null then myRef = result else assert(myRef != null) // must have been `update`d @@ -2729,7 +2729,7 @@ object Types { else make(RefinedType(parent, names.head, infos.head), names.tail, infos.tail) def apply(parent: Type, name: Name, info: Type)(using Context): RefinedType = { - assert(!ctx.erasedTypes) + assert(!currentlyAfterErasure) unique(new CachedRefinedType(parent, name, info)).checkInst } } @@ -2875,7 +2875,7 @@ object Types { private var myBaseClasses: List[ClassSymbol] = _ /** Base classes of are the merge of the operand base classes. */ override final def baseClasses(using Context): List[ClassSymbol] = { - if (myBaseClassesPeriod != ctx.period) { + if (myBaseClassesPeriod != currentPeriod) { val bcs1 = tp1.baseClasses val bcs1set = BaseClassSet(bcs1) def recur(bcs2: List[ClassSymbol]): List[ClassSymbol] = bcs2 match { @@ -2887,7 +2887,7 @@ object Types { case nil => bcs1 } myBaseClasses = recur(tp2.baseClasses) - myBaseClassesPeriod = ctx.period + myBaseClassesPeriod = currentPeriod } myBaseClasses } @@ -2940,7 +2940,7 @@ object Types { private var myBaseClasses: List[ClassSymbol] = _ /** Base classes of are the intersection of the operand base classes. */ override final def baseClasses(using Context): List[ClassSymbol] = { - if (myBaseClassesPeriod != ctx.period) { + if (myBaseClassesPeriod != currentPeriod) { val bcs1 = tp1.baseClasses val bcs1set = BaseClassSet(bcs1) def recur(bcs2: List[ClassSymbol]): List[ClassSymbol] = bcs2 match { @@ -2953,7 +2953,7 @@ object Types { bcs2 } myBaseClasses = recur(tp2.baseClasses) - myBaseClassesPeriod = ctx.period + myBaseClassesPeriod = currentPeriod } myBaseClasses } @@ -2966,11 +2966,11 @@ object Types { /** Replace or type by the closest non-or type above it */ def join(using Context): Type = { - if (myJoinPeriod != ctx.period) { + if (myJoinPeriod != currentPeriod) { myJoin = TypeOps.orDominator(this) core.println(i"join of $this == $myJoin") assert(myJoin != this) - myJoinPeriod = ctx.period + myJoinPeriod = currentPeriod } myJoin } @@ -2980,12 +2980,12 @@ object Types { private var myWidened: Type = _ private def ensureAtomsComputed()(using Context): Unit = - if atomsRunId != ctx.runId then + if atomsRunId != currentRunId then myAtoms = tp1.atoms | tp2.atoms val tp1w = tp1.widenSingletons val tp2w = tp2.widenSingletons myWidened = if ((tp1 eq tp1w) && (tp2 eq tp2w)) this else tp1w | tp2w - atomsRunId = ctx.runId + atomsRunId = currentRunId override def atoms(using Context): Atoms = ensureAtomsComputed() @@ -3070,9 +3070,9 @@ object Types { protected[dotc] def computeSignature(using Context): Signature final override def signature(using Context): Signature = { - if (ctx.runId != mySignatureRunId) { + if (currentRunId != mySignatureRunId) { mySignature = computeSignature - if (!mySignature.isUnderDefined) mySignatureRunId = ctx.runId + if (!mySignature.isUnderDefined) mySignatureRunId = currentRunId } mySignature } @@ -3790,14 +3790,14 @@ object Types { override def underlying(using Context): Type = tycon override def superType(using Context): Type = { - if (ctx.period != validSuper) { + if (currentPeriod != validSuper) { cachedSuper = tycon match { case tycon: HKTypeLambda => defn.AnyType case tycon: TypeRef if tycon.symbol.isClass => tycon case tycon: TypeProxy => tycon.superType.applyIfParameterized(args) case _ => defn.AnyType } - validSuper = if (tycon.isProvisional) Nowhere else ctx.period + validSuper = if (tycon.isProvisional) Nowhere else currentPeriod } cachedSuper } @@ -4380,7 +4380,7 @@ object Types { val givenSelf = clsd.givenSelfType if (!givenSelf.isValueType) appliedRef else if (clsd.is(Module)) givenSelf - else if (ctx.erasedTypes) appliedRef + else if (currentlyAfterErasure) appliedRef else AndType(givenSelf, appliedRef) } selfTypeCache @@ -4433,7 +4433,7 @@ object Types { else defn.AnyType // dummy type in case of errors def refineSelfType(selfType: Type) = RefinedType(selfType, sym.name, - TypeAlias(LazyRef(force(using _), reportCycles = true))) + TypeAlias(LazyRef(force, reportCycles = true))) cinfo.selfInfo match case self: Type => cinfo.derivedClassInfo( @@ -4992,14 +4992,14 @@ object Types { derivedSuperType(tp, this(thistp), this(supertp)) case tp: LazyRef => - LazyRef { c => - val ref1 = tp.ref(using c) - if c.runId == mapCtx.runId then this(ref1) + LazyRef { + val ref1 = tp.ref + if currentRunId == currentRunId(using mapCtx) then this(ref1) else // splice in new run into map context val saved = mapCtx mapCtx = mapCtx.fresh - .setPeriod(Period(c.runId, mapCtx.phaseId)) - .setRun(c.run) + .setPeriod(Period(currentRunId, currentPhaseId(using mapCtx))) + .setRun(ctx.run) try this(ref1) finally mapCtx = saved } @@ -5041,7 +5041,7 @@ object Types { private def treeTypeMap = new TreeTypeMap(typeMap = this) - def mapOver(syms: List[Symbol]): List[Symbol] = mapCtx.mapSymbols(syms, treeTypeMap) + def mapOver(syms: List[Symbol]): List[Symbol] = mapSymbols(syms, treeTypeMap) def mapOver(scope: Scope): Scope = { val elems = scope.toList @@ -5660,9 +5660,9 @@ object Types { } } - private val keepAlways: AnnotatedType => Context => Boolean = _ => _ => true - private val keepNever: AnnotatedType => Context => Boolean = _ => _ => false - private val keepIfRefining: AnnotatedType => Context => Boolean = tp => ctx => tp.isRefining(using ctx) + private val keepAlways: AnnotatedType => Context ?=> Boolean = _ => true + private val keepNever: AnnotatedType => Context ?=> Boolean = _ => false + private val keepIfRefining: AnnotatedType => Context ?=> Boolean = _.isRefining val isBounds: Type => Boolean = _.isInstanceOf[TypeBounds] } diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index d612d80d44af..6b3ff303c838 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -76,7 +76,7 @@ class ClassfileParser( private var Scala2UnpicklingMode = Mode.Scala2Unpickling classRoot.info = NoLoader().withDecls(instanceScope) - moduleRoot.info = NoLoader().withDecls(staticScope).withSourceModule(_ => staticModule) + moduleRoot.info = NoLoader().withDecls(staticScope).withSourceModule(staticModule) private def currentIsTopLevel(using Context) = classRoot.owner.is(Flags.PackageClass) @@ -84,7 +84,7 @@ class ClassfileParser( throw new IOException(s"class file '${in.file.canonicalPath}' has location not matching its contents: contains class $className") def run()(using Context): Option[Embedded] = try { - ctx.debuglog("[class] >> " + classRoot.fullName) + report.debuglog("[class] >> " + classRoot.fullName) parseHeader() this.pool = new ConstantPool parseClass() @@ -113,7 +113,7 @@ class ClassfileParser( /** Return the class symbol of the given name. */ def classNameToSymbol(name: Name)(using Context): Symbol = innerClasses.get(name) match { case Some(entry) => innerClasses.classSymbol(entry) - case None => ctx.requiredClass(name) + case None => requiredClass(name) } var sawPrivateConstructor: Boolean = false @@ -225,7 +225,7 @@ class ClassfileParser( else fieldTranslation.flags(jflags) val name = pool.getName(in.nextChar) if (!sflags.isOneOf(Flags.PrivateOrArtifact) || name == nme.CONSTRUCTOR) { - val member = ctx.newSymbol( + val member = newSymbol( getOwner(jflags), name, sflags, memberCompleter, getPrivateWithin(jflags), coord = start) getScope(jflags).enter(member) @@ -295,7 +295,7 @@ class ClassfileParser( if (isEnum) { val enumClass = sym.owner.linkedClass if (!enumClass.exists) - ctx.warning(s"no linked class for java enum $sym in ${sym.owner}. A referencing class file might be missing an InnerClasses entry.") + report.warning(s"no linked class for java enum $sym in ${sym.owner}. A referencing class file might be missing an InnerClasses entry.") else { if (!enumClass.is(Flags.Sealed)) enumClass.setFlag(Flags.AbstractSealed) enumClass.addAnnotation(Annotation.Child(sym, NoSpan)) @@ -309,7 +309,7 @@ class ClassfileParser( /** Map direct references to Object to references to Any */ final def objToAny(tp: Type)(using Context): Type = - if (tp.isDirectRef(defn.ObjectClass) && !ctx.phase.erasedTypes) defn.AnyType else tp + if (tp.isDirectRef(defn.ObjectClass) && !currentPhase.erasedTypes) defn.AnyType else tp def constantTagToType(tag: Int)(using Context): Type = (tag: @switch) match { @@ -452,7 +452,7 @@ class ClassfileParser( val start = index while (sig(index) != '>') { val tpname = subName(':'.==).toTypeName - val s = ctx.newSymbol( + val s = newSymbol( owner, tpname, owner.typeParamCreationFlags, typeParamCompleter(index), coord = indexCoord(index)) if (owner.isClass) owner.asClass.enter(s) @@ -510,7 +510,7 @@ class ClassfileParser( else if (s != NoSymbol) Some(lit(Constant(s))) else { - ctx.warning(s"""While parsing annotations in ${in.file}, could not find $n in enum $module.\nThis is likely due to an implementation restriction: an annotation argument cannot refer to a member of the annotated class (SI-7014).""") + report.warning(s"""While parsing annotations in ${in.file}, could not find $n in enum $module.\nThis is likely due to an implementation restriction: an annotation argument cannot refer to a member of the annotated class (SI-7014).""") None } case ARRAY_TAG => @@ -542,7 +542,7 @@ class ClassfileParser( // Silently ignore missing annotation classes like javac if tp.denot.infoOrCompleter.isInstanceOf[StubInfo] then if ctx.debug then - ctx.warning(i"Error while parsing annotations in ${in.file}: annotation class $tp not present on classpath") + report.warning(i"Error while parsing annotations in ${in.file}: annotation class $tp not present on classpath") return None case _ => @@ -568,7 +568,7 @@ class ClassfileParser( // the classpath would *not* end up here. A class not found is signaled // with a `FatalError` exception, handled above. Here you'd end up after a NPE (for example), // and that should never be swallowed silently. - ctx.warning("Caught: " + ex + " while parsing annotations in " + in.file) + report.warning("Caught: " + ex + " while parsing annotations in " + in.file) if (ctx.debug) ex.printStackTrace() None // ignore malformed annotations @@ -598,7 +598,7 @@ class ClassfileParser( case tpnme.ConstantValueATTR => val c = pool.getConstant(in.nextChar, symtype) if (c ne null) newType = ConstantType(c) - else ctx.warning(s"Invalid constant in attribute of ${sym.showLocated} while parsing ${classfile}") + else report.warning(s"Invalid constant in attribute of ${sym.showLocated} while parsing ${classfile}") case tpnme.AnnotationDefaultATTR => sym.addAnnotation(Annotation(defn.AnnotationDefaultAnnot, Nil)) // Java annotations on classes / methods / fields with RetentionPolicy.RUNTIME @@ -619,7 +619,7 @@ class ClassfileParser( if (sym.owner.isAllOf(Flags.JavaInterface)) { sym.resetFlag(Flags.Deferred) sym.owner.resetFlag(Flags.PureInterface) - ctx.log(s"$sym in ${sym.owner} is a java8+ default method.") + report.log(s"$sym in ${sym.owner} is a java8+ default method.") } in.skip(attrLen) @@ -664,7 +664,7 @@ class ClassfileParser( * parameters. For Java annotations we need to fake it by making up the constructor. */ def addAnnotationConstructor(classInfo: TempClassInfoType)(using Context): Unit = - ctx.newSymbol( + newSymbol( owner = classRoot.symbol, name = nme.CONSTRUCTOR, flags = Flags.Synthetic | Flags.JavaDefined | Flags.Method, @@ -752,7 +752,7 @@ class ClassfileParser( } val unpickler = new unpickleScala2.Scala2Unpickler(bytes, classRoot, moduleRoot)(ctx) - unpickler.run()(using ctx.addMode(Scala2UnpicklingMode)) + withMode(Scala2UnpicklingMode)(unpickler.run()) Some(unpickler) } @@ -807,18 +807,18 @@ class ClassfileParser( } } else { - ctx.error(s"Could not find $path in ${classfile.underlyingSource}") + report.error(s"Could not find $path in ${classfile.underlyingSource}") Array.empty } case _ => if (classfile.jpath == null) { - ctx.error("Could not load TASTY from .tasty for virtual file " + classfile) + report.error("Could not load TASTY from .tasty for virtual file " + classfile) Array.empty } else { val plainFile = new PlainFile(io.File(classfile.jpath).changeExtension("tasty")) if (plainFile.exists) plainFile.toByteArray else { - ctx.error("Could not find " + plainFile) + report.error("Could not find " + plainFile) Array.empty } } @@ -828,7 +828,7 @@ class ClassfileParser( val expectedUUID = new UUID(reader.readUncompressedLong(), reader.readUncompressedLong()) val tastyUUID = new TastyHeaderUnpickler(tastyBytes).readHeader() if (expectedUUID != tastyUUID) - ctx.warning(s"$classfile is out of sync with its TASTy file. Loaded TASTy file. Try cleaning the project to fix this issue", NoSourcePosition) + report.warning(s"$classfile is out of sync with its TASTy file. Loaded TASTy file. Try cleaning the project to fix this issue", NoSourcePosition) return unpickleTASTY(tastyBytes) } } @@ -1058,7 +1058,7 @@ class ClassfileParser( val name = getExternalName(in.getChar(start + 1)) if (name.endsWith("$") && (name ne nme.nothingRuntimeClass) && (name ne nme.nullRuntimeClass)) // Null$ and Nothing$ ARE classes - c = ctx.requiredModule(name.dropRight(1)) + c = requiredModule(name.dropRight(1)) else c = classNameToSymbol(name) values(index) = c } diff --git a/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala b/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala index b798130f8a55..07d73a4cd03d 100644 --- a/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala +++ b/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala @@ -53,7 +53,8 @@ object PickledQuotes { /** Unpickle the tree contained in the TastyExpr */ def unpickleExpr(tasty: PickledQuote, splices: PickledArgs)(using Context): Tree = { val tastyBytes = TastyString.unpickle(tasty) - val unpickled = unpickle(tastyBytes, splices, isType = false)(using ctx.addMode(Mode.ReadPositions)) + val unpickled = withMode(Mode.ReadPositions)( + unpickle(tastyBytes, splices, isType = false)) val Inlined(call, Nil, expnasion) = unpickled val inlineCtx = inlineContext(call) val expansion1 = spliceTypes(expnasion, splices)(using inlineCtx) @@ -64,7 +65,8 @@ object PickledQuotes { /** Unpickle the tree contained in the TastyType */ def unpickleType(tasty: PickledQuote, args: PickledArgs)(using Context): Tree = { val tastyBytes = TastyString.unpickle(tasty) - val unpickled = unpickle(tastyBytes, args, isType = true)(using ctx.addMode(Mode.ReadPositions)) + val unpickled = withMode(Mode.ReadPositions)( + unpickle(tastyBytes, args, isType = true)) spliceTypes(unpickled, args) } diff --git a/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala index 4133755e8c98..cd507c7f83d8 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala @@ -55,7 +55,7 @@ class PositionPickler(pickler: TastyPickler, addrOfTree: untpd.Tree => Addr) { val cwd = java.nio.file.Paths.get("").toAbsolutePath().normalize() try cwd.relativize(path) catch case _: IllegalArgumentException => - ctx.warning("Could not relativize path for pickling: " + originalPath) + report.warning("Could not relativize path for pickling: " + originalPath) originalPath else originalPath diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala index 85c6830de5cc..f60c4bdff191 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala @@ -84,7 +84,7 @@ class TreePickler(pickler: TastyPickler) { // I believe it's a bug in typer: the type of an implicit argument refers // to a closure parameter outside the closure itself. TODO: track this down, so that we // can eliminate this case. - ctx.log(i"pickling reference to as yet undefined $sym in ${sym.owner}", sym.sourcePos) + report.log(i"pickling reference to as yet undefined $sym in ${sym.owner}", sym.sourcePos) pickleForwardSymRef(sym) } @@ -622,7 +622,7 @@ class TreePickler(pickler: TastyPickler) { } catch { case ex: TypeError => - ctx.error(ex.toMessage, tree.sourcePos.focus) + report.error(ex.toMessage, tree.sourcePos.focus) case ex: AssertionError => println(i"error when pickling tree $tree") throw ex diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index ed39a3bb0caa..0057ab275ae7 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -18,6 +18,8 @@ import Flags._ import Constants._ import Annotations._ import NameKinds._ +import NamerOps._ +import ContextOps._ import Variances.Invariant import typer.ConstFold import typer.Checking.checkNonCyclic @@ -243,7 +245,7 @@ class TreeUnpickler(reader: TastyReader, sym case None => val sym = forkAt(addr).createSymbol()(using ctx.withOwner(ownerTree.findOwner(addr))) - ctx.log(i"forward reference to $sym") + report.log(i"forward reference to $sym") sym } @@ -455,7 +457,7 @@ class TreeUnpickler(reader: TastyReader, val name = readName() if (name == nme.ROOT || name == nme.ROOTPKG) defn.RootPackage else if (name == nme.EMPTY_PACKAGE) defn.EmptyPackageVal - else ctx.requiredPackage(name) + else requiredPackage(name) } def readTypeRef(): Type = @@ -514,7 +516,7 @@ class TreeUnpickler(reader: TastyReader, case BIND => createBindSymbol() case TEMPLATE => - val localDummy = ctx.newLocalDummy(ctx.owner) + val localDummy = newLocalDummy(ctx.owner) registerSym(currentAddr, localDummy) localDummy case tag => @@ -532,7 +534,7 @@ class TreeUnpickler(reader: TastyReader, def complete(denot: SymDenotation)(using Context) = denot.info = typeReader.readType() } - val sym = ctx.newSymbol(ctx.owner, name, Flags.Case, completer, coord = coordAt(start)) + val sym = newSymbol(ctx.owner, name, Flags.Case, completer, coord = coordAt(start)) registerSym(start, sym) sym } @@ -559,7 +561,7 @@ class TreeUnpickler(reader: TastyReader, pickling.println(i"creating symbol $name at $start with flags $givenFlags") val flags = normalizeFlags(tag, givenFlags, name, isAbsType, rhsIsEmpty) def adjustIfModule(completer: LazyType) = - if (flags.is(Module)) ctx.adjustModuleCompleter(completer, name) else completer + if (flags.is(Module)) adjustModuleCompleter(completer, name) else completer val coord = coordAt(start) val sym = roots.find(root => (root.owner eq ctx.owner) && root.name == name) match { @@ -575,9 +577,9 @@ class TreeUnpickler(reader: TastyReader, case _ => val completer = adjustIfModule(new Completer(subReader(start, end))) if (isClass) - ctx.newClassSymbol(ctx.owner, name.asTypeName, flags, completer, privateWithin, coord) + newClassSymbol(ctx.owner, name.asTypeName, flags, completer, privateWithin, coord) else - ctx.newSymbol(ctx.owner, name, flags, completer, privateWithin, coord) + newSymbol(ctx.owner, name, flags, completer, privateWithin, coord) } sym.annotations = annotFns.map(_(sym.owner)) if sym.isOpaqueAlias then sym.setFlag(Deferred) @@ -606,7 +608,7 @@ class TreeUnpickler(reader: TastyReader, * boundary symbol. */ def readModifiers[WithinType, AnnotType] - (end: Addr, readAnnot: Context => Symbol => AnnotType, readWithin: Context => WithinType, defaultWithin: WithinType) + (end: Addr, readAnnot: Context ?=> Symbol => AnnotType, readWithin: Context ?=> WithinType, defaultWithin: WithinType) (using Context): (FlagSet, List[Symbol => AnnotType], WithinType) = { var flags: FlagSet = EmptyFlags var annotFns: List[Symbol => AnnotType] = Nil @@ -660,12 +662,12 @@ class TreeUnpickler(reader: TastyReader, case OPEN => addFlag(Open) case PRIVATEqualified => readByte() - privateWithin = readWithin(ctx) + privateWithin = readWithin case PROTECTEDqualified => addFlag(Protected) - privateWithin = readWithin(ctx) + privateWithin = readWithin case ANNOTATION => - annotFns = readAnnot(ctx) :: annotFns + annotFns = readAnnot :: annotFns case tag => assert(false, s"illegal modifier tag $tag at $currentAddr, end = $end") } @@ -673,19 +675,15 @@ class TreeUnpickler(reader: TastyReader, (flags, annotFns.reverse, privateWithin) } - private val readTypedWithin: Context => Symbol = - implicit ctx => readType().typeSymbol + private val readTypedWithin: Context ?=> Symbol = readType().typeSymbol - private val readTypedAnnot: Context => Symbol => Annotation = { - implicit ctx => - readByte() - val end = readEnd() - val tp = readType() - val lazyAnnotTree = readLaterWithOwner(end, rdr => implicit ctx => rdr.readTerm()) - - owner => - Annotation.deferredSymAndTree(tp.typeSymbol)(lazyAnnotTree(owner).complete) - } + private val readTypedAnnot: Context ?=> Symbol => Annotation = + readByte() + val end = readEnd() + val tp = readType() + val lazyAnnotTree = readLaterWithOwner(end, _.readTerm()) + owner => + Annotation.deferredSymAndTree(tp.typeSymbol)(lazyAnnotTree(owner).complete) /** Create symbols for the definitions in the statement sequence between * current address and `end`. @@ -707,7 +705,7 @@ class TreeUnpickler(reader: TastyReader, case IMPORT => skipTree() case PACKAGE => - processPackage { (pid, end) => implicit ctx => indexStats(end) } + processPackage { (pid, end) => indexStats(end) } case _ => skipTree() initsFlags = EmptyFlags @@ -721,13 +719,13 @@ class TreeUnpickler(reader: TastyReader, * - an end address, * - a context which has the processed package as owner */ - def processPackage[T](op: (RefTree, Addr) => Context => T)(using Context): T = { + def processPackage[T](op: (RefTree, Addr) => Context ?=> T)(using Context): T = { val sctx = sourceChangeContext() if (sctx `ne` ctx) return processPackage(op)(using sctx) readByte() val end = readEnd() val pid = ref(readTermRef()).asInstanceOf[RefTree] - op(pid, end)(localContext(pid.symbol.moduleClass)) + op(pid, end)(using localContext(pid.symbol.moduleClass)) } /** Create symbols the longest consecutive sequence of parameters with given @@ -791,7 +789,7 @@ class TreeUnpickler(reader: TastyReader, def complete(using Context) = typer.Inliner.bodyToInline(sym) } else - readLater(end, rdr => implicit ctx => rdr.readTerm()) + readLater(end, _.readTerm()) def ValDef(tpt: Tree) = ta.assignType(untpd.ValDef(sym.name.asTermName, tpt, readRhs(using localCtx)), sym) @@ -815,10 +813,10 @@ class TreeUnpickler(reader: TastyReader, val vparamss = readParamss(using localCtx) val tpt = readTpt()(using localCtx) val typeParams = tparams.map(_.symbol) - val valueParamss = ctx.normalizeIfConstructor( + val valueParamss = normalizeIfConstructor( vparamss.nestedMap(_.symbol), name == nme.CONSTRUCTOR) - val resType = ctx.effectiveResultType(sym, typeParams, tpt.tpe) - sym.info = ctx.methodType(typeParams, valueParamss, resType) + val resType = effectiveResultType(sym, typeParams, tpt.tpe) + sym.info = methodType(typeParams, valueParamss, resType) DefDef(tparams, vparamss, tpt) case VALDEF => val tpt = readTpt()(using localCtx) @@ -928,7 +926,7 @@ class TreeUnpickler(reader: TastyReader, val constr = readIndexedDef().asInstanceOf[DefDef] val mappedParents = parents.map(_.changeOwner(localDummy, constr.symbol)) - val lazyStats = readLater(end, rdr => implicit ctx => { + val lazyStats = readLater(end, rdr => { val stats = rdr.readIndexedStats(localDummy, end) tparams ++ vparams ++ stats }) @@ -965,8 +963,7 @@ class TreeUnpickler(reader: TastyReader, readImport() case PACKAGE => val start = currentAddr - processPackage { (pid, end) => ctx => - given Context = ctx + processPackage { (pid, end) => setSpan(start, PackageDef(pid, readIndexedStats(exprOwner, end))) } case _ => @@ -1205,7 +1202,7 @@ class TreeUnpickler(reader: TastyReader, UnApply(fn, implicitArgs, argPats, patType) case REFINEDtpt => val refineCls = symAtAddr.getOrElse(start, - ctx.newRefinedClassSymbol(coordAt(start))).asClass + newRefinedClassSymbol(coordAt(start))).asClass registerSym(start, refineCls) typeAtAddr(start) = refineCls.typeRef val parent = readTpt() @@ -1311,10 +1308,10 @@ class TreeUnpickler(reader: TastyReader, setSpan(start, CaseDef(pat, guard, rhs)) } - def readLater[T <: AnyRef](end: Addr, op: TreeReader => Context => T)(using Context): Trees.Lazy[T] = + def readLater[T <: AnyRef](end: Addr, op: TreeReader => Context ?=> T)(using Context): Trees.Lazy[T] = readLaterWithOwner(end, op)(ctx.owner) - def readLaterWithOwner[T <: AnyRef](end: Addr, op: TreeReader => Context => T)(using Context): Symbol => Trees.Lazy[T] = { + def readLaterWithOwner[T <: AnyRef](end: Addr, op: TreeReader => Context ?=> T)(using Context): Symbol => Trees.Lazy[T] = { val localReader = fork goto(end) owner => new LazyReader(localReader, owner, ctx.mode, ctx.source, op) @@ -1375,10 +1372,10 @@ class TreeUnpickler(reader: TastyReader, class LazyReader[T <: AnyRef]( reader: TreeReader, owner: Symbol, mode: Mode, source: SourceFile, - op: TreeReader => Context => T) extends Trees.Lazy[T] { + op: TreeReader => Context ?=> T) extends Trees.Lazy[T] { def complete(using Context): T = { pickling.println(i"starting to read at ${reader.reader.currentAddr} with owner $owner") - op(reader)(ctx + op(reader)(using ctx .withPhaseNoLater(picklerPhase) .withOwner(owner) .withModeBits(mode) diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index 85c8f6a8d071..6a76dbe0ee26 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -27,8 +27,7 @@ import classfile.ClassfileParser import scala.collection.mutable import scala.collection.mutable.ListBuffer import scala.annotation.switch -import reporting.trace -import dotty.tools.dotc.reporting.messages.FailureToEliminateExistential +import reporting._ object Scala2Unpickler { @@ -77,7 +76,7 @@ object Scala2Unpickler { def ensureConstructor(cls: ClassSymbol, scope: Scope)(using Context): Unit = { if (scope.lookup(nme.CONSTRUCTOR) == NoSymbol) { - val constr = ctx.newDefaultConstructor(cls) + val constr = newDefaultConstructor(cls) addConstructorTypeParams(constr) cls.enter(constr, scope) } @@ -411,7 +410,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas // (3) Try as a nested object symbol. nestedObjectSymbol orElse { // (4) Call the mirror's "missing" hook. - adjust(ctx.base.missingHook(owner, name)) orElse { + adjust(missingHook(owner, name)) orElse { // println(owner.info.decls.toList.map(_.debugString).mkString("\n ")) // !!! DEBUG // } // (5) Create a stub symbol to defer hard failure a little longer. @@ -421,7 +420,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas if (slowSearch(name).exists) System.err.println(i"**** slow search found: ${slowSearch(name)}") if (ctx.settings.YdebugMissingRefs.value) Thread.dumpStack() - ctx.newStubSymbol(owner, name, source) + newStubSymbol(owner, name, source) } } } @@ -513,7 +512,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas var name1 = name.asTypeName var flags1 = flags if (flags.is(TypeParam)) flags1 |= owner.typeParamCreationFlags - ctx.newSymbol(owner, name1, flags1, localMemberUnpickler, privateWithin, coord = start) + newSymbol(owner, name1, flags1, localMemberUnpickler, privateWithin, coord = start) case CLASSsym => if (isClassRoot) completeRoot( @@ -525,21 +524,21 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas def completer(cls: Symbol) = { val unpickler = new ClassUnpickler(infoRef) withDecls symScope(cls) if (flags.is(ModuleClass)) - unpickler withSourceModule (implicit ctx => + unpickler.withSourceModule( cls.owner.info.decls.lookup(cls.name.sourceModuleName) .suchThat(_.is(Module)).symbol) else unpickler } - ctx.newClassSymbol(owner, name.asTypeName, flags, completer, privateWithin, coord = start) + newClassSymbol(owner, name.asTypeName, flags, completer, privateWithin, coord = start) } case VALsym => - ctx.newSymbol(owner, name.asTermName, flags, localMemberUnpickler, privateWithin, coord = start) + newSymbol(owner, name.asTermName, flags, localMemberUnpickler, privateWithin, coord = start) case MODULEsym => if (isModuleRoot) { moduleRoot setFlag flags moduleRoot.symbol - } else ctx.newSymbol(owner, name.asTermName, flags, - new LocalUnpickler() withModuleClass(implicit ctx => + } else newSymbol(owner, name.asTermName, flags, + new LocalUnpickler().withModuleClass( owner.info.decls.lookup(name.moduleClassName) .suchThat(_.is(Module)).symbol) , privateWithin, coord = start) @@ -607,8 +606,11 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas // println(s"unpickled ${denot.debugString}, info = ${denot.info}") !!! DEBUG } atReadPos(startCoord(denot).toIndex, - () => parseToCompletion(denot)( - using ctx.addMode(Mode.Scala2Unpickling).withPhaseNoLater(picklerPhase))) + () => withMode(Mode.Scala2Unpickling) { + atPhaseNoLater(picklerPhase) { + parseToCompletion(denot) + } + }) } catch { case ex: RuntimeException => handleRuntimeException(ex) @@ -640,7 +642,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas def rootClassUnpickler(start: Coord, cls: Symbol, module: Symbol, infoRef: Int): ClassUnpickler = (new ClassUnpickler(infoRef) with SymbolLoaders.SecondCompleter { override def startCoord(denot: SymDenotation): Coord = start - }) withDecls symScope(cls) withSourceModule (_ => module) + }).withDecls(symScope(cls)).withSourceModule(module) /** Convert * tp { type name = sym } forSome { sym >: L <: H } @@ -703,7 +705,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas val anyTypes = boundSyms map (_ => defn.AnyType) val boundBounds = boundSyms map (_.info.bounds.hi) val tp2 = tp1.subst(boundSyms, boundBounds).subst(boundSyms, anyTypes) - ctx.warning(FailureToEliminateExistential(tp, tp1, tp2, boundSyms)) + report.warning(FailureToEliminateExistential(tp, tp1, tp2, boundSyms)) tp2 } else tp1 @@ -984,7 +986,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas protected def deferredAnnot(end: Int)(using Context): Annotation = { val start = readIndex val atp = readTypeRef() - val phase = ctx.phase + val phase = currentPhase Annotation.deferred(atp.typeSymbol)( atReadPos(start, () => atPhase(phase)(readAnnotationContents(end)))) } @@ -1133,7 +1135,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas val body = readTreeRef() val vparams = until(end, () => readValDefRef()) val applyType = MethodType(vparams map (_.name), vparams map (_.tpt.tpe), body.tpe) - val applyMeth = ctx.newSymbol(symbol.owner, nme.apply, Method, applyType) + val applyMeth = newSymbol(symbol.owner, nme.apply, Method, applyType) Closure(applyMeth, Function.const(body.changeOwner(symbol, applyMeth)) _) case ASSIGNtree => diff --git a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala index 0a8f950b97bc..ac0f4df6f3c9 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala @@ -14,7 +14,7 @@ import dotty.tools.dotc.tastyreflect.ReflectionImpl class IDEDecompilerDriver(val settings: List[String]) extends dotc.Driver { private val myInitCtx: Context = { - val rootCtx = initCtx.fresh.addMode(Mode.Interactive).addMode(Mode.ReadPositions).addMode(Mode.ReadComments) + val rootCtx = initCtx.fresh.addMode(Mode.Interactive | Mode.ReadPositions | Mode.ReadComments) rootCtx.setSetting(rootCtx.settings.YretainTrees, true) rootCtx.setSetting(rootCtx.settings.fromTasty, true) val ctx = setup(settings.toArray :+ "dummy.scala", rootCtx)._2 diff --git a/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala b/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala index ad398a0036c9..feb9e63b0182 100644 --- a/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala +++ b/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala @@ -4,9 +4,10 @@ package fromtasty import core._ import Decorators._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols.{Symbol, ClassSymbol} import SymDenotations.ClassDenotation +import Denotations.staticRef import NameOps._ import ast.Trees.Tree import Phases.Phase @@ -21,14 +22,14 @@ class ReadTasty extends Phase { ctx.settings.fromTasty.value override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = - units.flatMap(readTASTY(_)(using ctx.addMode(Mode.ReadPositions))) + withMode(Mode.ReadPositions)(units.flatMap(readTASTY(_))) def readTASTY(unit: CompilationUnit)(using Context): Option[CompilationUnit] = unit match { case unit: TASTYCompilationUnit => val className = unit.className.toTypeName def cannotUnpickle(reason: String): None.type = { - ctx.error(s"class $className cannot be unpickled because $reason") + report.error(s"class $className cannot be unpickled because $reason") None } @@ -59,7 +60,7 @@ class ReadTasty extends Phase { // Note that if both the class and the object are present, then loading the class will also load // the object, this is why we use orElse here, otherwise we could load the object twice and // create ambiguities! - ctx.base.staticRef(className) match { + staticRef(className) match { case clsd: ClassDenotation => clsd.infoOrCompleter match { case info: ClassfileLoader => diff --git a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala index 938cd3230054..a88f9f80c15d 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala @@ -6,7 +6,8 @@ import scala.annotation.tailrec import scala.collection._ import ast.{NavigateAST, Trees, tpd, untpd} -import core._, core.Decorators._ +import core._ +import Decorators._, ContextOps._ import Contexts._, Flags._, Names._, NameOps._, Symbols._, Trees._, Types._ import transform.SymUtils.decorateSymbol import util.Spans._, util.SourceFile, util.SourcePosition diff --git a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala index 869147e9feb4..d9c7d286f5be 100644 --- a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala +++ b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala @@ -16,6 +16,7 @@ import dotty.tools.io.{ AbstractFile, ClassPath, ClassRepresentation, PlainFile, import ast.{Trees, tpd} import core._, core.Decorators._ import Contexts._, Names._, NameOps._, Symbols._, SymDenotations._, Trees._, Types._ +import Denotations.staticRef import classpath._ import reporting._ import util._ @@ -184,7 +185,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { */ private def treesFromClassName(className: TypeName, id: String)(using Context): List[SourceTree] = { def trees(className: TypeName, id: String): List[SourceTree] = { - val clsd = ctx.base.staticRef(className) + val clsd = staticRef(className) clsd match { case clsd: ClassDenotation => clsd.ensureCompleted() diff --git a/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala b/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala index d513122e7ae3..467228ded06b 100644 --- a/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala @@ -19,7 +19,7 @@ import Symbols._ import ast.Trees._ import Decorators._ import StdNames._ -import dotty.tools.dotc.reporting.messages.IdentifierExpected +import reporting._ import dotty.tools.dotc.util.SourceFile import util.Spans._ import scala.collection.mutable.ListBuffer diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index 1d744b6731c8..943fe2603a72 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -26,8 +26,7 @@ import Decorators._ import scala.internal.Chars import scala.annotation.{tailrec, switch} import rewrites.Rewrites.{patch, overlapsPatch} -import reporting.Message -import reporting.messages._ +import reporting._ import config.Feature.{sourceVersion, migrateTo3} import config.SourceVersion._ import config.SourceVersion @@ -149,7 +148,7 @@ object Parsers { * updating lastErrorOffset. */ def syntaxError(msg: Message, span: Span): Unit = - ctx.error(msg, source.atSpan(span)) + report.error(msg, source.atSpan(span)) def unimplementedExpr(using Context): Select = Select(Select(rootDot(nme.scala), nme.Predef), nme.???) @@ -315,17 +314,17 @@ object Parsers { } def warning(msg: Message, sourcePos: SourcePosition): Unit = - ctx.warning(msg, sourcePos) + report.warning(msg, sourcePos) def warning(msg: Message, offset: Int = in.offset): Unit = - ctx.warning(msg, source.atSpan(Span(offset))) + report.warning(msg, source.atSpan(Span(offset))) def deprecationWarning(msg: Message, offset: Int = in.offset): Unit = - ctx.deprecationWarning(msg, source.atSpan(Span(offset))) + report.deprecationWarning(msg, source.atSpan(Span(offset))) /** Issue an error at current offset that input is incomplete */ def incompleteInputError(msg: Message): Unit = - ctx.incompleteInputError(msg, source.atSpan(Span(in.offset))) + report.incompleteInputError(msg, source.atSpan(Span(in.offset))) /** If at end of file, issue an incompleteInputError. * Otherwise issue a syntax error and skip to next safe point. @@ -455,7 +454,7 @@ object Parsers { case Tuple(ts) => ts.map(convertToParam(_, mods)) case t: Typed => - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( em"parentheses are required around the parameter of a lambda${rewriteNotice()}", in.sourcePos()) if migrateTo3 then @@ -1198,7 +1197,7 @@ object Parsers { Quote(t) } else { - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( em"""symbol literal '${in.name} is no longer supported, |use a string literal "${in.name}" or an application Symbol("${in.name}") instead, |or enclose in braces '{${in.name}} if you want a quoted expression.""", @@ -1243,7 +1242,7 @@ object Parsers { if (inPattern) Block(Nil, inBraces(pattern())) else expr() else { - ctx.error(InterpolatedStringError(), source.atSpan(Span(in.offset))) + report.error(InterpolatedStringError(), source.atSpan(Span(in.offset))) EmptyTree } }) @@ -1291,7 +1290,7 @@ object Parsers { if migrateTo3 && in.token == NEWLINE && in.next.token == LBRACE then in.nextToken() if in.indentWidth(in.offset) == in.currentRegion.indentWidth then - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( i"""This opening brace will start a new statement in Scala 3. |It needs to be indented to the right to keep being treated as |an argument to the previous expression.${rewriteNotice()}""", @@ -1816,7 +1815,7 @@ object Parsers { AppliedTypeTree(toplevelTyp(), Ident(pname)) } :: contextBounds(pname) case VIEWBOUND => - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( "view bounds `<%' are deprecated, use a context bound `:' instead", in.sourcePos()) atSpan(in.skipToken()) { @@ -1963,7 +1962,7 @@ object Parsers { WhileDo(cond, body) } case DO => - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( i"""`do while ` is no longer supported, |use `while ; do ()` instead.${rewriteNotice()}""", in.sourcePos()) @@ -2091,7 +2090,7 @@ object Parsers { in.nextToken() if !(location.inArgs && in.token == RPAREN) then if opStack.nonEmpty - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( em"""`_*` can be used only for last argument of method application. |It is no longer allowed in operands of infix operations.""", in.sourcePos(uscoreStart)) @@ -2170,7 +2169,7 @@ object Parsers { if sourceVersion.isAtLeast(`3.1`) // Don't error in non-strict mode, as the alternative syntax "implicit (x: T) => ... " // is not supported by Scala2.x - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( s"This syntax is no longer supported; parameter needs to be enclosed in (...)", in.sourcePos()) in.nextToken() @@ -2654,7 +2653,7 @@ object Parsers { infixPattern() match { case pt @ Ident(tpnme.WILDCARD_STAR) => if sourceVersion.isAtLeast(`3.1`) then - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( "The syntax `x @ _*` is no longer supported; use `x : _*` instead", in.sourcePos(startOffset(p))) atSpan(startOffset(p), offset) { Typed(p, pt) } @@ -2664,7 +2663,7 @@ object Parsers { case p @ Ident(tpnme.WILDCARD_STAR) => // compatibility for Scala2 `_*` syntax if sourceVersion.isAtLeast(`3.1`) then - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( "The syntax `_*` is no longer supported; use `x : _*` instead", in.sourcePos(startOffset(p))) atSpan(startOffset(p)) { Typed(Ident(nme.WILDCARD), p) } @@ -3277,7 +3276,7 @@ object Parsers { if in.token == LBRACE then s"$resultTypeStr =" else ": Unit " // trailing space ensures that `def f()def g()` works. if migrateTo3 then - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( s"Procedure syntax no longer supported; `$toInsert` should be inserted here", in.sourcePos()) patch(source, Span(in.lastOffset), toInsert) @@ -3721,7 +3720,7 @@ object Parsers { if (in.token == EXTENDS) { in.nextToken() if (in.token == LBRACE || in.token == COLONEOL) { - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( "`extends` must be followed by at least one parent", in.sourcePos()) Nil diff --git a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala index 22a51d42deba..b37d933ab7be 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala @@ -126,11 +126,11 @@ object Scanners { } def errorButContinue(msg: String, off: Offset = offset): Unit = - ctx.error(msg, sourcePos(off)) + report.error(msg, sourcePos(off)) /** signal an error where the input ended in the middle of a token */ def incompleteInputError(msg: String): Unit = { - ctx.incompleteInputError(msg, sourcePos()) + report.incompleteInputError(msg, sourcePos()) token = EOF errOffset = offset } @@ -249,7 +249,7 @@ object Scanners { else keyword private def treatAsIdent(): Token = - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( i"$name is now a keyword, write `$name` instead of $name to keep it as an identifier", sourcePos()) patch(source, Span(offset), "`") @@ -390,7 +390,7 @@ object Scanners { val (what, previous) = if inConditional then ("Rest of line", "previous expression in parentheses") else ("Line", "expression on the previous line") - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( em"""$what starts with an operator; |it is now treated as a continuation of the $previous, |not as a separate statement.""", @@ -515,7 +515,7 @@ object Scanners { currentRegion = r.enclosing insert(OUTDENT, offset) case r: InBraces if !closingRegionTokens.contains(token) => - ctx.warning("Line is indented too far to the left, or a `}` is missing", + report.warning("Line is indented too far to the left, or a `}` is missing", source.atSpan(Span(offset))) case _ => diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala index 8f20515d7813..a4db7ef44a86 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala @@ -8,7 +8,6 @@ import dotty.tools.io._ import Phases._ import config.Printers.plugins.{ println => debug } - /** Support for run-time loading of compiler plugins. * * @author Lex Spoon @@ -35,8 +34,8 @@ trait Plugins { // Explicit parameterization of recover to avoid -Xlint warning about inferred Any errors foreach (_.recover[Any] { // legacy behavior ignores altogether, so at least warn devs - case e: MissingPluginException => ctx.warning(e.getMessage) - case e: Exception => ctx.inform(e.getMessage) + case e: MissingPluginException => report.warning(e.getMessage) + case e: Exception => report.inform(e.getMessage) }) goods map (_.get) @@ -65,7 +64,7 @@ trait Plugins { def withoutPlug = pick(tail, plugNames) def withPlug = plug :: pick(tail, plugNames + plug.name) - def note(msg: String): Unit = if (ctx.settings.verbose.value) ctx.inform(msg format plug.name) + def note(msg: String): Unit = if (ctx.settings.verbose.value) report.inform(msg format plug.name) def fail(msg: String) = { note(msg) ; withoutPlug } if (plugNames contains plug.name) @@ -82,14 +81,14 @@ trait Plugins { // Verify required plugins are present. for (req <- ctx.settings.require.value ; if !(plugs exists (_.name == req))) - ctx.error("Missing required plugin: " + req) + report.error("Missing required plugin: " + req) // Verify no non-existent plugin given with -P for { opt <- ctx.settings.pluginOptions.value if !(plugs exists (opt startsWith _.name + ":")) } - ctx.error("bad option: -P:" + opt) + report.error("bad option: -P:" + opt) plugs } diff --git a/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala b/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala index 8b0766c57615..936247e93549 100644 --- a/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala +++ b/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala @@ -32,7 +32,7 @@ object MessageLimiter extends Property.Key[MessageLimiter] class DefaultMessageLimiter extends MessageLimiter: override def recursionLimitExceeded()(using Context): Unit = if ctx.debug then - ctx.warning("Exceeded recursion depth attempting to print.") + report.warning("Exceeded recursion depth attempting to print.") Thread.dumpStack() class SummarizeMessageLimiter(depth: Int) extends MessageLimiter: diff --git a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala index f31daa33d13c..668ed1d9c3a6 100644 --- a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala +++ b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala @@ -3,7 +3,7 @@ package printing import core._ import Texts._, Types._, Flags._, Names._, Symbols._, NameOps._, Constants._, Denotations._ -import Contexts.{Context, ctx} +import Contexts._ import Scopes.Scope, Denotations.Denotation, Annotations.Annotation import StdNames.nme import ast.Trees._ @@ -48,7 +48,7 @@ class PlainPrinter(_ctx: Context) extends Printer { if (homogenizedView) tp match { case tp: ThisType if tp.cls.is(Package) && !tp.cls.isEffectiveRoot => - ctx.requiredPackage(tp.cls.fullName).termRef + requiredPackage(tp.cls.fullName).termRef case tp: TypeVar if tp.isInstantiated => homogenize(tp.instanceOpt) case AndType(tp1, tp2) => @@ -215,8 +215,10 @@ class PlainPrinter(_ctx: Context) extends Printer { else { val constr = ctx.typerState.constraint val bounds = - if (constr.contains(tp)) ctx.addMode(Mode.Printing).typeComparer.fullBounds(tp.origin) - else TypeBounds.empty + if constr.contains(tp) then + withMode(Mode.Printing)(ctx.typeComparer.fullBounds(tp.origin)) + else + TypeBounds.empty if (bounds.isTypeAlias) toText(bounds.lo) ~ (Str("^") provided printDebug) else if (ctx.settings.YshowVarBounds.value) "(" ~ toText(tp.origin) ~ "?" ~ toText(bounds) ~ ")" else toText(tp.origin) diff --git a/compiler/src/dotty/tools/dotc/printing/Printers.scala b/compiler/src/dotty/tools/dotc/printing/Printers.scala deleted file mode 100644 index c946990b90cf..000000000000 --- a/compiler/src/dotty/tools/dotc/printing/Printers.scala +++ /dev/null @@ -1,14 +0,0 @@ -package dotty.tools.dotc -package printing - -import core.Contexts.{Context, ctx} - -trait Printers { this: Context => - - /** A function creating a printer */ - def printer: Printer = { - val pr = printerFn(this) - if (this.settings.YplainPrinter.value) pr.plain else pr - } -} - diff --git a/compiler/src/dotty/tools/dotc/report.scala b/compiler/src/dotty/tools/dotc/report.scala new file mode 100644 index 000000000000..cc22c1fe11ea --- /dev/null +++ b/compiler/src/dotty/tools/dotc/report.scala @@ -0,0 +1,123 @@ +package dotty.tools.dotc + +import reporting._ +import Diagnostic._ +import util.{SourcePosition, NoSourcePosition} +import core._ +import Contexts._, Symbols._, Decorators._ +import config.SourceVersion +import ast._ +import config.Feature.sourceVersion +import java.lang.System.currentTimeMillis + + +object report: + + /** For sending messages that are printed only if -verbose is set */ + def inform(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + if ctx.settings.verbose.value then echo(msg, pos) + + def echo(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + ctx.reporter.report(new Info(msg, pos)) + + private def issueWarning(warning: Warning)(using Context): Unit = + if (!ctx.settings.silentWarnings.value) + if (ctx.settings.XfatalWarnings.value) + warning match { + case warning: ConditionalWarning if !warning.enablingOption.value => + ctx.reporter.report(warning) // conditional warnings that are not enabled are not fatal + case _ => + ctx.reporter.report(warning.toError) + } + else ctx.reporter.report(warning) + + def deprecationWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + issueWarning(new DeprecationWarning(msg, pos)) + + def migrationWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + issueWarning(new MigrationWarning(msg, pos)) + + def uncheckedWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + issueWarning(new UncheckedWarning(msg, pos)) + + def featureWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + issueWarning(new FeatureWarning(msg, pos)) + + def featureWarning(feature: String, featureDescription: String, + featureUseSite: Symbol, required: Boolean, pos: SourcePosition)(using Context): Unit = { + val req = if (required) "needs to" else "should" + val fqname = s"scala.language.$feature" + + val explain = + if ctx.reporter.isReportedFeatureUseSite(featureUseSite) then "" + else + ctx.reporter.reportNewFeatureUseSite(featureUseSite) + s""" + |See the Scala docs for value $fqname for a discussion + |why the feature $req be explicitly enabled.""".stripMargin + + val msg = s"""$featureDescription $req be enabled + |by adding the import clause 'import $fqname' + |or by setting the compiler option -language:$feature.$explain""".stripMargin + if (required) error(msg, pos) + else issueWarning(new FeatureWarning(msg, pos)) + } + + def warning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + issueWarning(new Warning(msg, addInlineds(pos))) + + def error(msg: Message, pos: SourcePosition = NoSourcePosition, sticky: Boolean = false)(using Context): Unit = + val fullPos = addInlineds(pos) + ctx.reporter.report(if (sticky) new StickyError(msg, fullPos) else new Error(msg, fullPos)) + if ctx.settings.YdebugError.value then Thread.dumpStack() + + def error(ex: TypeError, pos: SourcePosition)(using Context): Unit = + error(ex.toMessage, pos, sticky = true) + if ctx.settings.YdebugTypeError.value then ex.printStackTrace() + + def errorOrMigrationWarning(msg: Message, pos: SourcePosition = NoSourcePosition, + from: SourceVersion = SourceVersion.defaultSourceVersion)(using Context): Unit = + if sourceVersion.isAtLeast(from) then + if sourceVersion.isMigrating then migrationWarning(msg, pos) + else error(msg, pos) + + def restrictionError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + error(msg.mapMsg("Implementation restriction: " + _), pos) + + def incompleteInputError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + ctx.reporter.incomplete(new Error(msg, pos)) + + /** Log msg if settings.log contains the current phase. + * See [[config.CompilerCommand#explainAdvanced]] for the exact meaning of + * "contains" here. + */ + def log(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + if (ctx.settings.Ylog.value.containsPhase(currentPhase)) + echo(s"[log $currentPhase] $msg", pos) + + def debuglog(msg: => String)(using Context): Unit = + if (ctx.debug) log(msg) + + def informTime(msg: => String, start: Long)(using Context): Unit = { + def elapsed = s" in ${currentTimeMillis - start}ms" + informProgress(msg + elapsed) + } + + def informProgress(msg: => String)(using Context): Unit = + inform("[" + msg + "]") + + def logWith[T](msg: => String)(value: T)(using Context): T = { + log(msg + " " + value) + value + } + + def debugwarn(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + if (ctx.settings.Ydebug.value) warning(msg, pos) + + private def addInlineds(pos: SourcePosition)(using Context) = + def recur(pos: SourcePosition, inlineds: List[Trees.Tree[?]]): SourcePosition = inlineds match + case inlined :: inlineds1 => pos.withOuter(recur(inlined.sourcePos, inlineds1)) + case Nil => pos + recur(pos, tpd.enclosingInlineds) + +end report \ No newline at end of file diff --git a/compiler/src/dotty/tools/dotc/reporting/Message.scala b/compiler/src/dotty/tools/dotc/reporting/Message.scala index 43c456a7aa74..be711d060d47 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Message.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Message.scala @@ -4,8 +4,6 @@ package reporting import util.SourcePosition -import messages._ - object Message { val nonSensicalStartTag: String = "" val nonSensicalEndTag: String = "" diff --git a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala index b846ba7d9f17..47464eb43b00 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala @@ -5,8 +5,6 @@ package reporting import scala.annotation.internal.sharable import core.Contexts._ -import core.TypeError -import util.{SourcePosition, NoSourcePosition} import core.Decorators.PhaseListDecorator import collection.mutable import core.Mode @@ -15,10 +13,8 @@ import Diagnostic._ import ast.{tpd, Trees} import Message._ import core.Decorators._ -import config.Feature.sourceVersion -import config.SourceVersion +import util.NoSourcePosition -import java.lang.System.currentTimeMillis import java.io.{ BufferedReader, PrintWriter } @@ -68,122 +64,6 @@ object Reporter { } } -trait Reporting { thisCtx: Context => - - /** For sending messages that are printed only if -verbose is set */ - def inform(msg: => String, pos: SourcePosition = NoSourcePosition): Unit = - if (thisCtx.settings.verbose.value) thisCtx.echo(msg, pos) - - def echo(msg: => String, pos: SourcePosition = NoSourcePosition): Unit = - reporter.report(new Info(msg, pos)) - - def reportWarning(warning: Warning): Unit = - if (!thisCtx.settings.silentWarnings.value) - if (thisCtx.settings.XfatalWarnings.value) - warning match { - case warning: ConditionalWarning if !warning.enablingOption.value => - reporter.report(warning) // conditional warnings that are not enabled are not fatal - case _ => - reporter.report(warning.toError) - } - else reporter.report(warning) - - def deprecationWarning(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = - reportWarning(new DeprecationWarning(msg, pos)) - - def migrationWarning(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = - reportWarning(new MigrationWarning(msg, pos)) - - def uncheckedWarning(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = - reportWarning(new UncheckedWarning(msg, pos)) - - def featureWarning(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = - reportWarning(new FeatureWarning(msg, pos)) - - def featureWarning(feature: String, featureDescription: String, - featureUseSite: Symbol, required: Boolean, pos: SourcePosition): Unit = { - val req = if (required) "needs to" else "should" - val fqname = s"scala.language.$feature" - - val explain = - if (reporter.isReportedFeatureUseSite(featureUseSite)) "" - else { - reporter.reportNewFeatureUseSite(featureUseSite) - s""" - |See the Scala docs for value $fqname for a discussion - |why the feature $req be explicitly enabled.""".stripMargin - } - - val msg = s"""$featureDescription $req be enabled - |by adding the import clause 'import $fqname' - |or by setting the compiler option -language:$feature.$explain""".stripMargin - if (required) error(msg, pos) - else reportWarning(new FeatureWarning(msg, pos)) - } - - def warning(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = - reportWarning(new Warning(msg, addInlineds(pos))) - - def error(msg: Message, pos: SourcePosition = NoSourcePosition, sticky: Boolean = false): Unit = { - val fullPos = addInlineds(pos) - reporter.report(if (sticky) new StickyError(msg, fullPos) else new Error(msg, fullPos)) - if thisCtx.settings.YdebugError.value then Thread.dumpStack() - } - - def error(ex: TypeError, pos: SourcePosition): Unit = { - error(ex.toMessage, pos, sticky = true) - if (thisCtx.settings.YdebugTypeError.value) - ex.printStackTrace() - } - - def errorOrMigrationWarning(msg: Message, pos: SourcePosition = NoSourcePosition, - from: SourceVersion = SourceVersion.defaultSourceVersion): Unit = - if sourceVersion.isAtLeast(from) then - if sourceVersion.isMigrating then migrationWarning(msg, pos) - else error(msg, pos) - - def restrictionError(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = - error(msg.mapMsg("Implementation restriction: " + _), pos) - - def incompleteInputError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - reporter.incomplete(new Error(msg, pos)) - - /** Log msg if settings.log contains the current phase. - * See [[config.CompilerCommand#explainAdvanced]] for the exact meaning of - * "contains" here. - */ - def log(msg: => String, pos: SourcePosition = NoSourcePosition): Unit = - if (thisCtx.settings.Ylog.value.containsPhase(phase)) - echo(s"[log ${thisCtx.phasesStack.reverse.mkString(" -> ")}] $msg", pos) - - def debuglog(msg: => String): Unit = - if (thisCtx.debug) log(msg) - - def informTime(msg: => String, start: Long): Unit = { - def elapsed = s" in ${currentTimeMillis - start}ms" - informProgress(msg + elapsed) - } - - def informProgress(msg: => String): Unit = - inform("[" + msg + "]") - - def logWith[T](msg: => String)(value: T): T = { - log(msg + " " + value) - value - } - - def debugwarn(msg: => String, pos: SourcePosition = NoSourcePosition): Unit = - if (thisCtx.settings.Ydebug.value) warning(msg, pos) - - private def addInlineds(pos: SourcePosition)(using Context) = { - def recur(pos: SourcePosition, inlineds: List[Trees.Tree[?]]): SourcePosition = inlineds match { - case inlined :: inlineds1 => pos.withOuter(recur(inlined.sourcePos, inlineds1)) - case Nil => pos - } - recur(pos, tpd.enclosingInlineds) - } -} - /** * This interface provides methods to issue information, warning and * error messages. @@ -246,9 +126,9 @@ abstract class Reporter extends interfaces.ReporterResult { /** Run `op` and return `true` if errors were reported by this reporter. */ - def reportsErrorsFor(op: Context => Unit)(using Context): Boolean = { + def reportsErrorsFor(op: Context ?=> Unit)(using Context): Boolean = { val initial = errorCount - op(ctx) + op errorCount > initial } @@ -263,7 +143,7 @@ abstract class Reporter extends interfaces.ReporterResult { def report(dia: Diagnostic)(using Context): Unit = if (!isHidden(dia)) { - doReport(dia)(using ctx.addMode(Mode.Printing)) + withMode(Mode.Printing)(doReport(dia)) dia match { case dia: ConditionalWarning if !dia.enablingOption.value => val key = dia.enablingOption.name @@ -296,7 +176,7 @@ abstract class Reporter extends interfaces.ReporterResult { /** Print the summary of warnings and errors */ def printSummary(using Context): Unit = { val s = summary - if (s != "") ctx.echo(s) + if (s != "") report(new Info(s, NoSourcePosition)) } /** Returns a string meaning "n elements". */ diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index 1c7009e92128..c720ac1c372d 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -3,7 +3,7 @@ package dotc package reporting import core._ -import Contexts.{Context, ctx} +import Contexts._ import Decorators._, Symbols._, Names._, NameOps._, Types._, Flags._, Phases._ import Denotations.SingleDenotation import SymDenotations.SymDenotation @@ -20,6 +20,9 @@ import typer.ProtoTypes.ViewProto import scala.util.control.NonFatal import StdNames.nme import printing.Formatting.hl +import ast.Trees._ +import ast.untpd +import ast.tpd /** Messages * ======== @@ -33,16 +36,6 @@ import printing.Formatting.hl * EmptyCatchBlock(tree).warning(pos) // res: Warning * ``` */ -object messages { - - import ast.Trees._ - import ast.untpd - import ast.tpd - - /** Helper methods for messages */ - def implicitClassRestrictionsText(using Context): String = - em"""|For a full list of restrictions on implicit classes visit - |${Blue("http://docs.scala-lang.org/overviews/core/implicit-classes.html")}""" abstract class SyntaxMsg(errorId: ErrorMessageID) extends Message(errorId): def kind = "Syntax" @@ -407,9 +400,7 @@ object messages { |the implicit class and a case class automatically gets a companion object with |the same name created by the compiler which would cause a naming conflict if it |were allowed. - | - |""" + implicitClassRestrictionsText + em"""| - | + | | |To resolve the conflict declare ${cdef.name} inside of an ${hl("object")} then import the class |from the object at the use site if needed, for example: | @@ -431,7 +422,7 @@ object messages { | |implicit class ${cdef.name}... | - |""" + implicitClassRestrictionsText + |""" } class ImplicitClassPrimaryConstructorArity()(using Context) @@ -445,7 +436,7 @@ object messages { | |While it’s possible to create an implicit class with more than one non-implicit argument, |such classes aren’t used during implicit lookup. - |""" + implicitClassRestrictionsText + |""" } } @@ -2020,9 +2011,8 @@ object messages { case NoMatch => // If the signatures don't match at all at the current phase, then // they might match after erasure. - val elimErasedCtx = ctx.withPhaseNoEarlier(elimErasedValueTypePhase.next) - if (elimErasedCtx != ctx) - details(using elimErasedCtx) + if currentPhase.id <= elimErasedValueTypePhase.id then + atPhase(elimErasedValueTypePhase.next)(details) else "" // shouldn't be reachable case ParamMatch => @@ -2400,4 +2390,3 @@ object messages { def msg = s"Modifier `${flag.flagsString}` is not allowed for this definition" def explain = "" } -} diff --git a/compiler/src/dotty/tools/dotc/reporting/trace.scala b/compiler/src/dotty/tools/dotc/reporting/trace.scala index 1f9b8f0503a5..df31bbdd52e9 100644 --- a/compiler/src/dotty/tools/dotc/reporting/trace.scala +++ b/compiler/src/dotty/tools/dotc/reporting/trace.scala @@ -79,7 +79,7 @@ abstract class TraceSyntax { val log: String => Unit = if (isForced) Console.println else { var logctx = ctx while (logctx.reporter.isInstanceOf[StoreReporter]) logctx = logctx.outer - logctx.log(_) + report.log(_)(using logctx) } doApply(leading, trailing, log)(op) } diff --git a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala index c3835ded4df7..da72382aa12a 100644 --- a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala +++ b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala @@ -84,7 +84,7 @@ object Rewrites { */ def writeBack()(using Context): Unit = for (rewrites <- ctx.settings.rewrite.value; source <- rewrites.patched.keys) { - ctx.echo(s"[patched file ${source.file.path}]") + report.echo(s"[patched file ${source.file.path}]") rewrites.patched(source).writeBack() } } diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala index 544df262407e..6b095be28b44 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala @@ -248,7 +248,7 @@ private class ExtractAPICollector(using Context) extends ThunkHolder { case ex: TypeError => // See neg/i1750a for an example where a cyclic error can arise. // The root cause in this example is an illegal "override" of an inner trait - ctx.error(ex, csym.sourcePos) + report.error(ex, csym.sourcePos) defn.ObjectType :: Nil } if (ValueClasses.isDerivedValueClass(csym)) { @@ -453,7 +453,7 @@ private class ExtractAPICollector(using Context) extends ThunkHolder { case rinfo: TypeBounds => typeRefinement(name, rinfo) case _ => - ctx.debuglog(i"sbt-api: skipped structural refinement in $rt") + report.debuglog(i"sbt-api: skipped structural refinement in $rt") null } @@ -514,7 +514,7 @@ private class ExtractAPICollector(using Context) extends ThunkHolder { case tp: TypeVar => apiType(tp.underlying) case _ => { - ctx.warning(i"sbt-api: Unhandled type ${tp.getClass} : $tp") + report.warning(i"sbt-api: Unhandled type ${tp.getClass} : $tp") Constants.emptyType } } diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala index fa58b4a7c569..885aa98d6237 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala @@ -139,7 +139,7 @@ class ExtractDependencies extends Phase { binaryDependency(pf.file, binaryClassName(classSegments)) case _ => - ctx.warning(s"sbt-deps: Ignoring dependency $depFile of class ${depFile.getClass}}") + report.warning(s"sbt-deps: Ignoring dependency $depFile of class ${depFile.getClass}}") } } @@ -235,7 +235,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT val tree = ctx.compilationUnit.tpdTree _responsibleForImports = firstClassOrModule(tree) if (!_responsibleForImports.exists) - ctx.warning("""|No class, trait or object is defined in the compilation unit. + report.warning("""|No class, trait or object is defined in the compilation unit. |The incremental compiler cannot record the dependency information in such case. |Some errors like unused import referring to a non-existent class might not be reported. |""".stripMargin, tree.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala b/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala index 248b35c309aa..a41f8da4a158 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala @@ -28,7 +28,7 @@ object FromSymbol { case tpd.EmptyTree => val constrSym = cls.unforcedDecls.find(_.isPrimaryConstructor).orElse( // Dummy constructor for classes such as `` - ctx.newSymbol(cls, nme.CONSTRUCTOR, EmptyFlags, NoType) + newSymbol(cls, nme.CONSTRUCTOR, EmptyFlags, NoType) ) val constr = tpd.DefDef(constrSym.asTerm) val parents = cls.classParents.map(tpd.TypeTree(_)) diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala index 8067897ce3fe..2bc829282bf7 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala @@ -61,10 +61,10 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend def Context_GADT_approximation(self: Context)(sym: Symbol, fromBelow: Boolean): Type = self.gadt.approximation(sym, fromBelow) - def Context_requiredPackage(self: Context)(path: String): Symbol = self.requiredPackage(path) - def Context_requiredClass(self: Context)(path: String): Symbol = self.requiredClass(path) - def Context_requiredModule(self: Context)(path: String): Symbol = self.requiredModule(path) - def Context_requiredMethod(self: Context)(path: String): Symbol = self.requiredMethod(path) + def Context_requiredPackage(self: Context)(path: String): Symbol = requiredPackage(path)(using self) + def Context_requiredClass(self: Context)(path: String): Symbol = requiredClass(path)(using self) + def Context_requiredModule(self: Context)(path: String): Symbol = requiredModule(path)(using self) + def Context_requiredMethod(self: Context)(path: String): Symbol = requiredMethod(path)(using self) def Context_isJavaCompilationUnit(self: Context): Boolean = self.compilationUnit.isInstanceOf[fromtasty.JavaCompilationUnit] def Context_isScala2CompilationUnit(self: Context): Boolean = self.compilationUnit.isInstanceOf[fromtasty.Scala2CompilationUnit] def Context_isAlreadyLoadedCompilationUnit(self: Context): Boolean = self.compilationUnit.isInstanceOf[fromtasty.AlreadyLoadedCompilationUnit] @@ -82,16 +82,16 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend /////////////// def error(msg: => String, pos: Position)(using ctx: Context): Unit = - ctx.error(msg, pos) + report.error(msg, pos) def error(msg: => String, sourceFile: SourceFile, start: Int, end: Int)(using ctx: Context): Unit = - ctx.error(msg, util.SourcePosition(sourceFile, util.Spans.Span(start, end))) + report.error(msg, util.SourcePosition(sourceFile, util.Spans.Span(start, end))) def warning(msg: => String, pos: Position)(using ctx: Context): Unit = - ctx.warning(msg, pos) + report.warning(msg, pos) def warning(msg: => String, sourceFile: SourceFile, start: Int, end: Int)(using ctx: Context): Unit = - ctx.error(msg, util.SourcePosition(sourceFile, util.Spans.Span(start, end))) + report.error(msg, util.SourcePosition(sourceFile, util.Spans.Span(start, end))) ////////////// @@ -287,7 +287,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case t => t } val closureTpe = Types.MethodType(mtpe.paramNames, mtpe.paramInfos, closureResType) - val closureMethod = ctx.newSymbol(ctx.owner, nme.ANON_FUN, Synthetic | Method, closureTpe) + val closureMethod = newSymbol(ctx.owner, nme.ANON_FUN, Synthetic | Method, closureTpe) tpd.Closure(closureMethod, tss => Term_etaExpand(new tpd.TreeOps(term).appliedToArgs(tss.head))) case _ => term } @@ -1175,7 +1175,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend else enclosing.classSymbol.companionModule.termRef.select(name) } - else ctx.getClassIfDefined(clazz.getCanonicalName).typeRef + else getClassIfDefined(clazz.getCanonicalName).typeRef def Type_isTypeEq(self: Type)(that: Type)(using ctx: Context): Boolean = self =:= that @@ -1785,16 +1785,16 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend private def isField(sym: Symbol)(using ctx: Context): Boolean = sym.isTerm && !sym.is(Flags.Method) def Symbol_of(fullName: String)(using ctx: Context): Symbol = - ctx.requiredClass(fullName) + requiredClass(fullName) def Symbol_newMethod(parent: Symbol, name: String, flags: Flags, tpe: Type, privateWithin: Symbol)(using ctx: Context): Symbol = - ctx.newSymbol(parent, name.toTermName, flags | Flags.Method, tpe, privateWithin) + newSymbol(parent, name.toTermName, flags | Flags.Method, tpe, privateWithin) def Symbol_newVal(parent: Symbol, name: String, flags: Flags, tpe: Type, privateWithin: Symbol)(using ctx: Context): Symbol = - ctx.newSymbol(parent, name.toTermName, flags, tpe, privateWithin) + newSymbol(parent, name.toTermName, flags, tpe, privateWithin) def Symbol_newBind(parent: Symbol, name: String, flags: Flags, tpe: Type)(using ctx: Context): Symbol = - ctx.newSymbol(parent, name.toTermName, flags | Case, tpe) + newSymbol(parent, name.toTermName, flags | Case, tpe) def Symbol_isTypeParam(self: Symbol)(using ctx: Context): Boolean = self.isTypeParam diff --git a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala index 6626ca5123a3..17a7fe241174 100644 --- a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala +++ b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala @@ -76,7 +76,7 @@ abstract class AccessProxies { /** A fresh accessor symbol */ private def newAccessorSymbol(owner: Symbol, name: TermName, info: Type, span: Span)(using Context): TermSymbol = { - val sym = ctx.newSymbol(owner, name, Synthetic | Method, info, coord = span).entered + val sym = newSymbol(owner, name, Synthetic | Method, info, coord = span).entered if (sym.allOverriddenSymbols.exists(!_.is(Deferred))) sym.setFlag(Override) sym } @@ -145,7 +145,7 @@ abstract class AccessProxies { def accessorIfNeeded(tree: Tree)(using Context): Tree = tree match { case tree: RefTree if needsAccessor(tree.symbol) => if (tree.symbol.isConstructor) { - ctx.error("Implementation restriction: cannot use private constructors in inlineable methods", tree.sourcePos) + report.error("Implementation restriction: cannot use private constructors in inlineable methods", tree.sourcePos) tree // TODO: create a proper accessor for the private constructor } else useAccessor(tree) diff --git a/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala b/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala index 6591e847c099..7431cc94554d 100644 --- a/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala +++ b/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala @@ -38,7 +38,7 @@ class BetaReduce extends MiniPhase: override def transformApply(app: Apply)(using ctx: Context): Tree = app.fun match case Select(fn, nme.apply) if defn.isFunctionType(fn.tpe) => val app1 = betaReduce(app, fn, app.args) - if app1 ne app then ctx.log(i"beta reduce $app -> $app1") + if app1 ne app then report.log(i"beta reduce $app -> $app1") app1 case _ => app @@ -65,7 +65,7 @@ object BetaReduce: ref.symbol case _ => val flags = Synthetic | (param.symbol.flags & Erased) - val binding = ValDef(ctx.newSymbol(ctx.owner, param.name, flags, arg.tpe.widen, coord = arg.span), arg) + val binding = ValDef(newSymbol(ctx.owner, param.name, flags, arg.tpe.widen, coord = arg.span), arg) bindings += binding binding.symbol diff --git a/compiler/src/dotty/tools/dotc/transform/Bridges.scala b/compiler/src/dotty/tools/dotc/transform/Bridges.scala index b9c30746169b..a03585aa02b6 100644 --- a/compiler/src/dotty/tools/dotc/transform/Bridges.scala +++ b/compiler/src/dotty/tools/dotc/transform/Bridges.scala @@ -14,7 +14,7 @@ import util.SourcePosition class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { import ast.tpd._ - assert(ctx.phase == erasurePhase.next) + assert(currentPhase == erasurePhase.next) private val preErasureCtx = ctx.withPhase(erasurePhase) private lazy val elimErasedCtx = ctx.withPhase(elimErasedValueTypePhase.next) @@ -67,7 +67,7 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { } if (member.signature == other.signature) { if (!member.info.matches(other.info)) - ctx.error(em"""bridge generated for member ${desc(member)} + report.error(em"""bridge generated for member ${desc(member)} |which overrides ${desc(other)} |clashes with definition of the member itself; both have erased type ${info(member)(using elimErasedCtx)}."""", bridgePosFor(member)) @@ -85,7 +85,7 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { (Accessor | ParamAccessor | CaseAccessor | Deferred | Lazy | Module), coord = bridgePosFor(member).span).enteredAfter(thisPhase).asTerm - ctx.debuglog( + report.debuglog( i"""generating bridge from ${other.showLocated}: ${other.info} |to ${member.showLocated}: ${member.info} @ ${member.span} |bridge: ${bridge.showLocated} with flags: ${bridge.flagsString}""") @@ -113,7 +113,6 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { */ def add(stats: List[untpd.Tree]): List[untpd.Tree] = val opc = new BridgesCursor()(using preErasureCtx) - val ectx = ctx.withPhase(thisPhase) while opc.hasNext do if !opc.overriding.is(Deferred) then addBridgeIfNeeded(opc.overriding, opc.overridden) diff --git a/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala b/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala index 81de144ecf00..2547b6f24a38 100644 --- a/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala +++ b/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala @@ -3,6 +3,7 @@ package transform import core._ import Contexts._ +import Symbols._ import Types._ import Flags._ import DenotTransformers.IdentityDenotTransformer @@ -26,7 +27,7 @@ class ByNameClosures extends TransformByNameApply with IdentityDenotTransformer override def phaseName: String = ByNameClosures.name override def mkByNameClosure(arg: Tree, argType: Type)(using Context): Tree = { - val meth = ctx.newSymbol( + val meth = newSymbol( ctx.owner, nme.ANON_FUN, Synthetic | Method, MethodType(Nil, Nil, argType)) Closure(meth, _ => arg.changeOwnerAfter(ctx.owner, meth, thisPhase)).withSpan(arg.span) } diff --git a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala index 7e7a517b5dfc..2517b58ea617 100644 --- a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala +++ b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala @@ -38,10 +38,10 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = defn.ScalaNumericValueClasses() `union` Set(defn.BooleanClass, defn.ObjectClass) val refClass: Map[Symbol, Symbol] = - refClassKeys.map(rc => rc -> ctx.requiredClass(s"scala.runtime.${rc.name}Ref")).toMap + refClassKeys.map(rc => rc -> requiredClass(s"scala.runtime.${rc.name}Ref")).toMap val volatileRefClass: Map[Symbol, Symbol] = - refClassKeys.map(rc => rc -> ctx.requiredClass(s"scala.runtime.Volatile${rc.name}Ref")).toMap + refClassKeys.map(rc => rc -> requiredClass(s"scala.runtime.Volatile${rc.name}Ref")).toMap val boxedRefClasses: collection.Set[Symbol] = refClassKeys.flatMap(k => Set(refClass(k), volatileRefClass(k))) @@ -61,7 +61,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = if (sym.is(Mutable, butNot = Method) && sym.owner.isTerm) { val enclMeth = ctx.owner.enclosingMethod if (sym.enclosingMethod != enclMeth) { - ctx.log(i"capturing $sym in ${sym.enclosingMethod}, referenced from $enclMeth") + report.log(i"capturing $sym in ${sym.enclosingMethod}, referenced from $enclMeth") captured += sym } } diff --git a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala index ff2555aed00a..e163cfd65250 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala @@ -8,7 +8,6 @@ import Contexts.{Context, ctx} import Symbols._ import Decorators._ - /** A no-op transform that checks whether the compiled sources are re-entrant. * If -Ycheck:reentrant is set, the phase makes sure that there are no variables * that are accessible from a global object. It excludes from checking paths that @@ -37,12 +36,12 @@ class CheckReentrant extends MiniPhase { private var indent: Int = 0 private val sharableAnnot = new CtxLazy( - summon[Context].requiredClass("scala.annotation.internal.sharable")) + requiredClass("scala.annotation.internal.sharable")) private val unsharedAnnot = new CtxLazy( - summon[Context].requiredClass("scala.annotation.internal.unshared")) + requiredClass("scala.annotation.internal.unshared")) private val scalaJSIRPackageClass = new CtxLazy( - summon[Context].getPackageClassIfDefined("org.scalajs.ir")) + getPackageClassIfDefined("org.scalajs.ir")) def isIgnored(sym: Symbol)(using Context): Boolean = sym.hasAnnotation(sharableAnnot()) || @@ -55,7 +54,7 @@ class CheckReentrant extends MiniPhase { // in the long run, we should make them vals def scanning(sym: Symbol)(op: => Unit)(using Context): Unit = { - ctx.log(i"${" " * indent}scanning $sym") + report.log(i"${" " * indent}scanning $sym") indent += 1 try op finally indent -= 1 @@ -68,7 +67,7 @@ class CheckReentrant extends MiniPhase { for (sym <- cls.classInfo.decls) if (sym.isTerm && !sym.isSetter && !isIgnored(sym)) if (sym.is(Mutable)) { - ctx.error( + report.error( i"""possible data race involving globally reachable ${sym.showLocated}: ${sym.info} | use -Ylog:checkReentrant+ to find out more about why the variable is reachable.""") shared += sym diff --git a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala index 570d7a8e9ec4..a8a8dbb4cd9d 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala @@ -8,7 +8,7 @@ import Contexts.{Context, ctx} import Symbols._ import dotty.tools.dotc.ast.tpd import Decorators._ -import reporting.messages._ +import reporting._ import dotty.tools.dotc.transform.SymUtils._ @@ -35,24 +35,24 @@ class CheckStatic extends MiniPhase { for (defn <- defns) if (defn.symbol.isScalaStatic) { if (!ctx.owner.is(Module)) - ctx.error(StaticFieldsOnlyAllowedInObjects(defn.symbol), defn.sourcePos) + report.error(StaticFieldsOnlyAllowedInObjects(defn.symbol), defn.sourcePos) if (defn.isInstanceOf[ValDef] && hadNonStaticField) - ctx.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol, defns), defn.sourcePos) + report.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol, defns), defn.sourcePos) val companion = ctx.owner.companionClass def clashes = companion.asClass.membersNamed(defn.name) if (!companion.exists) - ctx.error(MissingCompanionForStatic(defn.symbol), defn.sourcePos) + report.error(MissingCompanionForStatic(defn.symbol), defn.sourcePos) else if (clashes.exists) - ctx.error(MemberWithSameNameAsStatic(), defn.sourcePos) + report.error(MemberWithSameNameAsStatic(), defn.sourcePos) else if (defn.symbol.is(Flags.Mutable) && companion.is(Flags.Trait)) - ctx.error(TraitCompanionWithMutableStatic(), defn.sourcePos) + report.error(TraitCompanionWithMutableStatic(), defn.sourcePos) else if (defn.symbol.is(Flags.Lazy)) - ctx.error(LazyStaticField(), defn.sourcePos) + report.error(LazyStaticField(), defn.sourcePos) else if (defn.symbol.allOverriddenSymbols.nonEmpty) - ctx.error(StaticOverridingNonStaticMembers(), defn.sourcePos) + report.error(StaticOverridingNonStaticMembers(), defn.sourcePos) } else hadNonStaticField = hadNonStaticField || defn.isInstanceOf[ValDef] diff --git a/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala b/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala index 26577ed2af99..1a32b42ce8bf 100644 --- a/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala +++ b/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala @@ -63,8 +63,8 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => * with given flags (either `Param` or `ParamAccessor`) */ private def addedParams(owner: Symbol, flag: FlagSet)(using Context): List[ValDef] = { - val nameParam = ctx.newSymbol(owner, nameParamName, flag | Synthetic, defn.StringType, coord = owner.span) - val ordinalParam = ctx.newSymbol(owner, ordinalParamName, flag | Synthetic, defn.IntType, coord = owner.span) + val nameParam = newSymbol(owner, nameParamName, flag | Synthetic, defn.StringType, coord = owner.span) + val ordinalParam = newSymbol(owner, ordinalParamName, flag | Synthetic, defn.IntType, coord = owner.span) List(ValDef(nameParam), ValDef(ordinalParam)) } @@ -98,7 +98,7 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => val enums = moduleCls.info.decls.filter(member => member.isAllOf(EnumValue)) for { enumValue <- enums } yield { - val fieldSym = ctx.newSymbol(clazz, enumValue.name.asTermName, EnumValue | JavaStatic, enumValue.info) + val fieldSym = newSymbol(clazz, enumValue.name.asTermName, EnumValue | JavaStatic, enumValue.info) fieldSym.addAnnotation(Annotations.Annotation(defn.ScalaStaticAnnot)) ValDef(fieldSym, moduleRef.select(enumValue)) } diff --git a/compiler/src/dotty/tools/dotc/transform/Constructors.scala b/compiler/src/dotty/tools/dotc/transform/Constructors.scala index 845f5cb45c4b..1d7c0f8b7b26 100644 --- a/compiler/src/dotty/tools/dotc/transform/Constructors.scala +++ b/compiler/src/dotty/tools/dotc/transform/Constructors.scala @@ -230,7 +230,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = else { val param = acc.subst(accessors, paramSyms) if (param.hasAnnotation(defn.ConstructorOnlyAnnot)) - ctx.error(em"${acc.name} is marked `@constructorOnly` but it is retained as a field in ${acc.owner}", acc.sourcePos) + report.error(em"${acc.name} is marked `@constructorOnly` but it is retained as a field in ${acc.owner}", acc.sourcePos) val target = if (acc.is(Method)) acc.field else acc if (!target.exists) Nil // this case arises when the parameter accessor is an alias else { diff --git a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala index 39055a56845e..c3bd96c4f45a 100644 --- a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala +++ b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala @@ -100,7 +100,7 @@ object ContextFunctionResults: * parameter count. */ def contextFunctionResultTypeCovering(meth: Symbol, paramCount: Int)(using Context) = - inContext(ctx.withPhase(erasurePhase)) { + atPhase(erasurePhase) { // Recursive instances return pairs of context types and the // # of parameters they represent. def missingCR(tp: Type, crCount: Int): (Type, Int) = @@ -120,7 +120,7 @@ object ContextFunctionResults: * @param `n` the select nodes seen in previous recursive iterations of this method */ def integrateSelect(tree: untpd.Tree, n: Int = 0)(using Context): Boolean = - if ctx.erasedTypes then + if currentlyAfterErasure then atPhase(erasurePhase)(integrateSelect(tree, n)) else tree match case Select(qual, name) => diff --git a/compiler/src/dotty/tools/dotc/transform/CookComments.scala b/compiler/src/dotty/tools/dotc/transform/CookComments.scala index c6d81f9d9edd..7eeb99c47045 100644 --- a/compiler/src/dotty/tools/dotc/transform/CookComments.scala +++ b/compiler/src/dotty/tools/dotc/transform/CookComments.scala @@ -2,6 +2,7 @@ package dotty.tools.dotc.transform import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.ContextOps._ import dotty.tools.dotc.typer.Docstrings class CookComments extends MegaPhase.MiniPhase { diff --git a/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled b/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled index ce63ff87bde8..9117a216515f 100644 --- a/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled @@ -40,7 +40,7 @@ class DropEmptyCompanions extends MiniPhase { thisTransform => case TypeDef(_, impl: Template) if tree.symbol.is(SyntheticModule) && tree.symbol.companionClass.exists && impl.body.forall(_.symbol.isPrimaryConstructor) => - ctx.log(i"removing ${tree.symbol}") + report.log(i"removing ${tree.symbol}") true case _ => false diff --git a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala index c632b46d6de2..b5a82b2ad44f 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala @@ -7,7 +7,7 @@ import MegaPhase._ import Types._, Contexts._, Flags._, DenotTransformers._, Phases._ import Symbols._, StdNames._, Trees._ import TypeErasure.ErasedValueType, ValueClasses._ -import reporting.messages.DoubleDefinition +import reporting._ import NameKinds.SuperAccessorName object ElimErasedValueType { @@ -78,11 +78,13 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => * this phase, yet do not have matching types before erasure. */ private def checkNoClashes(root: Symbol)(using Context) = { - val opc = new OverridingPairs.Cursor(root)(using ctx.withPhase(thisPhase)) { - override def exclude(sym: Symbol) = - !sym.is(Method) || sym.is(Bridge) || super.exclude(sym) - override def matches(sym1: Symbol, sym2: Symbol) = - sym1.signature == sym2.signature + val opc = atPhase(thisPhase) { + new OverridingPairs.Cursor(root) { + override def exclude(sym: Symbol) = + !sym.is(Method) || sym.is(Bridge) || super.exclude(sym) + override def matches(sym1: Symbol, sym2: Symbol) = + sym1.signature == sym2.signature + } } def checkNoConflict(sym1: Symbol, sym2: Symbol, info: Type)(using Context): Unit = { @@ -101,16 +103,15 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => def bothSuperAccessors = sym1.name.is(SuperAccessorName) && sym2.name.is(SuperAccessorName) if (sym1.name != sym2.name && !bothSuperAccessors || !info1.matchesLoosely(info2) && !bothPolyApply) - ctx.error(DoubleDefinition(sym1, sym2, root), root.sourcePos) + report.error(DoubleDefinition(sym1, sym2, root), root.sourcePos) } - val earlyCtx = ctx.withPhase(elimRepeatedPhase.next) while (opc.hasNext) { val sym1 = opc.overriding val sym2 = opc.overridden // Do the test at the earliest phase where both symbols existed. val phaseId = sym1.originDenotation.validFor.firstPhaseId max sym2.originDenotation.validFor.firstPhaseId - checkNoConflict(sym1, sym2, sym1.info)(using earlyCtx) + atPhase(elimRepeatedPhase.next)(checkNoConflict(sym1, sym2, sym1.info)) opc.next() } } diff --git a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala index c2effb6fc7b0..ddc8c4b91a31 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala @@ -128,7 +128,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => // see https://github.com/scala/bug/issues/11714 val validJava = atPhase(thisPhase)(isValidJavaVarArgs(sym.info)) if !validJava then - ctx.error("""To generate java-compatible varargs: + report.error("""To generate java-compatible varargs: | - there must be a single repeated parameter | - it must be the last argument in the last parameter list |""".stripMargin, @@ -141,7 +141,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => tree else if hasAnnotation then - ctx.error("A method without repeated parameters cannot be annotated with @varargs", sym.sourcePos) + report.error("A method without repeated parameters cannot be annotated with @varargs", sym.sourcePos) tree /** Is there a repeated parameter in some parameter list? */ @@ -204,7 +204,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => conflict match case Some(conflict) => - ctx.error(s"@varargs produces a forwarder method that conflicts with ${conflict.showDcl}", original.sourcePos) + report.error(s"@varargs produces a forwarder method that conflicts with ${conflict.showDcl}", original.sourcePos) ddef case None => val bridgeDef = polyDefDef(sym.enteredAfter(thisPhase), trefs => vrefss => { diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 5fa75d7633d6..e011b1fc453c 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -33,7 +33,7 @@ import ContextFunctionResults._ import ExplicitOuter._ import core.Mode import util.Property -import reporting.trace +import reporting._ import collection.mutable class Erasure extends Phase with DenotTransformer { @@ -50,13 +50,13 @@ class Erasure extends Phase with DenotTransformer { case ref: SymDenotation => def isCompacted(symd: SymDenotation) = symd.isAnonymousFunction && { - atPhase(ctx.phase.next)(symd.info) match { + atPhase(currentPhase.next)(symd.info) match { case MethodType(nme.ALLARGS :: Nil) => true case _ => false } } - assert(ctx.phase == this, s"transforming $ref at ${ctx.phase}") + assert(currentPhase == this, s"transforming $ref at ${currentPhase}") if (ref.symbol eq defn.ObjectClass) { // After erasure, all former Any members are now Object members val ClassInfo(pre, _, ps, decls, selfInfo) = ref.info @@ -99,7 +99,7 @@ class Erasure extends Phase with DenotTransformer { then ref else - assert(!ref.is(Flags.PackageClass), s"trans $ref @ ${ctx.phase} oldOwner = $oldOwner, newOwner = $newOwner, oldInfo = $oldInfo, newInfo = $newInfo ${oldOwner eq newOwner} ${oldInfo eq newInfo}") + assert(!ref.is(Flags.PackageClass), s"trans $ref @ ${currentPhase} oldOwner = $oldOwner, newOwner = $newOwner, oldInfo = $oldInfo, newInfo = $newInfo ${oldOwner eq newOwner} ${oldInfo eq newInfo}") ref.copySymDenotation( symbol = newSymbol, owner = newOwner, @@ -166,7 +166,7 @@ class Erasure extends Phase with DenotTransformer { isAllowed(defn.TupleClass, "Tuple.scala") || isAllowed(defn.NonEmptyTupleClass, "Tuple.scala") || isAllowed(defn.PairClass, "Tuple.scala"), - i"The type $tp - ${tp.toString} of class ${tp.getClass} of tree $tree : ${tree.tpe} / ${tree.getClass} is illegal after erasure, phase = ${ctx.phase.prev}") + i"The type $tp - ${tp.toString} of class ${tp.getClass} of tree $tree : ${tree.tpe} / ${tree.getClass} is illegal after erasure, phase = ${currentPhase.prev}") } } @@ -250,7 +250,7 @@ object Erasure { val arg = safelyRemovableUnboxArg(tree) if (arg.isEmpty) ref(boxMethod(cls.asClass)).appliedTo(tree) else { - ctx.log(s"boxing an unbox: ${tree.symbol} -> ${arg.tpe}") + report.log(s"boxing an unbox: ${tree.symbol} -> ${arg.tpe}") arg } } @@ -448,7 +448,7 @@ object Erasure { if (resultAdaptationNeeded) sam else implType.derivedLambdaType(paramInfos = samParamTypes) else implType.derivedLambdaType(resType = samResultType) - val bridge = ctx.newSymbol(ctx.owner, AdaptedClosureName(meth.symbol.name.asTermName), Flags.Synthetic | Flags.Method, bridgeType) + val bridge = newSymbol(ctx.owner, AdaptedClosureName(meth.symbol.name.asTermName), Flags.Synthetic | Flags.Method, bridgeType) Closure(bridge, bridgeParamss => inContext(ctx.withOwner(bridge)) { val List(bridgeParams) = bridgeParamss @@ -473,7 +473,7 @@ object Erasure { * not yet instantiated. */ def etaExpand(tree: Tree, mt: MethodType, pt: Type)(using Context): Tree = - ctx.log(i"eta expanding $tree") + report.log(i"eta expanding $tree") val defs = new mutable.ListBuffer[Tree] val tree1 = LiftErased.liftApp(defs, tree) val xmt = if tree.isInstanceOf[Apply] then mt else expandedMethodType(mt, tree) @@ -489,7 +489,7 @@ object Erasure { val defn.ContextFunctionType(argTpes, resTpe, isErased): @unchecked = tp if isErased then abstracted(args, resTpe, pt) else - val anonFun = ctx.newSymbol( + val anonFun = newSymbol( ctx.owner, nme.ANON_FUN, Flags.Synthetic | Flags.Method, MethodType(argTpes, resTpe), coord = tree.span.endPos) anonFun.info = transformInfo(anonFun, anonFun.info) @@ -543,19 +543,19 @@ object Erasure { if (sym is Flags.Package) || (sym.isAllOf(Flags.JavaModule) && !ctx.compilationUnit.isJava) then - ctx.error(reporting.messages.JavaSymbolIsNotAValue(sym), tree.sourcePos) + report.error(JavaSymbolIsNotAValue(sym), tree.sourcePos) private def checkNotErased(tree: Tree)(using Context): tree.type = { if (!ctx.mode.is(Mode.Type)) { if (isErased(tree)) - ctx.error(em"${tree.symbol} is declared as erased, but is in fact used", tree.sourcePos) + report.error(em"${tree.symbol} is declared as erased, but is in fact used", tree.sourcePos) tree.symbol.getAnnotation(defn.CompileTimeOnlyAnnot) match { case Some(annot) => def defaultMsg = i"""Reference to ${tree.symbol.showLocated} should not have survived, |it should have been processed and eliminated during expansion of an enclosing macro or term erasure.""" val message = annot.argumentConstant(0).fold(defaultMsg)(_.stringValue) - ctx.error(message, tree.sourcePos) + report.error(message, tree.sourcePos) case _ => // OK } } @@ -575,7 +575,7 @@ object Erasure { override def promote(tree: untpd.Tree)(using Context): tree.ThisTree[Type] = { assert(tree.hasType) val erasedTp = erasedType(tree) - ctx.log(s"promoting ${tree.show}: ${erasedTp.showWithUnderlying()}") + report.log(s"promoting ${tree.show}: ${erasedTp.showWithUnderlying()}") tree.withType(erasedTp) } @@ -741,7 +741,7 @@ object Erasure { override def typedThis(tree: untpd.This)(using Context): Tree = if (tree.symbol == ctx.owner.lexicallyEnclosingClass || tree.symbol.isStaticOwner) promote(tree) else { - ctx.log(i"computing outer path from ${ctx.owner.ownersIterator.toList}%, % to ${tree.symbol}, encl class = ${ctx.owner.enclosingClass}") + report.log(i"computing outer path from ${ctx.owner.ownersIterator.toList}%, % to ${tree.symbol}, encl class = ${ctx.owner.enclosingClass}") outer.path(toCls = tree.symbol) } @@ -872,7 +872,7 @@ object Erasure { var rhs1 = skipContextClosures(ddef.rhs.asInstanceOf[Tree], contextResultCount(sym)) if sym.isAnonymousFunction && vparams.length > MaxImplementedFunctionArity then - val bunchedParam = ctx.newSymbol(sym, nme.ALLARGS, Flags.TermParam, JavaArrayType(defn.ObjectType)) + val bunchedParam = newSymbol(sym, nme.ALLARGS, Flags.TermParam, JavaArrayType(defn.ObjectType)) def selector(n: Int) = ref(bunchedParam) .select(defn.Array_apply) .appliedTo(Literal(Constant(n))) @@ -896,7 +896,7 @@ object Erasure { if constr.isConstructor && hasOuterParam(constr.owner.asClass) then constr.info match case MethodTpe(outerName :: _, outerType :: _, _) => - val outerSym = ctx.newSymbol(constr, outerName, Flags.Param, outerType) + val outerSym = newSymbol(constr, outerName, Flags.Param, outerType) ValDef(outerSym) :: Nil case _ => // There's a possible race condition that a constructor was looked at @@ -981,7 +981,7 @@ object Erasure { override def adapt(tree: Tree, pt: Type, locked: TypeVars, tryGadtHealing: Boolean)(using Context): Tree = trace(i"adapting ${tree.showSummary}: ${tree.tpe} to $pt", show = true) { - if ctx.phase != erasurePhase && ctx.phase != erasurePhase.next then + if currentPhase != erasurePhase && currentPhase != erasurePhase.next then // this can happen when reading annotations loaded during erasure, // since these are loaded at phase typer. atPhase(erasurePhase.next)(adapt(tree, pt, locked)) diff --git a/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala b/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala index 34974e845452..44524572a967 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala @@ -6,7 +6,7 @@ import Contexts._, Symbols._, Types._, Flags._, Decorators._, StdNames._, Consta import MegaPhase._ import SymUtils._ import ast.Trees._ -import dotty.tools.dotc.reporting.messages.TypeMismatch +import reporting._ import dotty.tools.dotc.util.Spans.Span /** Expand SAM closures that cannot be represented by the JVM as lambdas to anonymous classes. @@ -111,7 +111,7 @@ class ExpandSAMs extends MiniPhase { val parents = List( defn.AbstractPartialFunctionClass.typeRef.appliedTo(anonTpe.firstParamTypes.head, anonTpe.resultType), defn.SerializableType) - val pfSym = ctx.newNormalizedClassSymbol(anonSym.owner, tpnme.ANON_CLASS, Synthetic | Final, parents, coord = tree.span) + val pfSym = newNormalizedClassSymbol(anonSym.owner, tpnme.ANON_CLASS, Synthetic | Final, parents, coord = tree.span) def overrideSym(sym: Symbol) = sym.copy( owner = pfSym, @@ -124,7 +124,7 @@ class ExpandSAMs extends MiniPhase { def translateMatch(tree: Match, pfParam: Symbol, cases: List[CaseDef], defaultValue: Tree)(using Context) = { val selector = tree.selector val selectorTpe = selector.tpe.widen - val defaultSym = ctx.newSymbol(pfParam.owner, nme.WILDCARD, Synthetic | Case, selectorTpe) + val defaultSym = newSymbol(pfParam.owner, nme.WILDCARD, Synthetic | Case, selectorTpe) val defaultCase = CaseDef( Bind(defaultSym, Underscore(selectorTpe)), @@ -155,7 +155,7 @@ class ExpandSAMs extends MiniPhase { translateMatch(pf, paramRef.symbol, pf.cases.map(translateCase), defaultValue) } - val constr = ctx.newConstructor(pfSym, Synthetic, Nil, Nil).entered + val constr = newConstructor(pfSym, Synthetic, Nil, Nil).entered val isDefinedAtDef = transformFollowingDeep(DefDef(isDefinedAtFn, isDefinedAtRhs(_)(using ctx.withOwner(isDefinedAtFn)))) val applyOrElseDef = transformFollowingDeep(DefDef(applyOrElseFn, applyOrElseRhs(_)(using ctx.withOwner(applyOrElseFn)))) val pfDef = ClassDef(pfSym, DefDef(constr), List(isDefinedAtDef, applyOrElseDef)) @@ -163,7 +163,7 @@ class ExpandSAMs extends MiniPhase { case _ => val found = tpe.baseType(defn.FunctionClass(1)) - ctx.error(TypeMismatch(found, tpe), tree.sourcePos) + report.error(TypeMismatch(found, tpe), tree.sourcePos) tree } } @@ -171,7 +171,7 @@ class ExpandSAMs extends MiniPhase { private def checkRefinements(tpe: Type, tree: Tree)(using Context): Type = tpe.dealias match { case RefinedType(parent, name, _) => if (name.isTermName && tpe.member(name).symbol.ownersIterator.isEmpty) // if member defined in the refinement - ctx.error("Lambda does not define " + name, tree.sourcePos) + report.error("Lambda does not define " + name, tree.sourcePos) checkRefinements(parent, tree) case tpe => tpe diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index e1f701658db1..6c85145faa5c 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -115,7 +115,7 @@ class ExplicitOuter extends MiniPhase with InfoTransformer { thisPhase => if (tree.tpt ne EmptyTree) { val cls = tree.tpt.asInstanceOf[TypeTree].tpe.classSymbol if (cls.exists && hasOuter(cls.asClass)) - ctx.error("Not a single abstract method type, requires an outer pointer", tree.sourcePos) + report.error("Not a single abstract method type, requires an outer pointer", tree.sourcePos) } tree } @@ -174,8 +174,9 @@ object ExplicitOuter { outerThis.baseType(outerCls).orElse( outerCls.typeRef.appliedTo(outerCls.typeParams.map(_ => TypeBounds.empty))) val info = if (flags.is(Method)) ExprType(target) else target - ctx.withPhaseNoEarlier(explicitOuterPhase.next) // outer accessors are entered at explicitOuter + 1, should not be defined before. - .newSymbol(owner, name, Synthetic | flags, info, coord = cls.coord) + atPhaseNoEarlier(explicitOuterPhase.next) { // outer accessors are entered at explicitOuter + 1, should not be defined before. + newSymbol(owner, name, Synthetic | flags, info, coord = cls.coord) + } } /** A new param accessor for the outer field in class `cls` */ @@ -299,7 +300,7 @@ object ExplicitOuter { else tpe.prefix case _ => // Need to be careful to dealias before erasure, otherwise we lose prefixes. - outerPrefix(tpe.underlying(using ctx.withPhaseNoLater(erasurePhase))) + atPhaseNoLater(erasurePhase)(outerPrefix(tpe.underlying)) } case tpe: TypeProxy => outerPrefix(tpe.underlying) @@ -397,7 +398,7 @@ object ExplicitOuter { @tailrec def loop(tree: Tree, count: Int): Tree = val treeCls = tree.tpe.widen.classSymbol val outerAccessorCtx = ctx.withPhaseNoLater(lambdaLiftPhase) // lambdalift mangles local class names, which means we cannot reliably find outer acessors anymore - ctx.log(i"outer to $toCls of $tree: ${tree.tpe}, looking for ${outerAccName(treeCls.asClass)(using outerAccessorCtx)} in $treeCls") + report.log(i"outer to $toCls of $tree: ${tree.tpe}, looking for ${outerAccName(treeCls.asClass)(using outerAccessorCtx)} in $treeCls") if (count == 0 || count < 0 && treeCls == toCls) tree else val enclClass = ctx.owner.lexicallyEnclosingClass.asClass @@ -410,7 +411,7 @@ object ExplicitOuter { i"failure to construct path from ${ctx.owner.ownersIterator.toList}%/% to `this` of ${toCls.showLocated};\n${treeCls.showLocated} does not have an outer accessor") loop(tree.select(outerAcc).ensureApplied, count - 1) - ctx.log(i"computing outerpath to $toCls from ${ctx.outersIterator.map(_.owner).toList}") + report.log(i"computing outerpath to $toCls from ${ctx.outersIterator.map(_.owner).toList}") loop(start, count) catch case ex: ClassCastException => throw new ClassCastException(i"no path exists from ${ctx.owner.enclosingClass} to $toCls") diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala index 7d3aa1d45e4e..b8a69397562b 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala @@ -28,7 +28,7 @@ class ExplicitSelf extends MiniPhase { override def transformIdent(tree: Ident)(using Context): Tree = tree.tpe match { case tp: ThisType => - ctx.debuglog(s"owner = ${ctx.owner}, context = ${ctx}") + report.debuglog(s"owner = ${ctx.owner}, context = ${ctx}") This(tp.cls).withSpan(tree.span) case _ => tree } diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index 863e19372774..d506be0b5365 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -85,9 +85,9 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete // and the ErasedValueType. These methods are removed in ElimErasedValueType. val underlying = valueErasure(underlyingOfValueClass(valueClass)) val evt = ErasedValueType(valueClass.typeRef, underlying) - val u2evtSym = ctx.newSymbol(moduleSym, nme.U2EVT, Synthetic | Method, + val u2evtSym = newSymbol(moduleSym, nme.U2EVT, Synthetic | Method, MethodType(List(nme.x_0), List(underlying), evt)) - val evt2uSym = ctx.newSymbol(moduleSym, nme.EVT2U, Synthetic | Method, + val evt2uSym = newSymbol(moduleSym, nme.EVT2U, Synthetic | Method, MethodType(List(nme.x_0), List(evt), underlying)) enterInModuleClass(u2evtSym) enterInModuleClass(evt2uSym) @@ -117,7 +117,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete case ClassInfo(pre, cls, _, _, _) if cls is ModuleClass => cls.linkedClass match { case valueClass: ClassSymbol if isDerivedValueClass(valueClass) => - val info1 = atPhase(ctx.phase.next)(cls.denot).asClass.classInfo.derivedClassInfo(prefix = pre) + val info1 = atPhase(currentPhase.next)(cls.denot).asClass.classInfo.derivedClassInfo(prefix = pre) ref.derivedSingleDenotation(ref.symbol, info1) case _ => ref } @@ -131,7 +131,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete else NoSymbol private def createExtensionMethod(imeth: Symbol, staticClass: Symbol)(using Context): TermSymbol = { - val extensionMeth = ctx.newSymbol(staticClass, extensionName(imeth), + val extensionMeth = newSymbol(staticClass, extensionName(imeth), (imeth.flags | Final) &~ (Override | Protected | AbsOverride), fullyParameterizedType(imeth.info, imeth.owner.asClass), privateWithin = imeth.privateWithin, coord = imeth.coord) @@ -167,7 +167,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete val staticClass = origClass.linkedClass assert(staticClass.exists, s"$origClass lacks companion, ${origClass.owner.definedPeriodsString} ${origClass.owner.info.decls} ${origClass.owner.info.decls}") val extensionMeth = extensionMethod(origMeth) - ctx.log(s"Value class $origClass spawns extension method.\n Old: ${origMeth.showDcl}\n New: ${extensionMeth.showDcl}") + report.log(s"Value class $origClass spawns extension method.\n Old: ${origMeth.showDcl}\n New: ${extensionMeth.showDcl}") val store = extensionDefs.getOrElseUpdate(staticClass, new mutable.ListBuffer[Tree]) store += fullyParameterizedDef(extensionMeth, tree) cpy.DefDef(tree)(rhs = forwarder(extensionMeth, tree)) diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala index 4d1045c33d43..23959f25f8f0 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala @@ -49,7 +49,7 @@ class FunctionXXLForwarders extends MiniPhase with IdentityDenotTransformer { yield { val xsType = defn.ArrayType.appliedTo(List(defn.ObjectType)) val methType = MethodType(List(nme.args))(_ => List(xsType), _ => defn.ObjectType) - val meth = ctx.newSymbol(tree.symbol.owner, nme.apply, Synthetic | Method, methType) + val meth = newSymbol(tree.symbol.owner, nme.apply, Synthetic | Method, methType) DefDef(meth, paramss => forwarderRhs(tree, paramss.head.head)) } diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala index 1449db02b51e..ba49b22ce263 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala @@ -40,7 +40,7 @@ class FunctionalInterfaces extends MiniPhase { val interfaceName = (functionName ++ implParamTypes.length.toString).specializedFor(implParamTypes ::: implResultType :: Nil, names, Nil, Nil) // symbols loaded from classpath aren't defined in periods earlier than when they where loaded - val interface = ctx.withPhase(typerPhase).requiredClass(functionPackage ++ interfaceName) + val interface = atPhase(typerPhase)(requiredClass(functionPackage ++ interfaceName)) val tpt = tpd.TypeTree(interface.asType.appliedRef) tpd.Closure(tree.env, tree.meth, tpt) } diff --git a/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala b/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala index 8bf263ec538a..851d65a1fcfc 100644 --- a/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala +++ b/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala @@ -91,7 +91,7 @@ class HoistSuperArgs extends MiniPhase with IdentityDenotTransformer { thisPhase val argTypeWrtConstr = argType.subst(origParams, allParamRefs(constr.info)) // argType with references to paramRefs of the primary constructor instead of // local parameter accessors - ctx.newSymbol( + newSymbol( owner = methOwner, name = SuperArgName.fresh(cls.name.toTermName), flags = Synthetic | Private | Method | staticFlag, @@ -166,7 +166,7 @@ class HoistSuperArgs extends MiniPhase with IdentityDenotTransformer { thisPhase val res = ref(superMeth) .appliedToTypes(typeParams.map(_.typeRef)) .appliedToArgss(termParamRefs(constr.info, termParams)) - ctx.log(i"hoist $arg, cls = $cls = $res") + report.log(i"hoist $arg, cls = $cls = $res") res case _ => arg } diff --git a/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala b/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala index c1e11be46a6c..eeab8c20b9b2 100644 --- a/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala +++ b/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala @@ -40,7 +40,7 @@ class InlinePatterns extends MiniPhase: app match case App(Select(fn, name), argss) => val app1 = betaReduce(app, fn, name, argss.flatten) - if app1 ne app then ctx.log(i"beta reduce $app -> $app1") + if app1 ne app then report.log(i"beta reduce $app -> $app1") app1 case _ => app diff --git a/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala b/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala index 5c9f6534c8fa..1b0359692b01 100644 --- a/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala @@ -41,7 +41,7 @@ class InterceptedMethods extends MiniPhase { case sel: Select => sel.qualifier } val rewritten = poundPoundValue(qual) - ctx.log(s"$phaseName rewrote $tree to $rewritten") + report.log(s"$phaseName rewrote $tree to $rewritten") rewritten } else tree diff --git a/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled b/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled index abcbfbcf9cb6..af37b606d791 100644 --- a/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled @@ -48,19 +48,19 @@ class IsInstanceOfEvaluator extends MiniPhase { def handleStaticallyKnown(qualifier: Tree, scrutinee: Type, selector: Type, inMatch: Boolean, pos: Position): Tree = { val scrutineeSubSelector = scrutinee <:< selector if (!scrutineeSubSelector && inMatch) { - ctx.error( + report.error( s"this case is unreachable due to `${selector.show}` not being a subclass of `${scrutinee.show}`", Span(pos.start - 5, pos.end - 5) ) rewrite(qualifier, to = false) } else if (!scrutineeSubSelector && !inMatch) { - ctx.warning( + report.warning( s"this will always yield false since `${scrutinee.show}` is not a subclass of `${selector.show}` (will be optimized away)", pos ) rewrite(qualifier, to = false) } else if (scrutineeSubSelector && !inMatch) { - ctx.warning( + report.warning( s"this will always yield true if the scrutinee is non-null, since `${scrutinee.show}` is a subclass of `${selector.show}` (will be optimized away)", pos ) @@ -71,13 +71,13 @@ class IsInstanceOfEvaluator extends MiniPhase { /** Rewrites cases with unrelated types */ def handleFalseUnrelated(qualifier: Tree, scrutinee: Type, selector: Type, inMatch: Boolean) = if (inMatch) { - ctx.error( + report.error( s"will never match since `${selector.show}` is not a subclass of `${scrutinee.show}`", Span(qualifier.pos.start - 5, qualifier.pos.end - 5) // WHY 5? ) rewrite(qualifier, to = false) } else { - ctx.warning( + report.warning( s"will always yield false since `${scrutinee.show}` is not a subclass of `${selector.show}`", tree.pos ) diff --git a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala index a87e9f00bd6b..e8791efeb97c 100644 --- a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala +++ b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala @@ -98,7 +98,7 @@ object LambdaLift { if (sym.maybeOwner.isTerm && owner.isProperlyContainedIn(liftedOwner(sym)) && owner != sym) { - ctx.log(i"narrow lifted $sym to $owner") + report.log(i"narrow lifted $sym to $owner") changedLiftedOwner = true liftedOwner(sym) = owner } @@ -154,7 +154,7 @@ object LambdaLift { def nestedInConstructor(sym: Symbol): Boolean = sym.isConstructor || sym.isTerm && nestedInConstructor(sym.enclosure) - ctx.debuglog(i"mark free: ${sym.showLocated} with owner ${sym.maybeOwner} marked free in $enclosure") + report.debuglog(i"mark free: ${sym.showLocated} with owner ${sym.maybeOwner} marked free in $enclosure") val intermediate = if (enclosure.is(PackageClass)) enclosure else if (enclosure.isConstructor) markFree(sym, enclosure.owner.enclosure) @@ -169,7 +169,7 @@ object LambdaLift { if (!enclosure.is(Trait)) if (symSet(free, enclosure).add(sym)) { changedFreeVars = true - ctx.log(i"$sym is free in $enclosure") + report.log(i"$sym is free in $enclosure") } if (intermediate.isRealClass) intermediate else if (enclosure.isRealClass) enclosure @@ -185,7 +185,7 @@ object LambdaLift { } private def markCalled(callee: Symbol, caller: Symbol)(using Context): Unit = { - ctx.debuglog(i"mark called: $callee of ${callee.owner} is called by $caller in ${caller.owner}") + report.debuglog(i"mark called: $callee of ${callee.owner} is called by $caller in ${caller.owner}") assert(isLocal(callee)) symSet(called, caller) += callee if (callee.enclosingClass != caller.enclosingClass) calledFromInner += callee @@ -306,12 +306,12 @@ object LambdaLift { private def generateProxies()(using Context): Unit = for ((owner, freeValues) <- free.iterator) { val newFlags = Synthetic | (if (owner.isClass) ParamAccessor | Private else Param) - ctx.debuglog(i"free var proxy of ${owner.showLocated}: ${freeValues.toList}%, %") + report.debuglog(i"free var proxy of ${owner.showLocated}: ${freeValues.toList}%, %") proxyMap(owner) = { for (fv <- freeValues.toList) yield { val proxyName = newName(fv) val proxy = - ctx.newSymbol(owner, proxyName.asTermName, newFlags, fv.info, coord = fv.coord) + newSymbol(owner, proxyName.asTermName, newFlags, fv.info, coord = fv.coord) .enteredAfter(thisPhase) (fv, proxy) } @@ -394,7 +394,7 @@ object LambdaLift { if (encl.exists) encl :: enclosures(liftedEnclosure(encl)) else Nil throw new IllegalArgumentException(i"Could not find proxy for ${sym.showDcl} in ${sym.ownersIterator.toList}, encl = $currentEnclosure, owners = ${currentEnclosure.ownersIterator.toList}%, %; enclosures = ${enclosures(currentEnclosure)}%, %") } - ctx.debuglog(i"searching for $sym(${sym.owner}) in $enclosure") + report.debuglog(i"searching for $sym(${sym.owner}) in $enclosure") proxyMap get enclosure match { case Some(pmap) => pmap get sym match { @@ -447,7 +447,7 @@ object LambdaLift { val fvs = freeVars(sym.owner) val classProxies = fvs.map(proxyOf(sym.owner, _)) val constrProxies = fvs.map(proxyOf(sym, _)) - ctx.debuglog(i"copy params ${constrProxies.map(_.showLocated)}%, % to ${classProxies.map(_.showLocated)}%, %}") + report.debuglog(i"copy params ${constrProxies.map(_.showLocated)}%, % to ${classProxies.map(_.showLocated)}%, %}") seq(classProxies.lazyZip(constrProxies).map(proxyInit), rhs) } diff --git a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala index 5a1c05a3ad5d..fad15d309625 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -1,21 +1,22 @@ -package dotty.tools.dotc.transform +package dotty.tools.dotc +package transform import java.util.IdentityHashMap -import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Annotations.Annotation -import dotty.tools.dotc.core.Constants.Constant -import dotty.tools.dotc.core.Contexts.{Context, ctx} -import dotty.tools.dotc.core.Decorators._ -import dotty.tools.dotc.core.DenotTransformers.IdentityDenotTransformer -import dotty.tools.dotc.core.Flags._ -import dotty.tools.dotc.core.NameKinds.{LazyBitMapName, LazyLocalInitName, LazyLocalName, ExpandedName} -import dotty.tools.dotc.core.StdNames.nme -import dotty.tools.dotc.core.Symbols._ -import dotty.tools.dotc.core.Types._ -import dotty.tools.dotc.core.{Names, StdNames} -import dotty.tools.dotc.transform.MegaPhase.MiniPhase -import dotty.tools.dotc.transform.SymUtils._ +import ast.tpd +import core.Annotations.Annotation +import core.Constants.Constant +import core.Contexts.{Context, ctx} +import core.Decorators._ +import core.DenotTransformers.IdentityDenotTransformer +import core.Flags._ +import core.NameKinds.{LazyBitMapName, LazyLocalInitName, LazyLocalName, ExpandedName} +import core.StdNames.nme +import core.Symbols._ +import core.Types._ +import core.{Names, StdNames} +import transform.MegaPhase.MiniPhase +import transform.SymUtils._ import scala.collection.mutable class LazyVals extends MiniPhase with IdentityDenotTransformer { @@ -87,7 +88,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { transformSyntheticModule(tree) else if (sym.isThreadUnsafe || ctx.settings.scalajs.value) if (sym.is(Module) && !ctx.settings.scalajs.value) { - ctx.error(em"@threadUnsafe is only supported on lazy vals", sym.sourcePos) + report.error(em"@threadUnsafe is only supported on lazy vals", sym.sourcePos) transformMemberDefThreadSafe(tree) } else @@ -124,7 +125,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { */ def transformSyntheticModule(tree: ValOrDefDef)(using Context): Thicket = { val sym = tree.symbol - val holderSymbol = ctx.newSymbol(sym.owner, LazyLocalName.fresh(sym.asTerm.name), + val holderSymbol = newSymbol(sym.owner, LazyLocalName.fresh(sym.asTerm.name), Synthetic, sym.info.widen.resultType).enteredAfter(this) val field = ValDef(holderSymbol, tree.rhs.changeOwnerAfter(sym, holderSymbol, this)) val getter = DefDef(sym.asTerm, ref(holderSymbol)) @@ -154,7 +155,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { // val x$lzy = new scala.runtime.LazyInt() val holderName = LazyLocalName.fresh(xname) val holderImpl = defn.LazyHolder()(tpe.typeSymbol) - val holderSymbol = ctx.newSymbol(x.symbol.owner, holderName, containerFlags, holderImpl.typeRef, coord = x.span) + val holderSymbol = newSymbol(x.symbol.owner, holderName, containerFlags, holderImpl.typeRef, coord = x.span) val holderTree = ValDef(holderSymbol, New(holderImpl.typeRef, Nil)) val holderRef = ref(holderSymbol) @@ -166,7 +167,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { // else x$lzy.initialize() // } val initName = LazyLocalInitName.fresh(xname) - val initSymbol = ctx.newSymbol(x.symbol.owner, initName, initFlags, MethodType(Nil, tpe), coord = x.span) + val initSymbol = newSymbol(x.symbol.owner, initName, initFlags, MethodType(Nil, tpe), coord = x.span) val rhs = x.rhs.changeOwnerAfter(x.symbol, initSymbol, this) val initialize = holderRef.select(lazyNme.initialize).appliedTo(rhs) val initBody = holderRef @@ -179,7 +180,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { val accessorBody = If(initialized, getValue, ref(initSymbol).ensureApplied).ensureConforms(tpe) val accessor = DefDef(x.symbol.asTerm, accessorBody) - ctx.debuglog(s"found a lazy val ${x.show},\nrewrote with ${holderTree.show}") + report.debuglog(s"found a lazy val ${x.show},\nrewrote with ${holderTree.show}") Thicket(holderTree, initTree, accessor) } @@ -254,7 +255,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { val tpe = x.tpe.widen.resultType.widen assert(!(x.symbol is Mutable)) val containerName = LazyLocalName.fresh(x.name.asTermName) - val containerSymbol = ctx.newSymbol(claz, containerName, + val containerSymbol = newSymbol(claz, containerName, x.symbol.flags &~ containerFlagsMask | containerFlags | Private, tpe, coord = x.symbol.coord ).enteredAfter(this) @@ -265,7 +266,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { Thicket(containerTree, mkDefThreadUnsafeNonNullable(x.symbol, containerSymbol, x.rhs)) else { val flagName = LazyBitMapName.fresh(x.name.asTermName) - val flagSymbol = ctx.newSymbol(x.symbol.owner, flagName, containerFlags | Private, defn.BooleanType).enteredAfter(this) + val flagSymbol = newSymbol(x.symbol.owner, flagName, containerFlags | Private, defn.BooleanType).enteredAfter(this) val flag = ValDef(flagSymbol, Literal(Constant(false))) Thicket(containerTree, flag, mkThreadUnsafeDef(x.symbol, flagSymbol, containerSymbol, x.rhs)) } @@ -321,16 +322,16 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { val thiz = This(claz) val fieldId = Literal(Constant(ord)) - val flagSymbol = ctx.newSymbol(methodSymbol, lazyNme.flag, Synthetic, defn.LongType) + val flagSymbol = newSymbol(methodSymbol, lazyNme.flag, Synthetic, defn.LongType) val flagDef = ValDef(flagSymbol, getFlag.appliedTo(thiz, offset)) val flagRef = ref(flagSymbol) - val stateSymbol = ctx.newSymbol(methodSymbol, lazyNme.state, Synthetic, defn.LongType) + val stateSymbol = newSymbol(methodSymbol, lazyNme.state, Synthetic, defn.LongType) val stateDef = ValDef(stateSymbol, stateMask.appliedTo(ref(flagSymbol), Literal(Constant(ord)))) val stateRef = ref(stateSymbol) val compute = { - val resultSymbol = ctx.newSymbol(methodSymbol, lazyNme.result, Synthetic, tp) + val resultSymbol = newSymbol(methodSymbol, lazyNme.result, Synthetic, tp) val resultRef = ref(resultSymbol) val stats = ( ValDef(resultSymbol, rhs) :: @@ -342,7 +343,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { } val retryCase = { - val caseSymbol = ctx.newSymbol(methodSymbol, nme.DEFAULT_EXCEPTION_NAME, Synthetic | Case, defn.ThrowableType) + val caseSymbol = newSymbol(methodSymbol, nme.DEFAULT_EXCEPTION_NAME, Synthetic | Case, defn.ThrowableType) val triggerRetry = setFlagState.appliedTo(thiz, offset, initState, fieldId) CaseDef( Bind(caseSymbol, ref(caseSymbol)), @@ -377,7 +378,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { val tpe = x.tpe.widen.resultType.widen val claz = x.symbol.owner.asClass val thizClass = Literal(Constant(claz.info)) - val helperModule = ctx.requiredModule("dotty.runtime.LazyVals") + val helperModule = requiredModule("dotty.runtime.LazyVals") val getOffset = Select(ref(helperModule), lazyNme.RLazyVals.getOffset) var offsetSymbol: TermSymbol = null var flag: Tree = EmptyTree @@ -398,27 +399,27 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { .suchThat(sym => sym.is(Synthetic) && sym.isTerm) .symbol.asTerm else { // need to create a new flag - offsetSymbol = ctx.newSymbol(claz, offsetById, Synthetic, defn.LongType).enteredAfter(this) + offsetSymbol = newSymbol(claz, offsetById, Synthetic, defn.LongType).enteredAfter(this) offsetSymbol.addAnnotation(Annotation(defn.ScalaStaticAnnot)) val flagName = s"${StdNames.nme.BITMAP_PREFIX}$id".toTermName - val flagSymbol = ctx.newSymbol(claz, flagName, containerFlags, defn.LongType).enteredAfter(this) + val flagSymbol = newSymbol(claz, flagName, containerFlags, defn.LongType).enteredAfter(this) flag = ValDef(flagSymbol, Literal(Constant(0L))) val offsetTree = ValDef(offsetSymbol, getOffset.appliedTo(thizClass, Literal(Constant(flagName.toString)))) info.defs = offsetTree :: info.defs } case None => - offsetSymbol = ctx.newSymbol(claz, offsetName(0), Synthetic, defn.LongType).enteredAfter(this) + offsetSymbol = newSymbol(claz, offsetName(0), Synthetic, defn.LongType).enteredAfter(this) offsetSymbol.addAnnotation(Annotation(defn.ScalaStaticAnnot)) val flagName = s"${StdNames.nme.BITMAP_PREFIX}0".toTermName - val flagSymbol = ctx.newSymbol(claz, flagName, containerFlags, defn.LongType).enteredAfter(this) + val flagSymbol = newSymbol(claz, flagName, containerFlags, defn.LongType).enteredAfter(this) flag = ValDef(flagSymbol, Literal(Constant(0L))) val offsetTree = ValDef(offsetSymbol, getOffset.appliedTo(thizClass, Literal(Constant(flagName.toString)))) appendOffsetDefs += (claz -> new OffsetInfo(List(offsetTree), ord)) } val containerName = LazyLocalName.fresh(x.name.asTermName) - val containerSymbol = ctx.newSymbol(claz, containerName, x.symbol.flags &~ containerFlagsMask | containerFlags, tpe, coord = x.symbol.coord).enteredAfter(this) + val containerSymbol = newSymbol(claz, containerName, x.symbol.flags &~ containerFlagsMask | containerFlags, tpe, coord = x.symbol.coord).enteredAfter(this) val containerTree = ValDef(containerSymbol, defaultValue(tpe)) diff --git a/compiler/src/dotty/tools/dotc/transform/LiftTry.scala b/compiler/src/dotty/tools/dotc/transform/LiftTry.scala index 34a1b482aa13..e5e234b8fe8e 100644 --- a/compiler/src/dotty/tools/dotc/transform/LiftTry.scala +++ b/compiler/src/dotty/tools/dotc/transform/LiftTry.scala @@ -69,8 +69,8 @@ class LiftTry extends MiniPhase with IdentityDenotTransformer { thisPhase => override def transformTry(tree: Try)(using Context): Tree = if (needLift && tree.cases.nonEmpty) { - ctx.debuglog(i"lifting tree at ${tree.span}, current owner = ${ctx.owner}") - val fn = ctx.newSymbol( + report.debuglog(i"lifting tree at ${tree.span}, current owner = ${ctx.owner}") + val fn = newSymbol( ctx.owner, LiftedTreeName.fresh(), Synthetic | Method, MethodType(Nil, tree.tpe.widenIfUnstable), coord = tree.span) tree.changeOwnerAfter(ctx.owner, fn, thisPhase) diff --git a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala index 947a80711842..7c670b4aed19 100644 --- a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala @@ -64,7 +64,7 @@ abstract class MacroTransform extends Phase { } catch { case ex: TypeError => - ctx.error(ex, tree.sourcePos) + report.error(ex, tree.sourcePos) tree } diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index 7963428f8847..c7f6ee252429 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -170,7 +170,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } catch { case ex: TypeError => - ctx.error(ex, tree.sourcePos) + report.error(ex, tree.sourcePos) tree } def goUnnamed(tree: Tree, start: Int) = @@ -205,7 +205,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } catch { case ex: TypeError => - ctx.error(ex, tree.sourcePos) + report.error(ex, tree.sourcePos) tree } if (tree.isInstanceOf[NameTree]) goNamed(tree, start) else goUnnamed(tree, start) @@ -308,7 +308,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { goTyped(cpy.Typed(tree)(expr, tpt), start) case tree: CaseDef => given Context = prepCaseDef(tree, start)(using outerCtx) - val pat = transformTree(tree.pat, start)(using ctx.addMode(Mode.Pattern)) + val pat = withMode(Mode.Pattern)(transformTree(tree.pat, start)) val guard = transformTree(tree.guard, start) val body = transformTree(tree.body, start) goCaseDef(cpy.CaseDef(tree)(pat, guard, body), start) diff --git a/compiler/src/dotty/tools/dotc/transform/Memoize.scala b/compiler/src/dotty/tools/dotc/transform/Memoize.scala index eac1c6913704..98231da9fb0b 100644 --- a/compiler/src/dotty/tools/dotc/transform/Memoize.scala +++ b/compiler/src/dotty/tools/dotc/transform/Memoize.scala @@ -4,6 +4,7 @@ package transform import core._ import DenotTransformers._ import Contexts.{Context, ctx} +import Phases.phaseOf import SymDenotations.SymDenotation import Denotations._ import Symbols._ @@ -43,8 +44,7 @@ class Memoize extends MiniPhase with IdentityDenotTransformer { thisPhase => * exist non-deferred definitions that are not implemented. */ override def checkPostCondition(tree: Tree)(using Context): Unit = { def errorLackImplementation(t: Tree) = { - val firstPhaseId = t.symbol.initial.validFor.firstPhaseId - val definingPhase = ctx.withPhase(firstPhaseId).phase.prev + val definingPhase = phaseOf(t.symbol.initial.validFor.firstPhaseId) throw new AssertionError( i"Non-deferred definition introduced by $definingPhase lacks implementation: $t") } @@ -77,7 +77,7 @@ class Memoize extends MiniPhase with IdentityDenotTransformer { thisPhase => if (sym.isGetter) sym.info.resultType else /*sym.isSetter*/ sym.info.firstParamTypes.head - ctx.newSymbol( + newSymbol( owner = ctx.owner, name = sym.name.asTermName.fieldName, flags = Private | (if (sym.is(StableRealizable)) EmptyFlags else Mutable), diff --git a/compiler/src/dotty/tools/dotc/transform/Mixin.scala b/compiler/src/dotty/tools/dotc/transform/Mixin.scala index 6b44c8887763..4c8d45e6671f 100644 --- a/compiler/src/dotty/tools/dotc/transform/Mixin.scala +++ b/compiler/src/dotty/tools/dotc/transform/Mixin.scala @@ -140,7 +140,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => val initName = InitializerName(sym.name.asTermName) sym.owner.info.decl(initName).symbol .orElse( - ctx.newSymbol( + newSymbol( sym.owner, initName, Protected | Synthetic | Method, @@ -234,7 +234,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => assert( impl.parents.forall(_.tpe.typeSymbol != mixin), i"missing parameters for $mixin from $impl should have been caught in typer") - ctx.error( + report.error( em"""parameterized $mixin is indirectly implemented, |needs to be implemented directly so that arguments can be passed""", cls.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/transform/MixinOps.scala b/compiler/src/dotty/tools/dotc/transform/MixinOps.scala index c08797f78749..345840f9dfa0 100644 --- a/compiler/src/dotty/tools/dotc/transform/MixinOps.scala +++ b/compiler/src/dotty/tools/dotc/transform/MixinOps.scala @@ -15,7 +15,7 @@ class MixinOps(cls: ClassSymbol, thisPhase: DenotTransformer)(using Context) { val mixins: List[ClassSymbol] = cls.mixins lazy val JUnit4Annotations: List[Symbol] = List("Test", "Ignore", "Before", "After", "BeforeClass", "AfterClass"). - map(n => ctx.getClassIfDefined("org.junit." + n)). + map(n => getClassIfDefined("org.junit." + n)). filter(_.exists) def mkForwarderSym(member: TermSymbol, extraFlags: FlagSet = EmptyFlags): TermSymbol = { diff --git a/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala b/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala index 2b69b431017d..345c729f9fbb 100644 --- a/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala +++ b/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala @@ -44,7 +44,7 @@ class MoveStatics extends MiniPhase with SymTransformer { val newBodyWithStaticConstr = if (staticFields.nonEmpty) { /* do NOT put Flags.JavaStatic here. It breaks .enclosingClass */ - val staticCostructor = ctx.newSymbol(orig.symbol, nme.STATIC_CONSTRUCTOR, Flags.Synthetic | Flags.Method | Flags.Private, MethodType(Nil, defn.UnitType)) + val staticCostructor = newSymbol(orig.symbol, nme.STATIC_CONSTRUCTOR, Flags.Synthetic | Flags.Method | Flags.Private, MethodType(Nil, defn.UnitType)) staticCostructor.addAnnotation(Annotation(defn.ScalaStaticAnnot)) staticCostructor.entered diff --git a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala index 14837ee8574b..4a691b363678 100644 --- a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala +++ b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala @@ -40,7 +40,7 @@ class NonLocalReturns extends MiniPhase { /** Return non-local return key for given method */ private def nonLocalReturnKey(meth: Symbol)(using Context) = nonLocalReturnKeys.getOrElseUpdate(meth, - ctx.newSymbol( + newSymbol( meth, NonLocalReturnKeyName.fresh(), Synthetic, defn.ObjectType, coord = meth.span)) /** Generate a non-local return throw with given return expression from given method. @@ -71,7 +71,7 @@ class NonLocalReturns extends MiniPhase { */ private def nonLocalReturnTry(body: Tree, key: TermSymbol, meth: Symbol)(using Context) = { val keyDef = ValDef(key, New(defn.ObjectType, Nil)) - val ex = ctx.newSymbol(meth, nme.ex, Case, nonLocalReturnControl, coord = body.span) + val ex = newSymbol(meth, nme.ex, Case, nonLocalReturnControl, coord = body.span) val pat = BindTyped(ex, nonLocalReturnControl) val rhs = If( ref(ex).select(nme.key).appliedToNone.select(nme.eq).appliedTo(ref(key)), @@ -91,7 +91,7 @@ class NonLocalReturns extends MiniPhase { override def transformReturn(tree: Return)(using Context): Tree = if isNonLocalReturn(tree) then if sourceVersion.isAtLeast(`3.1`) then - ctx.errorOrMigrationWarning("Non local returns are no longer supported; use scala.util.control.NonLocalReturns instead", tree.sourcePos) + report.errorOrMigrationWarning("Non local returns are no longer supported; use scala.util.control.NonLocalReturns instead", tree.sourcePos) nonLocalReturnThrow(tree.expr, tree.from.symbol).withSpan(tree.span) else tree } diff --git a/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala b/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala index 4e0df7fb6bbc..1bedd2e6e261 100644 --- a/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala +++ b/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala @@ -134,7 +134,7 @@ object OverridingPairs { case ex: TypeError => // See neg/i1750a for an example where a cyclic error can arise. // The root cause in this example is an illegal "override" of an inner trait - ctx.error(ex, base.sourcePos) + report.error(ex, base.sourcePos) } else { curEntry = curEntry.prev diff --git a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala index d371454acc8a..d572e8e2e84c 100644 --- a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala +++ b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala @@ -104,7 +104,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( val taggedTypes = new PCPCheckAndHeal.QuoteTypeTags(quote.span) if (ctx.property(InAnnotation).isDefined) - ctx.error("Cannot have a quote in an annotation", quote.sourcePos) + report.error("Cannot have a quote in an annotation", quote.sourcePos) val contextWithQuote = if level == 0 then contextWithQuoteTypeTags(taggedTypes)(using quoteContext) @@ -182,7 +182,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( case prefix: TermRef if tp.symbol.isSplice => prefix.symbol.info.argInfos match case (tb: TypeBounds) :: _ => - ctx.error(em"Cannot splice $tp because it is a wildcard type", pos) + report.error(em"Cannot splice $tp because it is a wildcard type", pos) case _ => // Heal explicit type splice in the code if level > 0 then getQuoteTypeTags.getTagRef(prefix) else tp @@ -228,13 +228,13 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( checkStable(tp, pos, "type witness") getQuoteTypeTags.getTagRef(tp) case _: SearchFailureType => - ctx.error(i"""Reference to $tp withing quotes requires a $reqType in scope. + report.error(i"""Reference to $tp withing quotes requires a $reqType in scope. |${ctx.typer.missingArgMsg(tag, reqType, "")} | |""", pos) tp case _ => - ctx.error(i"""Reference to $tp withing quotes requires a $reqType in scope. + report.error(i"""Reference to $tp withing quotes requires a $reqType in scope. | |""", pos) tp @@ -245,7 +245,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( if (!tp.isInstanceOf[ThisType]) sym.show else if (sym.is(ModuleClass)) sym.sourceModule.show else i"${sym.name}.this" - ctx.error( + report.error( em"""access to $symStr from wrong staging level: | - the definition is at level ${levelOf(sym)}, | - but the access is at level $level.""", pos) @@ -272,7 +272,7 @@ object PCPCheckAndHeal { val splicedTree = tpd.ref(spliced).withSpan(span) val rhs = splicedTree.select(tpnme.spliceType).withSpan(span) val alias = ctx.typeAssigner.assignType(untpd.TypeBoundsTree(rhs, rhs), rhs, rhs, EmptyTree) - val local = ctx.newSymbol( + val local = newSymbol( owner = ctx.owner, name = UniqueName.fresh((splicedTree.symbol.name.toString + "$_").toTermName).toTypeName, flags = Synthetic, diff --git a/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala b/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala index 0bac0f073398..028516f1ca07 100644 --- a/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala +++ b/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala @@ -69,7 +69,7 @@ class ParamForwarding extends MiniPhase with IdentityDenotTransformer: .select(alias) .ensureApplied .ensureConforms(sym.info.finalResultType) - ctx.log(i"adding param forwarder $superAcc") + report.log(i"adding param forwarder $superAcc") DefDef(sym, superAcc) else mdef else mdef diff --git a/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala b/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala index 42a085232343..d396d8f75247 100644 --- a/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala +++ b/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala @@ -14,7 +14,7 @@ import Flags._, Constants._ import Decorators._ import NameKinds.{PatMatStdBinderName, PatMatAltsName, PatMatResultName} import config.Printers.patmatch -import reporting.messages._ +import reporting._ import dotty.tools.dotc.ast._ import util.Property._ @@ -87,7 +87,7 @@ object PatternMatcher { // ------- Bindings for variables and labels --------------------- private val resultLabel = - ctx.newSymbol(ctx.owner, PatMatResultName.fresh(), Synthetic | Label, resultType) + newSymbol(ctx.owner, PatMatResultName.fresh(), Synthetic | Label, resultType) /** A map from variable symbols to their defining trees * and from labels to their defining plans @@ -95,7 +95,7 @@ object PatternMatcher { private val initializer = newMutableSymbolMap[Tree] private def newVar(rhs: Tree, flags: FlagSet): TermSymbol = - ctx.newSymbol(ctx.owner, PatMatStdBinderName.fresh(), Synthetic | Case | flags, + newSymbol(ctx.owner, PatMatStdBinderName.fresh(), Synthetic | Case | flags, sanitize(rhs.tpe), coord = rhs.span) // TODO: Drop Case once we use everywhere else `isPatmatGenerated`. @@ -108,7 +108,7 @@ object PatternMatcher { /** The plan `l: { expr(l) }` where `l` is a fresh label */ private def altsLabeledAbstract(expr: (=> Plan) => Plan): Plan = { - val label = ctx.newSymbol(ctx.owner, PatMatAltsName.fresh(), Synthetic | Label, + val label = newSymbol(ctx.owner, PatMatAltsName.fresh(), Synthetic | Label, defn.UnitType) LabeledPlan(label, expr(ReturnPlan(label))) } @@ -974,7 +974,7 @@ object PatternMatcher { patmatch.println(i"original types: ${typesInCases(original.cases)}%, %") patmatch.println(i"switch types : ${typesInCases(resultCases)}%, %") patmatch.println(i"tree = $result") - ctx.warning(UnableToEmitSwitch(numTypes(original.cases) < MinSwitchCases), original.sourcePos) + report.warning(UnableToEmitSwitch(numTypes(original.cases) < MinSwitchCases), original.sourcePos) } case _ => } diff --git a/compiler/src/dotty/tools/dotc/transform/Pickler.scala b/compiler/src/dotty/tools/dotc/transform/Pickler.scala index 5d08b9d13f67..7d7fc0dd0937 100644 --- a/compiler/src/dotty/tools/dotc/transform/Pickler.scala +++ b/compiler/src/dotty/tools/dotc/transform/Pickler.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc package transform import core._ -import Contexts.{Context, ctx} +import Contexts._ import Decorators._ import tasty._ import config.Printers.{noPrinter, pickling} @@ -47,7 +47,7 @@ class Pickler extends Phase { override def run(using Context): Unit = { val unit = ctx.compilationUnit - pickling.println(i"unpickling in run ${ctx.runId}") + pickling.println(i"unpickling in run ${currentRunId}") for { cls <- dropCompanionModuleClasses(topLevelClasses(unit.tpdTree)) @@ -92,7 +92,7 @@ class Pickler extends Phase { if (ctx.settings.YtestPickler.value) testUnpickler( using ctx.fresh - .setPeriod(Period(ctx.runId + 1, FirstPhaseId)) + .setPeriod(Period(currentRunId + 1, FirstPhaseId)) .setReporter(new ThrowingReporter(ctx.reporter)) .addMode(Mode.ReadPositions) .addMode(Mode.ReadComments) @@ -101,7 +101,7 @@ class Pickler extends Phase { } private def testUnpickler(using Context): Unit = { - pickling.println(i"testing unpickler at run ${ctx.runId}") + pickling.println(i"testing unpickler at run ${currentRunId}") ctx.initialize() val unpicklers = for ((cls, pickler) <- picklers) yield { @@ -120,7 +120,7 @@ class Pickler extends Phase { if (previous != unpickled) { output("before-pickling.txt", previous) output("after-pickling.txt", unpickled) - ctx.error(s"""pickling difference for $cls in ${cls.source}, for details: + report.error(s"""pickling difference for $cls in ${cls.source}, for details: | | diff before-pickling.txt after-pickling.txt""".stripMargin) } diff --git a/compiler/src/dotty/tools/dotc/transform/PostTyper.scala b/compiler/src/dotty/tools/dotc/transform/PostTyper.scala index ef21106f80c8..ad14b9e7b1d7 100644 --- a/compiler/src/dotty/tools/dotc/transform/PostTyper.scala +++ b/compiler/src/dotty/tools/dotc/transform/PostTyper.scala @@ -13,7 +13,7 @@ import Decorators._ import Symbols._, SymUtils._, NameOps._ import ContextFunctionResults.annotateContextResults import config.Printers.typr -import reporting.messages._ +import reporting._ object PostTyper { val name: String = "posttyper" @@ -149,7 +149,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase val sym = tree.symbol if sym.isScala2Macro && !ctx.settings.XignoreScala2Macros.value then if !sym.owner.unforcedDecls.exists(p => !p.isScala2Macro && p.name == sym.name && p.signature == sym.signature) then - ctx.error("No Scala 3 implementation found for this Scala 2 macro.", tree.sourcePos) + report.error("No Scala 3 implementation found for this Scala 2 macro.", tree.sourcePos) case _ => processMemberDef(tree) @@ -236,7 +236,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase case tree @ Select(qual, name) => if (name.isTypeName) { Checking.checkRealizable(qual.tpe, qual.posd) - super.transform(tree)(using ctx.addMode(Mode.Type)) + withMode(Mode.Type)(super.transform(tree)) } else transformSelect(tree, Nil) @@ -352,16 +352,16 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase if !exprTpe.member(sel.name).exists && !exprTpe.member(sel.name.toTypeName).exists && !exprTpe.member(sel.name.toExtensionName).exists then - ctx.error(NotAMember(exprTpe, sel.name, "value"), sel.imported.sourcePos) + report.error(NotAMember(exprTpe, sel.name, "value"), sel.imported.sourcePos) if seen.contains(sel.name) then - ctx.error(ImportRenamedTwice(sel.imported), sel.imported.sourcePos) + report.error(ImportRenamedTwice(sel.imported), sel.imported.sourcePos) seen += sel.name for sel <- selectors do if !sel.isWildcard then checkIdent(sel) super.transform(tree) case Typed(Ident(nme.WILDCARD), _) => - super.transform(tree)(using ctx.addMode(Mode.Pattern)) + withMode(Mode.Pattern)(super.transform(tree)) // The added mode signals that bounds in a pattern need not // conform to selector bounds. I.e. assume // type Tree[T >: Null <: Type] @@ -372,7 +372,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase case m @ MatchTypeTree(bounds, selector, cases) => // Analog to the case above for match types def tranformIgnoringBoundsCheck(x: CaseDef): CaseDef = - super.transform(x)(using ctx.addMode(Mode.Pattern)).asInstanceOf[CaseDef] + withMode(Mode.Pattern)(super.transform(x)).asInstanceOf[CaseDef] cpy.MatchTypeTree(tree)( super.transform(bounds), super.transform(selector), diff --git a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala index e510847e8d6b..f79478b8495c 100644 --- a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala @@ -57,7 +57,7 @@ class ProtectedAccessors extends MiniPhase { override def ifNoHost(reference: RefTree)(using Context): Tree = { val curCls = ctx.owner.enclosingClass transforms.println(i"${curCls.ownersIterator.toList}%, %") - ctx.error(i"illegal access to protected ${reference.symbol.showLocated} from $curCls", + report.error(i"illegal access to protected ${reference.symbol.showLocated} from $curCls", reference.sourcePos) reference } diff --git a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala index ad8c5776bc60..98aa8fc106d8 100644 --- a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala @@ -282,7 +282,7 @@ class ReifyQuotes extends MacroTransform { val lambdaOwner = if (level == -1) ctx.owner else outer.owner val tpe = MethodType(defn.SeqType.appliedTo(defn.AnyType) :: Nil, tree.tpe.widen) - val meth = ctx.newSymbol(lambdaOwner, UniqueName.fresh(nme.ANON_FUN), Synthetic | Method, tpe) + val meth = newSymbol(lambdaOwner, UniqueName.fresh(nme.ANON_FUN), Synthetic | Method, tpe) Closure(meth, tss => body(tss.head.head)(using ctx.withOwner(meth)).changeNonLocalOwners(meth)).withSpan(tree.span) } diff --git a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala index f58359946b17..457f824c011a 100644 --- a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala +++ b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala @@ -12,7 +12,7 @@ import DenotTransformers._ import NameOps._ import NameKinds._ import ResolveSuper._ -import reporting.messages.IllegalSuperAccessor +import reporting.IllegalSuperAccessor /** This phase implements super accessors in classes that need them. * @@ -81,11 +81,11 @@ object ResolveSuper { var bcs = base.info.baseClasses.dropWhile(acc.owner != _).tail var sym: Symbol = NoSymbol val SuperAccessorName(memberName) = acc.name.unexpandedName - ctx.debuglog(i"starting rebindsuper from $base of ${acc.showLocated}: ${acc.info} in $bcs, name = $memberName") + report.debuglog(i"starting rebindsuper from $base of ${acc.showLocated}: ${acc.info} in $bcs, name = $memberName") while (bcs.nonEmpty && sym == NoSymbol) { val other = bcs.head.info.nonPrivateDecl(memberName) .matchingDenotation(base.thisType, base.thisType.memberInfo(acc)) - ctx.debuglog(i"rebindsuper ${bcs.head} $other deferred = ${other.symbol.is(Deferred)}") + report.debuglog(i"rebindsuper ${bcs.head} $other deferred = ${other.symbol.is(Deferred)}") if other.exists && !other.symbol.is(Deferred) then sym = other.symbol // Having a matching denotation is not enough: it should also be a subtype @@ -93,7 +93,7 @@ object ResolveSuper { val otherTp = other.asSeenFrom(base.typeRef).info val accTp = acc.asSeenFrom(base.typeRef).info if (!(otherTp.overrides(accTp, matchLoosely = true))) - ctx.error(IllegalSuperAccessor(base, memberName, acc, accTp, other.symbol, otherTp), base.sourcePos) + report.error(IllegalSuperAccessor(base, memberName, acc, accTp, other.symbol, otherTp), base.sourcePos) bcs = bcs.tail } diff --git a/compiler/src/dotty/tools/dotc/transform/Splicer.scala b/compiler/src/dotty/tools/dotc/transform/Splicer.scala index 42c09b2ae3a1..76b1f6141707 100644 --- a/compiler/src/dotty/tools/dotc/transform/Splicer.scala +++ b/compiler/src/dotty/tools/dotc/transform/Splicer.scala @@ -15,6 +15,7 @@ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.quoted._ import dotty.tools.dotc.core.Types._ import dotty.tools.dotc.core.Symbols._ +import dotty.tools.dotc.core.Denotations.staticRef import dotty.tools.dotc.core.{NameKinds, TypeErasure} import dotty.tools.dotc.core.Constants.Constant import dotty.tools.dotc.tastyreflect.ReflectionImpl @@ -40,7 +41,7 @@ object Splicer { def splice(tree: Tree, pos: SourcePosition, classLoader: ClassLoader)(using Context): Tree = tree match { case Quoted(quotedTree) => quotedTree case _ => - val macroOwner = ctx.newSymbol(ctx.owner, nme.MACROkw, Macro | Synthetic, defn.AnyType, coord = tree.span) + val macroOwner = newSymbol(ctx.owner, nme.MACROkw, Macro | Synthetic, defn.AnyType, coord = tree.span) try inContext(ctx.withOwner(macroOwner)) { val interpreter = new Interpreter(pos, classLoader) @@ -58,7 +59,7 @@ object Splicer { // errors have been emitted EmptyTree case ex: StopInterpretation => - ctx.error(ex.msg, ex.pos) + report.error(ex.msg, ex.pos) EmptyTree case NonFatal(ex) => val msg = @@ -66,7 +67,7 @@ object Splicer { | Caused by ${ex.getClass}: ${if (ex.getMessage == null) "" else ex.getMessage} | ${ex.getStackTrace.takeWhile(_.getClassName != "dotty.tools.dotc.transform.Splicer$").drop(1).mkString("\n ")} """.stripMargin - ctx.error(msg, pos) + report.error(msg, pos) EmptyTree } } @@ -88,7 +89,7 @@ object Splicer { tree match case tree: Ident if isEscapedVariable(tree.symbol) => val sym = tree.symbol - ctx.error(em"While expanding a macro, a reference to $sym was used outside the scope where it was defined", tree.sourcePos) + report.error(em"While expanding a macro, a reference to $sym was used outside the scope where it was defined", tree.sourcePos) case Block(stats, _) => val last = locals stats.foreach(markDef) @@ -129,7 +130,7 @@ object Splicer { checkIfValidArgument(tree.rhs) summon[Env] + tree.symbol case _ => - ctx.error("Macro should not have statements", tree.sourcePos) + report.error("Macro should not have statements", tree.sourcePos) summon[Env] } @@ -163,7 +164,7 @@ object Splicer { case _ => val extra = if tree.span.isZeroExtent then ": " + tree.show else "" - ctx.error( + report.error( s"""Malformed macro parameter$extra | |Parameters may only be: @@ -188,11 +189,11 @@ object Splicer { fn.symbol.is(Module) || fn.symbol.isStatic || (fn.qualifier.symbol.is(Module) && fn.qualifier.symbol.isStatic) => if (fn.symbol.flags.is(Inline)) - ctx.error("Macro cannot be implemented with an `inline` method", fn.sourcePos) + report.error("Macro cannot be implemented with an `inline` method", fn.sourcePos) args.flatten.foreach(checkIfValidArgument) case _ => - ctx.error( + report.error( """Malformed macro. | |Expected the splice ${...} to contain a single call to a static method. @@ -215,7 +216,7 @@ object Splicer { case obj: T => Some(obj) case obj => // TODO upgrade to a full type tag check or something similar - ctx.error(s"Interpreted tree returned a result of an unexpected type. Expected ${ct.runtimeClass} but was ${obj.getClass}", pos) + report.error(s"Interpreted tree returned a result of an unexpected type. Expected ${ct.runtimeClass} but was ${obj.getClass}", pos) None } @@ -395,7 +396,7 @@ object Splicer { throw ex case MissingClassDefinedInCurrentRun(sym) if ctx.compilationUnit.isSuspendable => if (ctx.settings.XprintSuspension.value) - ctx.echo(i"suspension triggered by a dependency on $sym", pos) + report.echo(i"suspension triggered by a dependency on $sym", pos) ctx.compilationUnit.suspend() // this throws a SuspendException case targetException => val sw = new StringWriter() @@ -418,7 +419,7 @@ object Splicer { val className = targetException.getMessage if (className eq null) None else { - val sym = ctx.base.staticRef(className.toTypeName).symbol + val sym = staticRef(className.toTypeName).symbol if (sym.isDefinedInCurrentRun) Some(sym) else None } } diff --git a/compiler/src/dotty/tools/dotc/transform/Staging.scala b/compiler/src/dotty/tools/dotc/transform/Staging.scala index 6138ad5b42bb..eff95b7ad26e 100644 --- a/compiler/src/dotty/tools/dotc/transform/Staging.scala +++ b/compiler/src/dotty/tools/dotc/transform/Staging.scala @@ -39,7 +39,7 @@ class Staging extends MacroTransform { override def allowsImplicitSearch: Boolean = true override def checkPostCondition(tree: Tree)(using Context): Unit = - if (ctx.phase <= reifyQuotesPhase) { + if (currentPhase <= reifyQuotesPhase) { // Recheck that PCP holds but do not heal any inconsistent types as they should already have been heald tree match { case PackageDef(pid, _) if tree.symbol.owner == defn.RootClass => diff --git a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala index c3cffc0814cf..ef0b41bc8861 100644 --- a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala @@ -74,14 +74,14 @@ class SuperAccessors(thisPhase: DenotTransformer) { val superAcc = clazz.info.decl(superName) .suchThat(_.signature == superInfo.signature).symbol .orElse { - ctx.debuglog(s"add super acc ${sym.showLocated} to $clazz") + report.debuglog(s"add super acc ${sym.showLocated} to $clazz") val maybeDeferred = if (clazz.is(Trait)) Deferred else EmptyFlags - val acc = ctx.newSymbol( + val acc = newSymbol( clazz, superName, Artifact | Method | maybeDeferred, superInfo, coord = accRange).enteredAfter(thisPhase) // Diagnostic for SI-7091 if (!accDefs.contains(clazz)) - ctx.error( + report.error( s"Internal error: unable to store accessor definition in ${clazz}. clazz.hasPackageFlag=${clazz.is(Package)}. Accessor required for ${sel} (${sel.show})", sel.sourcePos) else accDefs(clazz) += DefDef(acc, EmptyTree).withSpan(accRange) @@ -102,18 +102,18 @@ class SuperAccessors(thisPhase: DenotTransformer) { if (sym.isTerm && !sym.is(Method, butNot = Accessor) && !ctx.owner.isAllOf(ParamForwarder)) // ParamForwaders as installed ParamForwarding.scala do use super calls to vals - ctx.error(s"super may be not be used on ${sym.underlyingSymbol}", sel.sourcePos) + report.error(s"super may be not be used on ${sym.underlyingSymbol}", sel.sourcePos) else if (isDisallowed(sym)) - ctx.error(s"super not allowed here: use this.${sel.name} instead", sel.sourcePos) + report.error(s"super not allowed here: use this.${sel.name} instead", sel.sourcePos) else if (sym.is(Deferred)) { val member = sym.overridingSymbol(clazz.asClass) if (!mix.name.isEmpty || !member.exists || !(member.is(AbsOverride) && member.isIncompleteIn(clazz))) - ctx.error( + report.error( i"${sym.showLocated} is accessed from super. It may not be abstract unless it is overridden by a member declared `abstract' and `override'", sel.sourcePos) - else ctx.log(i"ok super $sel ${sym.showLocated} $member $clazz ${member.isIncompleteIn(clazz)}") + else report.log(i"ok super $sel ${sym.showLocated} $member $clazz ${member.isIncompleteIn(clazz)}") } else { val owner = sym.owner @@ -123,7 +123,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { for (intermediateClass <- clazz.info.baseClasses.tail.takeWhile(_ != sym.owner)) { val overriding = sym.overridingSymbol(intermediateClass) if (overriding.is(Deferred, butNot = AbsOverride) && !overriding.owner.is(Trait)) - ctx.error( + report.error( s"${sym.showLocated} cannot be directly accessed from ${clazz} because ${overriding.owner} redeclares it as abstract", sel.sourcePos) } @@ -139,7 +139,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { else hasClassOverride(member, subCls.superClass.asClass) val superCls = clazz.asClass.superClass.asClass if (owner != superCls && hasClassOverride(sym, superCls)) - ctx.error( + report.error( em"""Super call cannot be emitted: the selected $sym is declared in $owner, which is not the direct superclass of $clazz. |An unqualified super call (super.${sym.name}) would be allowed.""", sel.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala index de572716298b..e78ef75a5fd9 100644 --- a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala +++ b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala @@ -80,8 +80,8 @@ class SyntheticMembers(thisPhase: DenotTransformer) { else NoSymbol } - private def synthesizeDef(sym: TermSymbol, rhsFn: List[List[Tree]] => Context => Tree)(using Context): Tree = - DefDef(sym, rhsFn(_)(ctx.withOwner(sym))).withSpan(ctx.owner.span.focus) + private def synthesizeDef(sym: TermSymbol, rhsFn: List[List[Tree]] => Context ?=> Tree)(using Context): Tree = + DefDef(sym, rhsFn(_)(using ctx.withOwner(sym))).withSpan(ctx.owner.span.focus) /** If this is a case or value class, return the appropriate additional methods, * otherwise return nothing. @@ -130,8 +130,8 @@ class SyntheticMembers(thisPhase: DenotTransformer) { case nme.productElementName => productElementNameBody(accessors.length, vrefss.head.head) case nme.ordinal => Select(This(clazz), nme.ordinalDollar) } - ctx.log(s"adding $synthetic to $clazz at ${ctx.phase}") - synthesizeDef(synthetic, treess => ctx => syntheticRHS(treess)(using ctx)) + report.log(s"adding $synthetic to $clazz at ${currentPhase}") + synthesizeDef(synthetic, syntheticRHS) } /** The class @@ -224,7 +224,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * */ def equalsBody(that: Tree)(using Context): Tree = { - val thatAsClazz = ctx.newSymbol(ctx.owner, nme.x_0, Synthetic | Case, clazzType, coord = ctx.owner.span) // x$0 + val thatAsClazz = newSymbol(ctx.owner, nme.x_0, Synthetic | Case, clazzType, coord = ctx.owner.span) // x$0 def wildcardAscription(tp: Type) = Typed(Underscore(tp), TypeTree(tp)) val pattern = Bind(thatAsClazz, wildcardAscription(AnnotatedType(clazzType, Annotation(defn.UncheckedAnnot)))) // x$0 @ (_: C @unchecked) // compare primitive fields first, slow equality checks of non-primitive fields can be skipped when primitives differ @@ -313,7 +313,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * ``` */ def caseHashCodeBody(using Context): Tree = { - val acc = ctx.newSymbol(ctx.owner, nme.acc, Mutable | Synthetic, defn.IntType, coord = ctx.owner.span) + val acc = newSymbol(ctx.owner, nme.acc, Mutable | Synthetic, defn.IntType, coord = ctx.owner.span) val accDef = ValDef(acc, Literal(Constant(0xcafebabe))) val mixPrefix = Assign(ref(acc), ref(defn.staticsMethod("mix")).appliedTo(ref(acc), This(clazz).select(defn.Product_productPrefix).select(defn.Any_hashCode).appliedToNone)) @@ -368,7 +368,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { .filterWithPredicate(s => s.signature == Signature(defn.AnyRefType, isJava = false)) .exists if (clazz.is(Module) && clazz.isStatic && clazz.isSerializable && !hasWriteReplace) { - val writeReplace = ctx.newSymbol(clazz, nme.writeReplace, Method | Private | Synthetic, + val writeReplace = newSymbol(clazz, nme.writeReplace, Method | Private | Synthetic, MethodType(Nil, defn.AnyRefType), coord = clazz.coord).entered.asTerm List( DefDef(writeReplace, @@ -476,12 +476,12 @@ class SyntheticMembers(thisPhase: DenotTransformer) { classParents = oldClassInfo.classParents :+ parent) clazz.copySymDenotation(info = newClassInfo).installAfter(thisPhase) } - def addMethod(name: TermName, info: Type, cls: Symbol, body: (Symbol, Tree, Context) => Tree): Unit = { - val meth = ctx.newSymbol(clazz, name, Synthetic | Method, info, coord = clazz.coord) + def addMethod(name: TermName, info: Type, cls: Symbol, body: (Symbol, Tree) => Context ?=> Tree): Unit = { + val meth = newSymbol(clazz, name, Synthetic | Method, info, coord = clazz.coord) if (!existingDef(meth, clazz).exists) { meth.entered newBody = newBody :+ - synthesizeDef(meth, vrefss => ctx => body(cls, vrefss.head.head, ctx)) + synthesizeDef(meth, vrefss => body(cls, vrefss.head.head)) } } val linked = clazz.linkedClass @@ -490,7 +490,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { if (existing.exists && !existing.is(Deferred)) existing else { val monoType = - ctx.newSymbol(clazz, tpnme.MirroredMonoType, Synthetic, TypeAlias(linked.rawTypeRef), coord = clazz.coord) + newSymbol(clazz, tpnme.MirroredMonoType, Synthetic, TypeAlias(linked.rawTypeRef), coord = clazz.coord) newBody = newBody :+ TypeDef(monoType).withSpan(ctx.owner.span.focus) monoType.entered } @@ -500,12 +500,12 @@ class SyntheticMembers(thisPhase: DenotTransformer) { def makeProductMirror(cls: Symbol) = { addParent(defn.Mirror_ProductClass.typeRef) addMethod(nme.fromProduct, MethodType(defn.ProductClass.typeRef :: Nil, monoType.typeRef), cls, - fromProductBody(_, _)(using _).ensureConforms(monoType.typeRef)) // t4758.scala or i3381.scala are examples where a cast is needed + fromProductBody(_, _).ensureConforms(monoType.typeRef)) // t4758.scala or i3381.scala are examples where a cast is needed } def makeSumMirror(cls: Symbol) = { addParent(defn.Mirror_SumClass.typeRef) addMethod(nme.ordinal, MethodType(monoType.typeRef :: Nil, defn.IntType), cls, - ordinalBody(_, _)(using _)) + ordinalBody(_, _)) } if (clazz.is(Module)) { diff --git a/compiler/src/dotty/tools/dotc/transform/TailRec.scala b/compiler/src/dotty/tools/dotc/transform/TailRec.scala index c03b439861a7..e2e70906adeb 100644 --- a/compiler/src/dotty/tools/dotc/transform/TailRec.scala +++ b/compiler/src/dotty/tools/dotc/transform/TailRec.scala @@ -1,18 +1,18 @@ package dotty.tools.dotc package transform -import dotty.tools.dotc.ast.Trees._ -import dotty.tools.dotc.ast.{TreeTypeMap, tpd} -import dotty.tools.dotc.config.Printers.tailrec -import dotty.tools.dotc.core.Contexts.{Context, ctx} -import dotty.tools.dotc.core.Constants.Constant -import dotty.tools.dotc.core.Decorators._ -import dotty.tools.dotc.core.Flags._ -import dotty.tools.dotc.core.NameKinds.{TailLabelName, TailLocalName, TailTempName} -import dotty.tools.dotc.core.StdNames.nme -import dotty.tools.dotc.core.Symbols._ -import dotty.tools.dotc.reporting.messages.TailrecNotApplicable -import dotty.tools.dotc.transform.MegaPhase.MiniPhase +import ast.Trees._ +import ast.{TreeTypeMap, tpd} +import config.Printers.tailrec +import core.Contexts.{Context, ctx} +import core.Constants.Constant +import core.Decorators._ +import core.Flags._ +import core.NameKinds.{TailLabelName, TailLocalName, TailTempName} +import core.StdNames.nme +import core.Symbols._ +import reporting._ +import transform.MegaPhase.MiniPhase import scala.collection.mutable @@ -124,7 +124,7 @@ class TailRec extends MiniPhase { // We don't report a new error if failures were reported // during the transformation. if (mandatory && !failureReported) - ctx.error(TailrecNotApplicable(method), method.sourcePos) + report.error(TailrecNotApplicable(method), method.sourcePos) tree } @@ -197,7 +197,7 @@ class TailRec extends MiniPhase { } if isInfiniteRecCall(rhsFullyTransformed) then - ctx.warning("Infinite recursive call", tree.sourcePos) + report.warning("Infinite recursive call", tree.sourcePos) cpy.DefDef(tree)(rhs = Block( @@ -224,7 +224,7 @@ class TailRec extends MiniPhase { private var myContinueLabel: Symbol = _ def continueLabel(using Context): Symbol = { if (myContinueLabel == null) - myContinueLabel = ctx.newSymbol(method, TailLabelName.fresh(), Label, defn.UnitType) + myContinueLabel = newSymbol(method, TailLabelName.fresh(), Label, defn.UnitType) myContinueLabel } @@ -242,7 +242,7 @@ class TailRec extends MiniPhase { val tpe = if (enclosingClass.is(Module)) enclosingClass.thisType else enclosingClass.classInfo.selfType - val sym = ctx.newSymbol(method, nme.SELF, Synthetic | Mutable, tpe) + val sym = newSymbol(method, nme.SELF, Synthetic | Mutable, tpe) varForRewrittenThis = Some(sym) sym } @@ -250,7 +250,7 @@ class TailRec extends MiniPhase { private def getVarForRewrittenParam(param: Symbol)(using Context): Symbol = rewrittenParamSyms.indexOf(param) match { case -1 => - val sym = ctx.newSymbol(method, TailLocalName.fresh(param.name.toTermName), Synthetic | Mutable, param.info) + val sym = newSymbol(method, TailLocalName.fresh(param.name.toTermName), Synthetic | Mutable, param.info) rewrittenParamSyms ::= param varsForRewrittenParamSyms ::= sym sym @@ -304,7 +304,7 @@ class TailRec extends MiniPhase { def fail(reason: String) = { if (isMandatory) { failureReported = true - ctx.error(s"Cannot rewrite recursive call: $reason", tree.sourcePos) + report.error(s"Cannot rewrite recursive call: $reason", tree.sourcePos) } else tailrec.println("Cannot rewrite recursive call at: " + tree.span + " because: " + reason) @@ -349,7 +349,7 @@ class TailRec extends MiniPhase { Assign(ref(lhs), rhs) :: Nil case _ :: _ => val (tempValDefs, assigns) = (for ((lhs, rhs) <- assignThisAndParamPairs) yield { - val temp = ctx.newSymbol(method, TailTempName.fresh(lhs.name.toTermName), Synthetic, lhs.info) + val temp = newSymbol(method, TailTempName.fresh(lhs.name.toTermName), Synthetic, lhs.info) (ValDef(temp, rhs), Assign(ref(lhs), ref(temp)).withSpan(tree.span)) }).unzip tempValDefs ::: assigns diff --git a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala index 90f7488b973d..42e3f3d2b801 100644 --- a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala @@ -37,7 +37,7 @@ abstract class TransformByNameApply extends MiniPhase { thisPhase: DenotTransfor def mkByNameClosure(arg: Tree, argType: Type)(using Context): Tree = unsupported(i"mkClosure($arg)") override def transformApply(tree: Apply)(using Context): Tree = - trace(s"transforming ${tree.show} at phase ${ctx.phase}", show = true) { + trace(s"transforming ${tree.show} at phase ${currentPhase}", show = true) { def transformArg(arg: Tree, formal: Type): Tree = formal.dealias match { case formalExpr: ExprType => diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index e8f93f15d417..1b49c68d82cb 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -15,8 +15,7 @@ import core.Phases._ import core.Mode import typer._ import typer.ErrorReporting._ -import reporting.ThrowingReporter -import reporting.messages.TypeMismatch +import reporting._ import ast.Trees._ import ast.{tpd, untpd} import scala.internal.Chars._ @@ -59,7 +58,7 @@ class TreeChecker extends Phase with SymTransformer { def checkCompanion(symd: SymDenotation)(using Context): Unit = { val cur = symd.linkedClass - val prev = atPhase(ctx.phase.prev) { + val prev = atPhase(currentPhase.prev) { symd.symbol.linkedClass } @@ -90,7 +89,7 @@ class TreeChecker extends Phase with SymTransformer { // Signatures are used to disambiguate overloads and need to stay stable // until erasure, see the comment above `Compiler#phases`. - if (ctx.phaseId <= erasurePhase.id) { + if (currentPhaseId <= erasurePhase.id) { val cur = symd.info val initial = symd.initial.info val curSig = cur match { @@ -101,7 +100,7 @@ class TreeChecker extends Phase with SymTransformer { cur.signature } assert(curSig == initial.signature, - i"""Signature of ${sym.showLocated} changed at phase ${ctx.base.squashed(ctx.phase.prev)} + i"""Signature of ${sym.showLocated} changed at phase ${ctx.base.squashed(currentPhase.prev)} |Initial info: ${initial} |Initial sig : ${initial.signature} |Current info: ${cur} @@ -115,9 +114,9 @@ class TreeChecker extends Phase with SymTransformer { def phaseName: String = "Ycheck" def run(using Context): Unit = - if (ctx.settings.YtestPickler.value && ctx.phase.prev.isInstanceOf[Pickler]) - ctx.echo("Skipping Ycheck after pickling with -Ytest-pickler, the returned tree contains stale symbols") - else if (ctx.phase.prev.isCheckable) + if (ctx.settings.YtestPickler.value && currentPhase.prev.isInstanceOf[Pickler]) + report.echo("Skipping Ycheck after pickling with -Ytest-pickler, the returned tree contains stale symbols") + else if (currentPhase.prev.isCheckable) check(ctx.base.allPhases.toIndexedSeq, ctx) private def previousPhases(phases: List[Phase])(using Context): List[Phase] = phases match { @@ -126,16 +125,16 @@ class TreeChecker extends Phase with SymTransformer { val previousSubPhases = previousPhases(subPhases.toList) if (previousSubPhases.length == subPhases.length) previousSubPhases ::: previousPhases(phases1) else previousSubPhases - case phase :: phases1 if phase ne ctx.phase => + case phase :: phases1 if phase ne currentPhase => phase :: previousPhases(phases1) case _ => Nil } def check(phasesToRun: Seq[Phase], ctx: Context): Tree = { - val prevPhase = ctx.phase.prev // can be a mini-phase - val squahsedPhase = ctx.base.squashed(prevPhase) - ctx.echo(s"checking ${ctx.compilationUnit} after phase ${squahsedPhase}") + val prevPhase = currentPhase(using ctx).prev // can be a mini-phase + val squashedPhase = ctx.base.squashed(prevPhase) + report.echo(s"checking ${ctx.compilationUnit} after phase ${squashedPhase}")(using ctx) inContext(ctx) { assertSelectWrapsNew(ctx.compilationUnit.tpdTree) @@ -153,7 +152,7 @@ class TreeChecker extends Phase with SymTransformer { catch { case NonFatal(ex) => //TODO CHECK. Check that we are bootstrapped inContext(checkingCtx) { - println(i"*** error while checking ${ctx.compilationUnit} after phase ${ctx.phase.prev} ***") + println(i"*** error while checking ${ctx.compilationUnit} after phase ${currentPhase.prev} ***") } throw ex } @@ -178,7 +177,7 @@ class TreeChecker extends Phase with SymTransformer { everDefinedSyms.get(sym) match { case Some(t) => if (t ne tree) - ctx.warning(i"symbol ${sym.fullName} is defined at least twice in different parts of AST") + report.warning(i"symbol ${sym.fullName} is defined at least twice in different parts of AST") // should become an error case None => everDefinedSyms(sym) = tree @@ -188,7 +187,7 @@ class TreeChecker extends Phase with SymTransformer { if (ctx.settings.YcheckMods.value) tree match { case t: untpd.MemberDef => - if (t.name ne sym.name) ctx.warning(s"symbol ${sym.fullName} name doesn't correspond to AST: ${t}") + if (t.name ne sym.name) report.warning(s"symbol ${sym.fullName} name doesn't correspond to AST: ${t}") // todo: compare trees inside annotations case _ => } @@ -238,7 +237,7 @@ class TreeChecker extends Phase with SymTransformer { i"undefined symbol ${sym} at line " + tree.sourcePos.line ) - if (!ctx.phase.patternTranslated) + if (!currentPhase.patternTranslated) assert( !sym.isPatternBound || patBoundSyms.contains(sym), i"sym.isPatternBound => patBoundSyms.contains(sym) is broken, sym = $sym, line " + tree.sourcePos.line @@ -317,7 +316,7 @@ class TreeChecker extends Phase with SymTransformer { override def typed(tree: untpd.Tree, pt: Type = WildcardType)(using Context): Tree = { val tpdTree = super.typed(tree, pt) Typer.assertPositioned(tree) - if (ctx.erasedTypes) + if (currentlyAfterErasure) // Can't be checked in earlier phases since `checkValue` is only run in // Erasure (because running it in Typer would force too much) checkIdentNotJavaClass(tpdTree) @@ -367,7 +366,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedIdent(tree: untpd.Ident, pt: Type)(using Context): Tree = { - assert(tree.isTerm || !ctx.isAfterTyper, tree.show + " at " + ctx.phase) + assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + currentPhase) assert(tree.isType || ctx.mode.is(Mode.Pattern) && untpd.isWildcardArg(tree) || !needsSelect(tree.tpe), i"bad type ${tree.tpe} for $tree # ${tree.uniqueId}") assertDefined(tree) @@ -379,11 +378,11 @@ class TreeChecker extends Phase with SymTransformer { * Approximately means: The two symbols might be different but one still overrides the other. */ override def typedSelect(tree: untpd.Select, pt: Type)(using Context): Tree = { - assert(tree.isTerm || !ctx.isAfterTyper, tree.show + " at " + ctx.phase) + assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + currentPhase) val tpe = tree.typeOpt val sym = tree.symbol val symIsFixed = tpe match { - case tpe: TermRef => ctx.erasedTypes || !tpe.isMemberRef + case tpe: TermRef => currentlyAfterErasure || !tpe.isMemberRef case _ => false } if (sym.exists && !sym.is(Private) && @@ -454,7 +453,7 @@ class TreeChecker extends Phase with SymTransformer { (ddef.tparams :: ddef.vparamss).filter(!_.isEmpty).map(_.map(_.symbol)) def layout(symss: List[List[Symbol]]): String = symss.map(syms => i"($syms%, %)").mkString - assert(ctx.erasedTypes || sym.rawParamss == defParamss, + assert(currentlyAfterErasure || sym.rawParamss == defParamss, i"""param mismatch for ${sym.showLocated}: |defined in tree = ${layout(defParamss)} |stored in symbol = ${layout(sym.rawParamss)}""") @@ -482,7 +481,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedClosure(tree: untpd.Closure, pt: Type)(using Context): Tree = { - if (!ctx.phase.lambdaLifted) nestingBlock match { + if (!currentPhase.lambdaLifted) nestingBlock match { case block @ Block((meth : untpd.DefDef) :: Nil, closure: untpd.Closure) => assert(meth.symbol == closure.meth.symbol, "closure.meth symbol not equal to method symbol. Block: " + block.show) @@ -532,7 +531,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedWhileDo(tree: untpd.WhileDo)(using Context): Tree = { - assert((tree.cond ne EmptyTree) || ctx.phase.refChecked, i"invalid empty condition in while at $tree") + assert((tree.cond ne EmptyTree) || currentPhase.refChecked, i"invalid empty condition in while at $tree") super.typedWhileDo(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala index ad3bc57cb779..701c48712bd4 100644 --- a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala +++ b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala @@ -87,7 +87,7 @@ class TryCatchPatterns extends MiniPhase { else { val exName = ExceptionBinderName.fresh() val fallbackSelector = - ctx.newSymbol(ctx.owner, exName, Flags.Synthetic | Flags.Case, defn.ThrowableType, coord = span) + newSymbol(ctx.owner, exName, Flags.Synthetic | Flags.Case, defn.ThrowableType, coord = span) val sel = Ident(fallbackSelector.termRef).withSpan(span) val rethrow = CaseDef(EmptyTree, EmptyTree, Throw(ref(fallbackSelector))) Some(CaseDef( diff --git a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala index a15d68b60e2c..4a937565f382 100644 --- a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala +++ b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala @@ -147,7 +147,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { val size = tpes.size val n = nTpe.value.intValue if (n < 0 || n >= size) { - ctx.error("index out of bounds: " + n, nTree.underlyingArgument.sourcePos) + report.error("index out of bounds: " + n, nTree.underlyingArgument.sourcePos) tree } else if (size <= MaxTupleArity) @@ -157,7 +157,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { // tup.asInstanceOf[TupleXXL].productElement(n) tup.asInstance(defn.TupleXXLClass.typeRef).select(nme.productElement).appliedTo(Literal(nTpe.value)) case (None, nTpe: ConstantType) if nTpe.value.intValue < 0 => - ctx.error("index out of bounds: " + nTpe.value.intValue, nTree.sourcePos) + report.error("index out of bounds: " + nTpe.value.intValue, nTree.sourcePos) tree case _ => // No optimization, keep: diff --git a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala index 2bf2565b92bd..2184591ceb16 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala @@ -11,8 +11,7 @@ import ValueClasses._ import SymUtils._ import core.Flags._ import util.Spans._ -import reporting.messages.TypeTestAlwaysSucceeds -import reporting.trace +import reporting._ import config.Printers.{ transforms => debug } /** This transform normalizes type tests and type casts, @@ -199,8 +198,8 @@ object TypeTestsCasts { def unreachable(why: => String)(using ctx: Context): Boolean = { if (flagUnrelated) - if (inMatch) ctx.error(em"this case is unreachable since $why", expr.sourcePos) - else ctx.warning(em"this will always yield false since $why", expr.sourcePos) + if (inMatch) report.error(em"this case is unreachable since $why", expr.sourcePos) + else report.warning(em"this will always yield false since $why", expr.sourcePos) false } @@ -242,14 +241,14 @@ object TypeTestsCasts { val foundEffectiveClass = effectiveClass(expr.tpe.widen) if foundEffectiveClass.isPrimitiveValueClass && !testCls.isPrimitiveValueClass then - ctx.error(i"cannot test if value of $exprType is a reference of $testCls", tree.sourcePos) + report.error(i"cannot test if value of $exprType is a reference of $testCls", tree.sourcePos) false else foundClasses.exists(check) end checkSensical if (expr.tpe <:< testType) if (expr.tpe.isNotNull) { - if (!inMatch) ctx.warning(TypeTestAlwaysSucceeds(expr.tpe, testType), tree.sourcePos) + if (!inMatch) report.warning(TypeTestAlwaysSucceeds(expr.tpe, testType), tree.sourcePos) constant(expr, Literal(Constant(true))) } else expr.testNotNull @@ -350,7 +349,7 @@ object TypeTestsCasts { val argType = tree.args.head.tpe val isTrusted = tree.hasAttachment(PatternMatcher.TrustedTypeTestKey) if (!isTrusted && !checkable(expr.tpe, argType, tree.span)) - ctx.warning(i"the type test for $argType cannot be checked at runtime", tree.sourcePos) + report.warning(i"the type test for $argType cannot be checked at runtime", tree.sourcePos) transformTypeTest(expr, tree.args.head.tpe, flagUnrelated = true) } else if (sym.isTypeCast) diff --git a/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala b/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala index d3cec855eafe..659c43311c78 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala @@ -23,7 +23,7 @@ object TypeUtils { def ensureMethodic(using Context): Type = self match { case self: MethodicType => self - case _ => if (ctx.erasedTypes) MethodType(Nil, self) else ExprType(self) + case _ => if (currentlyAfterErasure) MethodType(Nil, self) else ExprType(self) } def widenToParents(using Context): Type = self.parents match { diff --git a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala index 2b9d786bffe1..32925643aeb5 100644 --- a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala +++ b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala @@ -23,9 +23,9 @@ object ValueClasses { } def isMethodWithExtension(sym: Symbol)(using Context): Boolean = - atPhaseNotLaterThan(extensionMethodsPhase) { + atPhaseNoLater(extensionMethodsPhase) { val d = sym.denot - d.validFor.containsPhaseId(summon[Context].phaseId) && + d.validFor.containsPhaseId(currentPhaseId) && d.isRealMethod && isDerivedValueClass(d.owner) && !d.isConstructor && diff --git a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala index 6722701ad448..86b851a897ec 100644 --- a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala +++ b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala @@ -55,7 +55,7 @@ class YCheckPositions extends Phase { } private def isMacro(call: Tree)(using Context) = - if (ctx.phase <= postTyperPhase) call.symbol.is(Macro) + if (currentPhase <= postTyperPhase) call.symbol.is(Macro) else call.isInstanceOf[Select] // The call of a macro after typer is encoded as a Select while other inlines are Ident // TODO remove this distinction once Inline nodes of expanded macros can be trusted (also in Inliner.inlineCallTrace) } diff --git a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala index 56886e75cb98..8e8ac85886f1 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala @@ -87,7 +87,7 @@ object Checking { else checkSecondaryConstructor(ctor) } else if (!cls.isOneOf(Flags.EffectivelyOpenFlags)) - ctx.warning("Inheriting non-open class may cause initialization errors", source.sourcePos) + report.warning("Inheriting non-open class may cause initialization errors", source.sourcePos) } cls.paramAccessors.foreach { acc => @@ -143,7 +143,7 @@ object Checking { for { eff <- rebased error <- check(eff) - } error.report + } error.issue } private def check(eff: Effect)(implicit state: State): Errors = diff --git a/compiler/src/dotty/tools/dotc/transform/init/Env.scala b/compiler/src/dotty/tools/dotc/transform/init/Env.scala index cebbeb4cf0a5..f0e83f9e61c9 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Env.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Env.scala @@ -25,7 +25,7 @@ case class Env(ctx: Context, summaryCache: mutable.Map[ClassSymbol, ClassSummary // Methods that should be ignored in the checking lazy val ignoredMethods: Set[Symbol] = Set( - ctx.requiredClass("scala.runtime.EnumValues").requiredMethod("register"), + requiredClass("scala.runtime.EnumValues").requiredMethod("register"), defn.Any_getClass, defn.Any_isInstanceOf, defn.Object_eq, diff --git a/compiler/src/dotty/tools/dotc/transform/init/Errors.scala b/compiler/src/dotty/tools/dotc/transform/init/Errors.scala index 89300ce3adc1..e2914b780031 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Errors.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Errors.scala @@ -1,4 +1,5 @@ -package dotty.tools.dotc +package dotty.tools +package dotc package transform package init @@ -23,8 +24,8 @@ object Errors { def trace: Vector[Tree] def show(using Context): String - def report(using Context): Unit = - ctx.warning(show + stacktrace, source.sourcePos) + def issue(using Context): Unit = + report.warning(show + stacktrace, source.sourcePos) def toErrors: Errors = Set(this) @@ -65,7 +66,8 @@ object Errors { def show(using Context): String = "Access non-initialized field " + field.name.show + "." - override def report(using Context): Unit = ctx.error(show + stacktrace, field.sourcePos) + override def issue(using Context): Unit = + report.error(show + stacktrace, field.sourcePos) } /** Promote `this` under initialization to fully-initialized */ @@ -104,7 +106,8 @@ object Errors { case class UnsafePromotion(pot: Potential, source: Tree, trace: Vector[Tree], errors: Errors) extends Error { assert(errors.nonEmpty) - override def report(using Context): Unit = ctx.warning(show, source.sourcePos) + override def issue(using Context): Unit = + report.warning(show, source.sourcePos) def show(using Context): String = { var index = 0 diff --git a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala index 13f28ac95602..127f12f85bbf 100644 --- a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala +++ b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala @@ -1,4 +1,5 @@ -package dotty.tools.dotc.transform.localopt +package dotty.tools.dotc +package transform.localopt import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.tpd @@ -101,7 +102,7 @@ class StringInterpolatorOpt extends MiniPhase { case t @ InvalidEscapePosition(p) => { val errorSpan = stringPosition.span.startPos.shift(p) val errorPosition = stringPosition.withSpan(errorSpan) - ctx.error(t.getMessage() + "\n", errorPosition) + report.error(t.getMessage() + "\n", errorPosition) None } } diff --git a/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala b/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala index 737609ac644d..0ac620b804c4 100644 --- a/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala +++ b/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala @@ -18,8 +18,7 @@ import Applications._ import Inferencing._ import ProtoTypes._ import transform.SymUtils._ -import reporting.messages._ -import reporting.trace +import reporting._ import config.Printers.{exhaustivity => debug} import util.SourcePosition import NullOpsDecorator._ @@ -318,10 +317,10 @@ class SpaceEngine(using Context) extends SpaceLogic { import tpd._ import SpaceEngine._ - private val scalaSeqFactoryClass = ctx.requiredClass("scala.collection.SeqFactory") - private val scalaListType = ctx.requiredClassRef("scala.collection.immutable.List") - private val scalaNilType = ctx.requiredModuleRef("scala.collection.immutable.Nil") - private val scalaConsType = ctx.requiredClassRef("scala.collection.immutable.::") + private val scalaSeqFactoryClass = requiredClass("scala.collection.SeqFactory") + private val scalaListType = requiredClassRef("scala.collection.immutable.List") + private val scalaNilType = requiredModuleRef("scala.collection.immutable.Nil") + private val scalaConsType = requiredClassRef("scala.collection.immutable.::") private val constantNullType = ConstantType(Constant(null)) private val constantNullSpace = Typ(constantNullType) @@ -836,7 +835,7 @@ class SpaceEngine(using Context) extends SpaceLogic { } if (uncovered.nonEmpty) - ctx.warning(PatternMatchExhaustivity(show(uncovered)), sel.sourcePos) + report.warning(PatternMatchExhaustivity(show(uncovered)), sel.sourcePos) } private def redundancyCheckable(sel: Tree): Boolean = @@ -885,7 +884,7 @@ class SpaceEngine(using Context) extends SpaceLogic { if (covered == Empty && !isNullLit(pat)) covered = curr if (isSubspace(covered, prevs)) { - ctx.warning(MatchCaseUnreachable(), pat.sourcePos) + report.warning(MatchCaseUnreachable(), pat.sourcePos) } // if last case is `_` and only matches `null`, produce a warning @@ -894,7 +893,7 @@ class SpaceEngine(using Context) extends SpaceLogic { if (!ctx.explicitNulls && i == cases.length - 1 && !isNullLit(pat) ) { simplify(minus(covered, prevs)) match { case Typ(`constantNullType`, _) => - ctx.warning(MatchCaseOnlyNullWarning(), pat.sourcePos) + report.warning(MatchCaseOnlyNullWarning(), pat.sourcePos) case _ => } } diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index f823cc8a268c..56c1c3a9319c 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -19,9 +19,11 @@ import Trees._ import Names._ import StdNames._ import NameOps._ +import ContextOps._ import NameKinds.DefaultGetterName import ProtoTypes._ import Inferencing._ +import reporting._ import transform.TypeUtils._ import Nullables.{postProcessByNameArgs, given _} import config.Feature @@ -30,10 +32,7 @@ import collection.mutable import config.Printers.{overload, typr, unapp} import TypeApplications._ -import reporting.messages.{UnexpectedPatternForSummonFrom, NotFoundMsg, TypeMismatch} -import reporting.{trace, Message} import Constants.{Constant, IntTag, LongTag} -import dotty.tools.dotc.reporting.messages.{UnapplyInvalidReturnType, NotAnExtractor, UnapplyInvalidNumberOfArguments} import Denotations.SingleDenotation import annotation.{constructorOnly, threadUnsafe} @@ -160,7 +159,7 @@ object Applications { def getTp = extractorMemberType(unapplyResult, nme.get, pos) def fail = { - ctx.error(UnapplyInvalidReturnType(unapplyResult, unapplyName), pos) + report.error(UnapplyInvalidReturnType(unapplyResult, unapplyName), pos) Nil } @@ -728,12 +727,12 @@ trait Applications extends Compatibility { override def appPos: SourcePosition = app.sourcePos def fail(msg: Message, arg: Trees.Tree[T]): Unit = { - ctx.error(msg, arg.sourcePos) + report.error(msg, arg.sourcePos) ok = false } def fail(msg: Message): Unit = { - ctx.error(msg, app.sourcePos) + report.error(msg, app.sourcePos) ok = false } @@ -942,7 +941,7 @@ trait Applications extends Compatibility { case CaseDef(Bind(_, Typed(_: untpd.Ident, _)), _, _) => // OK case CaseDef(Ident(name), _, _) if name == nme.WILDCARD => // Ok case CaseDef(pat, _, _) => - ctx.error(UnexpectedPatternForSummonFrom(pat), pat.sourcePos) + report.error(UnexpectedPatternForSummonFrom(pat), pat.sourcePos) } typed(untpd.InlineMatch(EmptyTree, cases).withSpan(arg.span), pt) case _ => @@ -1049,7 +1048,7 @@ trait Applications extends Compatibility { typedFunPart(tree.fun, PolyProto(typedArgs, pt)) match { case IntegratedTypeArgs(app) => app - case _: TypeApply if !ctx.isAfterTyper => + case _: TypeApply if !currentlyAfterTyper => errorTree(tree, "illegal repeated type application") case typedFn => typedFn.tpe.widen match { @@ -1243,7 +1242,7 @@ trait Applications extends Compatibility { // We ignore whether constraining the pattern succeeded. // Constraining only fails if the pattern cannot possibly match, // but useless pattern checks detect more such cases, so we simply rely on them instead. - ctx.addMode(Mode.GadtConstraintInference).typeComparer.constrainPatternType(unapplyArgType, selType) + withMode(Mode.GadtConstraintInference)(ctx.typeComparer.constrainPatternType(unapplyArgType, selType)) val patternBound = maximizeType(unapplyArgType, tree.span, fromScala2x) if (patternBound.nonEmpty) unapplyFn = addBinders(unapplyFn, patternBound) unapp.println(i"case 2 $unapplyArgType ${ctx.typerState.constraint}") @@ -1257,7 +1256,7 @@ trait Applications extends Compatibility { case Apply(Apply(unapply, `dummyArg` :: Nil), args2) => assert(args2.nonEmpty); res ++= args2 case Apply(unapply, `dummyArg` :: Nil) => case Inlined(u, _, _) => loop(u) - case DynamicUnapply(_) => ctx.error("Structural unapply is not supported", unapplyFn.sourcePos) + case DynamicUnapply(_) => report.error("Structural unapply is not supported", unapplyFn.sourcePos) case Apply(fn, args) => assert(args.nonEmpty); loop(fn); res ++= args case _ => ().assertingErrorsReported } @@ -1274,7 +1273,7 @@ trait Applications extends Compatibility { case _ => args } if (argTypes.length != bunchedArgs.length) { - ctx.error(UnapplyInvalidNumberOfArguments(qual, argTypes), tree.sourcePos) + report.error(UnapplyInvalidNumberOfArguments(qual, argTypes), tree.sourcePos) argTypes = argTypes.take(args.length) ++ List.fill(argTypes.length - args.length)(WildcardType) } @@ -1466,7 +1465,7 @@ trait Applications extends Compatibility { val tp1Params = tp1.newLikeThis(tp1.paramNames, tp1.paramInfos, defn.AnyType) fullyDefinedType(tp1Params, "type parameters of alternative", alt1.symbol.span) - val tparams = ctx.newTypeParams(alt1.symbol, tp1.paramNames, EmptyFlags, tp1.instantiateParamInfos(_)) + val tparams = newTypeParams(alt1.symbol, tp1.paramNames, EmptyFlags, tp1.instantiateParamInfos(_)) isAsSpecific(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2) } case _ => // (3) @@ -1683,7 +1682,7 @@ trait Applications extends Compatibility { return resolveMapped(alts, alt => stripImplicit(alt.widen), pt) case _ => - var found = resolveOverloaded1(alts, pt)(using ctx.retractMode(Mode.ImplicitsEnabled)) + var found = withoutMode(Mode.ImplicitsEnabled)(resolveOverloaded1(alts, pt)) if found.isEmpty && ctx.mode.is(Mode.ImplicitsEnabled) then found = resolveOverloaded1(alts, pt) found match @@ -1831,7 +1830,7 @@ trait Applications extends Compatibility { val alts2 = alts.filter(alt => isDirectlyApplicableMethodRef(alt, args, resultType) ) - if (alts2.isEmpty && !ctx.isAfterTyper) + if (alts2.isEmpty && !currentlyAfterTyper) alts.filter(alt => isApplicableMethodRef(alt, args, resultType, keepConstraint = false) ) @@ -1840,11 +1839,11 @@ trait Applications extends Compatibility { } val alts1 = narrowBySize(alts) - //ctx.log(i"narrowed by size: ${alts1.map(_.symbol.showDcl)}%, %") + //report.log(i"narrowed by size: ${alts1.map(_.symbol.showDcl)}%, %") if isDetermined(alts1) then alts1 else val alts2 = narrowByShapes(alts1) - //ctx.log(i"narrowed by shape: ${alts2.map(_.symbol.showDcl)}%, %") + //report.log(i"narrowed by shape: ${alts2.map(_.symbol.showDcl)}%, %") if isDetermined(alts2) then alts2 else pretypeArgs(alts2, pt) @@ -1998,7 +1997,7 @@ trait Applications extends Compatibility { else defn.FunctionOf(commonParamTypes, WildcardType) overload.println(i"pretype arg $arg with expected type $commonFormal") if (commonParamTypes.forall(isFullyDefined(_, ForceDegree.flipBottom))) - pt.typedArg(arg, commonFormal)(using ctx.addMode(Mode.ImplicitsEnabled)) + withMode(Mode.ImplicitsEnabled)(pt.typedArg(arg, commonFormal)) } case None => } @@ -2049,7 +2048,7 @@ trait Applications extends Compatibility { case cdef: CaseDef => tpd.cpy.CaseDef(cdef)(body = adaptDeep(cdef.body, pt)) case _ => adapt(tree, pt) } - if (ctx.isAfterTyper) trees else harmonizeWith(trees)(_.tpe, adaptDeep) + if (currentlyAfterTyper) trees else harmonizeWith(trees)(_.tpe, adaptDeep) } /** Apply a transformation `harmonize` on the results of operation `op`, @@ -2101,16 +2100,16 @@ trait Applications extends Compatibility { (methodRef, pt) } val (core, pt1) = integrateTypeArgs(pt) - val app = - typed(untpd.Apply(core, untpd.TypedSplice(receiver) :: Nil), pt1, ctx.typerState.ownedVars)( - using ctx.addMode(Mode.SynthesizeExtMethodReceiver)) + val app = withMode(Mode.SynthesizeExtMethodReceiver) { + typed(untpd.Apply(core, untpd.TypedSplice(receiver) :: Nil), pt1, ctx.typerState.ownedVars) + } def isExtension(tree: Tree): Boolean = methPart(tree) match { case Inlined(call, _, _) => isExtension(call) case tree @ Select(qual, nme.apply) => tree.symbol.is(Extension) || isExtension(qual) case tree => tree.symbol.is(Extension) } if (!isExtension(app)) - ctx.error(em"not an extension method: $methodRef", receiver.sourcePos) + report.error(em"not an extension method: $methodRef", receiver.sourcePos) app } } diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index 248afc958ff6..957034ec71fc 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -37,8 +37,7 @@ import config.Feature._ import config.SourceVersion._ import collection.mutable -import reporting.Message -import reporting.messages._ +import reporting._ import scala.internal.Chars.isOperatorPart object Checking { @@ -71,7 +70,7 @@ object Checking { showInferred(MissingTypeParameterInTypeApp(arg.tpe), app, tpt)) } for (arg, which, bound) <- TypeOps.boundsViolations(args, boundss, instantiate, app) do - ctx.error( + report.error( showInferred(DoesNotConformToBound(arg.tpe, which, bound), app, tpt), arg.sourcePos.focus) @@ -114,14 +113,14 @@ object Checking { def checkWildcardApply(tp: Type): Unit = tp match { case tp @ AppliedType(tycon, _) => if (tycon.isLambdaSub && tp.hasWildcardArg) - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( showInferred(UnreducibleApplication(tycon), tp, tpt), tree.sourcePos) case _ => } def checkValidIfApply(using Context): Unit = checkWildcardApply(tycon.tpe.appliedTo(args.map(_.tpe))) - checkValidIfApply(using ctx.addMode(Mode.AllowLambdaWildcardApply)) + withMode(Mode.AllowLambdaWildcardApply)(checkValidIfApply) } /** Check all applied type trees in inferred type `tpt` for well-formedness */ @@ -174,21 +173,21 @@ object Checking { case tref: TypeRef => val cls = tref.symbol if (cls.isOneOf(AbstractOrTrait)) - ctx.error(CantInstantiateAbstractClassOrTrait(cls, isTrait = cls.is(Trait)), posd.sourcePos) + report.error(CantInstantiateAbstractClassOrTrait(cls, isTrait = cls.is(Trait)), posd.sourcePos) if !cls.is(Module) then // Create a synthetic singleton type instance, and check whether // it conforms to the self type of the class as seen from that instance. val stp = SkolemType(tp) val selfType = cls.declaredSelfTypeAsSeenFrom(stp) if selfType.exists && !(stp <:< selfType) then - ctx.error(DoesNotConformToSelfTypeCantBeInstantiated(tp, selfType), posd.sourcePos) + report.error(DoesNotConformToSelfTypeCantBeInstantiated(tp, selfType), posd.sourcePos) case _ => /** Check that type `tp` is realizable. */ def checkRealizable(tp: Type, posd: Positioned, what: String = "path")(using Context): Unit = { val rstatus = realizability(tp) if (rstatus ne Realizable) - ctx.errorOrMigrationWarning(em"$tp is not a legal $what\nsince it${rstatus.msg}", posd.sourcePos) + report.errorOrMigrationWarning(em"$tp is not a legal $what\nsince it${rstatus.msg}", posd.sourcePos) } /** A type map which checks that the only cycles in a type are F-bounds @@ -300,8 +299,8 @@ object Checking { } catch { case ex: CyclicReference => - ctx.debuglog(i"cycle detected for $tp, $nestedCycleOK, $cycleOK") - if (cycleOK) LazyRef(_ => tp) + report.debuglog(i"cycle detected for $tp, $nestedCycleOK, $cycleOK") + if (cycleOK) LazyRef(tp) else if (reportErrors) throw ex else tp } @@ -320,7 +319,7 @@ object Checking { && !sym.getAnnotation(defn.AlphaAnnot).isDefined && !sym.is(Synthetic) && sourceVersion.isAtLeast(`3.1`) => - ctx.deprecationWarning( + report.deprecationWarning( i"$sym has an operator name; it should come with an @alpha annotation", sym.sourcePos) case _ => } @@ -331,7 +330,7 @@ object Checking { * by a `LazyRef`, or `ErrorType` if a cycle was detected and reported. */ def checkNonCyclic(sym: Symbol, info: Type, reportErrors: Boolean)(using Context): Type = { - val checker = new CheckNonCyclicMap(sym, reportErrors)(using ctx.addMode(Mode.CheckCyclic)) + val checker = withMode(Mode.CheckCyclic)(new CheckNonCyclicMap(sym, reportErrors)) try checker.checkInfo(info) catch { case ex: CyclicReference => @@ -353,7 +352,7 @@ object Checking { def checkRefinementNonCyclic(refinement: Tree, refineCls: ClassSymbol, seen: mutable.Set[Symbol]) (using Context): Unit = { def flag(what: String, tree: Tree) = - ctx.warning(i"$what reference in refinement is deprecated", tree.sourcePos) + report.warning(i"$what reference in refinement is deprecated", tree.sourcePos) def forwardRef(tree: Tree) = flag("forward", tree) def selfRef(tree: Tree) = flag("self", tree) val checkTree = new TreeAccumulator[Unit] { @@ -419,14 +418,14 @@ object Checking { } catch { case ex: RecursionOverflow => - ctx.error(em"cyclic reference involving type $name", posd.sourcePos) + report.error(em"cyclic reference involving type $name", posd.sourcePos) false } } /** Check that symbol's definition is well-formed. */ def checkWellFormed(sym: Symbol)(using Context): Unit = { - def fail(msg: Message) = ctx.error(msg, sym.sourcePos) + def fail(msg: Message) = report.error(msg, sym.sourcePos) def checkWithDeferred(flag: FlagSet) = if (sym.isOneOf(flag)) @@ -580,7 +579,7 @@ object Checking { } val notPrivate = new NotPrivate val info = notPrivate(sym.info) - notPrivate.errors.foreach(error => ctx.errorOrMigrationWarning(error(), sym.sourcePos)) + notPrivate.errors.foreach(error => report.errorOrMigrationWarning(error(), sym.sourcePos)) info } @@ -588,25 +587,25 @@ object Checking { def checkDerivedValueClass(clazz: Symbol, stats: List[Tree])(using Context): Unit = { def checkValueClassMember(stat: Tree) = stat match { case _: TypeDef if stat.symbol.isClass => - ctx.error(ValueClassesMayNotDefineInner(clazz, stat.symbol), stat.sourcePos) + report.error(ValueClassesMayNotDefineInner(clazz, stat.symbol), stat.sourcePos) case _: ValDef if !stat.symbol.is(ParamAccessor) => - ctx.error(ValueClassesMayNotDefineNonParameterField(clazz, stat.symbol), stat.sourcePos) + report.error(ValueClassesMayNotDefineNonParameterField(clazz, stat.symbol), stat.sourcePos) case _: DefDef if stat.symbol.isConstructor => - ctx.error(ValueClassesMayNotDefineASecondaryConstructor(clazz, stat.symbol), stat.sourcePos) + report.error(ValueClassesMayNotDefineASecondaryConstructor(clazz, stat.symbol), stat.sourcePos) case _: MemberDef | _: Import | EmptyTree => // ok case _ => - ctx.error(ValueClassesMayNotContainInitalization(clazz), stat.sourcePos) + report.error(ValueClassesMayNotContainInitalization(clazz), stat.sourcePos) } if (isDerivedValueClass(clazz)) { if (clazz.is(Trait)) - ctx.error(CannotExtendAnyVal(clazz), clazz.sourcePos) + report.error(CannotExtendAnyVal(clazz), clazz.sourcePos) if (clazz.is(Abstract)) - ctx.error(ValueClassesMayNotBeAbstract(clazz), clazz.sourcePos) + report.error(ValueClassesMayNotBeAbstract(clazz), clazz.sourcePos) if (!clazz.isStatic) - ctx.error(ValueClassesMayNotBeContainted(clazz), clazz.sourcePos) + report.error(ValueClassesMayNotBeContainted(clazz), clazz.sourcePos) if (isCyclic(clazz.asClass)) - ctx.error(ValueClassesMayNotWrapItself(clazz), clazz.sourcePos) + report.error(ValueClassesMayNotWrapItself(clazz), clazz.sourcePos) else { val clParamAccessors = clazz.asClass.paramAccessors.filter { param => param.isTerm && !param.is(Flags.Accessor) @@ -614,16 +613,16 @@ object Checking { clParamAccessors match { case param :: params => if (param.is(Mutable)) - ctx.error(ValueClassParameterMayNotBeAVar(clazz, param), param.sourcePos) + report.error(ValueClassParameterMayNotBeAVar(clazz, param), param.sourcePos) if (param.info.isInstanceOf[ExprType]) - ctx.error(ValueClassParameterMayNotBeCallByName(clazz, param), param.sourcePos) + report.error(ValueClassParameterMayNotBeCallByName(clazz, param), param.sourcePos) if (param.is(Erased)) - ctx.error("value class first parameter cannot be `erased`", param.sourcePos) + report.error("value class first parameter cannot be `erased`", param.sourcePos) else for (p <- params if !p.is(Erased)) - ctx.error("value class can only have one non `erased` parameter", p.sourcePos) + report.error("value class can only have one non `erased` parameter", p.sourcePos) case Nil => - ctx.error(ValueClassNeedsOneValParam(clazz), clazz.sourcePos) + report.error(ValueClassNeedsOneValParam(clazz), clazz.sourcePos) } } stats.foreach(checkValueClassMember) @@ -639,7 +638,7 @@ object Checking { if enumCase.exists then val enumCls = enumCase.owner.linkedClass if !cls.info.parents.exists(_.typeSymbol == enumCls) then - ctx.error(i"enum case does not extend its enum $enumCls", enumCase.sourcePos) + report.error(i"enum case does not extend its enum $enumCls", enumCase.sourcePos) /** Check the inline override methods only use inline parameters if they override an inline parameter. */ def checkInlineOverrideParameters(sym: Symbol)(using Context): Unit = @@ -649,7 +648,7 @@ object Checking { (p1, p2) <- sym.paramSymss.flatten.lazyZip(sym2.paramSymss.flatten) if p1.is(Inline) != p2.is(Inline) do - ctx.error( + report.error( if p2.is(Inline) then "Cannot override inline parameter with a non-inline parameter" else "Cannot override non-inline parameter with an inline parameter", p1.sourcePos) @@ -668,13 +667,13 @@ trait Checking { /** Check that type `tp` is stable. */ def checkStable(tp: Type, pos: SourcePosition, kind: String)(using Context): Unit = - if !tp.isStable then ctx.error(NotAPath(tp, kind), pos) + if !tp.isStable then report.error(NotAPath(tp, kind), pos) /** Check that all type members of `tp` have realizable bounds */ def checkRealizableBounds(cls: Symbol, pos: SourcePosition)(using Context): Unit = { val rstatus = boundsRealizability(cls.thisType) if (rstatus ne Realizable) - ctx.error(ex"$cls cannot be instantiated since it${rstatus.msg}", pos) + report.error(ex"$cls cannot be instantiated since it${rstatus.msg}", pos) } /** Check that pattern `pat` is irrefutable for scrutinee tye `pt`. @@ -688,7 +687,7 @@ trait Checking { if (!pat.tpe.isSingleton) reportedPt = reportedPt.widen val problem = if (pat.tpe <:< reportedPt) "is more specialized than" else "does not match" val fix = if (isPatDef) "`: @unchecked` after" else "`case ` before" - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( ex"""pattern's type ${pat.tpe} $problem the right hand side expression's type $reportedPt | |If the narrowing is intentional, this can be communicated by writing $fix the full pattern.${err.rewriteNotice}""", @@ -728,7 +727,7 @@ trait Checking { /** Check that `path` is a legal prefix for an import or export clause */ def checkLegalImportPath(path: Tree)(using Context): Unit = { checkStable(path.tpe, path.sourcePos, "import prefix") - if (!ctx.isAfterTyper) Checking.checkRealizable(path.tpe, path.posd) + if (!currentlyAfterTyper) Checking.checkRealizable(path.tpe, path.posd) } /** Check that `tp` is a class type. @@ -740,11 +739,11 @@ trait Checking { def checkClassType(tp: Type, pos: SourcePosition, traitReq: Boolean, stablePrefixReq: Boolean)(using Context): Type = tp.underlyingClassRef(refinementOK = false) match { case tref: TypeRef => - if (traitReq && !tref.symbol.is(Trait)) ctx.error(TraitIsExpected(tref.symbol), pos) - if (stablePrefixReq && ctx.phase <= refchecksPhase) checkStable(tref.prefix, pos, "class prefix") + if (traitReq && !tref.symbol.is(Trait)) report.error(TraitIsExpected(tref.symbol), pos) + if (stablePrefixReq && currentPhase <= refchecksPhase) checkStable(tref.prefix, pos, "class prefix") tp case _ => - ctx.error(ex"$tp is not a class type", pos) + report.error(ex"$tp is not a class type", pos) defn.ObjectType } @@ -820,7 +819,7 @@ trait Checking { ("extractor", (n: Name) => s"prefix syntax $n(...)") else ("method", (n: Name) => s"method syntax .$n(...)") - ctx.deprecationWarning( + report.deprecationWarning( i"""Alphanumeric $kind $name is not declared @infix; it should not be used as infix operator. |The operation can be rewritten automatically to `$name` under -deprecation -rewrite. |Or rewrite to ${alternative(name)} manually.""", @@ -840,7 +839,7 @@ trait Checking { featureUseSite: Symbol, pos: SourcePosition)(using Context): Unit = if !enabled(name) then - ctx.featureWarning(name.toString, description, featureUseSite, required = false, pos) + report.featureWarning(name.toString, description, featureUseSite, required = false, pos) /** Check that `tp` is a class type and that any top-level type arguments in this type * are feasible, i.e. that their lower bound conforms to their upper bound. If a type @@ -849,14 +848,14 @@ trait Checking { def checkFeasibleParent(tp: Type, pos: SourcePosition, where: => String = "")(using Context): Type = { def checkGoodBounds(tp: Type) = tp match { case tp @ TypeBounds(lo, hi) if !(lo <:< hi) => - ctx.error(ex"no type exists between low bound $lo and high bound $hi$where", pos) + report.error(ex"no type exists between low bound $lo and high bound $hi$where", pos) TypeBounds(hi, hi) case _ => tp } tp match { case tp @ AndType(tp1, tp2) => - ctx.error(s"conflicting type arguments$where", pos) + report.error(s"conflicting type arguments$where", pos) tp1 case tp @ AppliedType(tycon, args) => tp.derivedAppliedType(tycon, args.mapConserve(checkGoodBounds)) @@ -869,14 +868,14 @@ trait Checking { /** Check that `tree` can be right hand-side or argument to `inline` value or parameter. */ def checkInlineConformant(tpt: Tree, tree: Tree, sym: Symbol)(using Context): Unit = { - if sym.is(Inline, butNot = DeferredOrTermParamOrAccessor) && !ctx.erasedTypes && !Inliner.inInlineMethod then + if sym.is(Inline, butNot = DeferredOrTermParamOrAccessor) && !currentlyAfterErasure && !Inliner.inInlineMethod then tpt.tpe.widenTermRefExpr.dealias.normalized match case tp: ConstantType => if !(exprPurity(tree) >= Pure) then - ctx.error(em"inline value must be pure", tree.sourcePos) + report.error(em"inline value must be pure", tree.sourcePos) case _ => val pos = if tpt.span.isZeroExtent then tree.sourcePos else tpt.sourcePos - ctx.error(em"inline value must have a literal constant type", pos) + report.error(em"inline value must have a literal constant type", pos) } /** A hook to exclude selected symbols from double declaration check */ @@ -898,12 +897,12 @@ trait Checking { if (decl.matches(other) && !javaFieldMethodPair) { def doubleDefError(decl: Symbol, other: Symbol): Unit = if (!decl.info.isErroneous && !other.info.isErroneous) - ctx.error(DoubleDefinition(decl, other, cls), decl.sourcePos) + report.error(DoubleDefinition(decl, other, cls), decl.sourcePos) if (decl is Synthetic) doubleDefError(other, decl) else doubleDefError(decl, other) } if decl.hasDefaultParams && other.hasDefaultParams then - ctx.error(em"two or more overloaded variants of $decl have default arguments", decl.sourcePos) + report.error(em"two or more overloaded variants of $decl have default arguments", decl.sourcePos) decl.resetFlag(HasDefaultParams) } if (!excludeFromDoubleDeclCheck(decl)) @@ -918,19 +917,19 @@ trait Checking { } def checkParentCall(call: Tree, caller: ClassSymbol)(using Context): Unit = - if (!ctx.isAfterTyper) { + if (!currentlyAfterTyper) { val called = call.tpe.classSymbol if (caller.is(Trait)) - ctx.error(i"$caller may not call constructor of $called", call.sourcePos) + report.error(i"$caller may not call constructor of $called", call.sourcePos) else if (called.is(Trait) && !caller.mixins.contains(called)) - ctx.error(i"""$called is already implemented by super${caller.superClass}, + report.error(i"""$called is already implemented by super${caller.superClass}, |its constructor cannot be called again""", call.sourcePos) if (caller.is(Module)) { val traverser = new TreeTraverser { def traverse(tree: Tree)(using Context) = tree match { case tree: RefTree if tree.isTerm && (tree.tpe.widen.classSymbol eq caller) => - ctx.error("super constructor cannot be passed a self reference", tree.sourcePos) + report.error("super constructor cannot be passed a self reference", tree.sourcePos) case _ => traverseChildren(tree) } @@ -944,7 +943,7 @@ trait Checking { case Apply(fn, _) => checkLegalConstructorCall(fn, tree, "") case TypeApply(fn, _) => checkLegalConstructorCall(fn, tree, "type ") case Select(_, nme.CONSTRUCTOR) => // ok - case _ => ctx.error(s"too many ${kind}arguments in parent constructor", encl.sourcePos) + case _ => report.error(s"too many ${kind}arguments in parent constructor", encl.sourcePos) } call match { case Apply(fn, _) => checkLegalConstructorCall(fn, call, "") @@ -963,7 +962,7 @@ trait Checking { /** Check that the signature of the class mamber does not return a repeated parameter type */ def checkSignatureRepeatedParam(sym: Symbol)(using Context): Unit = if (!sym.isOneOf(Synthetic | InlineProxy | Param) && sym.info.finalResultType.isRepeatedParam) - ctx.error(em"Cannot return repeated parameter type ${sym.info.finalResultType}", sym.sourcePos) + report.error(em"Cannot return repeated parameter type ${sym.info.finalResultType}", sym.sourcePos) /** Verify classes extending AnyVal meet the requirements */ def checkDerivedValueClass(clazz: Symbol, stats: List[Tree])(using Context): Unit = @@ -989,7 +988,7 @@ trait Checking { parent.is(JavaDefined) && csuper == defn.AnyClass && (parent == defn.JavaSerializableClass || parent == defn.ComparableClass) if (!ok) - ctx.error(em"illegal trait inheritance: super$csuper does not derive from $parent's super$psuper", pos) + report.error(em"illegal trait inheritance: super$csuper does not derive from $parent's super$psuper", pos) case _ => } @@ -999,7 +998,7 @@ trait Checking { parent match { case parent: ClassSymbol => if (parent.is(Case)) - ctx.error(ex"""case $caseCls has case ancestor $parent, but case-to-case inheritance is prohibited. + report.error(ex"""case $caseCls has case ancestor $parent, but case-to-case inheritance is prohibited. |To overcome this limitation, use extractors to pattern match on non-leaf nodes.""", pos) else checkCaseInheritance(parent.superClass, caseCls, pos) case _ => @@ -1013,7 +1012,7 @@ trait Checking { val check = new TreeTraverser { def traverse(tree: Tree)(using Context) = tree match { case id: Ident if vparams.exists(_.symbol == id.symbol) => - ctx.error("illegal forward reference to method parameter", id.sourcePos) + report.error("illegal forward reference to method parameter", id.sourcePos) case _ => traverseChildren(tree) } @@ -1035,7 +1034,7 @@ trait Checking { case ref: NamedType => val d = try ref.denot catch { case ex: TypeError => NoDenotation } if (!d.exists) { - ctx.error(em"$ref is not defined in inferred type $tp", pos) + report.error(em"$ref is not defined in inferred type $tp", pos) ok = false } case _ => @@ -1056,7 +1055,7 @@ trait Checking { if (t.span.isSourceDerived && owner == badOwner) t match { case t: RefTree if allowed(t.name, checkedSym) => - case _ => ctx.error(i"illegal reference to $checkedSym from $where", t.sourcePos) + case _ => report.error(i"illegal reference to $checkedSym from $where", t.sourcePos) } val sym = t.symbol t match { @@ -1083,12 +1082,12 @@ trait Checking { case _ => if tree.tpe.typeParams.nonEmpty then val what = if tree.symbol.exists then tree.symbol else i"type $tree" - ctx.error(em"$what takes type parameters", tree.sourcePos) + report.error(em"$what takes type parameters", tree.sourcePos) /** Check that we are in an inline context (inside an inline method or in inline code) */ def checkInInlineContext(what: String, posd: Positioned)(using Context): Unit = if !Inliner.inInlineMethod && !ctx.isInlineContext then - ctx.error(em"$what can only be used in an inline method", posd.sourcePos) + report.error(em"$what can only be used in an inline method", posd.sourcePos) /** 1. Check that all case classes that extend `scala.Enum` are `enum` cases * 2. Check that case class `enum` cases do not extend java.lang.Enum. @@ -1101,7 +1100,7 @@ trait Checking { if (!isEnumAnonCls) if (cdef.mods.isEnumCase) { if (cls.derivesFrom(defn.JavaEnumClass)) - ctx.error(em"paramerized case is not allowed in an enum that extends java.lang.Enum", cdef.sourcePos) + report.error(em"paramerized case is not allowed in an enum that extends java.lang.Enum", cdef.sourcePos) } else if (cls.is(Case) || firstParent.is(Enum)) // Since enums are classes and Namer checks that classes don't extend multiple classes, we only check the class @@ -1109,7 +1108,7 @@ trait Checking { // // Unlike firstParent.derivesFrom(defn.EnumClass), this test allows inheriting from `Enum` by hand; // see enum-List-control.scala. - ctx.error(ClassCannotExtendEnum(cls, firstParent), cdef.sourcePos) + report.error(ClassCannotExtendEnum(cls, firstParent), cdef.sourcePos) } /** Check that all references coming from enum cases in an enum companion object @@ -1175,14 +1174,14 @@ trait Checking { /** check that annotation `annot` is applicable to symbol `sym` */ def checkAnnotApplicable(annot: Tree, sym: Symbol)(using Context): Boolean = - !ctx.reporter.reportsErrorsFor { implicit ctx => + !ctx.reporter.reportsErrorsFor { val annotCls = Annotations.annotClass(annot) val pos = annot.sourcePos if (annotCls == defn.MainAnnot) { if (!sym.isRealMethod) - ctx.error(em"@main annotation cannot be applied to $sym", pos) + report.error(em"@main annotation cannot be applied to $sym", pos) if (!sym.owner.is(Module) || !sym.owner.isStatic) - ctx.error(em"$sym cannot be a @main method since it cannot be accessed statically", pos) + report.error(em"$sym cannot be a @main method since it cannot be accessed statically", pos) } // TODO: Add more checks here } @@ -1196,7 +1195,7 @@ trait Checking { if (ename != sym.name) { val preExisting = ctx.effectiveScope.lookup(ename) if (preExisting.exists || seen.contains(ename)) - ctx.error(em"@alpha annotation ${'"'}$ename${'"'} clashes with other definition is same scope", stat.sourcePos) + report.error(em"@alpha annotation ${'"'}$ename${'"'} clashes with other definition is same scope", stat.sourcePos) if stat.isDef then seen += ename } } diff --git a/compiler/src/dotty/tools/dotc/typer/Deriving.scala b/compiler/src/dotty/tools/dotc/typer/Deriving.scala index cbe7f980815a..e0056f398d5f 100644 --- a/compiler/src/dotty/tools/dotc/typer/Deriving.scala +++ b/compiler/src/dotty/tools/dotc/typer/Deriving.scala @@ -7,7 +7,7 @@ import ast._ import ast.Trees._ import StdNames._ import Contexts._, Symbols._, Types._, SymDenotations._, Names._, NameOps._, Flags._, Decorators._ -import ProtoTypes._ +import ProtoTypes._, ContextOps._ import util.Spans._ import util.SourcePosition import collection.mutable @@ -49,13 +49,13 @@ trait Deriving { private def addDerivedInstance(clsName: Name, info: Type, pos: SourcePosition): Unit = { val instanceName = s"derived$$$clsName".toTermName if (ctx.denotNamed(instanceName).exists) - ctx.error(i"duplicate type class derivation for $clsName", pos) + report.error(i"duplicate type class derivation for $clsName", pos) else // If we set the Synthetic flag here widenGiven will widen too far and the // derived instance will have too low a priority to be selected over a freshly // derived instance at the summoning site. synthetics += - ctx.newSymbol(ctx.owner, instanceName, Given | Method, info, coord = pos.span) + newSymbol(ctx.owner, instanceName, Given | Method, info, coord = pos.span) .entered } @@ -91,7 +91,7 @@ trait Deriving { xs.corresponds(ys)((x, y) => x.paramInfo.hasSameKindAs(y.paramInfo)) def cannotBeUnified = - ctx.error(i"${cls.name} cannot be unified with the type argument of ${typeClass.name}", derived.sourcePos) + report.error(i"${cls.name} cannot be unified with the type argument of ${typeClass.name}", derived.sourcePos) def addInstance(derivedParams: List[TypeSymbol], evidenceParamInfos: List[List[Type]], instanceTypes: List[Type]): Unit = { val resultType = typeClassType.appliedTo(instanceTypes) @@ -251,7 +251,7 @@ trait Deriving { if (typeClassArity == 1) deriveSingleParameter else if (typeClass == defn.EqlClass) deriveEql else if (typeClassArity == 0) - ctx.error(i"type ${typeClass.name} in derives clause of ${cls.name} has no type parameters", derived.sourcePos) + report.error(i"type ${typeClass.name} in derives clause of ${cls.name} has no type parameters", derived.sourcePos) else cannotBeUnified } @@ -272,8 +272,8 @@ trait Deriving { (tparamRefs: List[Type]) => (paramRefss: List[List[tpd.Tree]]) => val tparams = tparamRefs.map(_.typeSymbol.asType) val params = if (paramRefss.isEmpty) Nil else paramRefss.head.map(_.symbol.asTerm) - tparams.foreach(ctx.enter) - params.foreach(ctx.enter) + tparams.foreach(ctx.enter(_)) + params.foreach(ctx.enter(_)) def instantiated(info: Type): Type = info match { case info: PolyType => instantiated(info.instantiate(tparamRefs)) case info: MethodType => info.instantiate(params.map(_.termRef)) diff --git a/compiler/src/dotty/tools/dotc/typer/Docstrings.scala b/compiler/src/dotty/tools/dotc/typer/Docstrings.scala index 8b69a1a357ca..777f6848eecf 100644 --- a/compiler/src/dotty/tools/dotc/typer/Docstrings.scala +++ b/compiler/src/dotty/tools/dotc/typer/Docstrings.scala @@ -37,7 +37,7 @@ object Docstrings { case List(df: tpd.DefDef) => usecase.typed(df) case _ => - ctx.error("`@usecase` was not a valid definition", ctx.source.atSpan(usecase.codePos)) + report.error("`@usecase` was not a valid definition", ctx.source.atSpan(usecase.codePos)) usecase } } diff --git a/compiler/src/dotty/tools/dotc/typer/Dynamic.scala b/compiler/src/dotty/tools/dotc/typer/Dynamic.scala index ab27d1f2aaa7..6139d55652b1 100644 --- a/compiler/src/dotty/tools/dotc/typer/Dynamic.scala +++ b/compiler/src/dotty/tools/dotc/typer/Dynamic.scala @@ -15,7 +15,7 @@ import util.Spans._ import core.Symbols._ import core.Definitions import ErrorReporting._ -import dotty.tools.dotc.reporting.messages.ReassignmentToVal +import reporting._ object Dynamic { def isDynamicMethod(name: Name): Boolean = diff --git a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala index efd17996d818..b72f29ae1208 100644 --- a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala +++ b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala @@ -10,8 +10,7 @@ import util.Spans._ import util.SourcePosition import config.Feature import java.util.regex.Matcher.quoteReplacement -import reporting.Message -import reporting.messages._ +import reporting._ object ErrorReporting { @@ -27,12 +26,12 @@ object ErrorReporting { tree.withType(errorType(msg, pos)) def errorType(msg: Message, pos: SourcePosition)(using Context): ErrorType = { - ctx.error(msg, pos) + report.error(msg, pos) ErrorType(msg) } def errorType(ex: TypeError, pos: SourcePosition)(using Context): ErrorType = { - ctx.error(ex, pos) + report.error(ex, pos) ErrorType(ex.toMessage) } @@ -90,7 +89,7 @@ object ErrorReporting { if (tree.tpe.widen.exists) i"${exprStr(tree)} does not take ${kind}parameters" else { - i"undefined: $tree # ${tree.uniqueId}: ${tree.tpe.toString} at ${ctx.phase}" + i"undefined: $tree # ${tree.uniqueId}: ${tree.tpe.toString} at ${currentPhase}" } def patternConstrStr(tree: Tree): String = ??? diff --git a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala index dea583c072f1..2d89564f162f 100644 --- a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala +++ b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala @@ -50,7 +50,7 @@ abstract class Lifter { // don't instantiate here, as the type params could be further constrained, see tests/pos/pickleinf.scala var liftedType = expr.tpe.widen if (liftedFlags.is(Method)) liftedType = ExprType(liftedType) - val lifted = ctx.newSymbol(ctx.owner, name, liftedFlags | Synthetic, liftedType, coord = spanCoord(expr.span)) + val lifted = newSymbol(ctx.owner, name, liftedFlags | Synthetic, liftedType, coord = spanCoord(expr.span)) defs += liftedDef(lifted, expr) .withSpan(expr.span) .changeNonLocalOwners(lifted) @@ -223,7 +223,7 @@ object EtaExpansion extends LiftImpure { */ def etaExpand(tree: Tree, mt: MethodType, xarity: Int)(using Context): untpd.Tree = { import untpd._ - assert(!ctx.isAfterTyper) + assert(!currentlyAfterTyper) val defs = new mutable.ListBuffer[tpd.Tree] val lifted: Tree = TypedSplice(liftApp(defs, tree)) val isLastApplication = mt.resultType match { diff --git a/compiler/src/dotty/tools/dotc/typer/FrontEnd.scala b/compiler/src/dotty/tools/dotc/typer/FrontEnd.scala index 99be4cc440f8..774cac41cecd 100644 --- a/compiler/src/dotty/tools/dotc/typer/FrontEnd.scala +++ b/compiler/src/dotty/tools/dotc/typer/FrontEnd.scala @@ -42,7 +42,7 @@ class FrontEnd extends Phase { try body catch { case NonFatal(ex) => - ctx.echo(s"exception occurred while $doing ${ctx.compilationUnit}") + report.echo(s"exception occurred while $doing ${ctx.compilationUnit}") throw ex } @@ -97,7 +97,7 @@ class FrontEnd extends Phase { override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { val unitContexts = for unit <- units yield - ctx.inform(s"compiling ${unit.source}") + report.inform(s"compiling ${unit.source}") ctx.fresh.setCompilationUnit(unit) unitContexts.foreach(parse(using _)) record("parsedTrees", ast.Trees.ntrees) @@ -107,7 +107,7 @@ class FrontEnd extends Phase { remaining = remaining.tail if (firstXmlPos.exists && !defn.ScalaXmlPackageClass.exists) - ctx.error("""To support XML literals, your project must depend on scala-xml. + report.error("""To support XML literals, your project must depend on scala-xml. |See https://github.com/scala/scala-xml for more information.""".stripMargin, firstXmlPos) @@ -125,7 +125,7 @@ class FrontEnd extends Phase { val enableXprintSuspensionHint = if (ctx.settings.XprintSuspension.value) "" else "\n\nCompiling with -Xprint-suspension gives more information." - ctx.error(em"""Cyclic macro dependencies $where + report.error(em"""Cyclic macro dependencies $where |Compilation stopped since no further progress can be made. | |To fix this, place macros in one set of files and their callers in another.$enableXprintSuspensionHint""") diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index 8ff3603fc1d3..17cb75e7e6be 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -23,7 +23,6 @@ import StdNames._ import Constants._ import ProtoTypes._ import ErrorReporting._ -import reporting.Message import Inferencing.{fullyDefinedType, isFullyDefined} import Trees._ import transform.SymUtils._ @@ -34,7 +33,7 @@ import config.{Config, Feature} import Feature.migrateTo3 import config.Printers.{implicits, implicitsDetailed} import collection.mutable -import reporting.trace +import reporting._ import annotation.tailrec import scala.annotation.internal.sharable @@ -731,7 +730,7 @@ trait Implicits { self: Typer => override def viewExists(from: Type, to: Type)(using Context): Boolean = !from.isError && !to.isError - && !ctx.isAfterTyper + && !currentlyAfterTyper && ctx.mode.is(Mode.ImplicitsEnabled) && from.isValueType && ( from.isValueSubType(to) @@ -789,7 +788,7 @@ trait Implicits { self: Typer => def implicitArgTree(formal: Type, span: Span)(using Context): Tree = { val arg = inferImplicitArg(formal, span) if (arg.tpe.isInstanceOf[SearchFailureType]) - ctx.error(missingArgMsg(arg, formal, ""), ctx.source.atSpan(span)) + report.error(missingArgMsg(arg, formal, ""), ctx.source.atSpan(span)) arg } @@ -957,7 +956,7 @@ trait Implicits { self: Typer => /** Check that equality tests between types `ltp` and `rtp` make sense */ def checkCanEqual(ltp: Type, rtp: Type, span: Span)(using Context): Unit = - if (!ctx.isAfterTyper && !assumedCanEqual(ltp, rtp)) { + if (!currentlyAfterTyper && !assumedCanEqual(ltp, rtp)) { val res = implicitArgTree(defn.EqlClass.typeRef.appliedTo(ltp, rtp), span) implicits.println(i"Eql witness found for $ltp / $rtp: $res: ${res.tpe}") } @@ -971,7 +970,7 @@ trait Implicits { self: Typer => def inferImplicit(pt: Type, argument: Tree, span: Span)(using Context): SearchResult = trace(s"search implicit ${pt.show}, arg = ${argument.show}: ${argument.tpe.show}", implicits, show = true) { record("inferImplicit") - assert(ctx.phase.allowsImplicitSearch, + assert(currentPhase.allowsImplicitSearch, if (argument.isEmpty) i"missing implicit parameter of type $pt after typer" else i"type error: ${argument.tpe} does not conform to $pt${err.whyNoMatchStr(argument.tpe, pt)}") val result0 = @@ -995,9 +994,9 @@ trait Implicits { self: Typer => val deepPt = pt.deepenProto if (deepPt ne pt) inferImplicit(deepPt, argument, span) else if (migrateTo3 && !ctx.mode.is(Mode.OldOverloadingResolution)) - inferImplicit(pt, argument, span)(using ctx.addMode(Mode.OldOverloadingResolution)) match { + withMode(Mode.OldOverloadingResolution)(inferImplicit(pt, argument, span)) match { case altResult: SearchSuccess => - ctx.migrationWarning( + report.migrationWarning( s"According to new implicit resolution rules, this will be ambiguous:\n${result.reason.explanation}", ctx.source.atSpan(span)) altResult @@ -1052,7 +1051,7 @@ trait Implicits { self: Typer => if !extensionCtx.reporter.hasErrors then extensionCtx.typerState.commit() if !conversionCtx.reporter.hasErrors then - ctx.error(em"ambiguous implicit: $generated is eligible both as an implicit conversion and as an extension method container") + report.error(em"ambiguous implicit: $generated is eligible both as an implicit conversion and as an extension method container") extensionResult else conversionCtx.typerState.commit() @@ -1236,7 +1235,7 @@ trait Implicits { self: Typer => else result def warnAmbiguousNegation(ambi: AmbiguousImplicits) = - ctx.migrationWarning( + report.migrationWarning( i"""Ambiguous implicits ${ambi.alt1.ref.symbol.showLocated} and ${ambi.alt2.ref.symbol.showLocated} |seem to be used to implement a local failure in order to negate an implicit search. |According to the new implicit resolution rules this is no longer possible; @@ -1515,7 +1514,7 @@ final class SearchRoot extends SearchHistory { implicitDictionary.get(tpe) match { case Some((ref, _)) => ref case None => - val lazyImplicit = ctx.newLazyImplicit(tpe) + val lazyImplicit = newLazyImplicit(tpe) val ref = lazyImplicit.termRef implicitDictionary.put(tpe, (ref, tpd.EmptyTree)) ref @@ -1616,9 +1615,9 @@ final class SearchRoot extends SearchHistory { // } val parents = List(defn.ObjectType, defn.SerializableType) - val classSym = ctx.newNormalizedClassSymbol(ctx.owner, LazyImplicitName.fresh().toTypeName, Synthetic | Final, parents, coord = span) + val classSym = newNormalizedClassSymbol(ctx.owner, LazyImplicitName.fresh().toTypeName, Synthetic | Final, parents, coord = span) val vsyms = pruned.map(_._1.symbol) - val nsyms = vsyms.map(vsym => ctx.newSymbol(classSym, vsym.name, EmptyFlags, vsym.info, coord = span).entered) + val nsyms = vsyms.map(vsym => newSymbol(classSym, vsym.name, EmptyFlags, vsym.info, coord = span).entered) val vsymMap = (vsyms zip nsyms).toMap val rhss = pruned.map(_._2) @@ -1634,10 +1633,10 @@ final class SearchRoot extends SearchHistory { case (nsym, nrhs) => ValDef(nsym.asTerm, nrhs.changeNonLocalOwners(nsym)) } - val constr = ctx.newConstructor(classSym, Synthetic, Nil, Nil).entered + val constr = newConstructor(classSym, Synthetic, Nil, Nil).entered val classDef = ClassDef(classSym, DefDef(constr), vdefs) - val valSym = ctx.newLazyImplicit(classSym.typeRef, span) + val valSym = newLazyImplicit(classSym.typeRef, span) val inst = ValDef(valSym, New(classSym.typeRef, Nil)) // Substitute dictionary references into outermost result term. diff --git a/compiler/src/dotty/tools/dotc/typer/Inferencing.scala b/compiler/src/dotty/tools/dotc/typer/Inferencing.scala index 561243a75832..e11c14363c3f 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inferencing.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inferencing.scala @@ -361,7 +361,7 @@ object Inferencing { else { // We do not add the created symbols to GADT constraint immediately, since they may have inter-dependencies. // Instead, we simultaneously add them later on. - val wildCard = ctx.newPatternBoundSymbol(UniqueName.fresh(tvar.origin.paramName), bounds, span, addToGadt = false) + val wildCard = newPatternBoundSymbol(UniqueName.fresh(tvar.origin.paramName), bounds, span, addToGadt = false) tvar.instantiateWith(wildCard.typeRef) patternBound += wildCard } diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index 137946f5d133..ab98c8c5d72d 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -165,8 +165,8 @@ object Inliner { val UnApply(fun, implicits, patterns) = unapp val sym = unapp.symbol - val cls = ctx.newNormalizedClassSymbol(ctx.owner, tpnme.ANON_CLASS, Synthetic | Final, List(defn.ObjectType), coord = sym.coord) - val constr = ctx.newConstructor(cls, Synthetic, Nil, Nil, coord = sym.coord).entered + val cls = newNormalizedClassSymbol(ctx.owner, tpnme.ANON_CLASS, Synthetic | Final, List(defn.ObjectType), coord = sym.coord) + val constr = newConstructor(cls, Synthetic, Nil, Nil, coord = sym.coord).entered val targs = fun match case TypeApply(_, targs) => targs @@ -175,7 +175,7 @@ object Inliner { case info: PolyType => info.instantiate(targs.map(_.tpe)) case info => info - val unappplySym = ctx.newSymbol(cls, sym.name.toTermName, Synthetic | Method, unapplyInfo, coord = sym.coord).entered + val unappplySym = newSymbol(cls, sym.name.toTermName, Synthetic | Method, unapplyInfo, coord = sym.coord).entered val unapply = DefDef(unappplySym, argss => inlineCall(fun.appliedToArgss(argss).withSpan(unapp.span))(using ctx.withOwner(unappplySym)) ) @@ -306,7 +306,7 @@ object Inliner { res ++= typerErrors.map(e => ErrorKind.Typer -> e) res.toList case t => - ctx.error("argument to compileError must be a statically known String", underlyingCodeArg.sourcePos) + report.error("argument to compileError must be a statically known String", underlyingCodeArg.sourcePos) Nil } @@ -395,7 +395,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { private val bindingsBuf = new mutable.ListBuffer[ValOrDefDef] private def newSym(name: Name, flags: FlagSet, info: Type)(using Context): Symbol = - ctx.newSymbol(ctx.owner, name, flags, info, coord = call.span) + newSymbol(ctx.owner, name, flags, info, coord = call.span) /** A binding for the parameter of an inline method. This is a `val` def for * by-value parameters and a `def` def for by-name parameters. `val` defs inherit @@ -443,7 +443,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { computeParamBindings(tp.resultType, Nil, argss) case tp: MethodType => if argss.isEmpty then - ctx.error(i"missing arguments for inline method $inlinedMethod", call.sourcePos) + report.error(i"missing arguments for inline method $inlinedMethod", call.sourcePos) false else tp.paramNames.lazyZip(tp.paramInfos).lazyZip(argss.head).foreach { (name, paramtp, arg) => @@ -625,7 +625,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { if (inlinedMethod == defn.Compiletime_constValue) { val constVal = tryConstValue if (!constVal.isEmpty) return constVal - ctx.error(em"not a constant type: ${callTypeArgs.head}; cannot take constValue", call.sourcePos) + report.error(em"not a constant type: ${callTypeArgs.head}; cannot take constValue", call.sourcePos) } else if (inlinedMethod == defn.Compiletime_constValueOpt) { val constVal = tryConstValue @@ -720,7 +720,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { val callToReport = if (enclosingInlineds.nonEmpty) enclosingInlineds.last else call val ctxToReport = ctx.outersIterator.dropWhile(enclosingInlineds(using _).nonEmpty).next inContext(ctxToReport) { - ctx.error(message, callToReport.sourcePos) + report.error(message, callToReport.sourcePos) } case _ => } @@ -989,7 +989,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { val evidence = evTyper.inferImplicitArg(tpt.tpe, tpt.span)(using evCtx) evidence.tpe match { case fail: Implicits.AmbiguousImplicits => - ctx.error(evTyper.missingArgMsg(evidence, tpt.tpe, ""), tpt.sourcePos) + report.error(evTyper.missingArgMsg(evidence, tpt.tpe, ""), tpt.sourcePos) true // hard error: return true to stop implicit search here case fail: Implicits.SearchFailureType => false @@ -1411,9 +1411,9 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { if dependencies.nonEmpty && !ctx.reporter.errorsReported then for sym <- dependencies do if ctx.compilationUnit.source.file == sym.associatedFile then - ctx.error(em"Cannot call macro $sym defined in the same source file", call.sourcePos) + report.error(em"Cannot call macro $sym defined in the same source file", call.sourcePos) if (suspendable && ctx.settings.XprintSuspension.value) - ctx.echo(i"suspension triggered by macro call to ${sym.showLocated} in ${sym.associatedFile}", call.sourcePos) + report.echo(i"suspension triggered by macro call to ${sym.showLocated} in ${sym.associatedFile}", call.sourcePos) if suspendable then ctx.compilationUnit.suspend() // this throws a SuspendException diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index 97515593db91..f7fc45d66213 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -4,7 +4,7 @@ package typer import core._ import ast._ -import Trees._, StdNames._, Scopes._, Denotations._ +import Trees._, StdNames._, Scopes._, Denotations._, NamerOps._, ContextOps._ import Contexts._, Symbols._, Types._, SymDenotations._, Names._, NameOps._, Flags._ import Decorators.{given _}, Comments.{_, given _} import NameKinds.DefaultGetterName @@ -23,157 +23,10 @@ import Inferencing._ import transform.ValueClasses._ import transform.TypeUtils._ import transform.SymUtils._ -import reporting.messages._ -import reporting.TestingReporter +import reporting._ import config.Feature.sourceVersion import config.SourceVersion._ -trait NamerContextOps { - thisCtx: Context => - - import NamerContextOps._ - - def typer: Typer = this.typeAssigner match { - case typer: Typer => typer - case _ => new Typer - } - - /** Enter symbol into current class, if current class is owner of current context, - * or into current scope, if not. Should always be called instead of scope.enter - * in order to make sure that updates to class members are reflected in - * finger prints. - */ - def enter(sym: Symbol): Symbol = - thisCtx.owner match - case cls: ClassSymbol => cls.enter(sym) - case _ => thisCtx.scope.openForMutations.enter(sym) - sym - - /** The denotation with the given `name` and all `required` flags in current context - */ - def denotNamed(name: Name, required: FlagSet = EmptyFlags): Denotation = - if (owner.isClass) - if (outer.owner == owner) { // inner class scope; check whether we are referring to self - if (scope.size == 1) { - val elem = scope.lastEntry - if (elem.name == name) return elem.sym.denot // return self - } - val pre = owner.thisType - pre.findMember(name, pre, required, EmptyFlags) - } - else // we are in the outermost context belonging to a class; self is invisible here. See inClassContext. - owner.findMember(name, owner.thisType, required, EmptyFlags) - else - scope.denotsNamed(name).filterWithFlags(required, EmptyFlags).toDenot(NoPrefix) - - /** Either the current scope, or, if the current context owner is a class, - * the declarations of the current class. - */ - def effectiveScope: Scope = - if (owner != null && owner.isClass) owner.asClass.unforcedDecls - else scope - - /** The symbol (stored in some typer's symTree) of an enclosing context definition */ - def symOfContextTree(tree: untpd.Tree): Symbol = { - def go(contxt: Context): Symbol = - contxt.typeAssigner match { - case typer: Typer => - tree.getAttachment(typer.SymOfTree) match { - case Some(sym) => sym - case None => - var cx = ctx.outer - while (cx.typeAssigner eq typer) cx = cx.outer - go(cx) - } - case _ => NoSymbol - } - go(this) - } - - /** Context where `sym` is defined, assuming we are in a nested context. */ - def defContext(sym: Symbol): Context = - outersIterator - .dropWhile(_.owner != sym) - .dropWhile(_.owner == sym) - .next() - - /** A fresh local context with given tree and owner. - * Owner might not exist (can happen for self valdefs), in which case - * no owner is set in result context - */ - def localContext(tree: untpd.Tree, owner: Symbol): FreshContext = { - val freshCtx = fresh.setTree(tree) - if (owner.exists) freshCtx.setOwner(owner) else freshCtx - } - - /** A new context for the interior of a class */ - def inClassContext(selfInfo: TypeOrSymbol): Context = { - val localCtx: Context = thisCtx.fresh.setNewScope - selfInfo match { - case sym: Symbol if sym.exists && sym.name != nme.WILDCARD => localCtx.scope.openForMutations.enter(sym) - case _ => - } - localCtx - } - - def packageContext(tree: untpd.PackageDef, pkg: Symbol): Context = - if (pkg.is(Package)) thisCtx.fresh.setOwner(pkg.moduleClass).setTree(tree) - else thisCtx - - /** The given type, unless `sym` is a constructor, in which case the - * type of the constructed instance is returned - */ - def effectiveResultType(sym: Symbol, typeParams: List[Symbol], givenTp: Type): Type = - if (sym.name == nme.CONSTRUCTOR) sym.owner.typeRef.appliedTo(typeParams.map(_.typeRef)) - else givenTp - - /** if isConstructor, make sure it has one non-implicit parameter list */ - def normalizeIfConstructor(termParamss: List[List[Symbol]], isConstructor: Boolean): List[List[Symbol]] = - if (isConstructor && - (termParamss.isEmpty || termParamss.head.nonEmpty && termParamss.head.head.isOneOf(GivenOrImplicit))) - Nil :: termParamss - else - termParamss - - /** The method type corresponding to given parameters and result type */ - def methodType(typeParams: List[Symbol], valueParamss: List[List[Symbol]], resultType: Type, isJava: Boolean = false)(using Context): Type = { - val monotpe = - valueParamss.foldRight(resultType) { (params, resultType) => - val (isContextual, isImplicit, isErased) = - if (params.isEmpty) (false, false, false) - else (params.head.is(Given), params.head.is(Implicit), params.head.is(Erased)) - val make = MethodType.companion(isJava = isJava, isContextual = isContextual, isImplicit = isImplicit, isErased = isErased) - if (isJava) - for (param <- params) - if (param.info.isDirectRef(defn.ObjectClass)) param.info = defn.AnyType - make.fromSymbols(params, resultType) - } - if (typeParams.nonEmpty) PolyType.fromParams(typeParams.asInstanceOf[List[TypeSymbol]], monotpe) - else if (valueParamss.isEmpty) ExprType(monotpe) - else monotpe - } - - /** Add moduleClass or sourceModule functionality to completer - * for a module or module class - */ - def adjustModuleCompleter(completer: LazyType, name: Name): LazyType = { - val scope = this.effectiveScope - if (name.isTermName) - completer withModuleClass (implicit ctx => findModuleBuddy(name.moduleClassName, scope)) - else - completer withSourceModule (implicit ctx => findModuleBuddy(name.sourceModuleName, scope)) - } -} - -object NamerContextOps { - /** Find moduleClass/sourceModule in effective scope */ - private def findModuleBuddy(name: Name, scope: Scope)(using Context) = { - val it = scope.lookupAll(name).filter(_.is(Module)) - if (it.hasNext) it.next() - else NoSymbol.assertingErrorsReported(s"no companion $name in $scope") - } -} - /** This class creates symbols from definitions and imports and gives them * lazy types. * @@ -260,7 +113,7 @@ class Namer { typer: Typer => else { val cls = ctx.owner.enclosingClassNamed(name) if (!cls.exists) - ctx.error(UnknownNamedEnclosingClassOrObject(name), ctx.source.atSpan(span)) + report.error(UnknownNamedEnclosingClassOrObject(name), ctx.source.atSpan(span)) cls } @@ -286,7 +139,7 @@ class Namer { typer: Typer => if conflicting.owner == owner then "" else if conflicting.owner.isPackageObject then i" in ${conflicting.associatedFile}" else i" in ${conflicting.owner}" - ctx.error(i"$name is already defined as $conflicting$where", ctx.source.atSpan(span)) + report.error(i"$name is already defined as $conflicting$where", ctx.source.atSpan(span)) conflictsDetected = true def checkNoConflictIn(owner: Symbol) = @@ -347,13 +200,13 @@ class Namer { typer: Typer => case tree: MemberDef => SymDenotations.canBeLocal(tree.name, flags) case _ => false if !ok then - ctx.error(i"modifier(s) `${flags.flagsString}` incompatible with $kind definition", tree.sourcePos) + report.error(i"modifier(s) `${flags.flagsString}` incompatible with $kind definition", tree.sourcePos) if adapted.is(Private) && canBeLocal then adapted | Local else adapted } /** Add moduleClass/sourceModule to completer if it is for a module val or class */ def adjustIfModule(completer: LazyType, tree: MemberDef) = - if (tree.mods.is(Module)) ctx.adjustModuleCompleter(completer, tree.name) + if (tree.mods.is(Module)) adjustModuleCompleter(completer, tree.name) else completer typr.println(i"creating symbol for $tree in ${ctx.mode}") @@ -393,7 +246,7 @@ class Namer { typer: Typer => val cls = createOrRefine[ClassSymbol](tree, name, flags, ctx.owner, cls => adjustIfModule(new ClassCompleter(cls, tree)(ctx), tree), - ctx.newClassSymbol(ctx.owner, name, _, _, _, tree.nameSpan, ctx.source.file)) + newClassSymbol(ctx.owner, name, _, _, _, tree.nameSpan, ctx.source.file)) cls.completer.asInstanceOf[ClassCompleter].init() cls case tree: MemberDef => @@ -402,7 +255,7 @@ class Namer { typer: Typer => tree match case tree: ValOrDefDef => if tree.isInstanceOf[ValDef] && !flags.is(Param) && name.endsWith("_=") then - ctx.error("Names of vals or vars may not end in `_=`", tree.namePos) + report.error("Names of vals or vars may not end in `_=`", tree.namePos) if tree.unforcedRhs == EmptyTree && !flags.isOneOf(TermParamOrAccessor) && !tree.name.isConstructorName @@ -436,9 +289,9 @@ class Namer { typer: Typer => case _ => Completer(tree)(cctx) val info = adjustIfModule(completer, tree) createOrRefine[Symbol](tree, name, flags, ctx.owner, _ => info, - (fs, _, pwithin) => ctx.newSymbol(ctx.owner, name, fs, info, pwithin, tree.nameSpan)) + (fs, _, pwithin) => newSymbol(ctx.owner, name, fs, info, pwithin, tree.nameSpan)) case tree: Import => - recordSym(ctx.newImportSymbol(ctx.owner, Completer(tree)(ctx), tree.span), tree) + recordSym(newImportSymbol(ctx.owner, Completer(tree)(ctx), tree.span), tree) case _ => NoSymbol } @@ -475,10 +328,10 @@ class Namer { typer: Typer => /** If there's already an existing type, then the package is a dup of this type */ val existingType = pkgOwner.info.decls.lookup(pid.name.toTypeName) if (existingType.exists) { - ctx.error(PkgDuplicateSymbol(existingType), pid.sourcePos) - ctx.newCompletePackageSymbol(pkgOwner, (pid.name ++ "$_error_").toTermName).entered + report.error(PkgDuplicateSymbol(existingType), pid.sourcePos) + newCompletePackageSymbol(pkgOwner, (pid.name ++ "$_error_").toTermName).entered } - else ctx.newCompletePackageSymbol(pkgOwner, pid.name.asTermName).entered + else newCompletePackageSymbol(pkgOwner, pid.name.asTermName).entered } } @@ -638,7 +491,7 @@ class Namer { typer: Typer => body = fromTempl.body ++ modTempl.body)) if (fromTempl.derived.nonEmpty) { if (modTempl.derived.nonEmpty) - ctx.error(em"a class and its companion cannot both have `derives` clauses", mdef.sourcePos) + report.error(em"a class and its companion cannot both have `derives` clauses", mdef.sourcePos) res.putAttachment(desugar.DerivingCompanion, fromTempl.sourcePos.startPos) } res @@ -757,7 +610,7 @@ class Namer { typer: Typer => val className = moduleName.stripModuleClassSuffix.toTypeName val classSym = ctx.effectiveScope.lookup(className) if (!classSym.isDefinedInCurrentRun) { - val absentClassSymbol = ctx.newClassSymbol(ctx.owner, className, EmptyFlags, _ => NoType) + val absentClassSymbol = newClassSymbol(ctx.owner, className, EmptyFlags, _ => NoType) enterSymbol(absentClassSymbol) } } @@ -768,7 +621,7 @@ class Namer { typer: Typer => val moduleName = className.toTermName for (moduleSym <- ctx.effectiveScope.lookupAll(moduleName.encode)) if (moduleSym.is(Module) && !moduleSym.isDefinedInCurrentRun) { - val absentModuleSymbol = ctx.newModuleSymbol(ctx.owner, moduleName, EmptyFlags, EmptyFlags, (_, _) => NoType) + val absentModuleSymbol = newModuleSymbol(ctx.owner, moduleName, EmptyFlags, EmptyFlags, (_, _) => NoType) enterSymbol(absentModuleSymbol) } } @@ -806,7 +659,7 @@ class Namer { typer: Typer => } def missingType(sym: Symbol, modifier: String)(using Context): Unit = { - ctx.error(s"${modifier}type of implicit definition needs to be given explicitly", sym.sourcePos) + report.error(s"${modifier}type of implicit definition needs to be given explicitly", sym.sourcePos) sym.resetFlag(GivenOrImplicit) } @@ -850,10 +703,10 @@ class Namer { typer: Typer => else levels(c.outer) + 1 println(s"!!!completing ${denot.symbol.showLocated} in buried typerState, gap = ${levels(ctx)}") } - if (ctx.runId > creationContext.runId) { - assert(ctx.mode.is(Mode.Interactive), s"completing $denot in wrong run ${ctx.runId}, was created in ${creationContext.runId}") + val creationRunId = currentRunId(using creationContext) + if currentRunId > creationRunId then + assert(ctx.mode.is(Mode.Interactive), s"completing $denot in wrong run ${currentRunId}, was created in $creationRunId") denot.info = UnspecifiedErrorType - } else try completeInCreationContext(denot) @@ -871,7 +724,7 @@ class Namer { typer: Typer => for (annotTree <- original.mods.annotations) { val cls = typedAheadAnnotationClass(annotTree)(using annotCtx) if (cls eq sym) - ctx.error("An annotation class cannot be annotated with iself", annotTree.sourcePos) + report.error("An annotation class cannot be annotated with iself", annotTree.sourcePos) else { val ann = Annotation.deferred(cls)(typedAheadAnnotation(annotTree)(using annotCtx)) sym.addAnnotation(ann) @@ -924,7 +777,7 @@ class Namer { typer: Typer => else if (!parentCls.is(ChildrenQueried)) addChild(parentCls, child) else - ctx.error(em"""children of $parentCls were already queried before $sym was discovered. + report.error(em"""children of $parentCls were already queried before $sym was discovered. |As a remedy, you could move $sym on the same nesting level as $parentCls.""", child.sourcePos) } @@ -1036,7 +889,7 @@ class Namer { typer: Typer => def opaqueToBounds(info: Type): Type = if sym.isOpaqueAlias && tparamSyms.isEmpty && info.typeParams.nonEmpty then - ctx.error(em"opaque type alias must be fully applied", rhs.sourcePos) + report.error(em"opaque type alias must be fully applied", rhs.sourcePos) sym.opaqueToBounds(info, rhs1, tparamSyms) if (isDerived) sym.info = unsafeInfo @@ -1120,7 +973,7 @@ class Namer { typer: Typer => val forwarder = if mbr.isType then val forwarderName = checkNoConflict(alias.toTypeName, isPrivate = false, span) - ctx.newSymbol( + newSymbol( cls, forwarderName, Exported | Final, TypeAlias(path.tpe.select(sym)), @@ -1141,7 +994,7 @@ class Namer { typer: Typer => var mbrFlags = Exported | Method | Final | maybeStable | sym.flags & RetainedExportFlags if sym.isAllOf(ExtensionMethod) then mbrFlags |= Extension val forwarderName = checkNoConflict(alias, isPrivate = false, span) - ctx.newSymbol(cls, forwarderName, mbrFlags, mbrInfo, coord = span) + newSymbol(cls, forwarderName, mbrFlags, mbrInfo, coord = span) } forwarder.info = avoidPrivateLeaks(forwarder) forwarder.addAnnotations(sym.annotations) @@ -1170,7 +1023,7 @@ class Namer { typer: Typer => case Nil => "" case why :: _ => i"\n$path.$name cannot be exported because it $why" } - ctx.error(i"""no eligible member $name at $path$reason""", ctx.source.atSpan(span)) + report.error(i"""no eligible member $name at $path$reason""", ctx.source.atSpan(span)) } } @@ -1220,7 +1073,7 @@ class Namer { typer: Typer => val moduleType = cls.owner.thisType select sourceModule if (self.name == nme.WILDCARD) moduleType else recordSym( - completerCtx.newSymbol(cls, self.name, self.mods.flags, moduleType, coord = self.span), + newSymbol(cls, self.name, self.mods.flags, moduleType, coord = self.span), self) } else createSymbol(self) @@ -1236,7 +1089,7 @@ class Namer { typer: Typer => symbolOfTree(constr).info.stripPoly match // Completes constr symbol as a side effect case mt: MethodType if cls.is(Case) && mt.isParamDependent => // See issue #8073 for background - completerCtx.error( + report.error( i"""Implementation restriction: case classes cannot have dependencies between parameters""", cls.sourcePos) case _ => @@ -1293,16 +1146,16 @@ class Namer { typer: Typer => "\n(Note that inheriting a class of the same name is no longer allowed)" case _ => "" } - completerCtx.error(CyclicInheritance(cls, addendum), parent.sourcePos) + report.error(CyclicInheritance(cls, addendum), parent.sourcePos) defn.ObjectType } else { val pclazz = pt.typeSymbol if pclazz.is(Final) then - completerCtx.error(ExtendFinalClass(cls, pclazz), cls.sourcePos) + report.error(ExtendFinalClass(cls, pclazz), cls.sourcePos) else if pclazz.isEffectivelySealed && pclazz.associatedFile != cls.associatedFile then if pclazz.is(Sealed) then - completerCtx.error(UnableToExtendSealedClass(pclazz), cls.sourcePos) + report.error(UnableToExtendSealedClass(pclazz), cls.sourcePos) else if sourceVersion.isAtLeast(`3.1`) then checkFeature(nme.adhocExtensions, i"Unless $pclazz is declared 'open', its extension in a separate file", @@ -1363,10 +1216,16 @@ class Namer { typer: Typer => } def typedAheadType(tree: Tree, pt: Type = WildcardType)(using Context): tpd.Tree = - typedAhead(tree, typer.typed(_, pt)(using ctx.retractMode(Mode.PatternOrTypeBits).addMode(Mode.Type))) + withoutMode(Mode.PatternOrTypeBits) { + withMode(Mode.Type) { + typedAhead(tree, typer.typed(_, pt)) + } + } def typedAheadExpr(tree: Tree, pt: Type = WildcardType)(using Context): tpd.Tree = - typedAhead(tree, typer.typed(_, pt)(using ctx.retractMode(Mode.PatternOrTypeBits))) + withoutMode(Mode.PatternOrTypeBits) { + typedAhead(tree, typer.typed(_, pt)) + } def typedAheadAnnotation(tree: Tree)(using Context): tpd.Tree = typedAheadExpr(tree, defn.AnnotationClass.typeRef) @@ -1392,7 +1251,7 @@ class Namer { typer: Typer => def moduleValSig(sym: Symbol)(using Context): Type = { val clsName = sym.name.moduleClassName val cls = ctx.denotNamed(clsName).suchThat(_.is(ModuleClass)) - .orElse(ctx.newStubSymbol(ctx.owner, clsName).assertingErrorsReported) + .orElse(newStubSymbol(ctx.owner, clsName).assertingErrorsReported) ctx.owner.thisType.select(clsName, cls) } @@ -1553,7 +1412,7 @@ class Namer { typer: Typer => // instantiation. val hygienicType = TypeOps.avoid(rhsType, paramss.flatten) if (!hygienicType.isValueType || !(hygienicType <:< tpt.tpe)) - ctx.error(i"return type ${tpt.tpe} of lambda cannot be made hygienic;\n" + + report.error(i"return type ${tpt.tpe} of lambda cannot be made hygienic;\n" + i"it is not a supertype of the hygienic type $hygienicType", mdef.sourcePos) //println(i"lifting $rhsType over $paramss -> $hygienicType = ${tpt.tpe}") //println(TypeComparer.explained { implicit ctx => hygienicType <:< tpt.tpe }) @@ -1604,16 +1463,16 @@ class Namer { typer: Typer => vparamss foreach completeParams def typeParams = tparams map symbolOfTree - val termParamss = ctx.normalizeIfConstructor(vparamss.nestedMap(symbolOfTree), isConstructor) + val termParamss = normalizeIfConstructor(vparamss.nestedMap(symbolOfTree), isConstructor) sym.setParamss(typeParams, termParamss) def wrapMethType(restpe: Type): Type = { instantiateDependent(restpe, typeParams, termParamss) - ctx.methodType(tparams map symbolOfTree, termParamss, restpe, isJava = ddef.mods.is(JavaDefined)) + methodType(tparams map symbolOfTree, termParamss, restpe, isJava = ddef.mods.is(JavaDefined)) } if (isConstructor) { // set result type tree to unit, but take the current class as result type of the symbol typedAheadType(ddef.tpt, defn.UnitType) - wrapMethType(ctx.effectiveResultType(sym, typeParams, NoType)) + wrapMethType(effectiveResultType(sym, typeParams, NoType)) } else valOrDefDefSig(ddef, sym, typeParams, termParamss, wrapMethType) } diff --git a/compiler/src/dotty/tools/dotc/typer/Nullables.scala b/compiler/src/dotty/tools/dotc/typer/Nullables.scala index 4775b765c019..ed8f34249563 100644 --- a/compiler/src/dotty/tools/dotc/typer/Nullables.scala +++ b/compiler/src/dotty/tools/dotc/typer/Nullables.scala @@ -261,7 +261,7 @@ object Nullables: /* The nullability info of `tree` */ def notNullInfo(using Context): NotNullInfo = stripInlined(tree).getAttachment(NNInfo) match - case Some(info) if !ctx.erasedTypes => info + case Some(info) if !currentlyAfterErasure => info case _ => NotNullInfo.empty /* The nullability info of `tree`, assuming it is a condition that evaluates to `c` */ @@ -276,7 +276,7 @@ object Nullables: */ def notNullConditional(using Context): NotNullConditional = stripBlock(tree).getAttachment(NNConditional) match - case Some(cond) if !ctx.erasedTypes => cond + case Some(cond) if !currentlyAfterErasure => cond case _ => NotNullConditional.empty /** The current context augmented with nullability information of `tree` */ @@ -297,7 +297,7 @@ object Nullables: * of the left argument, if the application is a boolean `&&` or `||`. */ def nullableInArgContext(using Context): Context = tree match - case Select(x, _) if !ctx.erasedTypes => + case Select(x, _) if !currentlyAfterErasure => if tree.symbol == defn.Boolean_&& then x.nullableContextIf(true) else if tree.symbol == defn.Boolean_|| then x.nullableContextIf(false) else ctx @@ -313,7 +313,7 @@ object Nullables: def computeNullable()(using Context): tree.type = def setConditional(ifTrue: Set[TermRef], ifFalse: Set[TermRef]) = tree.putAttachment(NNConditional, NotNullConditional(ifTrue, ifFalse)) - if !ctx.erasedTypes && analyzedOps.contains(tree.symbol.name.toTermName) then + if !currentlyAfterErasure && analyzedOps.contains(tree.symbol.name.toTermName) then tree match case CompareNull(TrackedRef(ref), testEqual) => if testEqual then setConditional(Set(), Set(ref)) @@ -506,7 +506,7 @@ object Nullables: else val arg2 = retyper.typed(arg1, formal)(using nestedCtx) if nestedCtx.reporter.hasErrors || !(arg2.tpe <:< formal) then - ctx.error(em"""This argument was typed using flow assumptions about mutable variables + report.error(em"""This argument was typed using flow assumptions about mutable variables |but it is passed to a by-name parameter where such flow assumptions are unsound. |Wrapping the argument in `byName(...)` fixes the problem by disabling the flow assumptions. | diff --git a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala index fe934c77b481..83dca707c4a6 100644 --- a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala +++ b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala @@ -12,7 +12,7 @@ import Types._ import Decorators._ import NameKinds._ import StdNames.nme -import Contexts.{Context, ctx} +import Contexts._ import Names.Name import NameKinds.{InlineAccessorName, UniqueInlineName} import NameOps._ @@ -78,7 +78,7 @@ object PrepareInlineable { def preTransform(tree: Tree)(using Context): Tree = tree match { case tree: RefTree if needsAccessor(tree.symbol) => if (tree.symbol.isConstructor) { - ctx.error("Implementation restriction: cannot use private constructors in inlineinline methods", tree.sourcePos) + report.error("Implementation restriction: cannot use private constructors in inlineinline methods", tree.sourcePos) tree // TODO: create a proper accessor for the private constructor } else useAccessor(tree) @@ -234,7 +234,7 @@ object PrepareInlineable { case Some(ann: ConcreteBodyAnnotation) => case Some(ann: LazyBodyAnnotation) if ann.isEvaluated || ann.isEvaluating => case _ => - if (!ctx.isAfterTyper) { + if (!currentlyAfterTyper) { val inlineCtx = ctx inlined.updateAnnotation(LazyBodyAnnotation { given ctx as Context = inlineCtx @@ -251,16 +251,16 @@ object PrepareInlineable { def checkInlineMethod(inlined: Symbol, body: Tree)(using Context): body.type = { if (inlined.owner.isClass && inlined.owner.seesOpaques) - ctx.error(em"Implementation restriction: No inline methods allowed where opaque type aliases are in scope", inlined.sourcePos) + report.error(em"Implementation restriction: No inline methods allowed where opaque type aliases are in scope", inlined.sourcePos) if Inliner.inInlineMethod(using ctx.outer) then - ctx.error(ex"Implementation restriction: nested inline methods are not supported", inlined.sourcePos) + report.error(ex"Implementation restriction: nested inline methods are not supported", inlined.sourcePos) - if (inlined.is(Macro) && !ctx.isAfterTyper) { + if (inlined.is(Macro) && !currentlyAfterTyper) { def checkMacro(tree: Tree): Unit = tree match { case Spliced(code) => if (code.symbol.flags.is(Inline)) - ctx.error("Macro cannot be implemented with an `inline` method", code.sourcePos) + report.error("Macro cannot be implemented with an `inline` method", code.sourcePos) Splicer.checkValidMacroBody(code) new PCPCheckAndHeal(freshStagingContext).transform(body) // Ignore output, only check PCP case Block(List(stat), Literal(Constants.Constant(()))) => checkMacro(stat) @@ -268,13 +268,13 @@ object PrepareInlineable { case Typed(expr, _) => checkMacro(expr) case Block(DefDef(nme.ANON_FUN, _, _, _, _) :: Nil, Closure(_, fn, _)) if fn.symbol.info.isImplicitMethod => // TODO Support this pattern - ctx.error( + report.error( """Macros using a return type of the form `foo(): X ?=> Y` are not yet supported. | |Place the implicit as an argument (`foo()(using X): Y`) to overcome this limitation. |""".stripMargin, tree.sourcePos) case _ => - ctx.error( + report.error( """Malformed macro. | |Expected the splice ${...} to be at the top of the RHS: diff --git a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala index c0ba833e585e..2cb455ad8e2d 100644 --- a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala +++ b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala @@ -67,7 +67,7 @@ object ProtoTypes { * fits the given expected result type. */ def constrainResult(mt: Type, pt: Type)(using Context): Boolean = - inContext(ctx.addMode(Mode.ConstrainResult)) { + withMode(Mode.ConstrainResult) { val savedConstraint = ctx.typerState.constraint val res = pt.widenExpr match { case pt: FunProto => diff --git a/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala b/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala index b6ec34215410..6839b385d242 100644 --- a/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala +++ b/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala @@ -1,4 +1,5 @@ -package dotty.tools.dotc.typer +package dotty.tools.dotc +package typer import dotty.tools.dotc.ast._ import dotty.tools.dotc.ast.Trees._ @@ -41,17 +42,17 @@ trait QuotesAndSplices { ctx.compilationUnit.needsStaging = true tree.quoted match { case untpd.Splice(innerExpr) if tree.isTerm => - ctx.warning("Canceled splice directly inside a quote. '{ ${ XYZ } } is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled splice directly inside a quote. '{ ${ XYZ } } is equivalent to XYZ.", tree.sourcePos) case untpd.TypSplice(innerType) if tree.isType => - ctx.warning("Canceled splice directly inside a quote. '[ ${ XYZ } ] is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled splice directly inside a quote. '[ ${ XYZ } ] is equivalent to XYZ.", tree.sourcePos) case _ => } val qctx = inferImplicitArg(defn.QuoteContextClass.typeRef, tree.span) if qctx.tpe.isInstanceOf[SearchFailureType] then - ctx.error(missingArgMsg(qctx, defn.QuoteContextClass.typeRef, ""), ctx.source.atSpan(tree.span)) + report.error(missingArgMsg(qctx, defn.QuoteContextClass.typeRef, ""), ctx.source.atSpan(tree.span)) else if !qctx.tpe.isStable then - ctx.error(em"Quotes require stable QuoteContext, but found non stable $qctx", qctx.sourcePos) + report.error(em"Quotes require stable QuoteContext, but found non stable $qctx", qctx.sourcePos) val tree1 = if ctx.mode.is(Mode.Pattern) then @@ -70,7 +71,7 @@ trait QuotesAndSplices { checkSpliceOutsideQuote(tree) tree.expr match { case untpd.Quote(innerExpr) if innerExpr.isTerm => - ctx.warning("Canceled quote directly inside a splice. ${ '{ XYZ } } is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled quote directly inside a splice. ${ '{ XYZ } } is equivalent to XYZ.", tree.sourcePos) case _ => } if (ctx.mode.is(Mode.QuotedPattern)) @@ -84,7 +85,7 @@ trait QuotesAndSplices { ref(defn.InternalQuoted_exprSplice).appliedToType(argType).appliedTo(pat) } else { - ctx.error(i"Type must be fully defined.\nConsider annotating the splice using a type ascription:\n ($tree: XYZ).", tree.expr.sourcePos) + report.error(i"Type must be fully defined.\nConsider annotating the splice using a type ascription:\n ($tree: XYZ).", tree.expr.sourcePos) tree.withType(UnspecifiedErrorType) } else { @@ -120,7 +121,7 @@ trait QuotesAndSplices { assert(ctx.mode.is(Mode.QuotedPattern)) val untpd.Apply(splice: untpd.Splice, args) = tree if !isFullyDefined(pt, ForceDegree.flipBottom) then - ctx.error(i"Type must be fully defined.", splice.sourcePos) + report.error(i"Type must be fully defined.", splice.sourcePos) tree.withType(UnspecifiedErrorType) else if splice.isInBraces then // ${x}(...) match an application val typedArgs = args.map(arg => typedExpr(arg)) @@ -132,11 +133,11 @@ trait QuotesAndSplices { case arg: untpd.Ident => typedExpr(arg) case arg => - ctx.error("Open patttern exprected an identifier", arg.sourcePos) + report.error("Open patttern exprected an identifier", arg.sourcePos) EmptyTree } if args.isEmpty then - ctx.error("Missing arguments for open pattern", tree.sourcePos) + report.error("Missing arguments for open pattern", tree.sourcePos) val argTypes = typedArgs.map(_.tpe.widenTermRefExpr) val typedPat = typedSplice(splice, defn.FunctionOf(argTypes, pt)) ref(defn.InternalQuotedMatcher_patternHigherOrderHole).appliedToType(pt).appliedTo(typedPat, SeqLiteral(typedArgs, TypeTree(defn.AnyType))) @@ -149,7 +150,7 @@ trait QuotesAndSplices { checkSpliceOutsideQuote(tree) tree.expr match { case untpd.Quote(innerType) if innerType.isType => - ctx.warning("Canceled quote directly inside a splice. ${ '[ XYZ ] } is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled quote directly inside a splice. ${ '[ XYZ ] } is equivalent to XYZ.", tree.sourcePos) case _ => } @@ -159,14 +160,14 @@ trait QuotesAndSplices { val name = tree.expr match { case Ident(name) => ("$" + name).toTypeName case expr => - ctx.error("expected a name binding", expr.sourcePos) + report.error("expected a name binding", expr.sourcePos) "$error".toTypeName } val typeSymInfo = pt match case pt: TypeBounds => pt case _ => TypeBounds.empty - val typeSym = ctx.newSymbol(spliceOwner(ctx), name, EmptyFlags, typeSymInfo, NoSymbol, tree.expr.span) + val typeSym = newSymbol(spliceOwner(ctx), name, EmptyFlags, typeSymInfo, NoSymbol, tree.expr.span) typeSym.addAnnotation(Annotation(New(ref(defn.InternalQuotedMatcher_patternTypeAnnot.typeRef)).withSpan(tree.expr.span))) val pat = typedPattern(tree.expr, defn.QuotedTypeClass.typeRef.appliedTo(typeSym.typeRef))( using spliceContext.retractMode(Mode.QuotedPattern).withOwner(spliceOwner(ctx))) @@ -177,9 +178,9 @@ trait QuotesAndSplices { private def checkSpliceOutsideQuote(tree: untpd.Tree)(using Context): Unit = if (level == 0 && !ctx.owner.ownersIterator.exists(_.is(Inline))) - ctx.error("Splice ${...} outside quotes '{...} or inline method", tree.sourcePos) + report.error("Splice ${...} outside quotes '{...} or inline method", tree.sourcePos) else if (level < 0) - ctx.error( + report.error( s"""Splice $${...} at level $level. | |Inline method may contain a splice at level 0 but the contents of this splice cannot have a splice. @@ -212,7 +213,7 @@ trait QuotesAndSplices { def getBinding(sym: Symbol): Bind = typeBindings.getOrElseUpdate(sym, { val bindingBounds = sym.info - val bsym = ctx.newPatternBoundSymbol(sym.name.toTypeName, bindingBounds, quoted.span) + val bsym = newPatternBoundSymbol(sym.name.toTypeName, bindingBounds, quoted.span) Bind(bsym, untpd.Ident(nme.WILDCARD).withType(bindingBounds)).withSpan(quoted.span) }) @@ -266,7 +267,7 @@ trait QuotesAndSplices { transformTypeBindingTypeDef(tdef, typePatBuf) else if tdef.symbol.isClass then val kind = if tdef.symbol.is(Module) then "objects" else "classes" - ctx.error("Implementation restriction: cannot match " + kind, tree.sourcePos) + report.error("Implementation restriction: cannot match " + kind, tree.sourcePos) EmptyTree else super.transform(tree) @@ -280,16 +281,16 @@ trait QuotesAndSplices { cpy.AppliedTypeTree(tree)(transform(tpt), args1) case tree: NamedDefTree => if tree.name.isTermName && !tree.nameSpan.isSynthetic && tree.name.startsWith("$") then - ctx.error("Names cannot start with $ quote pattern ", tree.namePos) + report.error("Names cannot start with $ quote pattern ", tree.namePos) super.transform(tree) case _: Match => - ctx.error("Implementation restriction: cannot match `match` expressions", tree.sourcePos) + report.error("Implementation restriction: cannot match `match` expressions", tree.sourcePos) EmptyTree case _: Try => - ctx.error("Implementation restriction: cannot match `try` expressions", tree.sourcePos) + report.error("Implementation restriction: cannot match `try` expressions", tree.sourcePos) EmptyTree case _: Return => - ctx.error("Implementation restriction: cannot match `return` statements", tree.sourcePos) + report.error("Implementation restriction: cannot match `return` statements", tree.sourcePos) EmptyTree case _ => super.transform(tree) @@ -301,7 +302,7 @@ trait QuotesAndSplices { val bindingType = getBinding(tdef.symbol).symbol.typeRef val bindingTypeTpe = AppliedType(defn.QuotedTypeClass.typeRef, bindingType :: Nil) val bindName = tdef.name.toString.stripPrefix("$").toTermName - val sym = ctx0.newPatternBoundSymbol(bindName, bindingTypeTpe, tdef.span, flags = ImplicitTerm) + val sym = newPatternBoundSymbol(bindName, bindingTypeTpe, tdef.span, flags = ImplicitTerm)(using ctx0) buff += Bind(sym, untpd.Ident(nme.WILDCARD).withType(bindingTypeTpe)).withSpan(tdef.span) super.transform(tdef) } @@ -380,9 +381,9 @@ trait QuotesAndSplices { */ private def typedQuotePattern(tree: untpd.Quote, pt: Type, qctx: Tree)(using Context): Tree = { if tree.quoted.isTerm && !pt.derivesFrom(defn.QuotedExprClass) then - ctx.error("Quote pattern can only match scrutinees of type scala.quoted.Expr", tree.sourcePos) + report.error("Quote pattern can only match scrutinees of type scala.quoted.Expr", tree.sourcePos) else if tree.quoted.isType && !pt.derivesFrom(defn.QuotedTypeClass) then - ctx.error("Quote pattern can only match scrutinees of type scala.quoted.Type", tree.sourcePos) + report.error("Quote pattern can only match scrutinees of type scala.quoted.Type", tree.sourcePos) val quoted = tree.quoted val exprPt = pt.baseType(if quoted.isType then defn.QuotedTypeClass else defn.QuotedExprClass) @@ -418,7 +419,7 @@ trait QuotesAndSplices { case tree: Bind => val sym = tree.symbol val newInfo = replaceBindings(sym.info) - val newSym = ctx.newSymbol(sym.owner, sym.name, sym.flags, newInfo, sym.privateWithin, sym.coord) + val newSym = newSymbol(sym.owner, sym.name, sym.flags, newInfo, sym.privateWithin, sym.coord) bindMap += sym -> newSym Bind(newSym, transform(tree.body)).withSpan(sym.span) case _ => diff --git a/compiler/src/dotty/tools/dotc/typer/ReTyper.scala b/compiler/src/dotty/tools/dotc/typer/ReTyper.scala index e055d70c4965..20cb18bad09a 100644 --- a/compiler/src/dotty/tools/dotc/typer/ReTyper.scala +++ b/compiler/src/dotty/tools/dotc/typer/ReTyper.scala @@ -38,7 +38,7 @@ class ReTyper extends Typer with ReChecking { override def typedSelect(tree: untpd.Select, pt: Type)(using Context): Tree = { assertTyped(tree) - val qual1 = typed(tree.qualifier, AnySelectionProto)(using ctx.retractMode(Mode.Pattern)) + val qual1 = withoutMode(Mode.Pattern)(typed(tree.qualifier, AnySelectionProto)) untpd.cpy.Select(tree)(qual1, tree.name).withType(tree.typeOpt) } @@ -78,11 +78,9 @@ class ReTyper extends Typer with ReChecking { } override def typedUnApply(tree: untpd.UnApply, selType: Type)(using Context): UnApply = { - val fun1 = { + val fun1 = // retract PatternOrTypeBits like in typedExpr - val ctx1 = ctx.retractMode(Mode.PatternOrTypeBits) - typedUnadapted(tree.fun, AnyFunctionProto)(using ctx1) - } + withoutMode(Mode.PatternOrTypeBits)(typedUnadapted(tree.fun, AnyFunctionProto)) val implicits1 = tree.implicits.map(typedExpr(_)) val patterns1 = tree.patterns.mapconserve(pat => typed(pat, pat.tpe)) untpd.cpy.UnApply(tree)(fun1, implicits1, patterns1).withType(tree.tpe) @@ -124,7 +122,7 @@ class ReTyper extends Typer with ReChecking { try super.typedUnadapted(tree, pt, locked) catch { case NonFatal(ex) => - if (ctx.isAfterTyper) + if (currentlyAfterTyper) println(i"exception while typing $tree of class ${tree.getClass} # ${tree.uniqueId}") throw ex } diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index 7e28e84a2986..bc7aef564173 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -18,10 +18,10 @@ import config.{ScalaVersion, NoScalaVersion} import Decorators._ import typer.ErrorReporting._ import config.Feature.warnOnMigration +import reporting._ object RefChecks { import tpd.{Tree, MemberDef} - import reporting.messages._ val name: String = "refchecks" @@ -54,7 +54,7 @@ object RefChecks { val owners = haveDefaults map (_.owner) // constructors of different classes are allowed to have defaults if (haveDefaults.exists(x => !x.isConstructor) || owners.distinct.size < haveDefaults.size) - ctx.error( + report.error( "in " + clazz + ", multiple overloaded alternatives of " + haveDefaults.head + " define default arguments" + ( @@ -68,7 +68,7 @@ object RefChecks { // Check for doomed attempt to overload applyDynamic if (clazz derivesFrom defn.DynamicClass) for ((_, m1 :: m2 :: _) <- (clazz.info member nme.applyDynamic).alternatives groupBy (_.symbol.typeParams.length)) - ctx.error("implementation restriction: applyDynamic cannot be overloaded except by methods with different numbers of type parameters, e.g. applyDynamic[T1](method: String)(arg: T1) and applyDynamic[T1, T2](method: String)(arg1: T1, arg2: T2)", + report.error("implementation restriction: applyDynamic cannot be overloaded except by methods with different numbers of type parameters, e.g. applyDynamic[T1](method: String)(arg: T1) and applyDynamic[T1, T2](method: String)(arg1: T1, arg2: T2)", m1.symbol.sourcePos) } @@ -96,7 +96,7 @@ object RefChecks { def checkSelfConforms(other: ClassSymbol, category: String, relation: String) = { val otherSelf = other.declaredSelfTypeAsSeenFrom(cls.thisType) if otherSelf.exists && !(cinfo.selfType <:< otherSelf) then - ctx.error(DoesNotConformToSelfType(category, cinfo.selfType, cls, otherSelf, relation, other.classSymbol), + report.error(DoesNotConformToSelfType(category, cinfo.selfType, cls, otherSelf, relation, other.classSymbol), cls.sourcePos) } for (parent <- cinfo.classParents) @@ -116,7 +116,7 @@ object RefChecks { case TypeRef(ref: TermRef, _) => val paramRefs = ref.namedPartsWith(ntp => ntp.symbol.enclosingClass == cls) if (paramRefs.nonEmpty) - ctx.error(TraitParameterUsedAsParentPrefix(cls), parent.sourcePos) + report.error(TraitParameterUsedAsParentPrefix(cls), parent.sourcePos) case _ => } @@ -131,7 +131,7 @@ object RefChecks { val others = cls.owner.linkedClass.info.decls.filter(clashes) others.foreach { other => - ctx.error(ClassAndCompanionNameClash(cls, other), cls.sourcePos) + report.error(ClassAndCompanionNameClash(cls, other), cls.sourcePos) } } @@ -181,7 +181,7 @@ object RefChecks { mixinOverrideErrors.toList match { case Nil => case List(MixinOverrideError(_, msg)) => - ctx.error(msg, clazz.sourcePos) + report.error(msg, clazz.sourcePos) case MixinOverrideError(member, msg) :: others => val others1 = others.map(_.member).filter(_.name != member.name).distinct def othersMsg = { @@ -191,7 +191,7 @@ object RefChecks { if (others1.isEmpty) "" else i";\nother members with override errors are:: $others1%, %" } - ctx.error(msg + othersMsg, clazz.sourcePos) + report.error(msg + othersMsg, clazz.sourcePos) } def infoString(sym: Symbol) = infoString0(sym, sym.owner != clazz) @@ -218,7 +218,7 @@ object RefChecks { else self.memberInfo(member) def otherTp(self: Type) = self.memberInfo(other) - ctx.debuglog("Checking validity of %s overriding %s".format(member.showLocated, other.showLocated)) + report.debuglog("Checking validity of %s overriding %s".format(member.showLocated, other.showLocated)) def noErrorType = !memberTp(self).isErroneous && !otherTp(self).isErroneous @@ -242,7 +242,7 @@ object RefChecks { if (!(hasErrors && member.is(Synthetic) && member.is(Module))) { // suppress errors relating toi synthetic companion objects if other override // errors (e.g. relating to the companion class) have already been reported. - if (member.owner == clazz) ctx.error(fullmsg, member.sourcePos) + if (member.owner == clazz) report.error(fullmsg, member.sourcePos) else mixinOverrideErrors += new MixinOverrideError(member, fullmsg) hasErrors = true } @@ -257,8 +257,8 @@ object RefChecks { sym.is(Module)) // synthetic companion def overrideAccessError() = { - ctx.log(i"member: ${member.showLocated} ${member.flagsString}") // DEBUG - ctx.log(i"other: ${other.showLocated} ${other.flagsString}") // DEBUG + report.log(i"member: ${member.showLocated} ${member.flagsString}") // DEBUG + report.log(i"other: ${other.showLocated} ${other.flagsString}") // DEBUG val otherAccess = (other.flags & AccessFlags).flagsString overrideError("has weaker access privileges; it should be " + (if (otherAccess == "") "public" else "at least " + otherAccess)) @@ -611,8 +611,8 @@ object RefChecks { && !ignoreDeferred(decl) then val impl1 = clazz.thisType.nonPrivateMember(decl.name) // DEBUG - ctx.log(i"${impl1}: ${impl1.info}") // DEBUG - ctx.log(i"${clazz.thisType.memberInfo(decl)}") // DEBUG + report.log(i"${impl1}: ${impl1.info}") // DEBUG + report.log(i"${clazz.thisType.memberInfo(decl)}") // DEBUG abstractClassError(false, "there is a deferred declaration of " + infoString(decl) + " which is not implemented in a subclass" + err.abstractVarMessage(decl)) } @@ -658,7 +658,7 @@ object RefChecks { val mbr = mbrd.symbol val mbrType = mbr.info.asSeenFrom(self, mbr.owner) if (!mbrType.overrides(mbrd.info, matchLoosely = true)) - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( em"""${mbr.showLocated} is not a legal implementation of `$name` in $clazz | its type $mbrType | does not conform to ${mbrd.info}""", @@ -675,13 +675,13 @@ object RefChecks { for (baseCls <- caseCls.info.baseClasses.tail) if (baseCls.typeParams.exists(_.paramVarianceSign != 0)) for (problem <- variantInheritanceProblems(baseCls, caseCls, "non-variant", "case ")) - ctx.errorOrMigrationWarning(problem(), clazz.sourcePos) + report.errorOrMigrationWarning(problem(), clazz.sourcePos) checkNoAbstractMembers() if (abstractErrors.isEmpty) checkNoAbstractDecls(clazz) if (abstractErrors.nonEmpty) - ctx.error(abstractErrorMessage, clazz.sourcePos) + report.error(abstractErrorMessage, clazz.sourcePos) checkMemberTypesOK() checkCaseClassInheritanceInvariant() @@ -695,7 +695,7 @@ object RefChecks { // override a concrete method in Object. The jvm, however, does not. val overridden = decl.matchingDecl(defn.ObjectClass, defn.ObjectType) if (overridden.is(Final)) - ctx.error(TraitRedefinedFinalMethodFromAnyRef(overridden), decl.sourcePos) + report.error(TraitRedefinedFinalMethodFromAnyRef(overridden), decl.sourcePos) } if (!clazz.is(Trait)) { @@ -717,7 +717,7 @@ object RefChecks { if cls.paramAccessors.nonEmpty && !mixins.contains(cls) problem <- variantInheritanceProblems(cls, clazz.asClass.superClass, "parameterized", "super") } - ctx.error(problem(), clazz.sourcePos) + report.error(problem(), clazz.sourcePos) } checkParameterizedTraitsOK() @@ -795,7 +795,7 @@ object RefChecks { val nonMatching = clazz.info.member(member.name).altsWith(alt => alt.owner != clazz) nonMatching match { case Nil => - ctx.error(OverridesNothing(member), member.sourcePos) + report.error(OverridesNothing(member), member.sourcePos) case ms => // getClass in primitive value classes is defined in the standard library as: // override def getClass(): Class[Int] = ??? @@ -804,7 +804,7 @@ object RefChecks { // the standard library, we need to drop the override flag without reporting // an error. if (!(member.name == nme.getClass_ && clazz.isPrimitiveValueClass)) - ctx.error(OverridesNothingButNameExists(member, ms), member.sourcePos) + report.error(OverridesNothingButNameExists(member, ms), member.sourcePos) } member.resetFlag(Override) member.resetFlag(AbsOverride) @@ -834,7 +834,7 @@ object RefChecks { do val msg = annot.argumentConstant(0).map(": " + _.stringValue).getOrElse("") val since = annot.argumentConstant(1).map(" since " + _.stringValue).getOrElse("") - ctx.deprecationWarning(s"${sym.showLocated} is deprecated${since}${msg}", pos) + report.deprecationWarning(s"${sym.showLocated} is deprecated${since}${msg}", pos) /** If @migration is present (indicating that the symbol has changed semantics between versions), * emit a warning. @@ -845,9 +845,9 @@ object RefChecks { migrationVersion match case Success(symVersion) if xMigrationValue < symVersion => val msg = annot.argumentConstant(0).get.stringValue - ctx.warning(SymbolChangedSemanticsInVersion(sym, symVersion, msg), pos) + report.warning(SymbolChangedSemanticsInVersion(sym, symVersion, msg), pos) case Failure(ex) => - ctx.warning(SymbolHasUnparsableVersionNumber(sym, ex.getMessage), pos) + report.warning(SymbolHasUnparsableVersionNumber(sym, ex.getMessage), pos) case _ => /** Check that a deprecated val or def does not override a @@ -861,7 +861,7 @@ object RefChecks { symbol.allOverriddenSymbols.filter(sym => !sym.isDeprecated && !sym.is(Deferred)) if (!concrOvers.isEmpty) - ctx.deprecationWarning( + report.deprecationWarning( symbol.toString + " overrides concrete, non-deprecated symbol(s):" + concrOvers.map(_.name).mkString(" ", ", ", ""), tree.sourcePos) } @@ -888,7 +888,7 @@ object RefChecks { for bc <- cls.baseClasses.tail do val other = sym.matchingDecl(bc, cls.thisType) if other.exists then - ctx.error(i"private $sym cannot override ${other.showLocated}", sym.sourcePos) + report.error(i"private $sym cannot override ${other.showLocated}", sym.sourcePos) end checkNoPrivateOverrides type LevelAndIndex = immutable.Map[Symbol, (LevelInfo, Int)] @@ -962,8 +962,6 @@ import RefChecks._ class RefChecks extends MiniPhase { thisPhase => import tpd._ - import reporting.messages.ForwardReferenceExtendsOverDefinition - import dotty.tools.dotc.reporting.messages.UnboundPlaceholderParameter override def phaseName: String = RefChecks.name @@ -987,13 +985,13 @@ class RefChecks extends MiniPhase { thisPhase => val sym = tree.symbol if (sym.exists && sym.owner.isTerm) { tree.rhs match { - case Ident(nme.WILDCARD) => ctx.error(UnboundPlaceholderParameter(), sym.sourcePos) + case Ident(nme.WILDCARD) => report.error(UnboundPlaceholderParameter(), sym.sourcePos) case _ => } if (!sym.is(Lazy)) currentLevel.levelAndIndex.get(sym) match { case Some((level, symIdx)) if symIdx <= level.maxIndex => - ctx.error(ForwardReferenceExtendsOverDefinition(sym, level.refSym), + report.error(ForwardReferenceExtendsOverDefinition(sym, level.refSym), ctx.source.atSpan(level.refSpan)) case _ => } @@ -1018,7 +1016,7 @@ class RefChecks extends MiniPhase { thisPhase => } catch { case ex: TypeError => - ctx.error(ex, tree.sourcePos) + report.error(ex, tree.sourcePos) tree } @@ -1039,8 +1037,8 @@ class RefChecks extends MiniPhase { thisPhase => val level = currentLevel.asInstanceOf[LevelInfo] if (level.maxIndex > 0) { // An implementation restriction to avoid VerifyErrors and lazyvals mishaps; see SI-4717 - ctx.debuglog("refsym = " + level.refSym) - ctx.error("forward reference not allowed from self constructor invocation", + report.debuglog("refsym = " + level.refSym) + report.error("forward reference not allowed from self constructor invocation", ctx.source.atSpan(level.refSpan)) } } diff --git a/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala b/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala index 1ceb8d1a34cf..cf434da334e2 100644 --- a/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala @@ -57,7 +57,7 @@ class Synthesizer(typer: Typer)(using @constructorOnly c: Context): ctx.compilationUnit.needsStaging = true // We will need to run ReifyQuotes val qctx = ctx.typer.inferImplicitArg(defn.QuoteContextClass.typeRef, span) qctx.tpe match - case tpe: Implicits.SearchFailureType => ctx.error(tpe.msg, ctx.source.atSpan(span)) + case tpe: Implicits.SearchFailureType => report.error(tpe.msg, ctx.source.atSpan(span)) case _ => ref(defn.InternalQuoted_typeQuote).appliedToType(t).select(nme.apply).appliedTo(qctx) formal.argInfos match @@ -129,7 +129,7 @@ class Synthesizer(typer: Typer)(using @constructorOnly c: Context): */ def validEqAnyArgs(tp1: Type, tp2: Type)(using Context) = typer.assumedCanEqual(tp1, tp2) - || inContext(ctx.addMode(Mode.StrictEquality)) { + || withMode(Mode.StrictEquality) { !hasEq(tp1) && !hasEq(tp2) } diff --git a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala index be6a43de3976..9bf13555f4d4 100644 --- a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala +++ b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala @@ -13,7 +13,7 @@ import ast.Trees._ import NameOps._ import ProtoTypes._ import collection.mutable -import reporting.messages._ +import reporting._ import Checking.{checkNoPrivateLeaks, checkNoWildcard} trait TypeAssigner { @@ -32,7 +32,7 @@ trait TypeAssigner { case Some(c) if packageOK || !c.is(Package) => c case _ => - ctx.error( + report.error( if (qual.isEmpty) tree.show + " can be used only in a class, object, or template" else qual.show + " is not an enclosing class", tree.sourcePos) NoSymbol @@ -190,7 +190,7 @@ trait TypeAssigner { qualType match { case JavaArrayType(elemtp) => elemtp case _ => - ctx.error("Expected Array but was " + qualType.show, tree.sourcePos) + report.error("Expected Array but was " + qualType.show, tree.sourcePos) defn.NothingType } } @@ -228,7 +228,7 @@ trait TypeAssigner { value.tag match { case UnitTag => defn.UnitType case NullTag => defn.NullType - case _ => if (ctx.erasedTypes) value.tpe else ConstantType(value) + case _ => if (currentlyAfterErasure) value.tpe else ConstantType(value) } } @@ -256,7 +256,7 @@ trait TypeAssigner { val owntype = if (mixinClass.exists) mixinClass.appliedRef else if (!mix.isEmpty) findMixinSuper(cls.info) - else if (ctx.erasedTypes) cls.info.firstParent.typeConstructor + else if (currentlyAfterErasure) cls.info.firstParent.typeConstructor else { val ps = cls.classInfo.parents if (ps.isEmpty) defn.AnyType else ps.reduceLeft((x: Type, y: Type) => x & y) @@ -289,11 +289,11 @@ trait TypeAssigner { def assignType(tree: untpd.Apply, fn: Tree, args: List[Tree])(using Context): Apply = { val ownType = fn.tpe.widen match { case fntpe: MethodType => - if (sameLength(fntpe.paramInfos, args) || ctx.phase.prev.relaxedTyping) + if (sameLength(fntpe.paramInfos, args) || currentPhase.prev.relaxedTyping) if (fntpe.isResultDependent) safeSubstParams(fntpe.resultType, fntpe.paramRefs, args.tpes) else fntpe.resultType else - errorType(i"wrong number of arguments at ${ctx.phase.prev} for $fntpe: ${fn.tpe}, expected: ${fntpe.paramInfos.length}, found: ${args.length}", tree.sourcePos) + errorType(i"wrong number of arguments at ${currentPhase.prev} for $fntpe: ${fn.tpe}, expected: ${fntpe.paramInfos.length}, found: ${args.length}", tree.sourcePos) case t => if (ctx.settings.Ydebug.value) new FatalError("").printStackTrace() errorType(err.takesNoParamsStr(fn, ""), tree.sourcePos) @@ -314,9 +314,9 @@ trait TypeAssigner { val namedArgMap = new mutable.HashMap[Name, Type] for (NamedArg(name, arg) <- args) if (namedArgMap.contains(name)) - ctx.error(DuplicateNamedTypeParameter(name), arg.sourcePos) + report.error(DuplicateNamedTypeParameter(name), arg.sourcePos) else if (!paramNames.contains(name)) - ctx.error(UndefinedNamedTypeParameter(name, paramNames), arg.sourcePos) + report.error(UndefinedNamedTypeParameter(name, paramNames), arg.sourcePos) else namedArgMap(name) = arg.tpe @@ -431,7 +431,7 @@ trait TypeAssigner { def assignType(tree: untpd.SeqLiteral, elems: List[Tree], elemtpt: Tree)(using Context): SeqLiteral = { val ownType = tree match { case tree: untpd.JavaSeqLiteral => defn.ArrayOf(elemtpt.tpe) - case _ => if (ctx.erasedTypes) defn.SeqType else defn.SeqType.appliedTo(elemtpt.tpe) + case _ => if (currentlyAfterErasure) defn.SeqType else defn.SeqType.appliedTo(elemtpt.tpe) } tree.withType(ownType) } diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 6334ae23208a..0b7c794e2e30 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -18,6 +18,8 @@ import Annotations._ import Names._ import NameOps._ import NameKinds._ +import NamerOps._ +import ContextOps._ import Flags._ import Decorators.{given _} import ErrorReporting._ @@ -40,7 +42,7 @@ import rewrites.Rewrites.patch import NavigateAST._ import transform.SymUtils._ import transform.TypeUtils._ -import reporting.trace +import reporting._ import Nullables.{NotNullInfo, given _} import NullOpsDecorator._ @@ -100,8 +102,6 @@ class Typer extends Namer import Typer._ import tpd.{cpy => _, _} import untpd.cpy - import reporting.Message - import reporting.messages._ /** A temporary data item valid for a single typed ident: * The set of all root import symbols that have been @@ -130,6 +130,7 @@ class Typer extends Namer def findRef(name: Name, pt: Type, required: FlagSet, posd: Positioned)(using Context): Type = { val refctx = ctx val noImports = ctx.mode.is(Mode.InPackageClauseName) + def fail(msg: Message) = report.error(msg, posd.sourcePos) /** A symbol qualifies if it really exists and is not a package class. * In addition, if we are in a constructor of a pattern, we ignore all definitions @@ -176,7 +177,7 @@ class Typer extends Namer found else if !scala2pkg && !previous.isError && !found.isError then - refctx.error(AmbiguousReference(name, newPrec, prevPrec, prevCtx), posd.sourcePos) + fail(AmbiguousReference(name, newPrec, prevPrec, prevCtx)) previous /** Recurse in outer context. If final result is same as `previous`, check that it @@ -191,7 +192,7 @@ class Typer extends Namer def selection(imp: ImportInfo, name: Name, checkBounds: Boolean) = if imp.sym.isCompleting then - ctx.warning(i"cyclic ${imp.sym}, ignored", posd.sourcePos) + report.warning(i"cyclic ${imp.sym}, ignored", posd.sourcePos) NoType else if unimported.nonEmpty && unimported.contains(imp.site.termSymbol) then NoType @@ -221,7 +222,7 @@ class Typer extends Namer def checkUnambiguous(found: Type) = val other = recur(selectors.tail) if other.exists && found.exists && found != other then - refctx.error(em"reference to `$name` is ambiguous; it is imported twice", posd.sourcePos) + fail(em"reference to `$name` is ambiguous; it is imported twice") found if adjustExtension(selector.rename) == termName then @@ -323,7 +324,7 @@ class Typer extends Namer if scope.lookup(name).exists then val symsMatch = scope.lookupAll(name).exists(denot.containsSym) if !symsMatch then - ctx.errorOrMigrationWarning( + report.errorOrMigrationWarning( AmbiguousReference(name, Definition, Inheritance, prevCtx)(using outer), posd.sourcePos) if migrateTo3 then @@ -469,7 +470,7 @@ class Typer extends Namer try { var found = findRef(name, pt, EmptyFlags, tree.posd) if (foundUnderScala2.exists && !(foundUnderScala2 =:= found)) { - ctx.migrationWarning( + report.migrationWarning( ex"""Name resolution will change. | currently selected : $foundUnderScala2 | in the future, without -source 3.0-migration: $found""", tree.sourcePos) @@ -525,7 +526,7 @@ class Typer extends Namer && !tree.tpe.isStable && !isWildcardArg(tree) then - ctx.error(StableIdentPattern(tree, pt), tree.sourcePos) + report.error(StableIdentPattern(tree, pt), tree.sourcePos) def typedSelect(tree: untpd.Select, pt: Type, qual: Tree)(using Context): Tree = qual match { case qual @ IntegratedTypeArgs(app) => @@ -588,7 +589,7 @@ class Typer extends Namer val qual1 = typed(tree.qual) val enclosingInlineable = ctx.owner.ownersIterator.findSymbol(_.isInlineMethod) if (enclosingInlineable.exists && !PrepareInlineable.isLocal(qual1.symbol, enclosingInlineable)) - ctx.error(SuperCallsNotAllowedInlineable(enclosingInlineable), tree.sourcePos) + report.error(SuperCallsNotAllowedInlineable(enclosingInlineable), tree.sourcePos) pt match { case pt: SelectionProto if pt.name.isTypeName => qual1 // don't do super references for types; they are meaningless anyway @@ -659,7 +660,7 @@ class Typer extends Namer } catch { case ex: FromDigitsException => - ctx.error(ex.getMessage, tree.sourcePos) + report.error(ex.getMessage, tree.sourcePos) tree.kind match { case Whole(_) => lit(0) case _ => lit(0.0) @@ -702,7 +703,7 @@ class Typer extends Namer tpt1 match { case AppliedTypeTree(_, targs) => for case targ: TypeBoundsTree <- targs do - ctx.error(WildcardOnTypeArgumentNotAllowedOnNew(), targ.sourcePos) + report.error(WildcardOnTypeArgumentNotAllowedOnNew(), targ.sourcePos) case _ => } @@ -765,8 +766,8 @@ class Typer extends Namer def typedTpt = checkSimpleKinded(typedType(tree.tpt)) def handlePattern: Tree = { val tpt1 = typedTpt - if (!ctx.isAfterTyper && pt != defn.ImplicitScrutineeTypeRef) - ctx.addMode(Mode.GadtConstraintInference).typeComparer.constrainPatternType(tpt1.tpe, pt) + if (!currentlyAfterTyper && pt != defn.ImplicitScrutineeTypeRef) + withMode(Mode.GadtConstraintInference)(ctx.typeComparer.constrainPatternType(tpt1.tpe, pt)) // special case for an abstract type that comes with a class tag tryWithClassTag(ascription(tpt1, isWildcard = true), pt) } @@ -782,10 +783,11 @@ class Typer extends Namer * @pre We are in pattern-matching mode (Mode.Pattern) */ def tryWithClassTag(tree: Typed, pt: Type)(using Context): Tree = tree.tpt.tpe.dealias match { - case tref: TypeRef if !tref.symbol.isClass && !ctx.isAfterTyper && !(tref =:= pt) => + case tref: TypeRef if !tref.symbol.isClass && !currentlyAfterTyper && !(tref =:= pt) => require(ctx.mode.is(Mode.Pattern)) - inferImplicit(defn.ClassTagClass.typeRef.appliedTo(tref), - EmptyTree, tree.tpt.span)(using ctx.retractMode(Mode.Pattern)) match { + withoutMode(Mode.Pattern)( + inferImplicit(defn.ClassTagClass.typeRef.appliedTo(tref), EmptyTree, tree.tpt.span) + ) match { case SearchSuccess(clsTag, _, _) => typed(untpd.Apply(untpd.TypedSplice(clsTag), untpd.TypedSplice(tree.expr)), pt) case _ => @@ -863,8 +865,9 @@ class Typer extends Namer typedStats(stats, ctx.owner) def typedBlock(tree: untpd.Block, pt: Type)(using Context): Tree = { - val localCtx = ctx.retractMode(Mode.Pattern) - val (stats1, exprCtx) = typedBlockStats(tree.stats)(using localCtx) + val (stats1, exprCtx) = withoutMode(Mode.Pattern) { + typedBlockStats(tree.stats) + } val expr1 = typedExpr(tree.expr, pt.dropIfProto)(using exprCtx) ensureNoLocalRefs( cpy.Block(tree)(stats1, expr1) @@ -961,7 +964,7 @@ class Typer extends Namer if (pt1 ne pt1.dropDependentRefinement) && defn.isContextFunctionType(pt1.nonPrivateMember(nme.apply).info.finalResultType) then - ctx.error( + report.error( i"""Implementation restriction: Expected result type $pt1 |is a curried dependent context function type. Such types are not yet supported.""", tree.sourcePos) @@ -1018,7 +1021,7 @@ class Typer extends Namer val appDef = typed(appDef0).asInstanceOf[DefDef] val mt = appDef.symbol.info.asInstanceOf[MethodType] if (mt.isParamDependent) - ctx.error(i"$mt is an illegal function type because it has inter-parameter dependencies", tree.sourcePos) + report.error(i"$mt is an illegal function type because it has inter-parameter dependencies", tree.sourcePos) val resTpt = TypeTree(mt.nonDependentResultApprox).withSpan(body.span) val typeArgs = appDef.vparamss.head.map(_.tpt) :+ resTpt val tycon = TypeTree(funCls.typeRef) @@ -1029,7 +1032,7 @@ class Typer extends Namer args match { case ValDef(_, _, _) :: _ => typedDependent(args.asInstanceOf[List[untpd.ValDef]])( - using ctx.fresh.setOwner(ctx.newRefinedClassSymbol(tree.span)).setNewScope) + using ctx.fresh.setOwner(newRefinedClassSymbol(tree.span)).setNewScope) case _ => typed(cpy.AppliedTypeTree(tree)(untpd.TypeTree(funCls.typeRef), args :+ body), pt) } @@ -1229,11 +1232,11 @@ class Typer extends Namer // Replace the underspecified expected type by one based on the closure method type defn.PartialFunctionOf(mt.firstParamTypes.head, mt.resultType) else - ctx.error(ex"result type of lambda is an underspecified SAM type $pt", tree.sourcePos) + report.error(ex"result type of lambda is an underspecified SAM type $pt", tree.sourcePos) pt if (pt.classSymbol.isOneOf(FinalOrSealed)) { val offendingFlag = pt.classSymbol.flags & FinalOrSealed - ctx.error(ex"lambda cannot implement $offendingFlag ${pt.classSymbol}", tree.sourcePos) + report.error(ex"lambda cannot implement $offendingFlag ${pt.classSymbol}", tree.sourcePos) } TypeTree(targetTpe) case _ => @@ -1387,8 +1390,8 @@ class Typer extends Namer val sym = b.symbol if (sym.name != tpnme.WILDCARD) if (ctx.scope.lookup(b.name) == NoSymbol) ctx.enter(sym) - else ctx.error(new DuplicateBind(b, cdef), b.sourcePos) - if (!ctx.isAfterTyper) { + else report.error(new DuplicateBind(b, cdef), b.sourcePos) + if (!currentlyAfterTyper) { val bounds = ctx.gadt.fullBounds(sym) if (bounds != null) sym.info = bounds } @@ -1443,7 +1446,7 @@ class Typer extends Namer /** Type a case of a type match */ def typedTypeCase(cdef: untpd.CaseDef, selType: Type, pt: Type)(using Context): CaseDef = { def caseRest(using Context) = { - val pat1 = checkSimpleKinded(typedType(cdef.pat)(using ctx.addMode(Mode.Pattern))) + val pat1 = withMode(Mode.Pattern)(checkSimpleKinded(typedType(cdef.pat))) val pat2 = indexPattern(cdef).transform(pat1) var body1 = typedType(cdef.body, pt) if !body1.isType then @@ -1492,7 +1495,7 @@ class Typer extends Namer def enclMethInfo(cx: Context): (Tree, Type) = { val owner = cx.owner if (owner.isType) { - ctx.error(ReturnOutsideMethodDefinition(owner), tree.sourcePos) + report.error(ReturnOutsideMethodDefinition(owner), tree.sourcePos) (EmptyTree, WildcardType) } else if (owner != cx.outer.owner && owner.isRealMethod) @@ -1512,7 +1515,7 @@ class Typer extends Namer else { val from = tree.from.asInstanceOf[tpd.Tree] val proto = - if (ctx.erasedTypes) from.symbol.info.finalResultType + if (currentlyAfterErasure) from.symbol.info.finalResultType else WildcardType // We cannot reliably detect the internal type view of polymorphic or dependent methods // because we do not know the internal type params and method params. // Hence no adaptation is possible, and we assume WildcardType as prototype. @@ -1635,11 +1638,11 @@ class Typer extends Namer val polymorphicRefinementAllowed = tpt1.tpe.typeSymbol == defn.PolyFunctionClass && rsym.name == nme.apply if (!polymorphicRefinementAllowed && rsym.info.isInstanceOf[PolyType] && rsym.allOverriddenSymbols.isEmpty) - ctx.error(PolymorphicMethodMissingTypeInParent(rsym, tpt1.symbol), refinement.sourcePos) + report.error(PolymorphicMethodMissingTypeInParent(rsym, tpt1.symbol), refinement.sourcePos) val member = refineCls.info.member(rsym.name) if (member.isOverloaded) - ctx.error(OverloadInRefinement(rsym), refinement.sourcePos) + report.error(OverloadInRefinement(rsym), refinement.sourcePos) } assignType(cpy.RefinedTypeTree(tree)(tpt1, refinements1), tpt1, refinements1, refineCls) } @@ -1653,10 +1656,12 @@ class Typer extends Namer return errorTree(tree, dependentStr) case _ => - val tpt1 = typed(tree.tpt, AnyTypeConstructorProto)(using ctx.retractMode(Mode.Pattern)) + val tpt1 = withoutMode(Mode.Pattern) { + typed(tree.tpt, AnyTypeConstructorProto) + } val tparams = tpt1.tpe.typeParams if (tparams.isEmpty) { - ctx.error(TypeDoesNotTakeParameters(tpt1.tpe, tree.args), tree.sourcePos) + report.error(TypeDoesNotTakeParameters(tpt1.tpe, tree.args), tree.sourcePos) tpt1 } else { @@ -1774,7 +1779,7 @@ class Typer extends Namer if !alias1.isEmpty then val bounds = TypeBounds(lo2.tpe, hi2.tpe) if !bounds.contains(alias1.tpe) then - ctx.error(em"type ${alias1.tpe} outside bounds $bounds", tree.sourcePos) + report.error(em"type ${alias1.tpe} outside bounds $bounds", tree.sourcePos) val tree1 = assignType(cpy.TypeBoundsTree(tree)(lo2, hi2, alias1), lo2, hi2, alias1) if (ctx.mode.is(Mode.Pattern)) @@ -1784,9 +1789,9 @@ class Typer extends Namer // are eliminated once the enclosing pattern has been typechecked; see `indexPattern` // in `typedCase`. //val ptt = if (lo.isEmpty && hi.isEmpty) pt else - if (ctx.isAfterTyper) tree1 + if (currentlyAfterTyper) tree1 else { - val wildcardSym = ctx.newPatternBoundSymbol(tpnme.WILDCARD, tree1.tpe & pt, tree.span) + val wildcardSym = newPatternBoundSymbol(tpnme.WILDCARD, tree1.tpe & pt, tree.span) untpd.Bind(tpnme.WILDCARD, tree1).withType(wildcardSym.typeRef) } else tree1 @@ -1836,10 +1841,10 @@ class Typer extends Namer // See also #5649. then body1.tpe else pt & body1.tpe - val sym = ctx.newPatternBoundSymbol(name, symTp, tree.span) + val sym = newPatternBoundSymbol(name, symTp, tree.span) if (pt == defn.ImplicitScrutineeTypeRef || tree.mods.is(Given)) sym.setFlag(Given) if (ctx.mode.is(Mode.InPatternAlternative)) - ctx.error(i"Illegal variable ${sym.name} in pattern alternative", tree.sourcePos) + report.error(i"Illegal variable ${sym.name} in pattern alternative", tree.sourcePos) assignType(cpy.Bind(tree)(name, body1), sym) } } @@ -1947,7 +1952,7 @@ class Typer extends Namer if (sym.isConstructor && !sym.isPrimaryConstructor) { val ename = sym.erasedName if (ename != sym.name) - ctx.error(em"@alpha annotation ${'"'}$ename${'"'} may not be used on a constructor", ddef.sourcePos) + report.error(em"@alpha annotation ${'"'}$ename${'"'} may not be used on a constructor", ddef.sourcePos) for (param <- tparams1 ::: vparamss1.flatten) checkRefsLegal(param, sym.owner, (name, sym) => sym.is(TypeParam), "secondary constructor") @@ -1955,7 +1960,7 @@ class Typer extends Namer def checkThisConstrCall(tree: Tree): Unit = tree match { case app: Apply if untpd.isSelfConstrCall(app) => if (sym.span.exists && app.symbol.span.exists && sym.span.start <= app.symbol.span.start) - ctx.error("secondary constructor must call a preceding constructor", app.sourcePos) + report.error("secondary constructor must call a preceding constructor", app.sourcePos) case Block(call :: _, _) => checkThisConstrCall(call) case _ => } @@ -2003,9 +2008,9 @@ class Typer extends Namer case cinfo @ MethodType(Nil) if !cinfo.resultType.isInstanceOf[MethodType] => ref case cinfo: MethodType => - if (!ctx.erasedTypes) { // after constructors arguments are passed in super call. + if (!currentlyAfterErasure) { // after constructors arguments are passed in super call. typr.println(i"constr type: $cinfo") - ctx.error(ParameterizedTypeLacksArguments(psym), ref.sourcePos) + report.error(ParameterizedTypeLacksArguments(psym), ref.sourcePos) } ref case _ => @@ -2029,7 +2034,7 @@ class Typer extends Namer if (!tree.span.isSourceDerived) return EmptyTree - if (!ctx.isAfterTyper) ctx.error(i"$psym is extended twice", tree.sourcePos) + if (!currentlyAfterTyper) report.error(i"$psym is extended twice", tree.sourcePos) } else seenParents += psym if (tree.isType) { @@ -2054,7 +2059,7 @@ class Typer extends Namer val other = memberInSelfButNotThis(decl) if (other.exists) { val msg = CannotHaveSameNameAs(decl, other, CannotHaveSameNameAs.DefinedInSelf(self)) - ctx.error(msg, decl.sourcePos) + report.error(msg, decl.sourcePos) } foundRedef || other.exists } @@ -2078,7 +2083,7 @@ class Typer extends Namer checkNoDoubleDeclaration(cls) val impl1 = cpy.Template(impl)(constr1, parents1, Nil, self1, body1) .withType(dummy.termRef) - if (!cls.isOneOf(AbstractOrTrait) && !ctx.isAfterTyper) + if (!cls.isOneOf(AbstractOrTrait) && !currentlyAfterTyper) checkRealizableBounds(cls, cdef.sourcePos.withSpan(cdef.nameSpan)) if (cls.derivesFrom(defn.EnumClass)) { val firstParent = parents1.head.tpe.dealias.typeSymbol @@ -2087,13 +2092,13 @@ class Typer extends Namer val cdef1 = assignType(cpy.TypeDef(cdef)(name, impl1), cls) val reportDynamicInheritance = - ctx.phase.isTyper && + currentPhase.isTyper && cdef1.symbol.ne(defn.DynamicClass) && cdef1.tpe.derivesFrom(defn.DynamicClass) && !dynamicsEnabled if (reportDynamicInheritance) { val isRequired = parents1.exists(_.tpe.isRef(defn.DynamicClass)) - ctx.featureWarning(nme.dynamics.toString, "extension of type scala.Dynamic", cls, isRequired, cdef.sourcePos) + report.featureWarning(nme.dynamics.toString, "extension of type scala.Dynamic", cls, isRequired, cdef.sourcePos) } checkNonCyclicInherited(cls.thisType, cls.classParents, cls.info.decls, cdef.posd) @@ -2106,7 +2111,7 @@ class Typer extends Namer && !cls.isAllOf(PrivateLocal) && effectiveOwner.is(Trait) && !effectiveOwner.derivesFrom(defn.ObjectClass) - ctx.error(i"$cls cannot be defined in universal $effectiveOwner", cdef.sourcePos) + report.error(i"$cls cannot be defined in universal $effectiveOwner", cdef.sourcePos) // Temporarily set the typed class def as root tree so that we have at least some // information in the IDE in case we never reach `SetRootTree`. @@ -2179,7 +2184,7 @@ class Typer extends Namer } def localDummy(cls: ClassSymbol, impl: untpd.Template)(using Context): Symbol = - ctx.newLocalDummy(cls, impl.span) + newLocalDummy(cls, impl.span) def typedImport(imp: untpd.Import, sym: Symbol)(using Context): Import = { val expr1 = typedExpr(imp.expr, AnySelectionProto) @@ -2194,13 +2199,13 @@ class Typer extends Namer } def typedPackageDef(tree: untpd.PackageDef)(using Context): Tree = - val pid1 = typedExpr(tree.pid, AnySelectionProto)(using ctx.addMode(Mode.InPackageClauseName)) + val pid1 = withMode(Mode.InPackageClauseName)(typedExpr(tree.pid, AnySelectionProto)) val pkg = pid1.symbol pid1 match case pid1: RefTree if pkg.is(Package) => val packageCtx = ctx.packageContext(tree, pkg) var stats1 = typedStats(tree.stats, pkg.moduleClass)(using packageCtx)._1 - if (!ctx.isAfterTyper) + if (!currentlyAfterTyper) stats1 = stats1 ++ typedBlockStats(MainProxies.mainProxies(stats1))(using packageCtx)._1 cpy.PackageDef(tree)(pid1, stats1).withType(pkg.termRef) case _ => @@ -2258,7 +2263,7 @@ class Typer extends Namer case closure(_, _, _) => case _ => val recovered = typed(qual)(using ctx.fresh.setExploreTyperState()) - ctx.errorOrMigrationWarning(OnlyFunctionsCanBeFollowedByUnderscore(recovered.tpe.widen), tree.sourcePos) + report.errorOrMigrationWarning(OnlyFunctionsCanBeFollowedByUnderscore(recovered.tpe.widen), tree.sourcePos) if (migrateTo3) { // Under -rewrite, patch `x _` to `(() => x)` patch(Span(tree.span.start), "(() => ") @@ -2278,7 +2283,7 @@ class Typer extends Namer def remedy = if ((prefix ++ suffix).isEmpty) "simply leave out the trailing ` _`" else s"use `$prefix$suffix` instead" - ctx.errorOrMigrationWarning(i"""The syntax ` _` is no longer supported; + report.errorOrMigrationWarning(i"""The syntax ` _` is no longer supported; |you can $remedy""", tree.sourcePos, `3.1`) if sourceVersion.isMigrating then patch(Span(tree.span.start), prefix) @@ -2401,7 +2406,7 @@ class Typer extends Namer then ", use `_` to denote a higher-kinded type parameter" else "" val namePos = tree.sourcePos.withSpan(tree.nameSpan) - ctx.errorOrMigrationWarning(s"`?` is not a valid type name$addendum", namePos) + report.errorOrMigrationWarning(s"`?` is not a valid type name$addendum", namePos) if tree.isClassDef then typedClassDef(tree, sym.asClass)(using ctx.localContext(tree, sym)) else @@ -2470,7 +2475,7 @@ class Typer extends Namer && xtree.isTerm && !untpd.isContextualClosure(xtree) && !ctx.mode.is(Mode.Pattern) - && !ctx.isAfterTyper + && !currentlyAfterTyper && !ctx.isInlineContext then makeContextualFunction(xtree, ifpt) @@ -2539,7 +2544,7 @@ class Typer extends Namer trace(i"typing $tree, pt = $pt", typr, show = true) { record(s"typed $getClass") record("typed total") - if ctx.phase.isTyper then + if currentPhase.isTyper then assertPositioned(tree) if tree.source != ctx.source && tree.source.exists then typed(tree, pt, locked)(using ctx.withSource(tree.source)) @@ -2663,11 +2668,11 @@ class Typer extends Namer :: (if mdef.symbol.isRetainedInlineMethod then Inliner.bodyRetainer(mdef) :: Nil else Nil) def typedExpr(tree: untpd.Tree, pt: Type = WildcardType)(using Context): Tree = - typed(tree, pt)(using ctx.retractMode(Mode.PatternOrTypeBits)) + withoutMode(Mode.PatternOrTypeBits)(typed(tree, pt)) def typedType(tree: untpd.Tree, pt: Type = WildcardType)(using Context): Tree = // todo: retract mode between Type and Pattern? - typed(tree, pt)(using ctx.addMode(Mode.Type)) + withMode(Mode.Type)(typed(tree, pt)) def typedPattern(tree: untpd.Tree, selType: Type = WildcardType)(using Context): Tree = - typed(tree, selType)(using ctx.addMode(Mode.Pattern)) + withMode(Mode.Pattern)(typed(tree, selType)) def tryEither[T](op: Context ?=> T)(fallBack: (T, TyperState) => T)(using Context): T = { val nestedCtx = ctx.fresh.setNewTyperState() @@ -2891,8 +2896,8 @@ class Typer extends Namer def missingArgs(mt: MethodType) = { val meth = methPart(tree).symbol - if (mt.paramNames.length == 0) ctx.error(MissingEmptyArgumentList(meth), tree.sourcePos) - else ctx.error(em"missing arguments for $meth", tree.sourcePos) + if (mt.paramNames.length == 0) report.error(MissingEmptyArgumentList(meth), tree.sourcePos) + else report.error(em"missing arguments for $meth", tree.sourcePos) tree.withType(mt.resultType) } @@ -2988,7 +2993,7 @@ class Typer extends Namer if sourceVersion == `3.1-migration` && isContextBoundParams then // Under 3.1-migration, don't infer implicit arguments yet for parameters // coming from context bounds. Issue a warning instead and offer a patch. - ctx.migrationWarning( + report.migrationWarning( em"""Context bounds will map to context parameters. |A `using` clause is needed to pass explicit arguments to them. |This code can be rewritten automatically using -rewrite""", tree.sourcePos) @@ -3069,7 +3074,7 @@ class Typer extends Namer wtp.paramNames.lazyZip(wtp.paramInfos).lazyZip(args).foreach { (paramName, formal, arg) => arg.tpe match { case failure: SearchFailureType => - ctx.error( + report.error( missingArgMsg(arg, formal, implicitParamString(paramName, methodStr, tree)), tree.sourcePos.endPos) case _ => @@ -3168,7 +3173,7 @@ class Typer extends Namer if (!defn.isFunctionType(pt)) pt match { case SAMType(_) if !pt.classSymbol.hasAnnotation(defn.FunctionalInterfaceAnnot) => - ctx.warning(ex"${tree.symbol} is eta-expanded even though $pt does not have the @FunctionalInterface annotation.", tree.sourcePos) + report.warning(ex"${tree.symbol} is eta-expanded even though $pt does not have the @FunctionalInterface annotation.", tree.sourcePos) case _ => } simplify(typed(etaExpand(tree, wtp, arity), pt), pt, locked) @@ -3196,7 +3201,7 @@ class Typer extends Namer !isApplyProto(pt) && pt != AssignProto && !ctx.mode.is(Mode.Pattern) && - !ctx.isAfterTyper && + !currentlyAfterTyper && !ctx.isInlineContext) { typr.println(i"insert apply on implicit $tree") typed(untpd.Select(untpd.TypedSplice(tree), nme.apply), pt, locked) @@ -3232,13 +3237,13 @@ class Typer extends Namer readaptSimplified(Inliner.inlineCall(newCall)) } else if (ctx.settings.XignoreScala2Macros.value) { - ctx.warning("Scala 2 macro cannot be used in Dotty, this call will crash at runtime. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html", tree.sourcePos.startPos) + report.warning("Scala 2 macro cannot be used in Dotty, this call will crash at runtime. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html", tree.sourcePos.startPos) Throw(New(defn.MatchErrorClass.typeRef, Literal(Constant(s"Reached unexpanded Scala 2 macro call to ${tree.symbol.showFullName} compiled with -Xignore-scala2-macros.")) :: Nil)) .withType(tree.tpe) .withSpan(tree.span) } else { - ctx.error( + report.error( """Scala 2 macro cannot be used in Dotty. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html |To turn this error into a warning, pass -Xignore-scala2-macros to the compiler""".stripMargin, tree.sourcePos.startPos) tree @@ -3455,13 +3460,13 @@ class Typer extends Namer if ctx.mode.is(Mode.ImplicitsEnabled) && tree.typeOpt.isValueType then if pt.isRef(defn.AnyValClass) || pt.isRef(defn.ObjectClass) then - ctx.error(em"the result of an implicit conversion must be more specific than $pt", tree.sourcePos) + report.error(em"the result of an implicit conversion must be more specific than $pt", tree.sourcePos) inferView(tree, pt) match { case SearchSuccess(found: ExtMethodApply, _, _) => found // nothing to check or adapt for extension method applications case SearchSuccess(found, _, _) => checkImplicitConversionUseOK(found.symbol, tree.posd) - readapt(found)(using ctx.retractMode(Mode.ImplicitsEnabled)) + withoutMode(Mode.ImplicitsEnabled)(readapt(found)) case failure: SearchFailure => if (pt.isInstanceOf[ProtoType] && !failure.isAmbiguous) then // don't report the failure but return the tree unchanged. This @@ -3502,7 +3507,7 @@ class Typer extends Namer * tree that went unreported. A scenario where this happens is i1802.scala. */ def ensureReported(tp: Type) = tp match { - case err: ErrorType if !ctx.reporter.errorsReported => ctx.error(err.msg, tree.sourcePos) + case err: ErrorType if !ctx.reporter.errorsReported => report.error(err.msg, tree.sourcePos) case _ => } @@ -3551,7 +3556,7 @@ class Typer extends Namer } // Overridden in InlineTyper - def suppressInline(using Context): Boolean = ctx.isAfterTyper + def suppressInline(using Context): Boolean = currentlyAfterTyper /** Does the "contextuality" of the method type `methType` match the one of the prototype `pt`? * This is the case if @@ -3578,7 +3583,7 @@ class Typer extends Namer case _: RefTree | _: Literal if !isVarPattern(tree) && !(pt <:< tree.tpe) && - !ctx.addMode(Mode.GadtConstraintInference).typeComparer.constrainPatternType(tree.tpe, pt) => + !withMode(Mode.GadtConstraintInference)(ctx.typeComparer.constrainPatternType(tree.tpe, pt)) => val cmp = untpd.Apply( untpd.Select(untpd.TypedSplice(tree), nme.EQ), @@ -3588,9 +3593,9 @@ class Typer extends Namer } private def checkStatementPurity(tree: tpd.Tree)(original: untpd.Tree, exprOwner: Symbol)(using Context): Unit = - if (!tree.tpe.isErroneous && !ctx.isAfterTyper && isPureExpr(tree) && + if (!tree.tpe.isErroneous && !currentlyAfterTyper && isPureExpr(tree) && !tree.tpe.isRef(defn.UnitClass) && !isSelfOrSuperConstrCall(tree)) - ctx.warning(PureExpressionInStatementPosition(original, exprOwner), original.sourcePos) + report.warning(PureExpressionInStatementPosition(original, exprOwner), original.sourcePos) /** Types the body Scala 2 macro declaration `def f = macro ` */ private def typedScala2MacroBody(call: untpd.Tree)(using Context): Tree = @@ -3609,12 +3614,12 @@ class Typer extends Namer tpd.Block(List(bundleVal), splice(tpd.ref(bundleVal.symbol))).withSpan(call.span) } } - if ctx.phase.isTyper then + if currentPhase.isTyper then call match case untpd.Ident(nme.???) => // Instinsic macros ignored case _ => if !config.Feature.scala2ExperimentalMacroEnabled then - ctx.error( + report.error( """Scala 2 macro definition needs to be enabled |by making the implicit value scala.language.experimental.macros visible. |This can be achieved by adding the import clause 'import scala.language.experimental.macros' @@ -3634,7 +3639,7 @@ class Typer extends Namer typedTypeApply(call2, defn.AnyType) } case _ => - ctx.error("Invalid Scala 2 macro " + call.show, call.sourcePos) + report.error("Invalid Scala 2 macro " + call.show, call.sourcePos) EmptyTree else typedExpr(call, defn.AnyType) diff --git a/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala b/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala index 469960b1dacd..2678799fdecc 100644 --- a/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala +++ b/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala @@ -45,7 +45,7 @@ object VarianceChecker { .find(_.name.toTermName == paramName) .map(_.sourcePos) .getOrElse(tree.sourcePos) - accCtx.error(em"${paramVarianceStr}variant type parameter $paramName occurs in ${occursStr}variant position in ${tl.resType}", pos) + report.error(em"${paramVarianceStr}variant type parameter $paramName occurs in ${occursStr}variant position in ${tl.resType}", pos) } def apply(x: Boolean, t: Type) = x && { t match { @@ -116,10 +116,10 @@ class VarianceChecker(using Context) { val required = compose(relative, this.variance) def tvar_s = s"$tvar (${varianceLabel(tvar.flags)} ${tvar.showLocated})" def base_s = s"$base in ${base.owner}" + (if (base.owner.isClass) "" else " in " + base.owner.enclosingClass) - accCtx.log(s"verifying $tvar_s is ${varianceLabel(required)} at $base_s") - accCtx.log(s"relative variance: ${varianceLabel(relative)}") - accCtx.log(s"current variance: ${this.variance}") - accCtx.log(s"owner chain: ${base.ownersIterator.toList}") + report.log(s"verifying $tvar_s is ${varianceLabel(required)} at $base_s") + report.log(s"relative variance: ${varianceLabel(relative)}") + report.log(s"current variance: ${this.variance}") + report.log(s"owner chain: ${base.ownersIterator.toList}") if (tvar.isOneOf(required)) None else Some(VarianceError(tvar, required)) } @@ -169,14 +169,14 @@ class VarianceChecker(using Context) { def msg = i"${varianceLabel(tvar.flags)} $tvar occurs in ${varianceLabel(required)} position in type ${sym.info} of $sym" if (migrateTo3 && (sym.owner.isConstructor || sym.ownersIterator.exists(_.isAllOf(ProtectedLocal)))) - ctx.migrationWarning( + report.migrationWarning( s"According to new variance rules, this is no longer accepted; need to annotate with @uncheckedVariance:\n$msg", pos) // patch(Span(pos.end), " @scala.annotation.unchecked.uncheckedVariance") // Patch is disabled until two TODOs are solved: // TODO use an import or shorten if possible // TODO need to use a `:' if annotation is on term - else ctx.error(msg, pos) + else report.error(msg, pos) case None => } @@ -189,7 +189,7 @@ class VarianceChecker(using Context) { || sym.is(TypeParam) && sym.owner.isClass // already taken care of in primary constructor of class try tree match { case defn: MemberDef if skip => - ctx.debuglog(s"Skipping variance check of ${sym.showDcl}") + report.debuglog(s"Skipping variance check of ${sym.showDcl}") case tree: TypeDef => checkVariance(sym, tree.sourcePos) tree.rhs match { @@ -205,7 +205,7 @@ class VarianceChecker(using Context) { case _ => } catch { - case ex: TypeError => ctx.error(ex, tree.sourcePos.focus) + case ex: TypeError => report.error(ex, tree.sourcePos.focus) } } } diff --git a/compiler/src/dotty/tools/dotc/util/Signatures.scala b/compiler/src/dotty/tools/dotc/util/Signatures.scala index 5365aa652634..7ea6941c4282 100644 --- a/compiler/src/dotty/tools/dotc/util/Signatures.scala +++ b/compiler/src/dotty/tools/dotc/util/Signatures.scala @@ -1,15 +1,16 @@ -package dotty.tools.dotc.util - -import dotty.tools.dotc.ast.Trees._ -import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Constants.Constant -import dotty.tools.dotc.core.Contexts.{Context, ctx} -import dotty.tools.dotc.core.Denotations.SingleDenotation -import dotty.tools.dotc.core.Flags.Implicit -import dotty.tools.dotc.core.Names.TermName -import dotty.tools.dotc.util.Spans.Span -import dotty.tools.dotc.core.Types.{ErrorType, MethodType, PolyType} -import dotty.tools.dotc.reporting.messages +package dotty.tools.dotc +package util + +import ast.Trees._ +import ast.tpd +import core.Constants.Constant +import core.Contexts.{Context, ctx} +import core.Denotations.SingleDenotation +import core.Flags.Implicit +import core.Names.TermName +import util.Spans.Span +import core.Types.{ErrorType, MethodType, PolyType} +import reporting._ import scala.collection.JavaConverters._ @@ -163,8 +164,8 @@ object Signatures { private def alternativesFromError(err: ErrorType, params: List[tpd.Tree])(using Context): (Int, List[SingleDenotation]) = { val alternatives = err.msg match - case msg: messages.AmbiguousOverload => msg.alternatives - case msg: messages.NoMatchingOverload => msg.alternatives + case msg: AmbiguousOverload => msg.alternatives + case msg: NoMatchingOverload => msg.alternatives case _ => Nil // If the user writes `foo(bar, )`, the typer will insert a synthetic diff --git a/compiler/src/dotty/tools/repl/ReplCompiler.scala b/compiler/src/dotty/tools/repl/ReplCompiler.scala index 960a0aec84bc..7ad0a4cd236a 100644 --- a/compiler/src/dotty/tools/repl/ReplCompiler.scala +++ b/compiler/src/dotty/tools/repl/ReplCompiler.scala @@ -50,7 +50,7 @@ class ReplCompiler extends Compiler { val path = nme.EMPTY_PACKAGE ++ "." ++ objectNames(id) def importWrapper(c: Context, importGiven: Boolean) = { val importInfo = ImportInfo.rootImport(() => - c.requiredModuleRef(path), importGiven) + requiredModuleRef(path), importGiven)(using c) c.fresh.setNewScope.setImportInfo(importInfo) } val ctx0 = importWrapper(importWrapper(ctx, false), true) diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 679c5531b574..a83536fb03f6 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -5,7 +5,7 @@ import java.io.{File => JFile, PrintStream} import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.{tpd, untpd} import dotty.tools.dotc.core.Contexts._ -import dotty.tools.dotc.core.Phases.{curPhases, typerPhase} +import dotty.tools.dotc.core.Phases.{unfusedPhases, typerPhase} import dotty.tools.dotc.core.Denotations.Denotation import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Mode @@ -223,7 +223,7 @@ class ReplDriver(settings: Array[String], } def extractTopLevelImports(ctx: Context): List[tpd.Import] = - curPhases(using ctx).collectFirst { case phase: CollectTopLevelImports => phase.imports }.get + unfusedPhases(using ctx).collectFirst { case phase: CollectTopLevelImports => phase.imports }.get implicit val state = { val state0 = newRun(istate) diff --git a/compiler/test/dotty/tools/AnnotationsTests.scala b/compiler/test/dotty/tools/AnnotationsTests.scala index a468f22ecf54..61d84ac9ab0f 100644 --- a/compiler/test/dotty/tools/AnnotationsTests.scala +++ b/compiler/test/dotty/tools/AnnotationsTests.scala @@ -9,11 +9,13 @@ import dotc.core.Decorators._ import dotc.core.Contexts._ import dotc.core.Phases._ import dotc.core.Types._ +import dotc.core.Symbols._ import java.io.File import java.nio.file._ class AnnotationsTest: + @Test def annotTreeNotErased: Unit = withJavaCompiled( VirtualJavaSource("Annot.java", @@ -22,8 +24,8 @@ class AnnotationsTest: "@Annot(values = {}) public class A {}")) { javaOutputDir => inCompilerContext(javaOutputDir.toString + File.pathSeparator + TestConfiguration.basicClasspath) { val defn = ctx.definitions - val cls = ctx.requiredClass("A") - val annotCls = ctx.requiredClass("Annot") + val cls = requiredClass("A") + val annotCls = requiredClass("Annot") val arrayOfString = defn.ArrayType.appliedTo(List(defn.StringType)) atPhase(erasurePhase.next) { @@ -47,7 +49,7 @@ class AnnotationsTest: "@Annot() public class A {}")) { javaOutputDir => Files.delete(javaOutputDir.resolve("Annot.class")) inCompilerContext(javaOutputDir.toString + File.pathSeparator + TestConfiguration.basicClasspath) { - val cls = ctx.requiredClass("A") + val cls = requiredClass("A") val annots = cls.annotations.map(_.tree) assert(annots == Nil, s"class A should have no visible annotations since Annot is not on the classpath, but found: $annots") diff --git a/compiler/test/dotty/tools/SignatureTest.scala b/compiler/test/dotty/tools/SignatureTest.scala index b5644b09950f..43d517417108 100644 --- a/compiler/test/dotty/tools/SignatureTest.scala +++ b/compiler/test/dotty/tools/SignatureTest.scala @@ -9,6 +9,7 @@ import dotc.core.Decorators._ import dotc.core.Contexts._ import dotc.core.Phases._ import dotc.core.Types._ +import dotc.core.Symbols._ import java.io.File import java.nio.file._ @@ -17,7 +18,7 @@ class SignatureTest: @Test def signatureCaching: Unit = inCompilerContext(TestConfiguration.basicClasspath, separateRun = true, "case class Foo(value: Unit)") { val (ref, refSig) = atPhase(erasurePhase.next) { - val cls = ctx.requiredClass("Foo") + val cls = requiredClass("Foo") val ref = cls.requiredMethod("value").termRef (ref, ref.signature) } diff --git a/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala b/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala index e0db4a77c9d2..8c792aa692a5 100644 --- a/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala +++ b/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala @@ -23,8 +23,8 @@ class TestMessageLaziness extends DottyTest { } @Test def assureLazy = - ctx.error(LazyError()) + report.error(LazyError()) @Test def assureLazyExtendMessage = - ctx.errorOrMigrationWarning(LazyError(), from = config.SourceVersion.`3.1`) + report.errorOrMigrationWarning(LazyError(), from = config.SourceVersion.`3.1`) } diff --git a/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala b/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala index 6dbdebd33208..24890279accd 100644 --- a/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala +++ b/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala @@ -12,7 +12,6 @@ import scala.collection.mutable import util.SourcePosition import core.Contexts._ import Reporter._ -import messages._ import Diagnostic._ import interfaces.Diagnostic.{ ERROR, WARNING, INFO } diff --git a/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala b/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala index 5ce44bada89e..bd72ac6c6288 100644 --- a/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala +++ b/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala @@ -3,7 +3,6 @@ package dotc package reporting import dotty.tools.dotc.core.Contexts.Context -import dotty.tools.dotc.reporting.messages._ import org.junit.Assert._ import org.junit.Test diff --git a/compiler/test/dotty/tools/vulpix/ParallelTesting.scala b/compiler/test/dotty/tools/vulpix/ParallelTesting.scala index 77d9ab4c132f..a09f9de2c5dd 100644 --- a/compiler/test/dotty/tools/vulpix/ParallelTesting.scala +++ b/compiler/test/dotty/tools/vulpix/ParallelTesting.scala @@ -19,6 +19,7 @@ import scala.util.matching.Regex import dotc.{Compiler, Driver} import dotc.core.Contexts._ import dotc.decompiler +import dotc.report import dotc.interfaces.Diagnostic.ERROR import dotc.reporting.{Reporter, TestReporter} import dotc.reporting.Diagnostic @@ -471,7 +472,7 @@ trait ParallelTesting extends RunnerOrchestration { self => ntimes(times) { run => val start = System.nanoTime() val rep = super.doCompile(comp, files) - ctx.echo(s"\ntime run $run: ${(System.nanoTime - start) / 1000000}ms") + report.echo(s"\ntime run $run: ${(System.nanoTime - start) / 1000000}ms") rep } } diff --git a/compiler/test/worksheets/sigtest.sc b/compiler/test/worksheets/sigtest.sc index ed3793f1c189..5ded413f6e47 100644 --- a/compiler/test/worksheets/sigtest.sc +++ b/compiler/test/worksheets/sigtest.sc @@ -7,7 +7,7 @@ import Types._, Symbols._ object sigtest extends DottyTest { println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet - val int = ctx.requiredClass("scala.Int") //> int : dotty.tools.dotc.core.Symbols.ClassSymbol = class Int + val int = requiredClass("scala.Int") //> int : dotty.tools.dotc.core.Symbols.ClassSymbol = class Int int.signature //> res0: dotty.tools.dotc.core.Denotations.Signature = List() val intmeth = methType("x")(int.symbolicRef)() //> intmeth : dotty.tools.dotc.core.Types.MethodType = MethodType(List(x), List //| (TypeRef(ThisType(module class scala),Int)), TypeRef(ThisType(module class s @@ -18,8 +18,8 @@ object sigtest extends DottyTest { //| e class scala),Array), scala$Array$$T, TypeAlias(TypeRef(ThisType(module cla //| ss scala),Int)) | hash = 1907214242) val arraymeth = methType("x")(arr)() //> arraymeth : dotty.tools.dotc.core.Types.MethodType = MethodType(List(x), Li - //| st(RefinedType(TypeRef(ThisType(module class scala),Array), scala$Array$$T, - //| TypeAlias(TypeRef(ThisType(module class scala),Int)) | hash = 1907214242)), + //| st(RefinedType(TypeRef(ThisType(module class scala),Array), scala$Array$$T, + //| TypeAlias(TypeRef(ThisType(module class scala),Int)) | hash = 1907214242)), //| TypeRef(ThisType(module class scala),Unit)) arraymeth.signature //> res2: dotty.tools.dotc.core.Denotations.Signature = List(Int[]) val curriedmeth = methType("x", "y")(defn.IntType, defn.BooleanType)(methType("z")(defn.ArrayType.appliedTo(defn.IntType))()) diff --git a/doc-tool/src/dotty/tools/dottydoc/DocCompiler.scala b/doc-tool/src/dotty/tools/dottydoc/DocCompiler.scala index aac9171dbca1..f85b38ccc89c 100644 --- a/doc-tool/src/dotty/tools/dottydoc/DocCompiler.scala +++ b/doc-tool/src/dotty/tools/dottydoc/DocCompiler.scala @@ -3,7 +3,7 @@ package dottydoc import core._ import core.transform._ -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Phases.Phase import dotc.core.Mode import dotc.{Compiler, CompilationUnit, Run} @@ -26,7 +26,7 @@ import dotty.tools.dotc.transform.CookComments */ class DocCompiler extends Compiler { - override def newRun(implicit ctx: Context): Run = { + override def newRun(using Context): Run = { if (ctx.settings.fromTasty.value) { reset() new TASTYRun(this, ctx.addMode(Mode.ReadPositions).addMode(Mode.ReadComments)) @@ -45,10 +45,10 @@ class DocCompiler extends Compiler { * `discardAfterTyper`. */ private class DocFrontEnd extends FrontEnd { - override protected def discardAfterTyper(unit: CompilationUnit)(implicit ctx: Context) = + override protected def discardAfterTyper(unit: CompilationUnit)(using Context) = unit.isJava - override def isRunnable(implicit ctx: Context): Boolean = + override def isRunnable(using Context): Boolean = super.isRunnable && !ctx.settings.fromTasty.value } diff --git a/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala b/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala index b531f1c06322..9055fab81a80 100644 --- a/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala +++ b/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala @@ -10,6 +10,7 @@ import dotc.reporting.Reporter import dotc.{ Compiler, Driver } import dotc.config._ import dotc.core.Comments.ContextDoc +import dotc.report import staticsite.Site /** `DocDriver` implements the main entry point to the Dotty documentation @@ -32,7 +33,7 @@ class DocDriver extends Driver { fromTastySetup(fileNames, ctx) } - override def newCompiler(implicit ctx: Context): Compiler = new DocCompiler + override def newCompiler(using Context): Compiler = new DocCompiler override def process(args: Array[String], rootCtx: Context): Reporter = { val (filesToDocument, ictx) = setup(args, initCtx.fresh) @@ -54,9 +55,9 @@ class DocDriver extends Driver { val snapshotBaseUrl = s"$baseUrl/$snapshotFolderName" if (projectName.isEmpty) - ctx.error(s"Site project name not set. Use `-project ` to set the project name") + report.error(s"Site project name not set. Use `-project <title>` to set the project name") else if (!siteRoot.exists || !siteRoot.isDirectory) - ctx.error(s"Site root does not exist: $siteRoot") + report.error(s"Site root does not exist: $siteRoot") else { def generateSite(outDir: File, baseUrl: String) = Site(siteRoot, outDir, projectName, projectVersion, projectUrl, projectLogo, ctx.docbase.packages, baseUrl) diff --git a/doc-tool/src/dotty/tools/dottydoc/core/AlternateConstructorsPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/AlternateConstructorsPhase.scala index 345fac86db34..567d2dddbb53 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/AlternateConstructorsPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/AlternateConstructorsPhase.scala @@ -2,7 +2,7 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import transform.DocMiniPhase import model._ @@ -22,12 +22,12 @@ class AlternateConstructors extends DocMiniPhase { (ent.constructors ++ paramLists, members) } - override def transformClass(implicit ctx: Context) = { case cls: ClassImpl => + override def transformClass(using Context) = { case cls: ClassImpl => val (constructors, members) = partitionMembers(cls) cls.copy(members = members, constructors = constructors) :: Nil } - override def transformCaseClass(implicit ctx: Context) = { case cc: CaseClassImpl => + override def transformCaseClass(using Context) = { case cc: CaseClassImpl => val (constructors, members) = partitionMembers(cc) cc.copy(members = members, constructors = constructors) :: Nil } diff --git a/doc-tool/src/dotty/tools/dottydoc/core/ContextDottydoc.scala b/doc-tool/src/dotty/tools/dottydoc/core/ContextDottydoc.scala index 7b09877d1cce..31ae8bdda749 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/ContextDottydoc.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/ContextDottydoc.scala @@ -9,10 +9,11 @@ import dotc.core.Comments.ContextDocstrings import model.{ Package, Entity } import model.comment.Comment -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.printing.Highlighting._ import dotc.printing.Formatting.hl import dotc.util.{ SourcePosition, NoSourcePosition } +import dotc.report class ContextDottydoc extends ContextDocstrings { import scala.collection.mutable @@ -35,32 +36,32 @@ class ContextDottydoc extends ContextDocstrings { s -> _defs.get(s).map(xs => xs + d).getOrElse(Set(d)) }) - def error(msg: String, pos: SourcePosition)(implicit ctx: Context): Unit = ctx.error({ + def error(msg: String, pos: SourcePosition)(using Context): Unit = report.error({ NoColor("[") + Red("doc error") + "] " + msg }.toString, pos) - def error(msg: String)(implicit ctx: Context): Unit = error(msg, NoSourcePosition) + def error(msg: String)(using Context): Unit = error(msg, NoSourcePosition) - def warn(msg: String, pos: SourcePosition)(implicit ctx: Context): Unit = ctx.warning({ + def warn(msg: String, pos: SourcePosition)(using Context): Unit = report.warning({ NoColor("[") + Yellow("doc warn") + "] " + msg }.toString, pos) - def warn(msg: String)(implicit ctx: Context): Unit = warn(msg, NoSourcePosition) + def warn(msg: String)(using Context): Unit = warn(msg, NoSourcePosition) - def echo(msg: String, pos: SourcePosition)(implicit ctx: Context): Unit = ctx.echo({ + def echo(msg: String, pos: SourcePosition)(using Context): Unit = report.echo({ "[doc info] " + msg }.toString, pos) - def echo(msg: String)(implicit ctx: Context): Unit = echo(msg, NoSourcePosition) + def echo(msg: String)(using Context): Unit = echo(msg, NoSourcePosition) - def debug(msg: String, pos: SourcePosition)(implicit ctx: Context): Unit = - if (ctx.settings.Ydebug.value) ctx.inform({ + def debug(msg: String, pos: SourcePosition)(using Context): Unit = + if (ctx.settings.Ydebug.value) report.inform({ "[doc debug] " + msg }.toString, pos) - def debug(msg: String)(implicit ctx: Context): Unit = debug(msg, NoSourcePosition) + def debug(msg: String)(using Context): Unit = debug(msg, NoSourcePosition) - def printSummary()(implicit ctx: Context): Unit = { + def printSummary()(using Context): Unit = { def colored(part: Int, total: Int) = if (total == 0) "0" else { @@ -106,7 +107,7 @@ class ContextDottydoc extends ContextDocstrings { |""".stripMargin }).mkString("\n") - ctx.echo { + report.echo { s"""|${Blue("=" * ctx.settings.pageWidth.value)} |Dottydoc summary report for project `$projectName` |${Blue("=" * ctx.settings.pageWidth.value)} diff --git a/doc-tool/src/dotty/tools/dottydoc/core/DocASTPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/DocASTPhase.scala index 27e0716cd6de..33a297f73ef3 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/DocASTPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/DocASTPhase.scala @@ -5,11 +5,12 @@ package core /** Dotty and Dottydoc imports */ import dotc.ast.Trees._ import dotc.CompilationUnit -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Types.PolyType import dotc.core.Phases.Phase import dotc.core.Symbols.{ Symbol, NoSymbol } import dotc.core.NameOps._ +import dotc.report class DocASTPhase extends Phase { import model._ @@ -24,7 +25,7 @@ class DocASTPhase extends Phase { def phaseName = "docASTPhase" /** Build documentation hierarchy from existing tree */ - def collect(tree: Tree)(implicit ctx: Context): List[Entity] = { + def collect(tree: Tree)(using Context): List[Entity] = { val implicitConversions = ctx.docbase.defs(tree.symbol) def collectList(xs: List[Tree]): List[Entity] = @@ -33,7 +34,7 @@ class DocASTPhase extends Phase { def collectEntityMembers(xs: List[Tree]) = collectList(xs).asInstanceOf[List[Entity with Members]] - def collectMembers(tree: Tree)(implicit ctx: Context): List[Entity] = { + def collectMembers(tree: Tree)(using Context): List[Entity] = { val defs = tree match { case t: Template => collectList(t.body) case _ => Nil @@ -229,13 +230,13 @@ class DocASTPhase extends Phase { private[this] var totalRuns = 0 private[this] var currentRun = 0 - override def run(implicit ctx: Context): Unit = { + override def run(using Context): Unit = { currentRun += 1 - ctx.echo(s"Compiling ($currentRun/$totalRuns): ${ctx.compilationUnit.source.file.name}") + report.echo(s"Compiling ($currentRun/$totalRuns): ${ctx.compilationUnit.source.file.name}") collect(ctx.compilationUnit.tpdTree) // Will put packages in `packages` var } - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { // (1) Create package structure for all `units`, this will give us a complete structure totalRuns = units.length val compUnits = super.runOn(units) diff --git a/doc-tool/src/dotty/tools/dottydoc/core/DocImplicitsPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/DocImplicitsPhase.scala index 45892061d0c3..479dce95c068 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/DocImplicitsPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/DocImplicitsPhase.scala @@ -4,7 +4,7 @@ package core import dotty.tools.dotc.transform.MegaPhase.MiniPhase import dotty.tools.dotc.core.Flags -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import util.syntax._ class DocImplicitsPhase extends MiniPhase { @@ -12,7 +12,7 @@ class DocImplicitsPhase extends MiniPhase { def phaseName = "addImplicitsPhase" - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(tree: DefDef)(using Context): Tree = { if ( tree.symbol.isOneOf(Flags.GivenOrImplicit) && // has to have an implicit flag tree.symbol.owner.isStaticOwner && // owner has to be static (e.g. top-level `object`) diff --git a/doc-tool/src/dotty/tools/dottydoc/core/DocstringPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/DocstringPhase.scala index 025c56cfa91c..4b8b9402936a 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/DocstringPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/DocstringPhase.scala @@ -2,7 +2,7 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Symbols.Symbol import dotc.core.Comments.{ Comment => CompilerComment } import transform.DocMiniPhase @@ -14,7 +14,7 @@ import util.syntax._ /** Phase to add docstrings to the Dottydoc AST */ class DocstringPhase extends DocMiniPhase with CommentParser with CommentCleaner { - private def getComment(sym: Symbol)(implicit ctx: Context): Option[CompilerComment] = { + private def getComment(sym: Symbol)(using Context): Option[CompilerComment] = { ctx.docbase.docstring(sym) .orElse { // If the symbol doesn't have a docstring, look for an overridden @@ -27,7 +27,7 @@ class DocstringPhase extends DocMiniPhase with CommentParser with CommentCleaner } } - private def parsedComment(ent: Entity)(implicit ctx: Context): Option[Comment] = { + private def parsedComment(ent: Entity)(using Context): Option[Comment] = { for { comment <- getComment(ent.symbol) text <- comment.expandedBody @@ -40,35 +40,35 @@ class DocstringPhase extends DocMiniPhase with CommentParser with CommentCleaner } } - override def transformPackage(implicit ctx: Context) = { case ent: PackageImpl => + override def transformPackage(using Context) = { case ent: PackageImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformClass(implicit ctx: Context) = { case ent: ClassImpl => + override def transformClass(using Context) = { case ent: ClassImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformCaseClass(implicit ctx: Context) = { case ent: CaseClassImpl => + override def transformCaseClass(using Context) = { case ent: CaseClassImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformTrait(implicit ctx: Context) = { case ent: TraitImpl => + override def transformTrait(using Context) = { case ent: TraitImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformObject(implicit ctx: Context) = { case ent: ObjectImpl => + override def transformObject(using Context) = { case ent: ObjectImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformDef(implicit ctx: Context) = { case ent: DefImpl => + override def transformDef(using Context) = { case ent: DefImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformVal(implicit ctx: Context) = { case ent: ValImpl => + override def transformVal(using Context) = { case ent: ValImpl => ent.copy(comment = parsedComment(ent)) :: Nil } - override def transformTypeAlias(implicit ctx: Context) = { case ent: TypeAliasImpl => + override def transformTypeAlias(using Context) = { case ent: TypeAliasImpl => ent.copy(comment = parsedComment(ent)) :: Nil } } diff --git a/doc-tool/src/dotty/tools/dottydoc/core/LinkCompanionsPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/LinkCompanionsPhase.scala index 07e0c0f8ffcd..a3135a3b3f59 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/LinkCompanionsPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/LinkCompanionsPhase.scala @@ -2,14 +2,14 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import transform.DocMiniPhase import model.internal._ import model._ class LinkCompanions extends DocMiniPhase { - private def linkCompanions(ent: Entity)(implicit ctx: Context): ent.type = { + private def linkCompanions(ent: Entity)(using Context): ent.type = { ent.children.groupBy(_.name).foreach { case (_, List(x1: Companion, x2: Companion)) => x1.companionPath = x2.path @@ -20,23 +20,23 @@ class LinkCompanions extends DocMiniPhase { ent } - override def transformPackage(implicit ctx: Context) = { case ent: PackageImpl => + override def transformPackage(using Context) = { case ent: PackageImpl => linkCompanions(ent) :: Nil } - override def transformClass(implicit ctx: Context) = { case ent: ClassImpl => + override def transformClass(using Context) = { case ent: ClassImpl => linkCompanions(ent) :: Nil } - override def transformCaseClass(implicit ctx: Context) = { case ent: CaseClassImpl => + override def transformCaseClass(using Context) = { case ent: CaseClassImpl => linkCompanions(ent) :: Nil } - override def transformObject(implicit ctx: Context) = { case ent: ObjectImpl => + override def transformObject(using Context) = { case ent: ObjectImpl => linkCompanions(ent) :: Nil } - override def transformTrait(implicit ctx: Context) = { case ent: TraitImpl => + override def transformTrait(using Context) = { case ent: TraitImpl => linkCompanions(ent) :: Nil } } diff --git a/doc-tool/src/dotty/tools/dottydoc/core/PackageObjectsPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/PackageObjectsPhase.scala index ccb8d2f102cf..74636755c65d 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/PackageObjectsPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/PackageObjectsPhase.scala @@ -2,14 +2,14 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import model._ import model.internal._ import transform.DocMiniPhase class PackageObjectsPhase extends DocMiniPhase { - override def transformPackage(implicit ctx: Context) = { case pkg: PackageImpl => + override def transformPackage(using Context) = { case pkg: PackageImpl => pkg .members .collectFirst { case o: Object if o.symbol.isPackageObject => o } @@ -23,7 +23,7 @@ class PackageObjectsPhase extends DocMiniPhase { .getOrElse(pkg) :: Nil } - override def transformObject(implicit ctx: Context) = { case obj: Object => + override def transformObject(using Context) = { case obj: Object => if (obj.symbol.isPackageObject) Nil else obj :: Nil } diff --git a/doc-tool/src/dotty/tools/dottydoc/core/RemoveEmptyPackagesPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/RemoveEmptyPackagesPhase.scala index 33fb7d0030d5..19bcee63133e 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/RemoveEmptyPackagesPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/RemoveEmptyPackagesPhase.scala @@ -2,13 +2,13 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import transform.DocMiniPhase import model._ class RemoveEmptyPackages extends DocMiniPhase { - override def transformPackage(implicit ctx: Context) = { case p: Package => + override def transformPackage(using Context) = { case p: Package => if (p.members.exists(_.kind != "package")) p :: Nil else Nil } diff --git a/doc-tool/src/dotty/tools/dottydoc/core/SortMembersPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/SortMembersPhase.scala index 3f554fd7f236..a544df2c6a92 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/SortMembersPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/SortMembersPhase.scala @@ -2,7 +2,7 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import transform.DocMiniPhase import model._ @@ -33,23 +33,23 @@ class SortMembers extends DocMiniPhase { pkgs ++ nested ++ typs ++ vals ++ defs } - override def transformPackage(implicit ctx: Context) = { case p: PackageImpl => + override def transformPackage(using Context) = { case p: PackageImpl => p.copy(members = sort(p.members)) :: Nil } - override def transformClass(implicit ctx: Context) = { case c: ClassImpl => + override def transformClass(using Context) = { case c: ClassImpl => c.copy(members = sort(c.members)) :: Nil } - override def transformCaseClass(implicit ctx: Context) = { case cc: CaseClassImpl => + override def transformCaseClass(using Context) = { case cc: CaseClassImpl => cc.copy(members = sort(cc.members)) :: Nil } - override def transformTrait(implicit ctx: Context) = { case t: TraitImpl => + override def transformTrait(using Context) = { case t: TraitImpl => t.copy(members = sort(t.members)) :: Nil } - override def transformObject(implicit ctx: Context) = { case o: ObjectImpl => + override def transformObject(using Context) = { case o: ObjectImpl => o.copy(members = sort(o.members)) :: Nil } } diff --git a/doc-tool/src/dotty/tools/dottydoc/core/StatisticsPhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/StatisticsPhase.scala index e7f9a9ec7613..bb409bbb5259 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/StatisticsPhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/StatisticsPhase.scala @@ -3,7 +3,7 @@ package dottydoc package core import dotc.core.Phases.Phase -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Symbols.Symbol import dotc.core.Decorators._ import dotc.core.Flags._ @@ -57,9 +57,9 @@ class StatisticsPhase extends Phase { def phaseName = "StatisticsPhase" - override def run(implicit ctx: Context): Unit = () + override def run(using Context): Unit = () - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { for { (pkgName, pack) <- ctx.docbase.packages externalApi = collectPublicStats(pack) @@ -70,7 +70,7 @@ class StatisticsPhase extends Phase { units } - def collectPublicStats(pack: Package)(implicit ctx: Context): Counters = { + def collectPublicStats(pack: Package)(using Context): Counters = { var publicEntities: Int = 0 var protectedEntities: Int = 0 var publicDocstrings: Int = 0 @@ -112,7 +112,7 @@ class StatisticsPhase extends Phase { Counters(publicEntities, 0, protectedEntities, publicDocstrings, 0, protectedDocstrings) } - def collectInternalStats(pack: Package)(implicit ctx: Context): Counters = { + def collectInternalStats(pack: Package)(using Context): Counters = { var publicEntities: Int = 0 var privateEntities: Int = 0 var protectedEntities: Int = 0 diff --git a/doc-tool/src/dotty/tools/dottydoc/core/TypeLinkingPhases.scala b/doc-tool/src/dotty/tools/dottydoc/core/TypeLinkingPhases.scala index 1165fdb48cee..be780b7c06c1 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/TypeLinkingPhases.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/TypeLinkingPhases.scala @@ -2,7 +2,7 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import transform.DocMiniPhase import model._ @@ -14,17 +14,17 @@ import util.MemberLookup import util.syntax._ class LinkReturnTypes extends DocMiniPhase with TypeLinker { - override def transformDef(implicit ctx: Context) = { case df: DefImpl => + override def transformDef(using Context) = { case df: DefImpl => val returnValue = linkReference(df, df.returnValue, ctx.docbase.packages) df.copy(returnValue = returnValue) :: Nil } - override def transformVal(implicit ctx: Context) = { case vl: ValImpl => + override def transformVal(using Context) = { case vl: ValImpl => val returnValue = linkReference(vl, vl.returnValue, ctx.docbase.packages) vl.copy(returnValue = returnValue) :: Nil } - override def transformTypeAlias(implicit ctx: Context) = { case ta: TypeAliasImpl => + override def transformTypeAlias(using Context) = { case ta: TypeAliasImpl => ta.alias.map { alias => val linkedAlias = linkReference(ta, alias, ctx.docbase.packages) ta.copy(alias = Some(linkedAlias)) :: Nil @@ -34,7 +34,7 @@ class LinkReturnTypes extends DocMiniPhase with TypeLinker { } class LinkParamListTypes extends DocMiniPhase with TypeLinker { - override def transformDef(implicit ctx: Context) = { case df: DefImpl => + override def transformDef(using Context) = { case df: DefImpl => val newParamLists = for { ParamListImpl(list, isImplicit) <- df.paramLists newList = list.map(linkReference(df, _, ctx.docbase.packages)) @@ -45,37 +45,37 @@ class LinkParamListTypes extends DocMiniPhase with TypeLinker { } class LinkSuperTypes extends DocMiniPhase with TypeLinker { - def linkSuperTypes(ent: Entity with SuperTypes)(implicit ctx: Context): List[MaterializableLink] = + def linkSuperTypes(ent: Entity with SuperTypes)(using Context): List[MaterializableLink] = ent.superTypes.collect { case UnsetLink(title, query) => handleEntityLink(title, lookup(Some(ent), ctx.docbase.packages, query), ent) } - override def transformClass(implicit ctx: Context) = { case cls: ClassImpl => + override def transformClass(using Context) = { case cls: ClassImpl => cls.copy(superTypes = linkSuperTypes(cls)) :: Nil } - override def transformCaseClass(implicit ctx: Context) = { case cc: CaseClassImpl => + override def transformCaseClass(using Context) = { case cc: CaseClassImpl => cc.copy(superTypes = linkSuperTypes(cc)) :: Nil } - override def transformTrait(implicit ctx: Context) = { case trt: TraitImpl => + override def transformTrait(using Context) = { case trt: TraitImpl => trt.copy(superTypes = linkSuperTypes(trt)) :: Nil } - override def transformObject(implicit ctx: Context) = { case obj: ObjectImpl => + override def transformObject(using Context) = { case obj: ObjectImpl => obj.copy(superTypes = linkSuperTypes(obj)) :: Nil } } class LinkImplicitlyAddedTypes extends DocMiniPhase with TypeLinker { - override def transformDef(implicit ctx: Context) = { + override def transformDef(using Context) = { case df: DefImpl if df.implicitlyAddedFrom.isDefined => val implicitlyAddedFrom = linkReference(df, df.implicitlyAddedFrom.get, ctx.docbase.packages) df.copy(implicitlyAddedFrom = Some(implicitlyAddedFrom)) :: Nil } - override def transformVal(implicit ctx: Context) = { + override def transformVal(using Context) = { case vl: ValImpl if vl.implicitlyAddedFrom.isDefined => val implicitlyAddedFrom = linkReference(vl, vl.implicitlyAddedFrom.get, ctx.docbase.packages) vl.copy(implicitlyAddedFrom = Some(implicitlyAddedFrom)) :: Nil diff --git a/doc-tool/src/dotty/tools/dottydoc/core/UsecasePhase.scala b/doc-tool/src/dotty/tools/dottydoc/core/UsecasePhase.scala index f9c118055c1e..3bf100a059f9 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/UsecasePhase.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/UsecasePhase.scala @@ -2,7 +2,7 @@ package dotty.tools package dottydoc package core -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.ast.tpd import transform.DocMiniPhase @@ -12,7 +12,7 @@ import dotty.tools.dotc.core.Symbols.Symbol import util.syntax._ class UsecasePhase extends DocMiniPhase { - private def defdefToDef(d: tpd.DefDef, sym: Symbol)(implicit ctx: Context) = { + private def defdefToDef(d: tpd.DefDef, sym: Symbol)(using Context) = { val name = d.name.show.split("\\$").head DefImpl( sym, @@ -26,7 +26,7 @@ class UsecasePhase extends DocMiniPhase { ) } - override def transformDef(implicit ctx: Context) = { case df: DefImpl => + override def transformDef(using Context) = { case df: DefImpl => val defdefs = ctx.docbase.docstring(df.symbol) .map(_.usecases.flatMap(_.tpdCode)) diff --git a/doc-tool/src/dotty/tools/dottydoc/core/transform.scala b/doc-tool/src/dotty/tools/dottydoc/core/transform.scala index 664d8cea9ccc..04e2d771159a 100644 --- a/doc-tool/src/dotty/tools/dottydoc/core/transform.scala +++ b/doc-tool/src/dotty/tools/dottydoc/core/transform.scala @@ -3,7 +3,7 @@ package dottydoc package core import dotc.CompilationUnit -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Phases.Phase import model._ import model.internal._ @@ -22,7 +22,7 @@ object transform { * Create a `DocMiniPhase` which overrides the relevant method: * * ``` - * override def transformDef(implicit ctx: Context) = { + * override def transformDef(using Context) = { * case x if shouldTransform(x) => x.copy(newValue = ...) :: Nil * } * ``` @@ -47,7 +47,7 @@ object transform { abstract class DocMiniTransformations extends Phase { def transformations: List[DocMiniPhase] - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { for { pack <- rootPackages(ctx.docbase.packages) transformed = performPackageTransform(pack) @@ -59,7 +59,7 @@ object transform { units } - private def performPackageTransform(pack: Package)(implicit ctx: Context): List[Package] = { + private def performPackageTransform(pack: Package)(using Context): List[Package] = { def transformEntity[E <: Entity](e: E, f: DocMiniPhase => E => List[E])(createNew: E => E): List[Entity] = { val transformEntities = transformations.foldLeft(e :: Nil) { case (oldEs, transf) => oldEs.flatMap(f(transf)) @@ -194,7 +194,7 @@ object transform { traverse(pack).asInstanceOf[List[Package]] } - override def run(implicit ctx: Context): Unit = () + override def run(using Context): Unit = () } object DocMiniTransformations { @@ -213,22 +213,22 @@ object transform { case id: E @unchecked => id :: Nil } - def transformPackage(implicit ctx: Context): PartialFunction[Package, List[Package]] = identity - def transformTypeAlias(implicit ctx: Context): PartialFunction[TypeAlias, List[TypeAlias]] = identity - def transformClass(implicit ctx: Context): PartialFunction[Class, List[Class]] = identity - def transformCaseClass(implicit ctx: Context): PartialFunction[CaseClass, List[CaseClass]] = identity - def transformTrait(implicit ctx: Context): PartialFunction[Trait, List[Trait]] = identity - def transformObject(implicit ctx: Context): PartialFunction[Object, List[Object]] = identity - def transformDef(implicit ctx: Context): PartialFunction[Def, List[Def]] = identity - def transformVal(implicit ctx: Context): PartialFunction[Val, List[Val]] = identity + def transformPackage(using Context): PartialFunction[Package, List[Package]] = identity + def transformTypeAlias(using Context): PartialFunction[TypeAlias, List[TypeAlias]] = identity + def transformClass(using Context): PartialFunction[Class, List[Class]] = identity + def transformCaseClass(using Context): PartialFunction[CaseClass, List[CaseClass]] = identity + def transformTrait(using Context): PartialFunction[Trait, List[Trait]] = identity + def transformObject(using Context): PartialFunction[Object, List[Object]] = identity + def transformDef(using Context): PartialFunction[Def, List[Def]] = identity + def transformVal(using Context): PartialFunction[Val, List[Val]] = identity - private[transform] def packageTransformation(p: Package)(implicit ctx: Context) = (transformPackage orElse identity)(p) - private[transform] def typeAliasTransformation(alias: TypeAlias)(implicit ctx: Context) = (transformTypeAlias orElse identity)(alias) - private[transform] def classTransformation(cls: Class)(implicit ctx: Context) = (transformClass orElse identity)(cls) - private[transform] def caseClassTransformation(cc: CaseClass)(implicit ctx: Context) = (transformCaseClass orElse identity)(cc) - private[transform] def traitTransformation(trt: Trait)(implicit ctx: Context) = (transformTrait orElse identity)(trt) - private[transform] def objectTransformation(obj: Object)(implicit ctx: Context) = (transformObject orElse identity)(obj) - private[transform] def defTransformation(df: Def)(implicit ctx: Context) = (transformDef orElse identity)(df) - private[transform] def valTransformation(vl: Val)(implicit ctx: Context) = (transformVal orElse identity)(vl) + private[transform] def packageTransformation(p: Package)(using Context) = (transformPackage orElse identity)(p) + private[transform] def typeAliasTransformation(alias: TypeAlias)(using Context) = (transformTypeAlias orElse identity)(alias) + private[transform] def classTransformation(cls: Class)(using Context) = (transformClass orElse identity)(cls) + private[transform] def caseClassTransformation(cc: CaseClass)(using Context) = (transformCaseClass orElse identity)(cc) + private[transform] def traitTransformation(trt: Trait)(using Context) = (transformTrait orElse identity)(trt) + private[transform] def objectTransformation(obj: Object)(using Context) = (transformObject orElse identity)(obj) + private[transform] def defTransformation(df: Def)(using Context) = (transformDef orElse identity)(df) + private[transform] def valTransformation(vl: Val)(using Context) = (transformVal orElse identity)(vl) } } diff --git a/doc-tool/src/dotty/tools/dottydoc/model/comment/Comment.scala b/doc-tool/src/dotty/tools/dottydoc/model/comment/Comment.scala index f7b8b1308127..619445cf8d3b 100644 --- a/doc-tool/src/dotty/tools/dottydoc/model/comment/Comment.scala +++ b/doc-tool/src/dotty/tools/dottydoc/model/comment/Comment.scala @@ -4,7 +4,7 @@ package model package comment import dotty.tools.dottydoc.util.syntax._ -import dotty.tools.dotc.core.Contexts.Context +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.util.Spans._ import com.vladsch.flexmark.util.ast.{ Node => MarkdownNode } import HtmlParsers._ @@ -62,14 +62,14 @@ trait MarkupConversion[T] extends MemberLookup { def span: Span def parsed: ParsedComment - protected def linkedExceptions(m: Map[String, String])(implicit ctx: Context): Map[String, String] - protected def stringToMarkup(str: String)(implicit ctx: Context): T - protected def markupToHtml(t: T)(implicit ctx: Context): String - protected def stringToShortHtml(str: String)(implicit ctx: Context): String - protected def filterEmpty(xs: List[String])(implicit ctx: Context): List[T] - protected def filterEmpty(xs: Map[String, String])(implicit ctx: Context): Map[String, T] + protected def linkedExceptions(m: Map[String, String])(using Context): Map[String, String] + protected def stringToMarkup(str: String)(using Context): T + protected def markupToHtml(t: T)(using Context): String + protected def stringToShortHtml(str: String)(using Context): String + protected def filterEmpty(xs: List[String])(using Context): List[T] + protected def filterEmpty(xs: Map[String, String])(using Context): Map[String, T] - private def single(annot: String, xs: List[String], filter: Boolean = true)(implicit ctx: Context): Option[T] = + private def single(annot: String, xs: List[String], filter: Boolean = true)(using Context): Option[T] = (if (filter) filterEmpty(xs) else xs.map(stringToMarkup)) match { case x :: xs => if (xs.nonEmpty) ctx.docbase.warn( @@ -80,7 +80,7 @@ trait MarkupConversion[T] extends MemberLookup { case _ => None } - final def comment(implicit ctx: Context): Comment = Comment( + final def comment(using Context): Comment = Comment( body = markupToHtml(stringToMarkup(parsed.body)), short = stringToShortHtml(parsed.body), authors = filterEmpty(parsed.authors).map(markupToHtml), @@ -107,16 +107,16 @@ trait MarkupConversion[T] extends MemberLookup { case class MarkdownComment(ent: Entity, parsed: ParsedComment, span: Span) extends MarkupConversion[MarkdownNode] { - def stringToMarkup(str: String)(implicit ctx: Context) = + def stringToMarkup(str: String)(using Context) = str.toMarkdown(ent) - def stringToShortHtml(str: String)(implicit ctx: Context) = + def stringToShortHtml(str: String)(using Context) = str.toMarkdown(ent).shortenAndShow - def markupToHtml(md: MarkdownNode)(implicit ctx: Context) = + def markupToHtml(md: MarkdownNode)(using Context) = md.show - def linkedExceptions(m: Map[String, String])(implicit ctx: Context) = { + def linkedExceptions(m: Map[String, String])(using Context) = { val inlineToHtml = InlineToHtml(ent) m.map { case (targetStr, body) => val link = makeEntityLink(ent, ctx.docbase.packages, Monospace(Text(targetStr)), targetStr) @@ -124,12 +124,12 @@ extends MarkupConversion[MarkdownNode] { } } - def filterEmpty(xs: List[String])(implicit ctx: Context) = + def filterEmpty(xs: List[String])(using Context) = xs.map(_.trim) .filterNot(_.isEmpty) .map(stringToMarkup) - def filterEmpty(xs: Map[String, String])(implicit ctx: Context) = + def filterEmpty(xs: Map[String, String])(using Context) = xs.transform((_, v) => v.trim) .filterNot { case (_, v) => v.isEmpty } .transform((_, v) => stringToMarkup(v)) @@ -138,25 +138,25 @@ extends MarkupConversion[MarkdownNode] { case class WikiComment(ent: Entity, parsed: ParsedComment, span: Span) extends MarkupConversion[Body] { - def filterEmpty(xs: Map[String,String])(implicit ctx: Context) = + def filterEmpty(xs: Map[String,String])(using Context) = xs.transform((_, v) => v.toWiki(ent, ctx.docbase.packages, span)) .filterNot { case (_, v) => v.blocks.isEmpty } - def filterEmpty(xs: List[String])(implicit ctx: Context) = + def filterEmpty(xs: List[String])(using Context) = xs.map(_.toWiki(ent, ctx.docbase.packages, span)) - def markupToHtml(t: Body)(implicit ctx: Context) = + def markupToHtml(t: Body)(using Context) = t.show(ent) - def stringToMarkup(str: String)(implicit ctx: Context) = + def stringToMarkup(str: String)(using Context) = str.toWiki(ent, ctx.docbase.packages, span) - def stringToShortHtml(str: String)(implicit ctx: Context) = { + def stringToShortHtml(str: String)(using Context) = { val parsed = stringToMarkup(str) parsed.summary.getOrElse(parsed).show(ent) } - def linkedExceptions(m: Map[String, String])(implicit ctx: Context) = { + def linkedExceptions(m: Map[String, String])(using Context) = { m.transform((_, v) => v.toWiki(ent, ctx.docbase.packages, span)).map { case (targetStr, body) => val link = lookup(Some(ent), ctx.docbase.packages, targetStr) val newBody = body match { diff --git a/doc-tool/src/dotty/tools/dottydoc/model/comment/CommentParser.scala b/doc-tool/src/dotty/tools/dottydoc/model/comment/CommentParser.scala index 28629098409d..a73ab94bc18e 100644 --- a/doc-tool/src/dotty/tools/dottydoc/model/comment/CommentParser.scala +++ b/doc-tool/src/dotty/tools/dottydoc/model/comment/CommentParser.scala @@ -5,7 +5,7 @@ package comment import dotty.tools.dottydoc.util.syntax._ import dotty.tools.dotc.util.Spans._ import dotty.tools.dotc.core.Symbols._ -import dotty.tools.dotc.core.Contexts.Context +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.printing.Formatting.hl import scala.collection.mutable @@ -31,7 +31,7 @@ trait CommentParser extends util.MemberLookup { src: String, span: Span, site: Symbol = NoSymbol - )(implicit ctx: Context): ParsedComment = { + )(using Context): ParsedComment = { /** Parses a comment (in the form of a list of lines) to a `Comment` * instance, recursively on lines. To do so, it splits the whole comment @@ -239,5 +239,5 @@ trait CommentParser extends util.MemberLookup { string: String, span: Span, site: Symbol - )(implicit ctx: Context): Body = new WikiParser(entity, packages, string, span, site).document() + )(using Context): Body = new WikiParser(entity, packages, string, span, site).document() } diff --git a/doc-tool/src/dotty/tools/dottydoc/model/comment/HtmlParsers.scala b/doc-tool/src/dotty/tools/dottydoc/model/comment/HtmlParsers.scala index 7245622eb970..f23b16fa1528 100644 --- a/doc-tool/src/dotty/tools/dottydoc/model/comment/HtmlParsers.scala +++ b/doc-tool/src/dotty/tools/dottydoc/model/comment/HtmlParsers.scala @@ -3,7 +3,7 @@ package dottydoc package model package comment -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.util.Spans._ import dotty.tools.dottydoc.util.syntax._ import util.MemberLookup @@ -16,7 +16,7 @@ import com.vladsch.flexmark.util.sequence.CharSubSequence object HtmlParsers { implicit class StringToMarkdown(val text: String) extends AnyVal { - def toMarkdown(origin: Entity)(implicit ctx: Context): MarkdownNode = { + def toMarkdown(origin: Entity)(using Context): MarkdownNode = { import com.vladsch.flexmark.ast.Link import com.vladsch.flexmark.util.ast.{Visitor, VisitHandler, NodeVisitor } @@ -59,15 +59,15 @@ object HtmlParsers { node } - def toMarkdownString(origin: Entity)(implicit ctx: Context): String = + def toMarkdownString(origin: Entity)(using Context): String = toMarkdown(origin).show } implicit class MarkdownToHtml(val markdown: MarkdownNode) extends AnyVal { - def show(implicit ctx: Context): String = + def show(using Context): String = HtmlRenderer.builder(staticsite.Site.markdownOptions).build().render(markdown) - def shortenAndShow(implicit ctx: Context): String = + def shortenAndShow(using Context): String = (new MarkdownShortener).shorten(markdown).show } diff --git a/doc-tool/src/dotty/tools/dottydoc/model/comment/WikiParser.scala b/doc-tool/src/dotty/tools/dottydoc/model/comment/WikiParser.scala index 04baa96a672c..b0cd50b5db4d 100644 --- a/doc-tool/src/dotty/tools/dottydoc/model/comment/WikiParser.scala +++ b/doc-tool/src/dotty/tools/dottydoc/model/comment/WikiParser.scala @@ -2,7 +2,7 @@ package dotty.tools.dottydoc package model package comment -import dotty.tools.dotc.core.Contexts.Context +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.util.Spans._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.config.Printers.dottydoc diff --git a/doc-tool/src/dotty/tools/dottydoc/model/factories.scala b/doc-tool/src/dotty/tools/dottydoc/model/factories.scala index 4906fc736b38..ef35cd440a7c 100644 --- a/doc-tool/src/dotty/tools/dottydoc/model/factories.scala +++ b/doc-tool/src/dotty/tools/dottydoc/model/factories.scala @@ -5,7 +5,7 @@ import references._ import dotty.tools.dotc import dotc.core.Types import Types._ -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Symbols.{ Symbol, ClassSymbol } import dotty.tools.dotc.core.SymDenotations._ @@ -19,7 +19,7 @@ object factories { type TypeTree = dotty.tools.dotc.ast.Trees.Tree[Type] - def flags(t: Tree)(implicit ctx: Context): List[String] = { + def flags(t: Tree)(using Context): List[String] = { val pw = t.symbol.privateWithin val pwStr = if (pw.exists) pw.name.show else "" (t.symbol.flags & (if (t.symbol.isType) TypeSourceModifierFlags else TermSourceModifierFlags)) @@ -29,7 +29,7 @@ object factories { .filter(_ != "case") } - def path(sym: Symbol)(implicit ctx: Context): List[String] = { + def path(sym: Symbol)(using Context): List[String] = { @tailrec def go(sym: Symbol, acc: List[String]): List[String] = if (sym.isRoot) acc @@ -38,14 +38,14 @@ object factories { go(sym, Nil) } - def annotations(sym: Symbol)(implicit ctx: Context): List[String] = + def annotations(sym: Symbol)(using Context): List[String] = sym.annotations.collect { case ann if ann.symbol != ctx.definitions.SourceFileAnnot => ann.symbol.showFullName } private val product = """Product[1-9][0-9]*""".r - def alias(t: Type)(implicit ctx: Context): Option[Reference] = { + def alias(t: Type)(using Context): Option[Reference] = { val defn = ctx.definitions t match { case TypeBounds(low, high) if (low eq defn.NothingType) && (high eq defn.AnyType) => @@ -54,7 +54,7 @@ object factories { } } - def returnType(t: Type)(implicit ctx: Context): Reference = { + def returnType(t: Type)(using Context): Reference = { val defn = ctx.definitions def typeRef(name: String, query: String = "", params: List[Reference] = Nil) = { @@ -138,7 +138,7 @@ object factories { expandTpe(t) } - def typeParams(sym: Symbol)(implicit ctx: Context): List[String] = + def typeParams(sym: Symbol)(using Context): List[String] = sym.info match { case pt: TypeLambda => // TODO: not sure if this case is needed anymore pt.paramNames.map(_.show.split("\\$").last) @@ -159,16 +159,16 @@ object factories { Nil } - def constructors(sym: Symbol)(implicit ctx: Context): List[List[ParamList]] = sym match { + def constructors(sym: Symbol)(using Context): List[List[ParamList]] = sym match { case sym: ClassSymbol => paramLists(sym.primaryConstructor.info) :: Nil case _ => Nil } - def traitParameters(sym: Symbol)(implicit ctx: Context): List[ParamList] = + def traitParameters(sym: Symbol)(using Context): List[ParamList] = constructors(sym).head - def paramLists(tpe: Type)(implicit ctx: Context): List[ParamList] = tpe match { + def paramLists(tpe: Type)(using Context): List[ParamList] = tpe match { case pt: TypeLambda => paramLists(pt.resultType) @@ -192,7 +192,7 @@ object factories { Nil // return types should not be in the paramlist } - def superTypes(t: Tree)(implicit ctx: Context): List[MaterializableLink] = t.symbol.denot match { + def superTypes(t: Tree)(using Context): List[MaterializableLink] = t.symbol.denot match { case cd: ClassDenotation => def isJavaLangObject(prefix: Type): Boolean = prefix match { diff --git a/doc-tool/src/dotty/tools/dottydoc/staticsite/BlogPost.scala b/doc-tool/src/dotty/tools/dottydoc/staticsite/BlogPost.scala index 9268199ca398..deadb7825241 100644 --- a/doc-tool/src/dotty/tools/dottydoc/staticsite/BlogPost.scala +++ b/doc-tool/src/dotty/tools/dottydoc/staticsite/BlogPost.scala @@ -5,7 +5,7 @@ package staticsite import java.io.{ File => JFile } import java.util.{ List => JList, Map => JMap } -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import util.syntax._ import MapOperations._ @@ -43,7 +43,7 @@ class BlogPost( object BlogPost { val extract = """(\d\d\d\d)-(\d\d)-(\d\d)-(.*)\.(md|html)""".r - def apply(file: JFile, page: Page)(implicit ctx: Context): Option[BlogPost] = { + def apply(file: JFile, page: Page)(using Context): Option[BlogPost] = { def report(key: String, fallback: String = "") = { ctx.docbase.error(s"couldn't find page.$key in ${file.getName}") fallback diff --git a/doc-tool/src/dotty/tools/dottydoc/staticsite/Page.scala b/doc-tool/src/dotty/tools/dottydoc/staticsite/Page.scala index e82812794344..eb288bf60185 100644 --- a/doc-tool/src/dotty/tools/dottydoc/staticsite/Page.scala +++ b/doc-tool/src/dotty/tools/dottydoc/staticsite/Page.scala @@ -11,7 +11,7 @@ import java.util.{ Map => JMap, List => JList } import java.io.{ OutputStreamWriter, BufferedWriter } import io.VirtualFile -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import model.Package import scala.io.Codec @@ -37,19 +37,19 @@ trait Page { def path: String /** YAML front matter from the top of the file */ - def yaml(implicit ctx: Context): Map[String, AnyRef] = { + def yaml(using Context): Map[String, AnyRef] = { if (_yaml eq null) initFields _yaml } /** HTML generated from page */ - def html(implicit ctx: Context): Option[String] = { + def html(using Context): Option[String] = { if (_html eq null) initFields _html } /** First paragraph of page extracted from rendered HTML */ - def firstParagraph(implicit ctx: Context): String = { + def firstParagraph(using Context): String = { if (_html eq null) initFields _html.map { _html => @@ -91,7 +91,7 @@ trait Page { protected[this] var _yaml: Map[String, AnyRef /* String | JList[String] */] = _ protected[this] var _html: Option[String] = _ - protected[this] def initFields(implicit ctx: Context) = { + protected[this] def initFields(using Context) = { val md = Parser.builder(Site.markdownOptions).build.parse(content) val yamlCollector = new AbstractYamlFrontMatterVisitor() yamlCollector.visit(md) @@ -160,7 +160,7 @@ class MarkdownPage( docs: Map[String, Package] ) extends Page { - override protected[this] def initFields(implicit ctx: Context) = { + override protected[this] def initFields(using Context) = { super.initFields _html = _html.map { _html => val md = Parser.builder(Site.markdownOptions).build.parse(_html) diff --git a/doc-tool/src/dotty/tools/dottydoc/staticsite/Site.scala b/doc-tool/src/dotty/tools/dottydoc/staticsite/Site.scala index 16cd22444787..7998dfcc9e9d 100644 --- a/doc-tool/src/dotty/tools/dottydoc/staticsite/Site.scala +++ b/doc-tool/src/dotty/tools/dottydoc/staticsite/Site.scala @@ -21,7 +21,7 @@ import com.vladsch.flexmark.ext.yaml.front.matter.YamlFrontMatterExtension import com.vladsch.flexmark.html.HtmlRenderer import com.vladsch.flexmark.util.options.{ DataHolder, MutableDataSet } -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.util.SourceFile import model.Package import scala.io.{ Codec, Source } @@ -57,7 +57,7 @@ case class Site( * @note files that are *not* considered static are files ending in a compilable * extension. */ - def staticAssets(implicit ctx: Context): Array[JFile] = { + def staticAssets(using Context): Array[JFile] = { if (_staticAssets eq null) initFiles _staticAssets } @@ -68,7 +68,7 @@ case class Site( * * @note files that are considered compilable end in `.md` or `.html` */ - def compilableFiles(implicit ctx: Context): Array[JFile] = { + def compilableFiles(using Context): Array[JFile] = { if (_compilableFiles eq null) initFiles _compilableFiles } @@ -81,7 +81,7 @@ case class Site( * * where `ext` is either markdown or html. */ - def blogposts(implicit ctx: Context): Array[JFile] = { + def blogposts(using Context): Array[JFile] = { if (_blogposts eq null) initFiles _blogposts } @@ -97,7 +97,7 @@ case class Site( .getOrElse(Sidebar.empty) private[this] var _blogInfo: Array[BlogPost] = _ - protected def blogInfo(implicit ctx: Context): Array[BlogPost] = { + protected def blogInfo(using Context): Array[BlogPost] = { if (_blogInfo eq null) { _blogInfo = blogposts @@ -131,7 +131,7 @@ case class Site( new SourceFile(virtualFile, Codec.UTF8) } - def copyStaticFiles()(implicit ctx: Context): this.type = + def copyStaticFiles()(using Context): this.type = createOutput { // Copy user-defined static assets staticAssets.foreach { asset => @@ -181,7 +181,7 @@ case class Site( ) /* Creates output directories if allowed */ - private def createOutput(op: => Unit)(implicit ctx: Context): this.type = { + private def createOutput(op: => Unit)(using Context): this.type = { if (!outDir.isDirectory) outDir.mkdirs() if (!outDir.isDirectory) ctx.docbase.error(s"couldn't create output folder: $outDir") else op @@ -189,7 +189,7 @@ case class Site( } /** Generate HTML for the API documentation */ - def generateApiDocs()(implicit ctx: Context): this.type = + def generateApiDocs()(using Context): this.type = createOutput { def genDoc(e: model.Entity): Unit = { ctx.docbase.echo(s"Generating doc page for: ${e.path.mkString(".")}") @@ -235,7 +235,7 @@ case class Site( } /** Generate HTML files from markdown and .html sources */ - def generateHtmlFiles()(implicit ctx: Context): this.type = + def generateHtmlFiles()(using Context): this.type = createOutput { compilableFiles.foreach { asset => val pathFromRoot = stripRoot(asset) @@ -255,7 +255,7 @@ case class Site( } /** Generate blog from files in `blog/_posts` and output in `outDir` */ - def generateBlog()(implicit ctx: Context): this.type = + def generateBlog()(using Context): this.type = createOutput { blogposts.foreach { file => val BlogPost.extract(year, month, day, name, ext) = file.getName @@ -280,7 +280,7 @@ case class Site( } /** Create directories and issue an error if could not */ - private def mkdirs(path: Path)(implicit ctx: Context): path.type = { + private def mkdirs(path: Path)(using Context): path.type = { val parent = path.getParent.toFile if (!parent.isDirectory && !parent.mkdirs()) @@ -307,7 +307,7 @@ case class Site( private[this] var _compilableFiles: Array[JFile] = _ private[this] var _blogposts: Array[JFile] = _ - private[this] def initFiles(implicit ctx: Context) = { + private[this] def initFiles(using Context) = { // Split files between compilable and static assets def splitFiles(f: JFile, assets: ArrayBuffer[JFile], comp: ArrayBuffer[JFile]): Unit = { val name = f.getName @@ -423,7 +423,7 @@ case class Site( /** Render a page to html, the resulting string is the result of the complete * expansion of the template with all its layouts and includes. */ - def render(page: Page, params: Map[String, AnyRef] = Map.empty)(implicit ctx: Context): Option[String] = + def render(page: Page, params: Map[String, AnyRef] = Map.empty)(using Context): Option[String] = page.yaml.get("layout").flatMap(xs => layouts.get(xs.toString)) match { case Some(layout) if page.html.isDefined => val newParams = page.params ++ params ++ Map("page" -> page.yaml) ++ Map("content" -> page.html.get) diff --git a/doc-tool/src/dotty/tools/dottydoc/staticsite/Template.scala b/doc-tool/src/dotty/tools/dottydoc/staticsite/Template.scala index 0c84f87c18bc..21175cc3a3b2 100644 --- a/doc-tool/src/dotty/tools/dottydoc/staticsite/Template.scala +++ b/doc-tool/src/dotty/tools/dottydoc/staticsite/Template.scala @@ -5,8 +5,9 @@ package staticsite import scala.util.control.NonFatal import dotc.util.SourceFile -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.util.Spans.Span +import dotc.report import util.syntax._ trait Template { @@ -45,7 +46,7 @@ case class LiquidTemplate(path: String, content: SourceFile) extends Template wi map } - private def protectedRender(op: => String)(implicit ctx: Context) = try { + private def protectedRender(op: => String)(using Context) = try { Some(op) } catch { case NonFatal(ex) => { @@ -67,7 +68,7 @@ case class LiquidTemplate(path: String, content: SourceFile) extends Template wi // mm.index is incorrect, let's compute the index manually // mm.line starts at 1, not 0 val index = content.lineToOffset(mm.line-1) + mm.charPositionInLine - ctx.error( + report.error( if (unexpected == "EOF") s"unexpected end of file, expected $expected" else @@ -84,7 +85,7 @@ case class LiquidTemplate(path: String, content: SourceFile) extends Template wi } } - def render(params: Map[String, AnyRef], includes: Map[String, Include])(implicit ctx: Context): Option[String] = + def render(params: Map[String, AnyRef], includes: Map[String, Include])(using Context): Option[String] = protectedRender { Template.parse(show, JEKYLL) .`with`(ResourceInclude(params, includes)) diff --git a/doc-tool/src/dotty/tools/dottydoc/staticsite/tags.scala b/doc-tool/src/dotty/tools/dottydoc/staticsite/tags.scala index 992e213f027c..084233c3bc4c 100644 --- a/doc-tool/src/dotty/tools/dottydoc/staticsite/tags.scala +++ b/doc-tool/src/dotty/tools/dottydoc/staticsite/tags.scala @@ -3,7 +3,7 @@ package dottydoc package staticsite import model.references._ -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import liqp.tags.Tag import liqp.TemplateContext @@ -19,7 +19,7 @@ object tags { def params: Map[String, AnyRef] private[this] var _baseurl: String = _ - def baseurl(implicit ctx: Context): String = { + def baseurl(using Context): String = { if (_baseurl eq null) { _baseurl = params.get("site").flatMap { @@ -40,7 +40,7 @@ object tags { /** Renders a `MaterializableLink` into a HTML anchor tag. If the link is * `NoLink` it will just return a string with the link's title. */ - final case class RenderLink(params: Map[String, AnyRef])(implicit ctx: Context) + final case class RenderLink(params: Map[String, AnyRef])(using Context) extends Tag("renderLink") with ParamConverter { override def render(tctx: TemplateContext, nodes: LNode*): AnyRef = nodes(0).render(tctx) match { case map: JMap[String, AnyRef] @unchecked => @@ -58,14 +58,14 @@ object tags { } - private[this] def renderLink(baseurl: String, link: MaterializableLink)(implicit ctx: Context): String = + private[this] def renderLink(baseurl: String, link: MaterializableLink)(using Context): String = link match { case MaterializedLink(title, target) => s"""<a href="$baseurl/api/$target">$title</a>""" case _ => link.title } - final case class RenderReference(params: Map[String, AnyRef])(implicit ctx: Context) + final case class RenderReference(params: Map[String, AnyRef])(using Context) extends Tag("renderRef") with ParamConverter { private def renderReference(ref: Reference): String = ref match { @@ -125,7 +125,7 @@ object tags { } } - case class ResourceInclude(params: Map[String, AnyRef], includes: Map[String, Include])(implicit ctx: Context) + case class ResourceInclude(params: Map[String, AnyRef], includes: Map[String, Include])(using Context) extends Tag("include") { import scala.collection.JavaConverters._ val DefaultExtension = ".html" @@ -160,7 +160,7 @@ object tags { * {% renderTitle title, page.url %} * ``` */ - case class RenderTitle(params: Map[String, AnyRef])(implicit ctx: Context) + case class RenderTitle(params: Map[String, AnyRef])(using Context) extends Tag("renderTitle") with ParamConverter { private def isParent(t: Title, htmlPath: String): Boolean = { t.url match { diff --git a/doc-tool/src/dotty/tools/dottydoc/util/syntax.scala b/doc-tool/src/dotty/tools/dottydoc/util/syntax.scala index 10e9b70c23af..36bcc7ba04db 100644 --- a/doc-tool/src/dotty/tools/dottydoc/util/syntax.scala +++ b/doc-tool/src/dotty/tools/dottydoc/util/syntax.scala @@ -2,7 +2,7 @@ package dotty.tools package dottydoc package util -import dotc.core.Contexts.Context +import dotc.core.Contexts.{Context, ctx} import dotc.core.Comments.{_, given _} import model.Package import core.ContextDottydoc @@ -20,7 +20,7 @@ object syntax { } implicit class SymbolExtensions(val sym: Symbol) extends AnyVal { - def sourcePosition(span: Span)(implicit ctx: Context): SourcePosition = + def sourcePosition(span: Span)(using Context): SourcePosition = sym.source.atSpan(span) } } diff --git a/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala b/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala index cfd3faeff9d7..e2d0b494100c 100644 --- a/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala +++ b/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala @@ -124,7 +124,7 @@ trait DottyDocTest extends MessageRendering { ctx.setSetting(ctx.settings.fromTasty, true) } val fromTastyCompiler = compilerWithChecker(assertion) - val fromTastyRun = fromTastyCompiler.newRun(fromTastyCtx) + val fromTastyRun = fromTastyCompiler.newRun(using fromTastyCtx) fromTastyRun.compile(classNames) assert(!fromTastyCtx.reporter.hasErrors) } diff --git a/docs/docs/contributing/debugging.md b/docs/docs/contributing/debugging.md index 6d26501f284a..6b52a88b2b95 100644 --- a/docs/docs/contributing/debugging.md +++ b/docs/docs/contributing/debugging.md @@ -363,4 +363,4 @@ trace.force(i"typing $tree", typr, show = true) { // ... ``` ### Reporter -Defined in [Reporter.scala](https://github.com/lampepfl/dotty/blob/10526a7d0aa8910729b6036ee51942e05b71abf6/compiler/src/dotty/tools/dotc/reporting/Reporter.scala). Enables calls such as `ctx.log`, `ctx.error` etc. To enable, run dotc with `-Ylog:typer` option. +Defined in [Reporter.scala](https://github.com/lampepfl/dotty/blob/10526a7d0aa8910729b6036ee51942e05b71abf6/compiler/src/dotty/tools/dotc/reporting/Reporter.scala). Enables calls such as `report.log`. To enable, run dotc with `-Ylog:typer` option. diff --git a/docs/docs/reference/changed-features/compiler-plugins.md b/docs/docs/reference/changed-features/compiler-plugins.md index 396576f57e27..92cb75e0d6bf 100644 --- a/docs/docs/reference/changed-features/compiler-plugins.md +++ b/docs/docs/reference/changed-features/compiler-plugins.md @@ -81,7 +81,7 @@ class DivideZeroPhase extends PluginPhase { tree match { case Apply(Select(rcvr, nme.DIV), List(Literal(Constant(0)))) if rcvr.tpe <:< defn.IntType => - ctx.error("dividing by zero", tree.pos) + report.error("dividing by zero", tree.pos) case _ => () } @@ -90,7 +90,7 @@ class DivideZeroPhase extends PluginPhase { } ``` -The plugin main class (`DivideZero`) must extend the trait `StandardPlugin` +The plugin main class (`DivideZero`) must extend the trait `StandardPlugin` and implement the method `init` that takes the plugin's options as argument and returns a list of `PluginPhase`s to be inserted into the compilation pipeline. diff --git a/docs/docs/reference/changed-features/numeric-literals.md b/docs/docs/reference/changed-features/numeric-literals.md index 86f736320c5d..9678a9616d87 100644 --- a/docs/docs/reference/changed-features/numeric-literals.md +++ b/docs/docs/reference/changed-features/numeric-literals.md @@ -226,8 +226,7 @@ strings `fromDigitsImpl(digits)` is simply `apply(digits)`, i.e. everything is evaluated at runtime in this case. The interesting part is the `catch` part of the case where `digits` is constant. -If the `apply` method throws a `FromDigitsException`, the exception's message is issued as a compile time error -in the `ctx.error(ex.getMessage)` call. +If the `apply` method throws a `FromDigitsException`, the exception's message is issued as a compile time error in the `ctx.error(ex.getMessage)` call. With this new implementation, a definition like ```scala diff --git a/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala b/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala index 1035633896a0..277f80428cc5 100644 --- a/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala +++ b/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala @@ -298,7 +298,7 @@ class DottyLanguageServer extends LanguageServer /*thisServer.synchronized*/ {} } - // FIXME: share code with messages.NotAMember + // FIXME: share code with NotAMember override def completion(params: CompletionParams) = computeAsync { cancelToken => val uri = new URI(params.getTextDocument.getUri) val driver = driverFor(uri) @@ -732,7 +732,7 @@ object DottyLanguageServer { private def displayMessage(message: Message, sourceFile: SourceFile)(implicit ctx: Context): Boolean = { if (isWorksheet(sourceFile)) { message match { - case msg: messages.PureExpressionInStatementPosition => + case msg: PureExpressionInStatementPosition => val ownerSym = if (msg.exprOwner.isLocalDummy) msg.exprOwner.owner else msg.exprOwner !isWorksheetWrapper(ownerSym) case _ => diff --git a/sbt-bridge/src/xsbt/DelegatingReporter.java b/sbt-bridge/src/xsbt/DelegatingReporter.java index c90e5882d69c..1a6f778c8590 100644 --- a/sbt-bridge/src/xsbt/DelegatingReporter.java +++ b/sbt-bridge/src/xsbt/DelegatingReporter.java @@ -15,7 +15,6 @@ import dotty.tools.dotc.util.SourcePosition; import dotty.tools.dotc.reporting.*; import dotty.tools.dotc.reporting.Message; -import dotty.tools.dotc.reporting.messages; import dotty.tools.dotc.core.Contexts.*; import static dotty.tools.dotc.reporting.Diagnostic.*; diff --git a/sbt-dotty/sbt-test/sbt-dotty/analyzer-plugin/plugin/Analyzer.scala b/sbt-dotty/sbt-test/sbt-dotty/analyzer-plugin/plugin/Analyzer.scala index e88ba308e215..adf1105f4f73 100644 --- a/sbt-dotty/sbt-test/sbt-dotty/analyzer-plugin/plugin/Analyzer.scala +++ b/sbt-dotty/sbt-test/sbt-dotty/analyzer-plugin/plugin/Analyzer.scala @@ -34,7 +34,7 @@ class InitChecker extends PluginPhase { private def checkDef(tree: Tree)(implicit ctx: Context): Tree = { if (tree.symbol.defTree.isEmpty) - ctx.error("cannot get tree for " + tree.show, tree.sourcePos) + report.error("cannot get tree for " + tree.show, tree.sourcePos) tree } @@ -51,17 +51,17 @@ class InitChecker extends PluginPhase { if (enclosingPkg == helloPkgSym) { // source code checkDef(tree) - ctx.warning("tree: " + tree.symbol.defTree.show) + report.warning("tree: " + tree.symbol.defTree.show) } else if (enclosingPkg == libPkgSym) { // tasty from library checkDef(tree) // check that all sub-definitions have trees set properly // make sure that are no cycles in the code transformAllDeep(tree.symbol.defTree) - ctx.warning("tree: " + tree.symbol.defTree.show) + report.warning("tree: " + tree.symbol.defTree.show) } else { - ctx.warning(s"${tree.symbol} is neither in lib nor hello, owner = $enclosingPkg", tree.sourcePos) + report.warning(s"${tree.symbol} is neither in lib nor hello, owner = $enclosingPkg", tree.sourcePos) } tree } diff --git a/sbt-dotty/sbt-test/sbt-dotty/compiler-plugin/plugin/DivideZero.scala b/sbt-dotty/sbt-test/sbt-dotty/compiler-plugin/plugin/DivideZero.scala index feadac22115f..ed9b5b83c6ea 100644 --- a/sbt-dotty/sbt-test/sbt-dotty/compiler-plugin/plugin/DivideZero.scala +++ b/sbt-dotty/sbt-test/sbt-dotty/compiler-plugin/plugin/DivideZero.scala @@ -33,7 +33,7 @@ class DivideZero extends PluginPhase with StandardPlugin { override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = tree match { case tpd.Apply(fun, tpd.Literal(Constants.Constant(v)) :: Nil) if isNumericDivide(fun.symbol) && v == 0 => - ctx.error("divide by zero", tree.sourcePos) + report.error("divide by zero", tree.sourcePos) tpd.Literal(Constant(0)) case _ => tree diff --git a/staging/src/scala/quoted/staging/QuoteCompiler.scala b/staging/src/scala/quoted/staging/QuoteCompiler.scala index 9275bb672dc4..4cda6a7f5cc8 100644 --- a/staging/src/scala/quoted/staging/QuoteCompiler.scala +++ b/staging/src/scala/quoted/staging/QuoteCompiler.scala @@ -12,7 +12,7 @@ import dotty.tools.dotc.core.Names.TypeName import dotty.tools.dotc.core.Phases.Phase import dotty.tools.dotc.core.Scopes.{EmptyScope, newScope} import dotty.tools.dotc.core.StdNames.nme -import dotty.tools.dotc.core.Symbols.defn +import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Types.ExprType import dotty.tools.dotc.core.quoted.PickledQuotes import dotty.tools.dotc.tastyreflect.ReflectionImpl @@ -62,10 +62,10 @@ private class QuoteCompiler extends Compiler: // Places the contents of expr in a compilable tree for a class with the following format. // `package __root__ { class ' { def apply: Any = <expr> } }` - val cls = unitCtx.newCompleteClassSymbol(defn.RootClass, outputClassName, EmptyFlags, + val cls = newCompleteClassSymbol(defn.RootClass, outputClassName, EmptyFlags, defn.ObjectType :: Nil, newScope, coord = pos, assocFile = assocFile).entered.asClass - cls.enter(unitCtx.newDefaultConstructor(cls), EmptyScope) - val meth = unitCtx.newSymbol(cls, nme.apply, Method, ExprType(defn.AnyType), coord = pos).entered + cls.enter(newDefaultConstructor(cls), EmptyScope) + val meth = newSymbol(cls, nme.apply, Method, ExprType(defn.AnyType), coord = pos).entered val quoted = given Context = unitCtx.withOwner(meth) diff --git a/tests/plugins/custom/analyzer/Analyzer_1.scala b/tests/plugins/custom/analyzer/Analyzer_1.scala index 06262656786a..6faecc2ff2f9 100644 --- a/tests/plugins/custom/analyzer/Analyzer_1.scala +++ b/tests/plugins/custom/analyzer/Analyzer_1.scala @@ -16,7 +16,7 @@ import Phases.Phase import ast.tpd import transform.MegaPhase.MiniPhase import Decorators._ -import Symbols.Symbol +import Symbols.{Symbol, requiredPackage} import Constants.Constant import Types._ import transform.{ReifyQuotes, FirstTransform} @@ -56,7 +56,7 @@ class InitChecker extends PluginPhase with StandardPlugin { private def checkDef(tree: Tree)(implicit ctx: Context): Tree = { if (tree.symbol.defTree.isEmpty) - ctx.error("cannot get tree for " + tree.show, tree.sourcePos) + report.error("cannot get tree for " + tree.show, tree.sourcePos) tree } @@ -67,23 +67,23 @@ class InitChecker extends PluginPhase with StandardPlugin { private def checkRef(tree: Tree)(implicit ctx: Context): Tree = if (!checkable(tree.symbol)) tree else { - val helloPkgSym = ctx.requiredPackage("hello").moduleClass - val libPkgSym = ctx.requiredPackage("lib").moduleClass + val helloPkgSym = requiredPackage("hello").moduleClass + val libPkgSym = requiredPackage("lib").moduleClass val enclosingPkg = tree.symbol.enclosingPackageClass if (enclosingPkg == helloPkgSym) { // source code checkDef(tree) - ctx.warning("tree: " + tree.symbol.defTree.show) + report.warning("tree: " + tree.symbol.defTree.show) } else if (enclosingPkg == libPkgSym) { // tasty from library checkDef(tree) // check that all sub-definitions have trees set properly // make sure that are no cycles in the code transformAllDeep(tree.symbol.defTree) - ctx.warning("tree: " + tree.symbol.defTree.show) + report.warning("tree: " + tree.symbol.defTree.show) } else { - ctx.warning(tree.symbol.toString + " is neither in lib nor hello, owner = " + enclosingPkg, tree.sourcePos) + report.warning(tree.symbol.toString + " is neither in lib nor hello, owner = " + enclosingPkg, tree.sourcePos) } tree } diff --git a/tests/plugins/neg/divideZero-research/plugin_1.scala b/tests/plugins/neg/divideZero-research/plugin_1.scala index 45ef30a41150..411d01e7d26b 100644 --- a/tests/plugins/neg/divideZero-research/plugin_1.scala +++ b/tests/plugins/neg/divideZero-research/plugin_1.scala @@ -6,7 +6,7 @@ import Phases.Phase import ast.tpd import transform.MegaPhase.MiniPhase import Decorators._ -import Symbols.Symbol +import Symbols.{Symbol, requiredClass} import Constants.Constant import StdNames._ @@ -23,14 +23,14 @@ class DivideZero extends MiniPhase with ResearchPlugin { private def isNumericDivide(sym: Symbol)(implicit ctx: Context): Boolean = { def test(tpe: String): Boolean = - (sym.owner eq ctx.requiredClass(tpe)) && sym.name == nme.DIV + (sym.owner eq requiredClass(tpe)) && sym.name == nme.DIV test("scala.Int") || test("scala.Long") || test("scala.Short") || test("scala.Float") || test("scala.Double") } override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = tree match { case tpd.Apply(fun, tpd.Literal(Constants.Constant(v)) :: Nil) if isNumericDivide(fun.symbol) && v == 0 => - ctx.error("divide by zero", tree.sourcePos) + report.error("divide by zero", tree.sourcePos) tree case _ => tree diff --git a/tests/plugins/neg/divideZero/plugin_1.scala b/tests/plugins/neg/divideZero/plugin_1.scala index 4401c849bcf7..764221aeafca 100644 --- a/tests/plugins/neg/divideZero/plugin_1.scala +++ b/tests/plugins/neg/divideZero/plugin_1.scala @@ -6,7 +6,7 @@ import Phases.Phase import ast.tpd import transform.MegaPhase.MiniPhase import Decorators._ -import Symbols.Symbol +import Symbols.{Symbol, requiredClass} import Constants.Constant import transform.{Pickler, ReifyQuotes} import StdNames._ @@ -24,14 +24,14 @@ class DivideZero extends PluginPhase with StandardPlugin { private def isNumericDivide(sym: Symbol)(implicit ctx: Context): Boolean = { def test(tpe: String): Boolean = - (sym.owner eq ctx.requiredClass(tpe)) && sym.name == nme.DIV + (sym.owner eq requiredClass(tpe)) && sym.name == nme.DIV test("scala.Int") || test("scala.Long") || test("scala.Short") || test("scala.Float") || test("scala.Double") } override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = tree match { case tpd.Apply(fun, tpd.Literal(Constants.Constant(v)) :: Nil) if isNumericDivide(fun.symbol) && v == 0 => - ctx.error("divide by zero", tree.sourcePos) + report.error("divide by zero", tree.sourcePos) tree case _ => tree From f2d88429eb3e73c2d80920b33c8eb061966ae22f Mon Sep 17 00:00:00 2001 From: Martin Odersky <odersky@gmail.com> Date: Thu, 16 Jul 2020 11:59:41 +0200 Subject: [PATCH 05/10] Simplify context handling - Use only wildcard imports from Contexts - Use `(using Context)` throughout --- .../tools/backend/jvm/BCodeBodyBuilder.scala | 2 +- .../tools/backend/jvm/BCodeHelpers.scala | 4 +- .../tools/backend/jvm/BTypesFromSymbols.scala | 2 +- .../tools/backend/jvm/CollectSuperCalls.scala | 2 +- .../backend/jvm/DottyBackendInterface.scala | 2 +- .../dotty/tools/backend/jvm/GenBCode.scala | 2 +- .../tools/backend/jvm/scalaPrimitives.scala | 2 +- compiler/src/dotty/tools/dotc/Bench.scala | 2 +- .../dotty/tools/dotc/CompilationUnit.scala | 2 +- compiler/src/dotty/tools/dotc/Driver.scala | 2 +- compiler/src/dotty/tools/dotc/Resident.scala | 2 +- .../dotty/tools/dotc/ast/NavigateAST.scala | 2 +- .../src/dotty/tools/dotc/ast/Positioned.scala | 2 +- .../dotc/classpath/ClassPathFactory.scala | 2 +- .../ZipAndJarFileLookupFactory.scala | 2 +- .../tools/dotc/config/ScalaSettings.scala | 2 +- .../tools/dotc/config/SourceVersion.scala | 2 +- .../tools/dotc/core/GadtConstraint.scala | 2 +- .../tools/dotc/core/JavaNullInterop.scala | 2 +- .../src/dotty/tools/dotc/core/NameKinds.scala | 2 +- .../tools/dotc/core/NullOpsDecorator.scala | 2 +- .../src/dotty/tools/dotc/core/ParamInfo.scala | 2 +- .../tools/dotc/core/SymDenotations.scala | 4 +- .../dotc/core/tasty/CommentPickler.scala | 2 +- .../tools/dotc/fromtasty/TastyFileUtil.scala | 2 +- .../tools/dotc/interactive/Completion.scala | 2 +- .../tools/dotc/printing/Highlighting.scala | 2 +- .../tools/dotc/printing/MessageLimiter.scala | 2 +- .../tools/dotc/printing/RefinedPrinter.scala | 2 +- .../dotc/printing/SyntaxHighlighting.scala | 2 +- .../tools/dotc/profile/AsyncHelper.scala | 2 +- .../dotty/tools/dotc/profile/Profiler.scala | 2 +- .../tools/dotc/quoted/QuoteContext.scala | 2 +- .../tools/dotc/reporting/Diagnostic.scala | 2 +- .../reporting/HideNonSensicalMessages.scala | 2 +- .../dotc/reporting/MessageRendering.scala | 2 +- .../tools/dotc/reporting/StoreReporter.scala | 2 +- .../dotc/reporting/ThrowingReporter.scala | 2 +- .../reporting/UniqueMessagePositions.scala | 2 +- .../dotty/tools/dotc/reporting/messages.scala | 24 +- .../dotty/tools/dotc/reporting/trace.scala | 2 +- .../dotty/tools/dotc/rewrites/Rewrites.scala | 2 +- .../dotty/tools/dotc/semanticdb/Scala3.scala | 2 +- .../tools/dotc/tastyreflect/FromSymbol.scala | 2 +- .../ReflectionCompilerInterface.scala | 855 +++++++++--------- .../tools/dotc/tastyreflect/package.scala | 2 +- .../tools/dotc/transform/AccessProxies.scala | 2 +- .../tools/dotc/transform/ArrayApply.scala | 2 +- .../dotc/transform/ArrayConstructors.scala | 2 +- .../dotc/transform/AugmentScala2Traits.scala | 2 +- .../tools/dotc/transform/BetaReduce.scala | 6 +- .../tools/dotc/transform/CheckReentrant.scala | 2 +- .../tools/dotc/transform/CheckStatic.scala | 2 +- .../transform/CollectNullableFields.scala | 2 +- .../dotc/transform/CompleteJavaEnums.scala | 2 +- .../tools/dotc/transform/Constructors.scala | 2 +- .../tools/dotc/transform/CookComments.scala | 2 +- .../dotc/transform/CountOuterAccesses.scala | 2 +- .../tools/dotc/transform/CrossCastAnd.scala | 2 +- .../dotty/tools/dotc/transform/CtxLazy.scala | 2 +- .../DropEmptyCompanions.scala.disabled | 2 +- .../dotc/transform/DropOuterAccessors.scala | 2 +- .../tools/dotc/transform/ElimOpaque.scala | 2 +- .../dotc/transform/ElimOuterSelect.scala | 2 +- .../tools/dotc/transform/ElimRepeated.scala | 2 +- .../tools/dotc/transform/ElimStaticThis.scala | 2 +- .../tools/dotc/transform/ExpandPrivate.scala | 2 +- .../tools/dotc/transform/ExplicitSelf.scala | 2 +- .../dotty/tools/dotc/transform/Flatten.scala | 2 +- .../transform/FunctionXXLForwarders.scala | 2 +- .../dotty/tools/dotc/transform/Getters.scala | 2 +- .../tools/dotc/transform/InlinePatterns.scala | 4 +- .../dotc/transform/Instrumentation.scala | 2 +- .../IsInstanceOfEvaluator.scala.disabled | 2 +- .../dotty/tools/dotc/transform/LazyVals.scala | 2 +- .../tools/dotc/transform/LetOverApply.scala | 2 +- .../dotc/transform/LinkScala2Impls.scala | 2 +- .../dotty/tools/dotc/transform/Memoize.scala | 2 +- .../dotty/tools/dotc/transform/Mixin.scala | 2 +- .../tools/dotc/transform/MoveStatics.scala | 2 +- .../dotc/transform/ProtectedAccessors.scala | 2 +- .../tools/dotc/transform/ReifyQuotes.scala | 4 +- .../tools/dotc/transform/RenameLifted.scala | 2 +- .../tools/dotc/transform/ResolveSuper.scala | 2 +- .../tools/dotc/transform/RestoreScopes.scala | 2 +- .../tools/dotc/transform/SelectStatic.scala | 2 +- .../tools/dotc/transform/SeqLiterals.scala | 2 +- .../tools/dotc/transform/SetRootTree.scala | 2 +- .../dotty/tools/dotc/transform/TailRec.scala | 2 +- .../dotc/transform/TryCatchPatterns.scala | 2 +- .../dotc/transform/TupleOptimizations.scala | 2 +- .../tools/dotc/transform/TypeTestsCasts.scala | 2 +- .../tools/dotc/transform/init/Checker.scala | 2 +- .../tools/dotc/transform/init/Checking.scala | 2 +- .../dotty/tools/dotc/transform/init/Env.scala | 2 +- .../dotc/transform/init/SetDefTree.scala | 2 +- .../dotc/transform/init/Summarization.scala | 2 +- .../tools/dotc/transform/init/Summary.scala | 2 +- .../tools/dotc/transform/init/Util.scala | 2 +- .../localopt/StringInterpolatorOpt.scala | 2 +- .../src/dotty/tools/dotc/typer/Dynamic.scala | 2 +- .../src/dotty/tools/dotc/typer/Inliner.scala | 2 +- .../dotty/tools/dotc/util/ParsedComment.scala | 2 +- .../dotty/tools/dotc/util/Signatures.scala | 2 +- .../dotty/tools/dotc/util/SourceFile.scala | 2 +- .../tools/repl/CollectTopLevelImports.scala | 2 +- .../src/dotty/tools/repl/JLineTerminal.scala | 2 +- .../src/dotty/tools/repl/ParseResult.scala | 2 +- compiler/src/dotty/tools/repl/Rendering.scala | 2 +- .../src/dotty/tools/repl/ReplFrontEnd.scala | 2 +- 110 files changed, 554 insertions(+), 553 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala index df791164c5da..2350efca074a 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala @@ -19,7 +19,7 @@ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.transform.Erasure import dotty.tools.dotc.transform.SymUtils._ import dotty.tools.dotc.util.Spans._ -import dotty.tools.dotc.core.Contexts.{inContext, atPhase} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Phases._ import dotty.tools.dotc.report diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index 6516cbf95d73..5e13a9b4964b 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala @@ -13,7 +13,7 @@ import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.ast.Trees import dotty.tools.dotc.core.Annotations._ import dotty.tools.dotc.core.Constants._ -import dotty.tools.dotc.core.Contexts.{Context, atPhase} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Phases._ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Flags._ @@ -927,7 +927,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { throw new RuntimeException(msg) } - private def compilingArray(using ctx: Context) = + private def compilingArray(using Context) = ctx.compilationUnit.source.file.name == "Array.scala" } diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index 8b1abe032249..beea05e0dcc1 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala @@ -8,7 +8,7 @@ import scala.collection.mutable import scala.collection.generic.Clearable import dotty.tools.dotc.core.Flags._ -import dotty.tools.dotc.core.Contexts.{inContext, atPhase} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Phases._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Phases.Phase diff --git a/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala b/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala index 82aed9648aba..35bc25693d10 100644 --- a/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala +++ b/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala @@ -1,7 +1,7 @@ package dotty.tools.backend.jvm import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Phases._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Flags.Trait diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index 1e253df10d5f..2458de77ba9c 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -197,7 +197,7 @@ object DottyBackendInterface { * True if the current compilation unit is of a primitive class (scala.Boolean et al). * Used only in assertions. */ - def isCompilingPrimitive(using ctx: Context) = { + def isCompilingPrimitive(using Context) = { primitiveCompilationUnits(ctx.compilationUnit.source.file.name) } diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index 52138552bae4..8b5694ecff7a 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -75,7 +75,7 @@ object GenBCode { val name: String = "genBCode" } -class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) extends BCodeSyncAndTry { +class GenBCodePipeline(val int: DottyBackendInterface)(using Context) extends BCodeSyncAndTry { import DottyBackendInterface.symExtensions private var tree: Tree = _ diff --git a/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala b/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala index ff8d49945a48..018108834cf6 100644 --- a/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala +++ b/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala @@ -4,7 +4,7 @@ package backend.jvm import dotc.ast.Trees.Select import dotc.ast.tpd._ import dotc.core._ -import Contexts.{Context, ctx} +import Contexts._ import Names.TermName, StdNames._ import Types.{JavaArrayType, UnspecifiedErrorType, Type} import Symbols.{Symbol, NoSymbol} diff --git a/compiler/src/dotty/tools/dotc/Bench.scala b/compiler/src/dotty/tools/dotc/Bench.scala index 568503e4d783..ceb945004844 100644 --- a/compiler/src/dotty/tools/dotc/Bench.scala +++ b/compiler/src/dotty/tools/dotc/Bench.scala @@ -1,7 +1,7 @@ package dotty.tools package dotc -import core.Contexts.{Context, ctx} +import core.Contexts._ import reporting.Reporter import scala.annotation.internal.sharable diff --git a/compiler/src/dotty/tools/dotc/CompilationUnit.scala b/compiler/src/dotty/tools/dotc/CompilationUnit.scala index 58b4d97f131e..ee6e64acc33b 100644 --- a/compiler/src/dotty/tools/dotc/CompilationUnit.scala +++ b/compiler/src/dotty/tools/dotc/CompilationUnit.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc import core._ -import Contexts.{Context, ctx} +import Contexts._ import SymDenotations.ClassDenotation import Symbols._ import util.{FreshNameCreator, SourceFile, NoSource} diff --git a/compiler/src/dotty/tools/dotc/Driver.scala b/compiler/src/dotty/tools/dotc/Driver.scala index 9388f0f7bb75..4604103d93cd 100644 --- a/compiler/src/dotty/tools/dotc/Driver.scala +++ b/compiler/src/dotty/tools/dotc/Driver.scala @@ -5,7 +5,7 @@ import java.nio.file.{Files, Paths} import dotty.tools.FatalError import config.CompilerCommand import core.Comments.{ContextDoc, ContextDocstrings} -import core.Contexts.{Context, ContextBase, inContext, ctx} +import core.Contexts._ import core.{MacroClassLoader, Mode, TypeError} import core.StdNames.nme import dotty.tools.dotc.ast.Positioned diff --git a/compiler/src/dotty/tools/dotc/Resident.scala b/compiler/src/dotty/tools/dotc/Resident.scala index 116011942bd4..889b31ba4e76 100644 --- a/compiler/src/dotty/tools/dotc/Resident.scala +++ b/compiler/src/dotty/tools/dotc/Resident.scala @@ -1,7 +1,7 @@ package dotty.tools package dotc -import core.Contexts.{Context, ctx, inContext} +import core.Contexts._ import reporting.Reporter import java.io.EOFException import scala.annotation.tailrec diff --git a/compiler/src/dotty/tools/dotc/ast/NavigateAST.scala b/compiler/src/dotty/tools/dotc/ast/NavigateAST.scala index ffb1ac3b5c80..ffc7d04faa52 100644 --- a/compiler/src/dotty/tools/dotc/ast/NavigateAST.scala +++ b/compiler/src/dotty/tools/dotc/ast/NavigateAST.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc package ast -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Decorators._ import util.Spans._ import Trees.{MemberDef, DefTree, WithLazyField} diff --git a/compiler/src/dotty/tools/dotc/ast/Positioned.scala b/compiler/src/dotty/tools/dotc/ast/Positioned.scala index 28690a242417..0629950e7b3b 100644 --- a/compiler/src/dotty/tools/dotc/ast/Positioned.scala +++ b/compiler/src/dotty/tools/dotc/ast/Positioned.scala @@ -4,7 +4,7 @@ package ast import util.Spans._ import util.{SourceFile, NoSource, SourcePosition} -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Decorators._ import core.Flags.{JavaDefined, Extension} import core.StdNames.nme diff --git a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala index 81cd18657da2..66ae5b1ceb1e 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala @@ -6,7 +6,7 @@ package dotty.tools.dotc.classpath import dotty.tools.io.{AbstractFile, VirtualDirectory} import FileUtils.AbstractFileOps import dotty.tools.io.ClassPath -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ /** * Provides factory methods for classpath. When creating classpath instances for a given path, diff --git a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala index 75dcdf3c1979..3b4c79feda0d 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala @@ -10,7 +10,7 @@ import java.nio.file.attribute.{BasicFileAttributes, FileTime} import scala.annotation.tailrec import dotty.tools.io.{AbstractFile, ClassPath, ClassRepresentation, FileZipArchive, ManifestResources} -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import FileUtils._ /** diff --git a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala index 2e30ec911974..f875452c7252 100644 --- a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala +++ b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc package config -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.io.{ Directory, PlainDirectory, AbstractFile } import PathResolver.Defaults import rewrites.Rewrites diff --git a/compiler/src/dotty/tools/dotc/config/SourceVersion.scala b/compiler/src/dotty/tools/dotc/config/SourceVersion.scala index c30780527c62..cc9221bad6cf 100644 --- a/compiler/src/dotty/tools/dotc/config/SourceVersion.scala +++ b/compiler/src/dotty/tools/dotc/config/SourceVersion.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package config -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Names.TermName import core.StdNames.nme import core.Decorators.{given _} diff --git a/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala b/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala index c598cea81a13..6d7bd9f1c302 100644 --- a/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala +++ b/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala @@ -217,7 +217,7 @@ final class ProperGadtConstraint private( // ---- Protected/internal ----------------------------------------------- - override def comparerCtx(using ctx: Context): Context = ctx + override def comparerCtx(using Context): Context = ctx override protected def constraint = myConstraint override protected def constraint_=(c: Constraint) = myConstraint = c diff --git a/compiler/src/dotty/tools/dotc/core/JavaNullInterop.scala b/compiler/src/dotty/tools/dotc/core/JavaNullInterop.scala index 1a64389bab82..8d6e2552bb32 100644 --- a/compiler/src/dotty/tools/dotc/core/JavaNullInterop.scala +++ b/compiler/src/dotty/tools/dotc/core/JavaNullInterop.scala @@ -1,6 +1,6 @@ package dotty.tools.dotc.core -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Flags.JavaDefined import dotty.tools.dotc.core.StdNames.{jnme, nme} import dotty.tools.dotc.core.Symbols._ diff --git a/compiler/src/dotty/tools/dotc/core/NameKinds.scala b/compiler/src/dotty/tools/dotc/core/NameKinds.scala index 8b5f6e6d326c..ef9e62d113a8 100644 --- a/compiler/src/dotty/tools/dotc/core/NameKinds.scala +++ b/compiler/src/dotty/tools/dotc/core/NameKinds.scala @@ -6,7 +6,7 @@ import Names._ import NameOps._ import StdNames._ import NameTags._ -import Contexts.{Context, ctx} +import Contexts._ import collection.mutable import scala.annotation.internal.sharable diff --git a/compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala b/compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala index e14c331ee3f6..1f138213dde4 100644 --- a/compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala +++ b/compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala @@ -1,6 +1,6 @@ package dotty.tools.dotc.core -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Symbols.defn import dotty.tools.dotc.core.Types._ diff --git a/compiler/src/dotty/tools/dotc/core/ParamInfo.scala b/compiler/src/dotty/tools/dotc/core/ParamInfo.scala index 449a30c684b5..e88d6540e64b 100644 --- a/compiler/src/dotty/tools/dotc/core/ParamInfo.scala +++ b/compiler/src/dotty/tools/dotc/core/ParamInfo.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc.core import Names.Name -import Contexts.{Context, ctx} +import Contexts._ import Types.Type import Variances.{Variance, varianceToInt} diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index c71c81eaed1b..96f578a50af5 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -300,7 +300,7 @@ object SymDenotations { * Makes use of `rawParamss` when present, or constructs fresh parameter symbols otherwise. * This method can be allocation-heavy. */ - final def paramSymss(using ctx: Context): List[List[Symbol]] = + final def paramSymss(using Context): List[List[Symbol]] = def recurWithParamss(info: Type, paramss: List[List[Symbol]]): List[List[Symbol]] = info match @@ -1446,7 +1446,7 @@ object SymDenotations { privateWithin: Symbol = null, annotations: List[Annotation] = null, rawParamss: List[List[Symbol]] = null)( - using ctx: Context): SymDenotation = { + using Context): SymDenotation = { // simulate default parameters, while also passing implicit context ctx to the default values val initFlags1 = (if (initFlags != UndefinedFlags) initFlags else this.flags) val info1 = if (info != null) info else this.info diff --git a/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala index aaea6a8212d8..4ef513d731df 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc.core.tasty import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.core.Comments.{Comment, CommentsContext, ContextDocstrings} -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.tasty.TastyBuffer import TastyBuffer.{Addr, NoAddr} diff --git a/compiler/src/dotty/tools/dotc/fromtasty/TastyFileUtil.scala b/compiler/src/dotty/tools/dotc/fromtasty/TastyFileUtil.scala index 8054387d27cc..e92ebc4a6eed 100644 --- a/compiler/src/dotty/tools/dotc/fromtasty/TastyFileUtil.scala +++ b/compiler/src/dotty/tools/dotc/fromtasty/TastyFileUtil.scala @@ -4,7 +4,7 @@ package fromtasty import java.nio.file.{Files, Path, Paths} import java.io -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.NameKinds import dotty.tools.dotc.core.Names.SimpleName import dotty.tools.dotc.core.StdNames.nme diff --git a/compiler/src/dotty/tools/dotc/interactive/Completion.scala b/compiler/src/dotty/tools/dotc/interactive/Completion.scala index d44c4b710a61..f0ab6d176229 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Completion.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Completion.scala @@ -5,7 +5,7 @@ import java.nio.charset.Charset import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.untpd import dotty.tools.dotc.config.Printers.interactiv -import dotty.tools.dotc.core.Contexts.{Context, NoContext, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.CheckRealizable import dotty.tools.dotc.core.Decorators.StringInterpolators import dotty.tools.dotc.core.Denotations.SingleDenotation diff --git a/compiler/src/dotty/tools/dotc/printing/Highlighting.scala b/compiler/src/dotty/tools/dotc/printing/Highlighting.scala index 1678e8efd2f5..f5d6597fc0f7 100644 --- a/compiler/src/dotty/tools/dotc/printing/Highlighting.scala +++ b/compiler/src/dotty/tools/dotc/printing/Highlighting.scala @@ -3,7 +3,7 @@ package dotc package printing import scala.collection.mutable -import core.Contexts.{Context, ctx} +import core.Contexts._ object Highlighting { diff --git a/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala b/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala index 936247e93549..0fcd6a800c9b 100644 --- a/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala +++ b/compiler/src/dotty/tools/dotc/printing/MessageLimiter.scala @@ -3,7 +3,7 @@ package dotc package printing import core._ -import Contexts.{Context, ctx} +import Contexts._ import util.Property import Texts.Text diff --git a/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala b/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala index 7fafb72c5e24..6e7c0b901378 100644 --- a/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala +++ b/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala @@ -9,7 +9,7 @@ import Names._ import Symbols._ import NameOps._ import TypeErasure.ErasedValueType -import Contexts.{Context, ctx} +import Contexts._ import Annotations.Annotation import Denotations._ import SymDenotations._ diff --git a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala index 62da8a6a1d0d..cce2c6d00859 100644 --- a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala +++ b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc package printing import dotty.tools.dotc.ast.untpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.parsing.Parsers.Parser import dotty.tools.dotc.parsing.Scanners.Scanner diff --git a/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala b/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala index a9278430940a..977dd596f031 100644 --- a/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala +++ b/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala @@ -5,7 +5,7 @@ import java.util.concurrent._ import java.util.concurrent.atomic.AtomicInteger import dotty.tools.dotc.core.Phases.Phase -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ sealed trait AsyncHelper { diff --git a/compiler/src/dotty/tools/dotc/profile/Profiler.scala b/compiler/src/dotty/tools/dotc/profile/Profiler.scala index ff99c7646a87..0a4c3dd4d691 100644 --- a/compiler/src/dotty/tools/dotc/profile/Profiler.scala +++ b/compiler/src/dotty/tools/dotc/profile/Profiler.scala @@ -8,7 +8,7 @@ import javax.management.openmbean.CompositeData import javax.management.{Notification, NotificationEmitter, NotificationListener} import dotty.tools.dotc.core.Phases.Phase -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.io.AbstractFile object Profiler { diff --git a/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala b/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala index c279e25c9b3a..5a3904d89491 100644 --- a/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala +++ b/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala @@ -1,6 +1,6 @@ package dotty.tools.dotc.quoted -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.tastyreflect.ReflectionImpl object QuoteContext { diff --git a/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala b/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala index c6d46bd8d502..3c6ea46f12e5 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala @@ -3,7 +3,7 @@ package dotc package reporting import util.SourcePosition -import core.Contexts.{Context, ctx} +import core.Contexts._ import config.Settings.Setting import interfaces.Diagnostic.{ERROR, INFO, WARNING} diff --git a/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala b/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala index 4225f00c1ba1..9b6a3c75ba5d 100644 --- a/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package reporting -import core.Contexts.{Context, ctx} +import core.Contexts._ /** * This trait implements `isHidden` so that we avoid reporting non-sensical messages. diff --git a/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala b/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala index 4e6260a1f4bb..edcf0864df84 100644 --- a/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala +++ b/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala @@ -4,7 +4,7 @@ package reporting import java.lang.System.{lineSeparator => EOL} -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Decorators._ import printing.Highlighting.{Blue, Red, Yellow} import printing.SyntaxHighlighting diff --git a/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala b/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala index 38e803ec9ba6..0d069ee07a1d 100644 --- a/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package reporting -import core.Contexts.{Context, ctx} +import core.Contexts._ import collection.mutable import config.Printers.typr import Diagnostic._ diff --git a/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala b/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala index e3fb4aaccf3d..ad47a9d30536 100644 --- a/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package reporting -import core.Contexts.{Context, ctx} +import core.Contexts._ import Diagnostic.Error /** diff --git a/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala b/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala index e20dac2b31ad..fb4c92c12f83 100644 --- a/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala +++ b/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala @@ -4,7 +4,7 @@ package reporting import scala.collection.mutable import util.SourceFile -import core.Contexts.{Context, ctx} +import core.Contexts._ /** This trait implements `isHidden` so that multiple messages per position * are suppressed, unless they are of increasing severity. */ diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index c720ac1c372d..f14295b64f7e 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -2090,7 +2090,7 @@ import ast.tpd |This mechanism is used for instance in pattern ${hl("case List(x1, ..., xn)")}""".stripMargin } - class MemberWithSameNameAsStatic()(using ctx: Context) + class MemberWithSameNameAsStatic()(using Context) extends SyntaxMsg(MemberWithSameNameAsStaticID) { def msg = em"Companion classes cannot define members with same name as a ${hl("@static")} member" def explain = "" @@ -2105,25 +2105,25 @@ import ast.tpd |It can be removed without changing the semantics of the program. This may indicate an error.""".stripMargin } - class TraitCompanionWithMutableStatic()(using ctx: Context) + class TraitCompanionWithMutableStatic()(using Context) extends SyntaxMsg(TraitCompanionWithMutableStaticID) { def msg = em"Companion of traits cannot define mutable @static fields" def explain = "" } - class LazyStaticField()(using ctx: Context) + class LazyStaticField()(using Context) extends SyntaxMsg(LazyStaticFieldID) { def msg = em"Lazy @static fields are not supported" def explain = "" } - class StaticOverridingNonStaticMembers()(using ctx: Context) + class StaticOverridingNonStaticMembers()(using Context) extends SyntaxMsg(StaticOverridingNonStaticMembersID) { def msg = em"${hl("@static")} members cannot override or implement non-static ones" def explain = "" } - class OverloadInRefinement(rsym: Symbol)(using ctx: Context) + class OverloadInRefinement(rsym: Symbol)(using Context) extends DeclarationMsg(OverloadInRefinementID) { def msg = "Refinements cannot introduce overloaded definitions" def explain = @@ -2131,14 +2131,14 @@ import ast.tpd |Refinements cannot contain overloaded definitions.""".stripMargin } - class NoMatchingOverload(val alternatives: List[SingleDenotation], pt: Type)(using ctx: Context) + class NoMatchingOverload(val alternatives: List[SingleDenotation], pt: Type)(using Context) extends TypeMismatchMsg(NoMatchingOverloadID) { def msg = em"""None of the ${err.overloadedAltsStr(alternatives)} |match ${err.expectedTypeStr(pt)}""" def explain = "" } - class StableIdentPattern(tree: untpd.Tree, pt: Type)(using ctx: Context) + class StableIdentPattern(tree: untpd.Tree, pt: Type)(using Context) extends TypeMsg(StableIdentPatternID) { def msg = em"""Stable identifier required, but $tree found""" @@ -2147,7 +2147,7 @@ import ast.tpd class IllegalSuperAccessor(base: Symbol, memberName: Name, acc: Symbol, accTp: Type, - other: Symbol, otherTp: Type)(using ctx: Context) extends DeclarationMsg(IllegalSuperAccessorID) { + other: Symbol, otherTp: Type)(using Context) extends DeclarationMsg(IllegalSuperAccessorID) { def msg = { // The mixin containing a super-call that requires a super-accessor val accMixin = acc.owner @@ -2200,7 +2200,7 @@ import ast.tpd def explain = "" } - class TraitParameterUsedAsParentPrefix(cls: Symbol)(using ctx: Context) + class TraitParameterUsedAsParentPrefix(cls: Symbol)(using Context) extends DeclarationMsg(TraitParameterUsedAsParentPrefixID) { def msg = s"${cls.show} cannot extend from a parent that is derived via its own parameters" @@ -2215,7 +2215,7 @@ import ast.tpd |""".stripMargin } - class UnknownNamedEnclosingClassOrObject(name: TypeName)(using ctx: Context) + class UnknownNamedEnclosingClassOrObject(name: TypeName)(using Context) extends ReferenceMsg(UnknownNamedEnclosingClassOrObjectID) { def msg = em"""no enclosing class or object is named '${hl(name.show)}'""" @@ -2228,7 +2228,7 @@ import ast.tpd """.stripMargin } - class IllegalCyclicTypeReference(sym: Symbol, where: String, lastChecked: Type)(using ctx: Context) + class IllegalCyclicTypeReference(sym: Symbol, where: String, lastChecked: Type)(using Context) extends CyclicMsg(IllegalCyclicTypeReferenceID) { def msg = val lastCheckedStr = @@ -2238,7 +2238,7 @@ import ast.tpd def explain = "" } - class ErasedTypesCanOnlyBeFunctionTypes()(using ctx: Context) + class ErasedTypesCanOnlyBeFunctionTypes()(using Context) extends SyntaxMsg(ErasedTypesCanOnlyBeFunctionTypesID) { def msg = "Types with erased keyword can only be function types `(erased ...) => ...`" def explain = "" diff --git a/compiler/src/dotty/tools/dotc/reporting/trace.scala b/compiler/src/dotty/tools/dotc/reporting/trace.scala index df31bbdd52e9..bbecb7238328 100644 --- a/compiler/src/dotty/tools/dotc/reporting/trace.scala +++ b/compiler/src/dotty/tools/dotc/reporting/trace.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package reporting -import core.Contexts.{Context, ctx} +import core.Contexts._ import config.Config import config.Printers import core.Mode diff --git a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala index da72382aa12a..5eeee5dc1dd3 100644 --- a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala +++ b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala @@ -3,7 +3,7 @@ package rewrites import util.{SourceFile, Spans} import Spans.Span -import core.Contexts.{Context, ctx} +import core.Contexts._ import collection.mutable import scala.annotation.tailrec import dotty.tools.dotc.reporting.Reporter diff --git a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala index f38113bdaaf3..3e9a0356f607 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc.semanticdb import dotty.tools.dotc.core import core.Symbols.{ Symbol , defn } -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Names import core.Names.Name import core.Types.Type diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala b/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala index a41f8da4a158..14ba0dca6d56 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc.tastyreflect import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.ast.untpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Symbols._ diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala index 2bc829282bf7..d04226fc139f 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala @@ -6,6 +6,7 @@ import dotty.tools.dotc.ast.{TreeTypeMap, Trees, tpd, untpd} import dotty.tools.dotc.typer.{Implicits, Typer} import dotty.tools.dotc.core._ import dotty.tools.dotc.core.Flags._ +import dotty.tools.dotc.core.Contexts.{ctx, CState} import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.quoted.PickledQuotes import dotty.tools.dotc.core.Symbols._ @@ -81,16 +82,16 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend // REPORTING // /////////////// - def error(msg: => String, pos: Position)(using ctx: Context): Unit = + def error(msg: => String, pos: Position)(using Context): Unit = report.error(msg, pos) - def error(msg: => String, sourceFile: SourceFile, start: Int, end: Int)(using ctx: Context): Unit = + def error(msg: => String, sourceFile: SourceFile, start: Int, end: Int)(using Context): Unit = report.error(msg, util.SourcePosition(sourceFile, util.Spans.Span(start, end))) - def warning(msg: => String, pos: Position)(using ctx: Context): Unit = + def warning(msg: => String, pos: Position)(using Context): Unit = report.warning(msg, pos) - def warning(msg: => String, sourceFile: SourceFile, start: Int, end: Int)(using ctx: Context): Unit = + def warning(msg: => String, sourceFile: SourceFile, start: Int, end: Int)(using Context): Unit = report.error(msg, util.SourcePosition(sourceFile, util.Spans.Span(start, end))) @@ -109,30 +110,30 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type Tree = tpd.Tree - def Tree_pos(self: Tree)(using ctx: Context): Position = self.sourcePos - def Tree_symbol(self: Tree)(using ctx: Context): Symbol = self.symbol + def Tree_pos(self: Tree)(using Context): Position = self.sourcePos + def Tree_symbol(self: Tree)(using Context): Symbol = self.symbol type PackageClause = tpd.PackageDef - def PackageClause_TypeTest(using ctx: Context): TypeTest[Tree, PackageClause] = new { + def PackageClause_TypeTest(using Context): TypeTest[Tree, PackageClause] = new { def runtimeClass: Class[?] = classOf[PackageClause] override def unapply(x: Any): Option[PackageClause] = x match case x: tpd.PackageDef @unchecked => Some(x) case _ => None } - def PackageClause_pid(self: PackageClause)(using ctx: Context): Ref = self.pid - def PackageClause_stats(self: PackageClause)(using ctx: Context): List[Tree] = self.stats + def PackageClause_pid(self: PackageClause)(using Context): Ref = self.pid + def PackageClause_stats(self: PackageClause)(using Context): List[Tree] = self.stats - def PackageClause_apply(pid: Ref, stats: List[Tree])(using ctx: Context): PackageClause = + def PackageClause_apply(pid: Ref, stats: List[Tree])(using Context): PackageClause = withDefaultPos(tpd.PackageDef(pid.asInstanceOf[tpd.RefTree], stats)) - def PackageClause_copy(original: Tree)(pid: Ref, stats: List[Tree])(using ctx: Context): PackageClause = + def PackageClause_copy(original: Tree)(pid: Ref, stats: List[Tree])(using Context): PackageClause = tpd.cpy.PackageDef(original)(pid, stats) type Statement = tpd.Tree - def Statement_TypeTest(using ctx: Context): TypeTest[Tree, Statement] = new { + def Statement_TypeTest(using Context): TypeTest[Tree, Statement] = new { def runtimeClass: Class[?] = classOf[Statement] override def unapply(x: Any): Option[Statement] = x match case _: PatternTree @unchecked => None @@ -143,7 +144,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type Import = tpd.Import - def Import_TypeTest(using ctx: Context): TypeTest[Tree, Import] = new { + def Import_TypeTest(using Context): TypeTest[Tree, Import] = new { def runtimeClass: Class[?] = classOf[Import] override def unapply(x: Any): Option[Import] = x match case tree: tpd.Import @unchecked => Some(tree) @@ -151,18 +152,18 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } def Import_implied(self: Import): Boolean = false // TODO: adapt to new import scheme - def Import_expr(self: Import)(using ctx: Context): Tree = self.expr - def Import_selectors(self: Import)(using ctx: Context): List[ImportSelector] = self.selectors + def Import_expr(self: Import)(using Context): Tree = self.expr + def Import_selectors(self: Import)(using Context): List[ImportSelector] = self.selectors - def Import_apply(expr: Term, selectors: List[ImportSelector])(using ctx: Context): Import = + def Import_apply(expr: Term, selectors: List[ImportSelector])(using Context): Import = withDefaultPos(tpd.Import(expr, selectors)) - def Import_copy(original: Tree)(expr: Term, selectors: List[ImportSelector])(using ctx: Context): Import = + def Import_copy(original: Tree)(expr: Term, selectors: List[ImportSelector])(using Context): Import = tpd.cpy.Import(original)(expr, selectors) type Definition = tpd.Tree - def Definition_TypeTest(using ctx: Context): TypeTest[Tree, Definition] = new { + def Definition_TypeTest(using Context): TypeTest[Tree, Definition] = new { def runtimeClass: Class[?] = classOf[Definition] override def unapply(x: Any): Option[Definition] = x match case x: tpd.MemberDef @unchecked => Some(x) @@ -170,103 +171,103 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def Definition_name(self: Definition)(using ctx: Context): String = self match { + def Definition_name(self: Definition)(using Context): String = self match { case self: tpd.MemberDef => self.name.toString case self: PackageDefinition => self.symbol.name.toString // TODO make PackageDefinition a MemberDef or NameTree } type PackageDef = PackageDefinition - def PackageDef_TypeTest(using ctx: Context): TypeTest[Tree, PackageDef] = new { + def PackageDef_TypeTest(using Context): TypeTest[Tree, PackageDef] = new { def runtimeClass: Class[?] = classOf[PackageDef] override def unapply(x: Any): Option[PackageDef] = x match case x: PackageDefinition @unchecked => Some(x) case _ => None } - def PackageDef_owner(self: PackageDef)(using ctx: Context): PackageDef = packageDefFromSym(self.symbol.owner) + def PackageDef_owner(self: PackageDef)(using Context): PackageDef = packageDefFromSym(self.symbol.owner) - def PackageDef_members(self: PackageDef)(using ctx: Context): List[Statement] = + def PackageDef_members(self: PackageDef)(using Context): List[Statement] = if (self.symbol.is(core.Flags.JavaDefined)) Nil // FIXME should also support java packages else self.symbol.info.decls.iterator.map(definitionFromSym).toList type ClassDef = tpd.TypeDef - def ClassDef_TypeTest(using ctx: Context): TypeTest[Tree, ClassDef] = new { + def ClassDef_TypeTest(using Context): TypeTest[Tree, ClassDef] = new { def runtimeClass: Class[?] = classOf[ClassDef] override def unapply(x: Any): Option[ClassDef] = x match case x: tpd.TypeDef @unchecked if x.isClassDef => Some(x) case _ => None } - def ClassDef_constructor(self: ClassDef)(using ctx: Context): DefDef = ClassDef_rhs(self).constr - def ClassDef_parents(self: ClassDef)(using ctx: Context): List[Term | TypeTree] = ClassDef_rhs(self).parents - def ClassDef_derived(self: ClassDef)(using ctx: Context): List[TypeTree] = ClassDef_rhs(self).derived.asInstanceOf[List[TypeTree]] - def ClassDef_self(self: ClassDef)(using ctx: Context): Option[ValDef] = optional(ClassDef_rhs(self).self) - def ClassDef_body(self: ClassDef)(using ctx: Context): List[Statement] = ClassDef_rhs(self).body + def ClassDef_constructor(self: ClassDef)(using Context): DefDef = ClassDef_rhs(self).constr + def ClassDef_parents(self: ClassDef)(using Context): List[Term | TypeTree] = ClassDef_rhs(self).parents + def ClassDef_derived(self: ClassDef)(using Context): List[TypeTree] = ClassDef_rhs(self).derived.asInstanceOf[List[TypeTree]] + def ClassDef_self(self: ClassDef)(using Context): Option[ValDef] = optional(ClassDef_rhs(self).self) + def ClassDef_body(self: ClassDef)(using Context): List[Statement] = ClassDef_rhs(self).body private def ClassDef_rhs(self: ClassDef) = self.rhs.asInstanceOf[tpd.Template] - def ClassDef_copy(original: Tree)(name: String, constr: DefDef, parents: List[Term | TypeTree], derived: List[TypeTree], selfOpt: Option[ValDef], body: List[Statement])(using ctx: Context): ClassDef = { + def ClassDef_copy(original: Tree)(name: String, constr: DefDef, parents: List[Term | TypeTree], derived: List[TypeTree], selfOpt: Option[ValDef], body: List[Statement])(using Context): ClassDef = { val Trees.TypeDef(_, originalImpl: tpd.Template) = original tpd.cpy.TypeDef(original)(name.toTypeName, tpd.cpy.Template(originalImpl)(constr, parents, derived, selfOpt.getOrElse(tpd.EmptyValDef), body)) } type TypeDef = tpd.TypeDef - def TypeDef_TypeTest(using ctx: Context): TypeTest[Tree, TypeDef] = new { + def TypeDef_TypeTest(using Context): TypeTest[Tree, TypeDef] = new { def runtimeClass: Class[?] = classOf[TypeDef] override def unapply(x: Any): Option[TypeDef] = x match case x: tpd.TypeDef @unchecked if !x.isClassDef => Some(x) case _ => None } - def TypeDef_rhs(self: TypeDef)(using ctx: Context): TypeTree | TypeBoundsTree = self.rhs + def TypeDef_rhs(self: TypeDef)(using Context): TypeTree | TypeBoundsTree = self.rhs - def TypeDef_apply(symbol: Symbol)(using ctx: Context): TypeDef = withDefaultPos(tpd.TypeDef(symbol.asType)) - def TypeDef_copy(original: Tree)(name: String, rhs: TypeTree | TypeBoundsTree)(using ctx: Context): TypeDef = + def TypeDef_apply(symbol: Symbol)(using Context): TypeDef = withDefaultPos(tpd.TypeDef(symbol.asType)) + def TypeDef_copy(original: Tree)(name: String, rhs: TypeTree | TypeBoundsTree)(using Context): TypeDef = tpd.cpy.TypeDef(original)(name.toTypeName, rhs) type DefDef = tpd.DefDef - def DefDef_TypeTest(using ctx: Context): TypeTest[Tree, DefDef] = new { + def DefDef_TypeTest(using Context): TypeTest[Tree, DefDef] = new { def runtimeClass: Class[?] = classOf[DefDef] override def unapply(x: Any): Option[DefDef] = x match case x: tpd.DefDef @unchecked => Some(x) case _ => None } - def DefDef_typeParams(self: DefDef)(using ctx: Context): List[TypeDef] = self.tparams - def DefDef_paramss(self: DefDef)(using ctx: Context): List[List[ValDef]] = self.vparamss - def DefDef_returnTpt(self: DefDef)(using ctx: Context): TypeTree = self.tpt - def DefDef_rhs(self: DefDef)(using ctx: Context): Option[Tree] = optional(self.rhs) + def DefDef_typeParams(self: DefDef)(using Context): List[TypeDef] = self.tparams + def DefDef_paramss(self: DefDef)(using Context): List[List[ValDef]] = self.vparamss + def DefDef_returnTpt(self: DefDef)(using Context): TypeTree = self.tpt + def DefDef_rhs(self: DefDef)(using Context): Option[Tree] = optional(self.rhs) - def DefDef_apply(symbol: Symbol, rhsFn: List[Type] => List[List[Term]] => Option[Term])(using ctx: Context): DefDef = + def DefDef_apply(symbol: Symbol, rhsFn: List[Type] => List[List[Term]] => Option[Term])(using Context): DefDef = withDefaultPos(tpd.polyDefDef(symbol.asTerm, tparams => vparamss => rhsFn(tparams)(vparamss).getOrElse(tpd.EmptyTree))) - def DefDef_copy(original: Tree)(name: String, typeParams: List[TypeDef], paramss: List[List[ValDef]], tpt: TypeTree, rhs: Option[Term])(using ctx: Context): DefDef = + def DefDef_copy(original: Tree)(name: String, typeParams: List[TypeDef], paramss: List[List[ValDef]], tpt: TypeTree, rhs: Option[Term])(using Context): DefDef = tpd.cpy.DefDef(original)(name.toTermName, typeParams, paramss, tpt, rhs.getOrElse(tpd.EmptyTree)) type ValDef = tpd.ValDef - def ValDef_TypeTest(using ctx: Context): TypeTest[Tree, ValDef] = new { + def ValDef_TypeTest(using Context): TypeTest[Tree, ValDef] = new { def runtimeClass: Class[?] = classOf[ValDef] override def unapply(x: Any): Option[ValDef] = x match case x: tpd.ValDef @unchecked => Some(x) case _ => None } - def ValDef_tpt(self: ValDef)(using ctx: Context): TypeTree = self.tpt - def ValDef_rhs(self: ValDef)(using ctx: Context): Option[Tree] = optional(self.rhs) + def ValDef_tpt(self: ValDef)(using Context): TypeTree = self.tpt + def ValDef_rhs(self: ValDef)(using Context): Option[Tree] = optional(self.rhs) - def ValDef_apply(symbol: Symbol, rhs: Option[Term])(using ctx: Context): ValDef = + def ValDef_apply(symbol: Symbol, rhs: Option[Term])(using Context): ValDef = tpd.ValDef(symbol.asTerm, rhs.getOrElse(tpd.EmptyTree)) - def ValDef_copy(original: Tree)(name: String, tpt: TypeTree, rhs: Option[Term])(using ctx: Context): ValDef = + def ValDef_copy(original: Tree)(name: String, tpt: TypeTree, rhs: Option[Term])(using Context): ValDef = tpd.cpy.ValDef(original)(name.toTermName, tpt, rhs.getOrElse(tpd.EmptyTree)) type Term = tpd.Tree - def Term_TypeTest(using ctx: Context): TypeTest[Tree, Term] = new { + def Term_TypeTest(using Context): TypeTest[Tree, Term] = new { def runtimeClass: Class[?] = classOf[Term] override def unapply(x: Any): Option[Term] = x match case _ if Unapply_TypeTest.unapply(x).isDefined => None @@ -276,11 +277,11 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def Term_tpe(self: Term)(using ctx: Context): Type = self.tpe - def Term_underlyingArgument(self: Term)(using ctx: Context): Term = self.underlyingArgument - def Term_underlying(self: Term)(using ctx: Context): Term = self.underlying + def Term_tpe(self: Term)(using Context): Type = self.tpe + def Term_underlyingArgument(self: Term)(using Context): Term = self.underlyingArgument + def Term_underlying(self: Term)(using Context): Term = self.underlying - def Term_etaExpand(term: Term)(using ctx: Context): Term = term.tpe.widen match { + def Term_etaExpand(term: Term)(using Context): Term = term.tpe.widen match { case mtpe: Types.MethodType if !mtpe.isParamDependent => val closureResType = mtpe.resType match { case t: Types.MethodType @unchecked => t.toFunctionType() @@ -292,238 +293,238 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => term } - def TypeRef_apply(sym: Symbol)(using ctx: Context): TypeTree = { + def TypeRef_apply(sym: Symbol)(using Context): TypeTree = { assert(sym.isType) withDefaultPos(tpd.ref(sym).asInstanceOf[tpd.TypeTree]) } type Ref = tpd.RefTree - def Ref_TypeTest(using ctx: Context): TypeTest[Tree, Ref] = new { + def Ref_TypeTest(using Context): TypeTest[Tree, Ref] = new { def runtimeClass: Class[?] = classOf[Ref] override def unapply(x: Any): Option[Ref] = x match case x: tpd.RefTree @unchecked if x.isTerm => Some(x) case _ => None } - def Ref_term(tp: TermRef)(using ctx: Context): Ref = + def Ref_term(tp: TermRef)(using Context): Ref = withDefaultPos(tpd.ref(tp).asInstanceOf[tpd.RefTree]) - def Ref_apply(sym: Symbol)(using ctx: Context): Ref = { + def Ref_apply(sym: Symbol)(using Context): Ref = { assert(sym.isTerm) withDefaultPos(tpd.ref(sym).asInstanceOf[tpd.RefTree]) } type Ident = tpd.Ident - def Ident_TypeTest(using ctx: Context): TypeTest[Tree, Ident] = new { + def Ident_TypeTest(using Context): TypeTest[Tree, Ident] = new { def runtimeClass: Class[?] = classOf[Ident] override def unapply(x: Any): Option[Ident] = x match case x: tpd.Ident @unchecked if x.isTerm => Some(x) case _ => None } - def Ident_name(self: Ident)(using ctx: Context): String = self.name.show + def Ident_name(self: Ident)(using Context): String = self.name.show - def Ident_apply(tmref: TermRef)(using ctx: Context): Term = + def Ident_apply(tmref: TermRef)(using Context): Term = withDefaultPos(tpd.ref(tmref).asInstanceOf[Term]) - def Ident_copy(original: Tree)(name: String)(using ctx: Context): Ident = + def Ident_copy(original: Tree)(name: String)(using Context): Ident = tpd.cpy.Ident(original)(name.toTermName) type Select = tpd.Select - def Select_TypeTest(using ctx: Context): TypeTest[Tree, Select] = new { + def Select_TypeTest(using Context): TypeTest[Tree, Select] = new { def runtimeClass: Class[?] = classOf[Select] override def unapply(x: Any): Option[Select] = x match case x: tpd.Select @unchecked if x.isTerm => Some(x) case _ => None } - def Select_qualifier(self: Select)(using ctx: Context): Term = self.qualifier - def Select_name(self: Select)(using ctx: Context): String = self.name.toString - def Select_signature(self: Select)(using ctx: Context): Option[Signature] = + def Select_qualifier(self: Select)(using Context): Term = self.qualifier + def Select_name(self: Select)(using Context): String = self.name.toString + def Select_signature(self: Select)(using Context): Option[Signature] = if (self.symbol.signature == core.Signature.NotAMethod) None else Some(self.symbol.signature) - def Select_apply(qualifier: Term, symbol: Symbol)(using ctx: Context): Select = + def Select_apply(qualifier: Term, symbol: Symbol)(using Context): Select = withDefaultPos(tpd.Select(qualifier, Types.TermRef(qualifier.tpe, symbol))) - def Select_unique(qualifier: Term, name: String)(using ctx: Context): Select = { + def Select_unique(qualifier: Term, name: String)(using Context): Select = { val denot = qualifier.tpe.member(name.toTermName) assert(!denot.isOverloaded, s"The symbol `$name` is overloaded. The method Select.unique can only be used for non-overloaded symbols.") withDefaultPos(tpd.Select(qualifier, name.toTermName)) } // TODO rename, this returns an Apply and not a Select - def Select_overloaded(qualifier: Term, name: String, targs: List[Type], args: List[Term])(using ctx: Context): Apply = + def Select_overloaded(qualifier: Term, name: String, targs: List[Type], args: List[Term])(using Context): Apply = withDefaultPos(tpd.applyOverloaded(qualifier, name.toTermName, args, targs, Types.WildcardType).asInstanceOf[Apply]) - def Select_copy(original: Tree)(qualifier: Term, name: String)(using ctx: Context): Select = + def Select_copy(original: Tree)(qualifier: Term, name: String)(using Context): Select = tpd.cpy.Select(original)(qualifier, name.toTermName) type Literal = tpd.Literal - def Literal_TypeTest(using ctx: Context): TypeTest[Tree, Literal] = new { + def Literal_TypeTest(using Context): TypeTest[Tree, Literal] = new { def runtimeClass: Class[?] = classOf[Literal] override def unapply(x: Any): Option[Literal] = x match case x: tpd.Literal @unchecked => Some(x) case _ => None } - def Literal_constant(self: Literal)(using ctx: Context): Constant = self.const + def Literal_constant(self: Literal)(using Context): Constant = self.const - def Literal_apply(constant: Constant)(using ctx: Context): Literal = + def Literal_apply(constant: Constant)(using Context): Literal = withDefaultPos(tpd.Literal(constant)) - def Literal_copy(original: Tree)(constant: Constant)(using ctx: Context): Literal = + def Literal_copy(original: Tree)(constant: Constant)(using Context): Literal = tpd.cpy.Literal(original)(constant) type This = tpd.This - def This_TypeTest(using ctx: Context): TypeTest[Tree, This] = new { + def This_TypeTest(using Context): TypeTest[Tree, This] = new { def runtimeClass: Class[?] = classOf[This] override def unapply(x: Any): Option[This] = x match case x: tpd.This @unchecked => Some(x) case _ => None } - def This_id(self: This)(using ctx: Context): Option[Id] = optional(self.qual) + def This_id(self: This)(using Context): Option[Id] = optional(self.qual) - def This_apply(cls: Symbol)(using ctx: Context): This = + def This_apply(cls: Symbol)(using Context): This = withDefaultPos(tpd.This(cls.asClass)) - def This_copy(original: Tree)(qual: Option[Id])(using ctx: Context): This = + def This_copy(original: Tree)(qual: Option[Id])(using Context): This = tpd.cpy.This(original)(qual.getOrElse(untpd.EmptyTypeIdent)) type New = tpd.New - def New_TypeTest(using ctx: Context): TypeTest[Tree, New] = new { + def New_TypeTest(using Context): TypeTest[Tree, New] = new { def runtimeClass: Class[?] = classOf[New] override def unapply(x: Any): Option[New] = x match case x: tpd.New @unchecked => Some(x) case _ => None } - def New_tpt(self: New)(using ctx: Context): TypeTree = self.tpt + def New_tpt(self: New)(using Context): TypeTree = self.tpt - def New_apply(tpt: TypeTree)(using ctx: Context): New = withDefaultPos(tpd.New(tpt)) + def New_apply(tpt: TypeTree)(using Context): New = withDefaultPos(tpd.New(tpt)) - def New_copy(original: Tree)(tpt: TypeTree)(using ctx: Context): New = + def New_copy(original: Tree)(tpt: TypeTree)(using Context): New = tpd.cpy.New(original)(tpt) type NamedArg = tpd.NamedArg - def NamedArg_TypeTest(using ctx: Context): TypeTest[Tree, NamedArg] = new { + def NamedArg_TypeTest(using Context): TypeTest[Tree, NamedArg] = new { def runtimeClass: Class[?] = classOf[NamedArg] override def unapply(x: Any): Option[NamedArg] = x match case x: tpd.NamedArg @unchecked if x.name.isInstanceOf[core.Names.TermName] => Some(x) // TODO: Now, the name should alwas be a term name case _ => None } - def NamedArg_name(self: NamedArg)(using ctx: Context): String = self.name.toString - def NamedArg_value(self: NamedArg)(using ctx: Context): Term = self.arg + def NamedArg_name(self: NamedArg)(using Context): String = self.name.toString + def NamedArg_value(self: NamedArg)(using Context): Term = self.arg - def NamedArg_apply(name: String, arg: Term)(using ctx: Context): NamedArg = + def NamedArg_apply(name: String, arg: Term)(using Context): NamedArg = withDefaultPos(tpd.NamedArg(name.toTermName, arg)) - def NamedArg_copy(original: Tree)(name: String, arg: Term)(using ctx: Context): NamedArg = + def NamedArg_copy(original: Tree)(name: String, arg: Term)(using Context): NamedArg = tpd.cpy.NamedArg(original)(name.toTermName, arg) type Apply = tpd.Apply - def Apply_TypeTest(using ctx: Context): TypeTest[Tree, Apply] = new { + def Apply_TypeTest(using Context): TypeTest[Tree, Apply] = new { def runtimeClass: Class[?] = classOf[Apply] override def unapply(x: Any): Option[Apply] = x match case x: tpd.Apply @unchecked => Some(x) case _ => None } - def Apply_fun(self: Apply)(using ctx: Context): Term = self.fun - def Apply_args(self: Apply)(using ctx: Context): List[Term] = self.args + def Apply_fun(self: Apply)(using Context): Term = self.fun + def Apply_args(self: Apply)(using Context): List[Term] = self.args - def Apply_apply(fn: Term, args: List[Term])(using ctx: Context): Apply = + def Apply_apply(fn: Term, args: List[Term])(using Context): Apply = withDefaultPos(tpd.Apply(fn, args)) - def Apply_copy(original: Tree)(fun: Term, args: List[Term])(using ctx: Context): Apply = + def Apply_copy(original: Tree)(fun: Term, args: List[Term])(using Context): Apply = tpd.cpy.Apply(original)(fun, args) type TypeApply = tpd.TypeApply - def TypeApply_TypeTest(using ctx: Context): TypeTest[Tree, TypeApply] = new { + def TypeApply_TypeTest(using Context): TypeTest[Tree, TypeApply] = new { def runtimeClass: Class[?] = classOf[TypeApply] override def unapply(x: Any): Option[TypeApply] = x match case x: tpd.TypeApply @unchecked => Some(x) case _ => None } - def TypeApply_fun(self: TypeApply)(using ctx: Context): Term = self.fun - def TypeApply_args(self: TypeApply)(using ctx: Context): List[TypeTree] = self.args + def TypeApply_fun(self: TypeApply)(using Context): Term = self.fun + def TypeApply_args(self: TypeApply)(using Context): List[TypeTree] = self.args - def TypeApply_apply(fn: Term, args: List[TypeTree])(using ctx: Context): TypeApply = + def TypeApply_apply(fn: Term, args: List[TypeTree])(using Context): TypeApply = withDefaultPos(tpd.TypeApply(fn, args)) - def TypeApply_copy(original: Tree)(fun: Term, args: List[TypeTree])(using ctx: Context): TypeApply = + def TypeApply_copy(original: Tree)(fun: Term, args: List[TypeTree])(using Context): TypeApply = tpd.cpy.TypeApply(original)(fun, args) type Super = tpd.Super - def Super_TypeTest(using ctx: Context): TypeTest[Tree, Super] = new { + def Super_TypeTest(using Context): TypeTest[Tree, Super] = new { def runtimeClass: Class[?] = classOf[Super] override def unapply(x: Any): Option[Super] = x match case x: tpd.Super @unchecked => Some(x) case _ => None } - def Super_qualifier(self: Super)(using ctx: Context): Term = self.qual - def Super_id(self: Super)(using ctx: Context): Option[Id] = optional(self.mix) + def Super_qualifier(self: Super)(using Context): Term = self.qual + def Super_id(self: Super)(using Context): Option[Id] = optional(self.mix) - def Super_apply(qual: Term, mix: Option[Id])(using ctx: Context): Super = + def Super_apply(qual: Term, mix: Option[Id])(using Context): Super = withDefaultPos(tpd.Super(qual, mix.getOrElse(untpd.EmptyTypeIdent), NoSymbol)) - def Super_copy(original: Tree)(qual: Term, mix: Option[Id])(using ctx: Context): Super = + def Super_copy(original: Tree)(qual: Term, mix: Option[Id])(using Context): Super = tpd.cpy.Super(original)(qual, mix.getOrElse(untpd.EmptyTypeIdent)) type Typed = tpd.Typed - def Typed_TypeTest(using ctx: Context): TypeTest[Tree, Typed] = new { + def Typed_TypeTest(using Context): TypeTest[Tree, Typed] = new { def runtimeClass: Class[?] = classOf[Typed] override def unapply(x: Any): Option[Typed] = x match case x: tpd.Typed @unchecked => Some(x) case _ => None } - def Typed_expr(self: Typed)(using ctx: Context): Term = self.expr - def Typed_tpt(self: Typed)(using ctx: Context): TypeTree = self.tpt + def Typed_expr(self: Typed)(using Context): Term = self.expr + def Typed_tpt(self: Typed)(using Context): TypeTree = self.tpt - def Typed_apply(expr: Term, tpt: TypeTree)(using ctx: Context): Typed = + def Typed_apply(expr: Term, tpt: TypeTree)(using Context): Typed = withDefaultPos(tpd.Typed(expr, tpt)) - def Typed_copy(original: Tree)(expr: Term, tpt: TypeTree)(using ctx: Context): Typed = + def Typed_copy(original: Tree)(expr: Term, tpt: TypeTree)(using Context): Typed = tpd.cpy.Typed(original)(expr, tpt) type Assign = tpd.Assign - def Assign_TypeTest(using ctx: Context): TypeTest[Tree, Assign] = new { + def Assign_TypeTest(using Context): TypeTest[Tree, Assign] = new { def runtimeClass: Class[?] = classOf[Assign] override def unapply(x: Any): Option[Assign] = x match case x: tpd.Assign @unchecked => Some(x) case _ => None } - def Assign_lhs(self: Assign)(using ctx: Context): Term = self.lhs - def Assign_rhs(self: Assign)(using ctx: Context): Term = self.rhs + def Assign_lhs(self: Assign)(using Context): Term = self.lhs + def Assign_rhs(self: Assign)(using Context): Term = self.rhs - def Assign_apply(lhs: Term, rhs: Term)(using ctx: Context): Assign = + def Assign_apply(lhs: Term, rhs: Term)(using Context): Assign = withDefaultPos(tpd.Assign(lhs, rhs)) - def Assign_copy(original: Tree)(lhs: Term, rhs: Term)(using ctx: Context): Assign = + def Assign_copy(original: Tree)(lhs: Term, rhs: Term)(using Context): Assign = tpd.cpy.Assign(original)(lhs, rhs) type Block = tpd.Block - def Block_TypeTest(using ctx: Context): TypeTest[Tree, Block] = new { + def Block_TypeTest(using Context): TypeTest[Tree, Block] = new { def runtimeClass: Class[?] = classOf[Block] override def unapply(x: Any): Option[Block] = x match @@ -538,7 +539,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend * i) Put `while` loops in their own blocks: `{ def while$() = ...; while$() }` * ii) Put closures in their own blocks: `{ def anon$() = ...; closure(anon$, ...) }` */ - private def normalizedLoops(tree: tpd.Tree)(using ctx: Context): tpd.Tree = tree match { + private def normalizedLoops(tree: tpd.Tree)(using Context): tpd.Tree = tree match { case block: tpd.Block if block.stats.size > 1 => def normalizeInnerLoops(stats: List[tpd.Tree]): List[tpd.Tree] = stats match { case (x: tpd.DefDef) :: y :: xs if needsNormalization(y) => @@ -559,171 +560,171 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } /** If it is the second statement of a closure. See: `normalizedLoops` */ - private def needsNormalization(tree: tpd.Tree)(using ctx: Context): Boolean = tree match { + private def needsNormalization(tree: tpd.Tree)(using Context): Boolean = tree match { case _: tpd.Closure => true case _ => false } - def Block_statements(self: Block)(using ctx: Context): List[Statement] = self.stats - def Block_expr(self: Block)(using ctx: Context): Term = self.expr + def Block_statements(self: Block)(using Context): List[Statement] = self.stats + def Block_expr(self: Block)(using Context): Term = self.expr - def Block_apply(stats: List[Statement], expr: Term)(using ctx: Context): Block = + def Block_apply(stats: List[Statement], expr: Term)(using Context): Block = withDefaultPos(tpd.Block(stats, expr)) - def Block_copy(original: Tree)(stats: List[Statement], expr: Term)(using ctx: Context): Block = + def Block_copy(original: Tree)(stats: List[Statement], expr: Term)(using Context): Block = tpd.cpy.Block(original)(stats, expr) type Inlined = tpd.Inlined - def Inlined_TypeTest(using ctx: Context): TypeTest[Tree, Inlined] = new { + def Inlined_TypeTest(using Context): TypeTest[Tree, Inlined] = new { def runtimeClass: Class[?] = classOf[Inlined] override def unapply(x: Any): Option[Inlined] = x match case x: tpd.Inlined @unchecked => Some(x) case _ => None } - def Inlined_call(self: Inlined)(using ctx: Context): Option[Term | TypeTree] = optional(self.call) - def Inlined_bindings(self: Inlined)(using ctx: Context): List[Definition] = self.bindings - def Inlined_body(self: Inlined)(using ctx: Context): Term = self.expansion + def Inlined_call(self: Inlined)(using Context): Option[Term | TypeTree] = optional(self.call) + def Inlined_bindings(self: Inlined)(using Context): List[Definition] = self.bindings + def Inlined_body(self: Inlined)(using Context): Term = self.expansion - def Inlined_apply(call: Option[Term | TypeTree], bindings: List[Definition], expansion: Term)(using ctx: Context): Inlined = + def Inlined_apply(call: Option[Term | TypeTree], bindings: List[Definition], expansion: Term)(using Context): Inlined = withDefaultPos(tpd.Inlined(call.getOrElse(tpd.EmptyTree), bindings.map { case b: tpd.MemberDef => b }, expansion)) - def Inlined_copy(original: Tree)(call: Option[Term | TypeTree], bindings: List[Definition], expansion: Term)(using ctx: Context): Inlined = + def Inlined_copy(original: Tree)(call: Option[Term | TypeTree], bindings: List[Definition], expansion: Term)(using Context): Inlined = tpd.cpy.Inlined(original)(call.getOrElse(tpd.EmptyTree), bindings.asInstanceOf[List[tpd.MemberDef]], expansion) type Closure = tpd.Closure - def Closure_TypeTest(using ctx: Context): TypeTest[Tree, Closure] = new { + def Closure_TypeTest(using Context): TypeTest[Tree, Closure] = new { def runtimeClass: Class[?] = classOf[Closure] override def unapply(x: Any): Option[Closure] = x match case x: tpd.Closure @unchecked => Some(x) case _ => None } - def Closure_meth(self: Closure)(using ctx: Context): Term = self.meth - def Closure_tpeOpt(self: Closure)(using ctx: Context): Option[Type] = optional(self.tpt).map(_.tpe) + def Closure_meth(self: Closure)(using Context): Term = self.meth + def Closure_tpeOpt(self: Closure)(using Context): Option[Type] = optional(self.tpt).map(_.tpe) - def Closure_apply(meth: Term, tpe: Option[Type])(using ctx: Context): Closure = + def Closure_apply(meth: Term, tpe: Option[Type])(using Context): Closure = withDefaultPos(tpd.Closure(Nil, meth, tpe.map(tpd.TypeTree(_)).getOrElse(tpd.EmptyTree))) - def Closure_copy(original: Tree)(meth: Tree, tpe: Option[Type])(using ctx: Context): Closure = + def Closure_copy(original: Tree)(meth: Tree, tpe: Option[Type])(using Context): Closure = tpd.cpy.Closure(original)(Nil, meth, tpe.map(tpd.TypeTree(_)).getOrElse(tpd.EmptyTree)) - def Lambda_apply(tpe: MethodType, rhsFn: List[Tree] => Tree)(using ctx: Context): Block = + def Lambda_apply(tpe: MethodType, rhsFn: List[Tree] => Tree)(using Context): Block = tpd.Lambda(tpe, rhsFn) type If = tpd.If - def If_TypeTest(using ctx: Context): TypeTest[Tree, If] = new { + def If_TypeTest(using Context): TypeTest[Tree, If] = new { def runtimeClass: Class[?] = classOf[If] override def unapply(x: Any): Option[If] = x match case x: tpd.If @unchecked => Some(x) case _ => None } - def If_cond(self: If)(using ctx: Context): Term = self.cond - def If_thenp(self: If)(using ctx: Context): Term = self.thenp - def If_elsep(self: If)(using ctx: Context): Term = self.elsep + def If_cond(self: If)(using Context): Term = self.cond + def If_thenp(self: If)(using Context): Term = self.thenp + def If_elsep(self: If)(using Context): Term = self.elsep - def If_apply(cond: Term, thenp: Term, elsep: Term)(using ctx: Context): If = + def If_apply(cond: Term, thenp: Term, elsep: Term)(using Context): If = withDefaultPos(tpd.If(cond, thenp, elsep)) - def If_copy(original: Tree)(cond: Term, thenp: Term, elsep: Term)(using ctx: Context): If = + def If_copy(original: Tree)(cond: Term, thenp: Term, elsep: Term)(using Context): If = tpd.cpy.If(original)(cond, thenp, elsep) type Match = tpd.Match - def Match_TypeTest(using ctx: Context): TypeTest[Tree, Match] = new { + def Match_TypeTest(using Context): TypeTest[Tree, Match] = new { def runtimeClass: Class[?] = classOf[Match] override def unapply(x: Any): Option[Match] = x match case x: tpd.Match @unchecked if !x.selector.isEmpty => Some(x) case _ => None } - def Match_scrutinee(self: Match)(using ctx: Context): Term = self.selector - def Match_cases(self: Match)(using ctx: Context): List[CaseDef] = self.cases + def Match_scrutinee(self: Match)(using Context): Term = self.selector + def Match_cases(self: Match)(using Context): List[CaseDef] = self.cases - def Match_apply(selector: Term, cases: List[CaseDef])(using ctx: Context): Match = + def Match_apply(selector: Term, cases: List[CaseDef])(using Context): Match = withDefaultPos(tpd.Match(selector, cases)) - def Match_copy(original: Tree)(selector: Term, cases: List[CaseDef])(using ctx: Context): Match = + def Match_copy(original: Tree)(selector: Term, cases: List[CaseDef])(using Context): Match = tpd.cpy.Match(original)(selector, cases) type GivenMatch = tpd.Match - def GivenMatch_TypeTest(using ctx: Context): TypeTest[Tree, GivenMatch] = new { + def GivenMatch_TypeTest(using Context): TypeTest[Tree, GivenMatch] = new { def runtimeClass: Class[?] = classOf[GivenMatch] override def unapply(x: Any): Option[GivenMatch] = x match case x: tpd.Match @unchecked if x.selector.isEmpty => Some(x) case _ => None } - def GivenMatch_cases(self: Match)(using ctx: Context): List[CaseDef] = self.cases + def GivenMatch_cases(self: Match)(using Context): List[CaseDef] = self.cases - def GivenMatch_apply(cases: List[CaseDef])(using ctx: Context): GivenMatch = + def GivenMatch_apply(cases: List[CaseDef])(using Context): GivenMatch = withDefaultPos(tpd.Match(tpd.EmptyTree, cases)) - def GivenMatch_copy(original: Tree)(cases: List[CaseDef])(using ctx: Context): GivenMatch = + def GivenMatch_copy(original: Tree)(cases: List[CaseDef])(using Context): GivenMatch = tpd.cpy.Match(original)(tpd.EmptyTree, cases) type Try = tpd.Try - def Try_TypeTest(using ctx: Context): TypeTest[Tree, Try] = new { + def Try_TypeTest(using Context): TypeTest[Tree, Try] = new { def runtimeClass: Class[?] = classOf[Try] override def unapply(x: Any): Option[Try] = x match case x: tpd.Try @unchecked => Some(x) case _ => None } - def Try_body(self: Try)(using ctx: Context): Term = self.expr - def Try_cases(self: Try)(using ctx: Context): List[CaseDef] = self.cases - def Try_finalizer(self: Try)(using ctx: Context): Option[Term] = optional(self.finalizer) + def Try_body(self: Try)(using Context): Term = self.expr + def Try_cases(self: Try)(using Context): List[CaseDef] = self.cases + def Try_finalizer(self: Try)(using Context): Option[Term] = optional(self.finalizer) - def Try_apply(expr: Term, cases: List[CaseDef], finalizer: Option[Term])(using ctx: Context): Try = + def Try_apply(expr: Term, cases: List[CaseDef], finalizer: Option[Term])(using Context): Try = withDefaultPos(tpd.Try(expr, cases, finalizer.getOrElse(tpd.EmptyTree))) - def Try_copy(original: Tree)(expr: Term, cases: List[CaseDef], finalizer: Option[Term])(using ctx: Context): Try = + def Try_copy(original: Tree)(expr: Term, cases: List[CaseDef], finalizer: Option[Term])(using Context): Try = tpd.cpy.Try(original)(expr, cases, finalizer.getOrElse(tpd.EmptyTree)) type Return = tpd.Return - def Return_TypeTest(using ctx: Context): TypeTest[Tree, Return] = new { + def Return_TypeTest(using Context): TypeTest[Tree, Return] = new { def runtimeClass: Class[?] = classOf[Return] override def unapply(x: Any): Option[Return] = x match case x: tpd.Return @unchecked => Some(x) case _ => None } - def Return_expr(self: Return)(using ctx: Context): Term = self.expr + def Return_expr(self: Return)(using Context): Term = self.expr - def Return_apply(expr: Term)(using ctx: Context): Return = + def Return_apply(expr: Term)(using Context): Return = withDefaultPos(tpd.Return(expr, ctx.owner)) - def Return_copy(original: Tree)(expr: Term)(using ctx: Context): Return = + def Return_copy(original: Tree)(expr: Term)(using Context): Return = tpd.cpy.Return(original)(expr, tpd.ref(ctx.owner)) type Repeated = tpd.SeqLiteral - def Repeated_TypeTest(using ctx: Context): TypeTest[Tree, Repeated] = new { + def Repeated_TypeTest(using Context): TypeTest[Tree, Repeated] = new { def runtimeClass: Class[?] = classOf[Repeated] override def unapply(x: Any): Option[Repeated] = x match case x: tpd.SeqLiteral @unchecked => Some(x) case _ => None } - def Repeated_elems(self: Repeated)(using ctx: Context): List[Term] = self.elems - def Repeated_elemtpt(self: Repeated)(using ctx: Context): TypeTree = self.elemtpt + def Repeated_elems(self: Repeated)(using Context): List[Term] = self.elems + def Repeated_elemtpt(self: Repeated)(using Context): TypeTree = self.elemtpt - def Repeated_apply(elems: List[Term], elemtpt: TypeTree)(using ctx: Context): Repeated = + def Repeated_apply(elems: List[Term], elemtpt: TypeTree)(using Context): Repeated = withDefaultPos(tpd.SeqLiteral(elems, elemtpt)) - def Repeated_copy(original: Tree)(elems: List[Term], elemtpt: TypeTree)(using ctx: Context): Repeated = + def Repeated_copy(original: Tree)(elems: List[Term], elemtpt: TypeTree)(using Context): Repeated = tpd.cpy.SeqLiteral(original)(elems, elemtpt) type SelectOuter = tpd.Select - def SelectOuter_TypeTest(using ctx: Context): TypeTest[Tree, SelectOuter] = new { + def SelectOuter_TypeTest(using Context): TypeTest[Tree, SelectOuter] = new { def runtimeClass: Class[?] = classOf[SelectOuter] override def unapply(x: Any): Option[SelectOuter] = x match case x: tpd.Select @unchecked => @@ -733,39 +734,39 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def SelectOuter_qualifier(self: SelectOuter)(using ctx: Context): Term = self.qualifier - def SelectOuter_level(self: SelectOuter)(using ctx: Context): Int = { + def SelectOuter_qualifier(self: SelectOuter)(using Context): Term = self.qualifier + def SelectOuter_level(self: SelectOuter)(using Context): Int = { val NameKinds.OuterSelectName(_, levels) = self.name levels } - def SelectOuter_apply(qualifier: Term, name: String, levels: Int)(using ctx: Context): SelectOuter = + def SelectOuter_apply(qualifier: Term, name: String, levels: Int)(using Context): SelectOuter = withDefaultPos(tpd.Select(qualifier, NameKinds.OuterSelectName(name.toTermName, levels))) - def SelectOuter_copy(original: Tree)(qualifier: Term, name: String, levels: Int)(using ctx: Context): SelectOuter = + def SelectOuter_copy(original: Tree)(qualifier: Term, name: String, levels: Int)(using Context): SelectOuter = tpd.cpy.Select(original)(qualifier, NameKinds.OuterSelectName(name.toTermName, levels)) type While = tpd.WhileDo - def While_TypeTest(using ctx: Context): TypeTest[Tree, While] = new { + def While_TypeTest(using Context): TypeTest[Tree, While] = new { def runtimeClass: Class[?] = classOf[While] override def unapply(x: Any): Option[While] = x match case x: tpd.WhileDo @unchecked => Some(x) case _ => None } - def While_cond(self: While)(using ctx: Context): Term = self.cond - def While_body(self: While)(using ctx: Context): Term = self.body + def While_cond(self: While)(using Context): Term = self.cond + def While_body(self: While)(using Context): Term = self.body - def While_apply(cond: Term, body: Term)(using ctx: Context): While = + def While_apply(cond: Term, body: Term)(using Context): While = withDefaultPos(tpd.WhileDo(cond, body)) - def While_copy(original: Tree)(cond: Term, body: Term)(using ctx: Context): While = + def While_copy(original: Tree)(cond: Term, body: Term)(using Context): While = tpd.cpy.WhileDo(original)(cond, body) type TypeTree = tpd.Tree - def TypeTree_TypeTest(using ctx: Context): TypeTest[Tree, TypeTree] = new { + def TypeTree_TypeTest(using Context): TypeTest[Tree, TypeTree] = new { def runtimeClass: Class[?] = classOf[TypeTree] override def unapply(x: Any): Option[TypeTree] = x match case x: tpd.TypeBoundsTree @unchecked => None @@ -773,225 +774,225 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def TypeTree_tpe(self: TypeTree)(using ctx: Context): Type = self.tpe.stripTypeVar + def TypeTree_tpe(self: TypeTree)(using Context): Type = self.tpe.stripTypeVar type Inferred = tpd.TypeTree - def Inferred_TypeTest(using ctx: Context): TypeTest[Tree, Inferred] = new { + def Inferred_TypeTest(using Context): TypeTest[Tree, Inferred] = new { def runtimeClass: Class[?] = classOf[Inferred] override def unapply(x: Any): Option[Inferred] = x match case tpt: tpd.TypeTree @unchecked if !tpt.tpe.isInstanceOf[Types.TypeBounds] => Some(tpt) case _ => None } - def Inferred_apply(tpe: Type)(using ctx: Context): Inferred = withDefaultPos(tpd.TypeTree(tpe)) + def Inferred_apply(tpe: Type)(using Context): Inferred = withDefaultPos(tpd.TypeTree(tpe)) type TypeIdent = tpd.Ident - def TypeIdent_TypeTest(using ctx: Context): TypeTest[Tree, TypeIdent] = new { + def TypeIdent_TypeTest(using Context): TypeTest[Tree, TypeIdent] = new { def runtimeClass: Class[?] = classOf[TypeIdent] override def unapply(x: Any): Option[TypeIdent] = x match case tpt: tpd.Ident @unchecked if tpt.isType => Some(tpt) case _ => None } - def TypeIdent_name(self: TypeIdent)(using ctx: Context): String = self.name.toString + def TypeIdent_name(self: TypeIdent)(using Context): String = self.name.toString - def TypeIdent_copy(original: Tree)(name: String)(using ctx: Context): TypeIdent = + def TypeIdent_copy(original: Tree)(name: String)(using Context): TypeIdent = tpd.cpy.Ident(original)(name.toTypeName) type TypeSelect = tpd.Select - def TypeSelect_TypeTest(using ctx: Context): TypeTest[Tree, TypeSelect] = new { + def TypeSelect_TypeTest(using Context): TypeTest[Tree, TypeSelect] = new { def runtimeClass: Class[?] = classOf[TypeSelect] override def unapply(x: Any): Option[TypeSelect] = x match case tpt: tpd.Select @unchecked if tpt.isType && tpt.qualifier.isTerm => Some(tpt) case _ => None } - def TypeSelect_qualifier(self: TypeSelect)(using ctx: Context): Term = self.qualifier - def TypeSelect_name(self: TypeSelect)(using ctx: Context): String = self.name.toString + def TypeSelect_qualifier(self: TypeSelect)(using Context): Term = self.qualifier + def TypeSelect_name(self: TypeSelect)(using Context): String = self.name.toString - def TypeSelect_apply(qualifier: Term, name: String)(using ctx: Context): TypeSelect = + def TypeSelect_apply(qualifier: Term, name: String)(using Context): TypeSelect = withDefaultPos(tpd.Select(qualifier, name.toTypeName)) - def TypeSelect_copy(original: Tree)(qualifier: Term, name: String)(using ctx: Context): TypeSelect = + def TypeSelect_copy(original: Tree)(qualifier: Term, name: String)(using Context): TypeSelect = tpd.cpy.Select(original)(qualifier, name.toTypeName) type Projection = tpd.Select - def Projection_TypeTest(using ctx: Context): TypeTest[Tree, Projection] = new { + def Projection_TypeTest(using Context): TypeTest[Tree, Projection] = new { def runtimeClass: Class[?] = classOf[Projection] override def unapply(x: Any): Option[Projection] = x match case tpt: tpd.Select @unchecked if tpt.isType && tpt.qualifier.isType => Some(tpt) case _ => None } - def Projection_qualifier(self: Projection)(using ctx: Context): TypeTree = self.qualifier - def Projection_name(self: Projection)(using ctx: Context): String = self.name.toString + def Projection_qualifier(self: Projection)(using Context): TypeTree = self.qualifier + def Projection_name(self: Projection)(using Context): String = self.name.toString - def Projection_copy(original: Tree)(qualifier: TypeTree, name: String)(using ctx: Context): Projection = + def Projection_copy(original: Tree)(qualifier: TypeTree, name: String)(using Context): Projection = tpd.cpy.Select(original)(qualifier, name.toTypeName) type Singleton = tpd.SingletonTypeTree - def Singleton_TypeTest(using ctx: Context): TypeTest[Tree, Singleton] = new { + def Singleton_TypeTest(using Context): TypeTest[Tree, Singleton] = new { def runtimeClass: Class[?] = classOf[Singleton] override def unapply(x: Any): Option[Singleton] = x match case tpt: tpd.SingletonTypeTree @unchecked => Some(tpt) case _ => None } - def Singleton_ref(self: Singleton)(using ctx: Context): Term = self.ref + def Singleton_ref(self: Singleton)(using Context): Term = self.ref - def Singleton_apply(ref: Term)(using ctx: Context): Singleton = + def Singleton_apply(ref: Term)(using Context): Singleton = withDefaultPos(tpd.SingletonTypeTree(ref)) - def Singleton_copy(original: Tree)(ref: Term)(using ctx: Context): Singleton = + def Singleton_copy(original: Tree)(ref: Term)(using Context): Singleton = tpd.cpy.SingletonTypeTree(original)(ref) type Refined = tpd.RefinedTypeTree - def Refined_TypeTest(using ctx: Context): TypeTest[Tree, Refined] = new { + def Refined_TypeTest(using Context): TypeTest[Tree, Refined] = new { def runtimeClass: Class[?] = classOf[Refined] override def unapply(x: Any): Option[Refined] = x match case tpt: tpd.RefinedTypeTree @unchecked => Some(tpt) case _ => None } - def Refined_tpt(self: Refined)(using ctx: Context): TypeTree = self.tpt - def Refined_refinements(self: Refined)(using ctx: Context): List[Definition] = self.refinements + def Refined_tpt(self: Refined)(using Context): TypeTree = self.tpt + def Refined_refinements(self: Refined)(using Context): List[Definition] = self.refinements - def Refined_copy(original: Tree)(tpt: TypeTree, refinements: List[Definition])(using ctx: Context): Refined = + def Refined_copy(original: Tree)(tpt: TypeTree, refinements: List[Definition])(using Context): Refined = tpd.cpy.RefinedTypeTree(original)(tpt, refinements) type Applied = tpd.AppliedTypeTree - def Applied_TypeTest(using ctx: Context): TypeTest[Tree, Applied] = new { + def Applied_TypeTest(using Context): TypeTest[Tree, Applied] = new { def runtimeClass: Class[?] = classOf[Applied] override def unapply(x: Any): Option[Applied] = x match case tpt: tpd.AppliedTypeTree @unchecked => Some(tpt) case _ => None } - def Applied_tpt(self: Applied)(using ctx: Context): TypeTree = self.tpt - def Applied_args(self: Applied)(using ctx: Context): List[TypeTree | TypeBoundsTree] = self.args + def Applied_tpt(self: Applied)(using Context): TypeTree = self.tpt + def Applied_args(self: Applied)(using Context): List[TypeTree | TypeBoundsTree] = self.args - def Applied_apply(tpt: TypeTree, args: List[TypeTree | TypeBoundsTree])(using ctx: Context): Applied = + def Applied_apply(tpt: TypeTree, args: List[TypeTree | TypeBoundsTree])(using Context): Applied = withDefaultPos(tpd.AppliedTypeTree(tpt, args)) - def Applied_copy(original: Tree)(tpt: TypeTree, args: List[TypeTree | TypeBoundsTree])(using ctx: Context): Applied = + def Applied_copy(original: Tree)(tpt: TypeTree, args: List[TypeTree | TypeBoundsTree])(using Context): Applied = tpd.cpy.AppliedTypeTree(original)(tpt, args) type Annotated = tpd.Annotated - def Annotated_TypeTest(using ctx: Context): TypeTest[Tree, Annotated] = new { + def Annotated_TypeTest(using Context): TypeTest[Tree, Annotated] = new { def runtimeClass: Class[?] = classOf[Annotated] override def unapply(x: Any): Option[Annotated] = x match case tpt: tpd.Annotated @unchecked => Some(tpt) case _ => None } - def Annotated_arg(self: Annotated)(using ctx: Context): TypeTree = self.arg - def Annotated_annotation(self: Annotated)(using ctx: Context): Term = self.annot + def Annotated_arg(self: Annotated)(using Context): TypeTree = self.arg + def Annotated_annotation(self: Annotated)(using Context): Term = self.annot - def Annotated_apply(arg: TypeTree, annotation: Term)(using ctx: Context): Annotated = + def Annotated_apply(arg: TypeTree, annotation: Term)(using Context): Annotated = withDefaultPos(tpd.Annotated(arg, annotation)) - def Annotated_copy(original: Tree)(arg: TypeTree, annotation: Term)(using ctx: Context): Annotated = + def Annotated_copy(original: Tree)(arg: TypeTree, annotation: Term)(using Context): Annotated = tpd.cpy.Annotated(original)(arg, annotation) type MatchTypeTree = tpd.MatchTypeTree - def MatchTypeTree_TypeTest(using ctx: Context): TypeTest[Tree, MatchTypeTree] = new { + def MatchTypeTree_TypeTest(using Context): TypeTest[Tree, MatchTypeTree] = new { def runtimeClass: Class[?] = classOf[MatchTypeTree] override def unapply(x: Any): Option[MatchTypeTree] = x match case tpt: tpd.MatchTypeTree @unchecked => Some(tpt) case _ => None } - def MatchTypeTree_bound(self: MatchTypeTree)(using ctx: Context): Option[TypeTree] = if (self.bound == tpd.EmptyTree) None else Some(self.bound) - def MatchTypeTree_selector(self: MatchTypeTree)(using ctx: Context): TypeTree = self.selector - def MatchTypeTree_cases(self: MatchTypeTree)(using ctx: Context): List[CaseDef] = self.cases + def MatchTypeTree_bound(self: MatchTypeTree)(using Context): Option[TypeTree] = if (self.bound == tpd.EmptyTree) None else Some(self.bound) + def MatchTypeTree_selector(self: MatchTypeTree)(using Context): TypeTree = self.selector + def MatchTypeTree_cases(self: MatchTypeTree)(using Context): List[CaseDef] = self.cases - def MatchTypeTree_apply(bound: Option[TypeTree], selector: TypeTree, cases: List[TypeCaseDef])(using ctx: Context): MatchTypeTree = + def MatchTypeTree_apply(bound: Option[TypeTree], selector: TypeTree, cases: List[TypeCaseDef])(using Context): MatchTypeTree = withDefaultPos(tpd.MatchTypeTree(bound.getOrElse(tpd.EmptyTree), selector, cases)) - def MatchTypeTree_copy(original: Tree)(bound: Option[TypeTree], selector: TypeTree, cases: List[TypeCaseDef])(using ctx: Context): MatchTypeTree = + def MatchTypeTree_copy(original: Tree)(bound: Option[TypeTree], selector: TypeTree, cases: List[TypeCaseDef])(using Context): MatchTypeTree = tpd.cpy.MatchTypeTree(original)(bound.getOrElse(tpd.EmptyTree), selector, cases) type ByName = tpd.ByNameTypeTree - def ByName_TypeTest(using ctx: Context): TypeTest[Tree, ByName] = new { + def ByName_TypeTest(using Context): TypeTest[Tree, ByName] = new { def runtimeClass: Class[?] = classOf[ByName] override def unapply(x: Any): Option[ByName] = x match case tpt: tpd.ByNameTypeTree @unchecked => Some(tpt) case _ => None } - def ByName_result(self: ByName)(using ctx: Context): TypeTree = self.result + def ByName_result(self: ByName)(using Context): TypeTree = self.result - def ByName_apply(result: TypeTree)(using ctx: Context): ByName = + def ByName_apply(result: TypeTree)(using Context): ByName = withDefaultPos(tpd.ByNameTypeTree(result)) - def ByName_copy(original: Tree)(result: TypeTree)(using ctx: Context): ByName = + def ByName_copy(original: Tree)(result: TypeTree)(using Context): ByName = tpd.cpy.ByNameTypeTree(original)(result) type LambdaTypeTree = tpd.LambdaTypeTree - def LambdaTypeTree_TypeTest(using ctx: Context): TypeTest[Tree, LambdaTypeTree] = new { + def LambdaTypeTree_TypeTest(using Context): TypeTest[Tree, LambdaTypeTree] = new { def runtimeClass: Class[?] = classOf[LambdaTypeTree] override def unapply(x: Any): Option[LambdaTypeTree] = x match case tpt: tpd.LambdaTypeTree @unchecked => Some(tpt) case _ => None } - def Lambdatparams(self: LambdaTypeTree)(using ctx: Context): List[TypeDef] = self.tparams - def Lambdabody(self: LambdaTypeTree)(using ctx: Context): TypeTree | TypeBoundsTree = self.body + def Lambdatparams(self: LambdaTypeTree)(using Context): List[TypeDef] = self.tparams + def Lambdabody(self: LambdaTypeTree)(using Context): TypeTree | TypeBoundsTree = self.body - def Lambdaapply(tparams: List[TypeDef], body: TypeTree | TypeBoundsTree)(using ctx: Context): LambdaTypeTree = + def Lambdaapply(tparams: List[TypeDef], body: TypeTree | TypeBoundsTree)(using Context): LambdaTypeTree = withDefaultPos(tpd.LambdaTypeTree(tparams, body)) - def Lambdacopy(original: Tree)(tparams: List[TypeDef], body: TypeTree | TypeBoundsTree)(using ctx: Context): LambdaTypeTree = + def Lambdacopy(original: Tree)(tparams: List[TypeDef], body: TypeTree | TypeBoundsTree)(using Context): LambdaTypeTree = tpd.cpy.LambdaTypeTree(original)(tparams, body) type TypeBind = tpd.Bind - def TypeBind_TypeTest(using ctx: Context): TypeTest[Tree, TypeBind] = new { + def TypeBind_TypeTest(using Context): TypeTest[Tree, TypeBind] = new { def runtimeClass: Class[?] = classOf[TypeBind] override def unapply(x: Any): Option[TypeBind] = x match case tpt: tpd.Bind @unchecked if tpt.name.isTypeName => Some(tpt) case _ => None } - def TypeBind_name(self: TypeBind)(using ctx: Context): String = self.name.toString - def TypeBind_body(self: TypeBind)(using ctx: Context): TypeTree | TypeBoundsTree = self.body + def TypeBind_name(self: TypeBind)(using Context): String = self.name.toString + def TypeBind_body(self: TypeBind)(using Context): TypeTree | TypeBoundsTree = self.body - def TypeBind_copy(original: Tree)(name: String, tpt: TypeTree | TypeBoundsTree)(using ctx: Context): TypeBind = + def TypeBind_copy(original: Tree)(name: String, tpt: TypeTree | TypeBoundsTree)(using Context): TypeBind = tpd.cpy.Bind(original)(name.toTypeName, tpt) type TypeBlock = tpd.Block - def TypeBlock_TypeTest(using ctx: Context): TypeTest[Tree, TypeBlock] = new { + def TypeBlock_TypeTest(using Context): TypeTest[Tree, TypeBlock] = new { def runtimeClass: Class[?] = classOf[TypeBlock] override def unapply(x: Any): Option[TypeBlock] = x match case tpt: tpd.Block @unchecked => Some(tpt) case _ => None } - def TypeBlock_aliases(self: TypeBlock)(using ctx: Context): List[TypeDef] = self.stats.map { case alias: TypeDef => alias } - def TypeBlock_tpt(self: TypeBlock)(using ctx: Context): TypeTree = self.expr + def TypeBlock_aliases(self: TypeBlock)(using Context): List[TypeDef] = self.stats.map { case alias: TypeDef => alias } + def TypeBlock_tpt(self: TypeBlock)(using Context): TypeTree = self.expr - def TypeBlock_apply(aliases: List[TypeDef], tpt: TypeTree)(using ctx: Context): TypeBlock = + def TypeBlock_apply(aliases: List[TypeDef], tpt: TypeTree)(using Context): TypeBlock = withDefaultPos(tpd.Block(aliases, tpt)) - def TypeBlock_copy(original: Tree)(aliases: List[TypeDef], tpt: TypeTree)(using ctx: Context): TypeBlock = + def TypeBlock_copy(original: Tree)(aliases: List[TypeDef], tpt: TypeTree)(using Context): TypeBlock = tpd.cpy.Block(original)(aliases, tpt) type TypeBoundsTree = tpd.TypeBoundsTree - def TypeBoundsTree_TypeTest(using ctx: Context): TypeTest[Tree, TypeBoundsTree] = new { + def TypeBoundsTree_TypeTest(using Context): TypeTest[Tree, TypeBoundsTree] = new { def runtimeClass: Class[?] = classOf[TypeBoundsTree] override def unapply(x: Any): Option[TypeBoundsTree] = x match case x: tpd.TypeBoundsTree @unchecked => Some(x) @@ -1005,80 +1006,80 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def TypeBoundsTree_tpe(self: TypeBoundsTree)(using ctx: Context): TypeBounds = self.tpe.asInstanceOf[Types.TypeBounds] - def TypeBoundsTree_low(self: TypeBoundsTree)(using ctx: Context): TypeTree = self.lo - def TypeBoundsTree_hi(self: TypeBoundsTree)(using ctx: Context): TypeTree = self.hi + def TypeBoundsTree_tpe(self: TypeBoundsTree)(using Context): TypeBounds = self.tpe.asInstanceOf[Types.TypeBounds] + def TypeBoundsTree_low(self: TypeBoundsTree)(using Context): TypeTree = self.lo + def TypeBoundsTree_hi(self: TypeBoundsTree)(using Context): TypeTree = self.hi type WildcardTypeTree = tpd.Ident - def WildcardTypeTree_TypeTest(using ctx: Context): TypeTest[Tree, WildcardTypeTree] = new { + def WildcardTypeTree_TypeTest(using Context): TypeTest[Tree, WildcardTypeTree] = new { def runtimeClass: Class[?] = classOf[WildcardTypeTree] override def unapply(x: Any): Option[WildcardTypeTree] = x match case x: tpd.Ident @unchecked if x.name == nme.WILDCARD => Some(x) case _ => None } - def WildcardTypeTree_tpe(self: WildcardTypeTree)(using ctx: Context): TypeOrBounds = self.tpe.stripTypeVar + def WildcardTypeTree_tpe(self: WildcardTypeTree)(using Context): TypeOrBounds = self.tpe.stripTypeVar type CaseDef = tpd.CaseDef - def CaseDef_TypeTest(using ctx: Context): TypeTest[Tree, CaseDef] = new { + def CaseDef_TypeTest(using Context): TypeTest[Tree, CaseDef] = new { def runtimeClass: Class[?] = classOf[CaseDef] override def unapply(x: Any): Option[CaseDef] = x match case tree: tpd.CaseDef @unchecked if tree.body.isTerm => Some(tree) case _ => None } - def CaseDef_pattern(self: CaseDef)(using ctx: Context): Tree = self.pat - def CaseDef_guard(self: CaseDef)(using ctx: Context): Option[Term] = optional(self.guard) - def CaseDef_rhs(self: CaseDef)(using ctx: Context): Term = self.body + def CaseDef_pattern(self: CaseDef)(using Context): Tree = self.pat + def CaseDef_guard(self: CaseDef)(using Context): Option[Term] = optional(self.guard) + def CaseDef_rhs(self: CaseDef)(using Context): Term = self.body - def CaseDef_module_apply(pattern: Tree, guard: Option[Term], body: Term)(using ctx: Context): CaseDef = + def CaseDef_module_apply(pattern: Tree, guard: Option[Term], body: Term)(using Context): CaseDef = tpd.CaseDef(pattern, guard.getOrElse(tpd.EmptyTree), body) - def CaseDef_module_copy(original: Tree)(pattern: Tree, guard: Option[Term], body: Term)(using ctx: Context): CaseDef = + def CaseDef_module_copy(original: Tree)(pattern: Tree, guard: Option[Term], body: Term)(using Context): CaseDef = tpd.cpy.CaseDef(original)(pattern, guard.getOrElse(tpd.EmptyTree), body) type TypeCaseDef = tpd.CaseDef - def TypeCaseDef_TypeTest(using ctx: Context): TypeTest[Tree, TypeCaseDef] = new { + def TypeCaseDef_TypeTest(using Context): TypeTest[Tree, TypeCaseDef] = new { def runtimeClass: Class[?] = classOf[TypeCaseDef] override def unapply(x: Any): Option[TypeCaseDef] = x match case tree: tpd.CaseDef @unchecked if tree.body.isType => Some(tree) case _ => None } - def TypeCaseDef_pattern(self: TypeCaseDef)(using ctx: Context): TypeTree = self.pat - def TypeCaseDef_rhs(self: TypeCaseDef)(using ctx: Context): TypeTree = self.body + def TypeCaseDef_pattern(self: TypeCaseDef)(using Context): TypeTree = self.pat + def TypeCaseDef_rhs(self: TypeCaseDef)(using Context): TypeTree = self.body - def TypeCaseDef_module_apply(pattern: TypeTree, body: TypeTree)(using ctx: Context): TypeCaseDef = + def TypeCaseDef_module_apply(pattern: TypeTree, body: TypeTree)(using Context): TypeCaseDef = tpd.CaseDef(pattern, tpd.EmptyTree, body) - def TypeCaseDef_module_copy(original: Tree)(pattern: TypeTree, body: TypeTree)(using ctx: Context): TypeCaseDef = + def TypeCaseDef_module_copy(original: Tree)(pattern: TypeTree, body: TypeTree)(using Context): TypeCaseDef = tpd.cpy.CaseDef(original)(pattern, tpd.EmptyTree, body) type Bind = tpd.Bind - def Bind_TypeTest(using ctx: Context): TypeTest[Tree, Bind] = new { + def Bind_TypeTest(using Context): TypeTest[Tree, Bind] = new { def runtimeClass: Class[?] = classOf[Bind] override def unapply(x: Any): Option[Bind] = x match case x: tpd.Bind @unchecked if x.name.isTermName => Some(x) case _ => None } - def Tree_Bind_name(self: Bind)(using ctx: Context): String = self.name.toString + def Tree_Bind_name(self: Bind)(using Context): String = self.name.toString - def Tree_Bind_pattern(self: Bind)(using ctx: Context): Tree = self.body + def Tree_Bind_pattern(self: Bind)(using Context): Tree = self.body - def Tree_Bind_module_apply(sym: Symbol, body: Tree)(using ctx: Context): Bind = + def Tree_Bind_module_apply(sym: Symbol, body: Tree)(using Context): Bind = tpd.Bind(sym, body) - def Tree_Bind_module_copy(original: Tree)(name: String, pattern: Tree)(using ctx: Context): Bind = + def Tree_Bind_module_copy(original: Tree)(name: String, pattern: Tree)(using Context): Bind = withDefaultPos(tpd.cpy.Bind(original)(name.toTermName, pattern)) type Unapply = tpd.UnApply - def Unapply_TypeTest(using ctx: Context): TypeTest[Tree, Unapply] = new { + def Unapply_TypeTest(using Context): TypeTest[Tree, Unapply] = new { def runtimeClass: Class[?] = classOf[Unapply] override def unapply(x: Any): Option[Unapply] = x match case pattern: tpd.UnApply @unchecked => Some(pattern) @@ -1086,11 +1087,11 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def Tree_Unapply_fun(self: Unapply)(using ctx: Context): Term = self.fun - def Tree_Unapply_implicits(self: Unapply)(using ctx: Context): List[Term] = self.implicits - def Tree_Unapply_patterns(self: Unapply)(using ctx: Context): List[Tree] = effectivePatterns(self.patterns) + def Tree_Unapply_fun(self: Unapply)(using Context): Term = self.fun + def Tree_Unapply_implicits(self: Unapply)(using Context): List[Term] = self.implicits + def Tree_Unapply_patterns(self: Unapply)(using Context): List[Tree] = effectivePatterns(self.patterns) - def Tree_Unapply_module_copy(original: Tree)(fun: Term, implicits: List[Term], patterns: List[Tree])(using ctx: Context): Unapply = + def Tree_Unapply_module_copy(original: Tree)(fun: Term, implicits: List[Term], patterns: List[Tree])(using Context): Unapply = withDefaultPos(tpd.cpy.UnApply(original)(fun, implicits, patterns)) private def effectivePatterns(patterns: List[Tree]): List[Tree] = patterns match { @@ -1100,19 +1101,19 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type Alternatives = tpd.Alternative - def Alternatives_TypeTest(using ctx: Context): TypeTest[Tree, Alternatives] = new { + def Alternatives_TypeTest(using Context): TypeTest[Tree, Alternatives] = new { def runtimeClass: Class[?] = classOf[Alternatives] override def unapply(x: Any): Option[Alternatives] = x match case x: tpd.Alternative @unchecked => Some(x) case _ => None } - def Tree_Alternatives_patterns(self: Alternatives)(using ctx: Context): List[Tree] = self.trees + def Tree_Alternatives_patterns(self: Alternatives)(using Context): List[Tree] = self.trees - def Tree_Alternatives_module_apply(patterns: List[Tree])(using ctx: Context): Alternatives = + def Tree_Alternatives_module_apply(patterns: List[Tree])(using Context): Alternatives = withDefaultPos(tpd.Alternative(patterns)) - def Tree_Alternatives_module_copy(original: Tree)(patterns: List[Tree])(using ctx: Context): Alternatives = + def Tree_Alternatives_module_copy(original: Tree)(patterns: List[Tree])(using Context): Alternatives = tpd.cpy.Alternative(original)(patterns) @@ -1124,7 +1125,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type NoPrefix = Types.NoPrefix.type - def NoPrefix_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, NoPrefix] = new { + def NoPrefix_TypeTest(using Context): TypeTest[TypeOrBounds, NoPrefix] = new { def runtimeClass: Class[?] = classOf[Types.NoPrefix.type] override def unapply(x: Any): Option[NoPrefix] = if (x == Types.NoPrefix) Some(Types.NoPrefix) else None @@ -1132,22 +1133,22 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type TypeBounds = Types.TypeBounds - def TypeBounds_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, TypeBounds] = new { + def TypeBounds_TypeTest(using Context): TypeTest[TypeOrBounds, TypeBounds] = new { def runtimeClass: Class[?] = classOf[TypeBounds] override def unapply(x: Any): Option[TypeBounds] = x match case x: Types.TypeBounds => Some(x) case _ => None } - def TypeBounds_apply(low: Type, hi: Type)(using ctx: Context): TypeBounds = + def TypeBounds_apply(low: Type, hi: Type)(using Context): TypeBounds = Types.TypeBounds(low, hi) - def TypeBounds_low(self: TypeBounds)(using ctx: Context): Type = self.lo - def TypeBounds_hi(self: TypeBounds)(using ctx: Context): Type = self.hi + def TypeBounds_low(self: TypeBounds)(using Context): Type = self.lo + def TypeBounds_hi(self: TypeBounds)(using Context): Type = self.hi type Type = Types.Type - def Type_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, Type] = new { + def Type_TypeTest(using Context): TypeTest[TypeOrBounds, Type] = new { def runtimeClass: Class[?] = classOf[Type] override def unapply(x: Any): Option[Type] = x match case x: TypeBounds => None @@ -1155,7 +1156,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def Type_apply(clazz: Class[?])(using ctx: Context): Type = + def Type_apply(clazz: Class[?])(using Context): Type = if (clazz.isPrimitive) if (clazz == classOf[Boolean]) defn.BooleanType else if (clazz == classOf[Byte]) defn.ByteType @@ -1177,103 +1178,103 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } else getClassIfDefined(clazz.getCanonicalName).typeRef - def Type_isTypeEq(self: Type)(that: Type)(using ctx: Context): Boolean = self =:= that + def Type_isTypeEq(self: Type)(that: Type)(using Context): Boolean = self =:= that - def Type_isSubType(self: Type)(that: Type)(using ctx: Context): Boolean = self <:< that + def Type_isSubType(self: Type)(that: Type)(using Context): Boolean = self <:< that - def Type_widen(self: Type)(using ctx: Context): Type = self.widen + def Type_widen(self: Type)(using Context): Type = self.widen - def Type_widenTermRefExpr(self: Type)(using ctx: Context): Type = self.widenTermRefExpr + def Type_widenTermRefExpr(self: Type)(using Context): Type = self.widenTermRefExpr - def Type_dealias(self: Type)(using ctx: Context): Type = self.dealias + def Type_dealias(self: Type)(using Context): Type = self.dealias - def Type_simplified(self: Type)(using ctx: Context): Type = self.simplified + def Type_simplified(self: Type)(using Context): Type = self.simplified - def Type_classSymbol(self: Type)(using ctx: Context): Option[Symbol] = + def Type_classSymbol(self: Type)(using Context): Option[Symbol] = if (self.classSymbol.exists) Some(self.classSymbol.asClass) else None - def Type_typeSymbol(self: Type)(using ctx: Context): Symbol = self.typeSymbol + def Type_typeSymbol(self: Type)(using Context): Symbol = self.typeSymbol - def Type_termSymbol(self: Type)(using ctx: Context): Symbol = self.termSymbol + def Type_termSymbol(self: Type)(using Context): Symbol = self.termSymbol - def Type_isSingleton(self: Type)(using ctx: Context): Boolean = self.isSingleton + def Type_isSingleton(self: Type)(using Context): Boolean = self.isSingleton - def Type_memberType(self: Type)(member: Symbol)(using ctx: Context): Type = + def Type_memberType(self: Type)(member: Symbol)(using Context): Type = member.info.asSeenFrom(self, member.owner) - def Type_baseClasses(self: Type)(using ctx: Context): List[Symbol] = + def Type_baseClasses(self: Type)(using Context): List[Symbol] = self.baseClasses - def Type_derivesFrom(self: Type)(cls: Symbol)(using ctx: Context): Boolean = + def Type_derivesFrom(self: Type)(cls: Symbol)(using Context): Boolean = self.derivesFrom(cls) - def Type_isFunctionType(self: Type)(using ctx: Context): Boolean = + def Type_isFunctionType(self: Type)(using Context): Boolean = defn.isFunctionType(self) - def Type_isContextFunctionType(self: Type)(using ctx: Context): Boolean = + def Type_isContextFunctionType(self: Type)(using Context): Boolean = defn.isContextFunctionType(self) - def Type_isErasedFunctionType(self: Type)(using ctx: Context): Boolean = + def Type_isErasedFunctionType(self: Type)(using Context): Boolean = defn.isErasedFunctionType(self) - def Type_isDependentFunctionType(self: Type)(using ctx: Context): Boolean = { + def Type_isDependentFunctionType(self: Type)(using Context): Boolean = { val tpNoRefinement = self.dropDependentRefinement tpNoRefinement != self && defn.isNonRefinedFunction(tpNoRefinement) } - def Type_select(self: Type)(sym: Symbol)(using ctx: Context): Type = + def Type_select(self: Type)(sym: Symbol)(using Context): Type = self.select(sym) type ConstantType = Types.ConstantType - def ConstantType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, ConstantType] = new { + def ConstantType_TypeTest(using Context): TypeTest[TypeOrBounds, ConstantType] = new { def runtimeClass: Class[?] = classOf[ConstantType] override def unapply(x: Any): Option[ConstantType] = x match case tpe: Types.ConstantType => Some(tpe) case _ => None } - def ConstantType_apply(const: Constant)(using ctx: Context): ConstantType = + def ConstantType_apply(const: Constant)(using Context): ConstantType = Types.ConstantType(const) - def ConstantType_constant(self: ConstantType)(using ctx: Context): Constant = self.value + def ConstantType_constant(self: ConstantType)(using Context): Constant = self.value type TermRef = Types.NamedType - def TermRef_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, TermRef] = new { + def TermRef_TypeTest(using Context): TypeTest[TypeOrBounds, TermRef] = new { def runtimeClass: Class[?] = classOf[TermRef] override def unapply(x: Any): Option[TermRef] = x match case tp: Types.TermRef => Some(tp) case _ => None } - def TermRef_apply(qual: TypeOrBounds, name: String)(using ctx: Context): TermRef = + def TermRef_apply(qual: TypeOrBounds, name: String)(using Context): TermRef = Types.TermRef(qual, name.toTermName) - def TermRef_qualifier(self: TermRef)(using ctx: Context): TypeOrBounds = self.prefix + def TermRef_qualifier(self: TermRef)(using Context): TypeOrBounds = self.prefix - def TermRef_name(self: TermRef)(using ctx: Context): String = self.name.toString + def TermRef_name(self: TermRef)(using Context): String = self.name.toString type TypeRef = Types.NamedType - def TypeRef_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, TypeRef] = new { + def TypeRef_TypeTest(using Context): TypeTest[TypeOrBounds, TypeRef] = new { def runtimeClass: Class[?] = classOf[TypeRef] override def unapply(x: Any): Option[TypeRef] = x match case tp: Types.TypeRef => Some(tp) case _ => None } - def TypeRef_qualifier(self: TypeRef)(using ctx: Context): TypeOrBounds = self.prefix + def TypeRef_qualifier(self: TypeRef)(using Context): TypeOrBounds = self.prefix - def TypeRef_name(self: TypeRef)(using ctx: Context): String = self.name.toString + def TypeRef_name(self: TypeRef)(using Context): String = self.name.toString - def TypeRef_isOpaqueAlias(self: TypeRef)(using ctx: Context): Boolean = self.symbol.isOpaqueAlias + def TypeRef_isOpaqueAlias(self: TypeRef)(using Context): Boolean = self.symbol.isOpaqueAlias - def TypeRef_translucentSuperType(self: TypeRef)(using ctx: Context): Type = self.translucentSuperType + def TypeRef_translucentSuperType(self: TypeRef)(using Context): Type = self.translucentSuperType type NamedTermRef = Types.NamedType - def NamedTermRef_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, NamedTermRef] = new { + def NamedTermRef_TypeTest(using Context): TypeTest[TypeOrBounds, NamedTermRef] = new { def runtimeClass: Class[?] = classOf[NamedTermRef] override def unapply(x: Any): Option[NamedTermRef] = x match case tpe: Types.NamedType => @@ -1284,34 +1285,34 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def NamedTermRef_name(self: NamedTermRef)(using ctx: Context): String = self.name.toString - def NamedTermRef_qualifier(self: NamedTermRef)(using ctx: Context): TypeOrBounds = self.prefix + def NamedTermRef_name(self: NamedTermRef)(using Context): String = self.name.toString + def NamedTermRef_qualifier(self: NamedTermRef)(using Context): TypeOrBounds = self.prefix type SuperType = Types.SuperType - def SuperType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, SuperType] = new { + def SuperType_TypeTest(using Context): TypeTest[TypeOrBounds, SuperType] = new { def runtimeClass: Class[?] = classOf[SuperType] override def unapply(x: Any): Option[SuperType] = x match case tpe: Types.SuperType => Some(tpe) case _ => None } - def SuperType_apply(thistpe: Type, supertpe: Type)(using ctx: Context): SuperType = + def SuperType_apply(thistpe: Type, supertpe: Type)(using Context): SuperType = Types.SuperType(thistpe, supertpe) - def SuperType_thistpe(self: SuperType)(using ctx: Context): Type = self.thistpe - def SuperType_supertpe(self: SuperType)(using ctx: Context): Type = self.supertpe + def SuperType_thistpe(self: SuperType)(using Context): Type = self.thistpe + def SuperType_supertpe(self: SuperType)(using Context): Type = self.supertpe type Refinement = Types.RefinedType - def Refinement_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, Refinement] = new { + def Refinement_TypeTest(using Context): TypeTest[TypeOrBounds, Refinement] = new { def runtimeClass: Class[?] = classOf[Refinement] override def unapply(x: Any): Option[Refinement] = x match case tpe: Types.RefinedType => Some(tpe) case _ => None } - def Refinement_apply(parent: Type, name: String, info: TypeOrBounds /* Type | TypeBounds */)(using ctx: Context): Refinement = { + def Refinement_apply(parent: Type, name: String, info: TypeOrBounds /* Type | TypeBounds */)(using Context): Refinement = { val name1 = info match case _: TypeBounds => name.toTypeName @@ -1319,101 +1320,101 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend Types.RefinedType(parent, name1, info) } - def Refinement_parent(self: Refinement)(using ctx: Context): Type = self.parent - def Refinement_name(self: Refinement)(using ctx: Context): String = self.refinedName.toString - def Refinement_info(self: Refinement)(using ctx: Context): TypeOrBounds = self.refinedInfo + def Refinement_parent(self: Refinement)(using Context): Type = self.parent + def Refinement_name(self: Refinement)(using Context): String = self.refinedName.toString + def Refinement_info(self: Refinement)(using Context): TypeOrBounds = self.refinedInfo type AppliedType = Types.AppliedType - def AppliedType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, AppliedType] = new { + def AppliedType_TypeTest(using Context): TypeTest[TypeOrBounds, AppliedType] = new { def runtimeClass: Class[?] = classOf[AppliedType] override def unapply(x: Any): Option[AppliedType] = x match case tpe: Types.AppliedType => Some(tpe) case _ => None } - def AppliedType_tycon(self: AppliedType)(using ctx: Context): Type = self.tycon - def AppliedType_args(self: AppliedType)(using ctx: Context): List[TypeOrBounds] = self.args + def AppliedType_tycon(self: AppliedType)(using Context): Type = self.tycon + def AppliedType_args(self: AppliedType)(using Context): List[TypeOrBounds] = self.args - def AppliedType_apply(tycon: Type, args: List[TypeOrBounds])(using ctx: Context): AppliedType = Types.AppliedType(tycon, args) + def AppliedType_apply(tycon: Type, args: List[TypeOrBounds])(using Context): AppliedType = Types.AppliedType(tycon, args) type AnnotatedType = Types.AnnotatedType - def AnnotatedType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, AnnotatedType] = new { + def AnnotatedType_TypeTest(using Context): TypeTest[TypeOrBounds, AnnotatedType] = new { def runtimeClass: Class[?] = classOf[AnnotatedType] override def unapply(x: Any): Option[AnnotatedType] = x match case tpe: Types.AnnotatedType => Some(tpe) case _ => None } - def AnnotatedType_apply(underlying: Type, annot: Term)(using ctx: Context): AnnotatedType = + def AnnotatedType_apply(underlying: Type, annot: Term)(using Context): AnnotatedType = Types.AnnotatedType(underlying, Annotations.Annotation(annot)) - def AnnotatedType_underlying(self: AnnotatedType)(using ctx: Context): Type = self.underlying.stripTypeVar - def AnnotatedType_annot(self: AnnotatedType)(using ctx: Context): Term = self.annot.tree + def AnnotatedType_underlying(self: AnnotatedType)(using Context): Type = self.underlying.stripTypeVar + def AnnotatedType_annot(self: AnnotatedType)(using Context): Term = self.annot.tree type AndType = Types.AndType - def AndType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, AndType] = new { + def AndType_TypeTest(using Context): TypeTest[TypeOrBounds, AndType] = new { def runtimeClass: Class[?] = classOf[AndType] override def unapply(x: Any): Option[AndType] = x match case tpe: Types.AndType => Some(tpe) case _ => None } - def AndType_apply(lhs: Type, rhs: Type)(using ctx: Context): AndType = + def AndType_apply(lhs: Type, rhs: Type)(using Context): AndType = Types.AndType(lhs, rhs) - def AndType_left(self: AndType)(using ctx: Context): Type = self.tp1.stripTypeVar - def AndType_right(self: AndType)(using ctx: Context): Type = self.tp2.stripTypeVar + def AndType_left(self: AndType)(using Context): Type = self.tp1.stripTypeVar + def AndType_right(self: AndType)(using Context): Type = self.tp2.stripTypeVar type OrType = Types.OrType - def OrType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, OrType] = new { + def OrType_TypeTest(using Context): TypeTest[TypeOrBounds, OrType] = new { def runtimeClass: Class[?] = classOf[OrType] override def unapply(x: Any): Option[OrType] = x match case tpe: Types.OrType => Some(tpe) case _ => None } - def OrType_apply(lhs: Type, rhs: Type)(using ctx: Context): OrType = + def OrType_apply(lhs: Type, rhs: Type)(using Context): OrType = Types.OrType(lhs, rhs) - def OrType_left(self: OrType)(using ctx: Context): Type = self.tp1.stripTypeVar - def OrType_right(self: OrType)(using ctx: Context): Type = self.tp2.stripTypeVar + def OrType_left(self: OrType)(using Context): Type = self.tp1.stripTypeVar + def OrType_right(self: OrType)(using Context): Type = self.tp2.stripTypeVar type MatchType = Types.MatchType - def MatchType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, MatchType] = new { + def MatchType_TypeTest(using Context): TypeTest[TypeOrBounds, MatchType] = new { def runtimeClass: Class[?] = classOf[MatchType] override def unapply(x: Any): Option[MatchType] = x match case tpe: Types.MatchType => Some(tpe) case _ => None } - def MatchType_apply(bound: Type, scrutinee: Type, cases: List[Type])(using ctx: Context): MatchType = + def MatchType_apply(bound: Type, scrutinee: Type, cases: List[Type])(using Context): MatchType = Types.MatchType(bound, scrutinee, cases) - def MatchType_bound(self: MatchType)(using ctx: Context): Type = self.bound - def MatchType_scrutinee(self: MatchType)(using ctx: Context): Type = self.scrutinee - def MatchType_cases(self: MatchType)(using ctx: Context): List[Type] = self.cases + def MatchType_bound(self: MatchType)(using Context): Type = self.bound + def MatchType_scrutinee(self: MatchType)(using Context): Type = self.scrutinee + def MatchType_cases(self: MatchType)(using Context): List[Type] = self.cases type ByNameType = Types.ExprType - def ByNameType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, ByNameType] = new { + def ByNameType_TypeTest(using Context): TypeTest[TypeOrBounds, ByNameType] = new { def runtimeClass: Class[?] = classOf[ByNameType] override def unapply(x: Any): Option[ByNameType] = x match case tpe: Types.ExprType => Some(tpe) case _ => None } - def ByNameType_apply(underlying: Type)(using ctx: Context): Type = Types.ExprType(underlying) + def ByNameType_apply(underlying: Type)(using Context): Type = Types.ExprType(underlying) - def ByNameType_underlying(self: ByNameType)(using ctx: Context): Type = self.resType.stripTypeVar + def ByNameType_underlying(self: ByNameType)(using Context): Type = self.resType.stripTypeVar type ParamRef = Types.ParamRef - def ParamRef_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, ParamRef] = new { + def ParamRef_TypeTest(using Context): TypeTest[TypeOrBounds, ParamRef] = new { def runtimeClass: Class[?] = classOf[ParamRef] override def unapply(x: Any): Option[ParamRef] = x match case tpe: Types.TypeParamRef => Some(tpe) @@ -1421,53 +1422,53 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def ParamRef_binder(self: ParamRef)(using ctx: Context): LambdaType[TypeOrBounds] = + def ParamRef_binder(self: ParamRef)(using Context): LambdaType[TypeOrBounds] = self.binder.asInstanceOf[LambdaType[TypeOrBounds]] // Cast to tpd - def ParamRef_paramNum(self: ParamRef)(using ctx: Context): Int = self.paramNum + def ParamRef_paramNum(self: ParamRef)(using Context): Int = self.paramNum type ThisType = Types.ThisType - def ThisType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, ThisType] = new { + def ThisType_TypeTest(using Context): TypeTest[TypeOrBounds, ThisType] = new { def runtimeClass: Class[?] = classOf[ThisType] override def unapply(x: Any): Option[ThisType] = x match case tpe: Types.ThisType => Some(tpe) case _ => None } - def ThisType_tref(self: ThisType)(using ctx: Context): Type = self.tref + def ThisType_tref(self: ThisType)(using Context): Type = self.tref type RecursiveThis = Types.RecThis - def RecursiveThis_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, RecursiveThis] = new { + def RecursiveThis_TypeTest(using Context): TypeTest[TypeOrBounds, RecursiveThis] = new { def runtimeClass: Class[?] = classOf[RecursiveThis] override def unapply(x: Any): Option[RecursiveThis] = x match case tpe: Types.RecThis => Some(tpe) case _ => None } - def RecursiveThis_binder(self: RecursiveThis)(using ctx: Context): RecursiveType = self.binder + def RecursiveThis_binder(self: RecursiveThis)(using Context): RecursiveType = self.binder type RecursiveType = Types.RecType - def RecursiveType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, RecursiveType] = new { + def RecursiveType_TypeTest(using Context): TypeTest[TypeOrBounds, RecursiveType] = new { def runtimeClass: Class[?] = classOf[RecursiveType] override def unapply(x: Any): Option[RecursiveType] = x match case tpe: Types.RecType => Some(tpe) case _ => None } - def RecursiveType_apply(parentExp: RecursiveType => Type)(using ctx: Context): RecursiveType = + def RecursiveType_apply(parentExp: RecursiveType => Type)(using Context): RecursiveType = Types.RecType(parentExp) - def RecursiveType_underlying(self: RecursiveType)(using ctx: Context): Type = self.underlying.stripTypeVar + def RecursiveType_underlying(self: RecursiveType)(using Context): Type = self.underlying.stripTypeVar - def RecursiveThis_recThis(self: RecursiveType)(using ctx: Context): RecursiveThis = self.recThis + def RecursiveThis_recThis(self: RecursiveType)(using Context): RecursiveThis = self.recThis type LambdaType[ParamInfo] = Types.LambdaType { type PInfo = ParamInfo } type MethodType = Types.MethodType - def MethodType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, MethodType] = new { + def MethodType_TypeTest(using Context): TypeTest[TypeOrBounds, MethodType] = new { def runtimeClass: Class[?] = classOf[MethodType] override def unapply(x: Any): Option[MethodType] = x match case tpe: Types.MethodType => Some(tpe) @@ -1479,31 +1480,31 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend def MethodType_isErased(self: MethodType): Boolean = self.isErasedMethod def MethodType_isImplicit(self: MethodType): Boolean = self.isImplicitMethod - def MethodType_param(self: MethodType, idx: Int)(using ctx: Context): Type = self.newParamRef(idx) - def MethodType_paramNames(self: MethodType)(using ctx: Context): List[String] = self.paramNames.map(_.toString) - def MethodType_paramTypes(self: MethodType)(using ctx: Context): List[Type] = self.paramInfos - def MethodType_resType(self: MethodType)(using ctx: Context): Type = self.resType + def MethodType_param(self: MethodType, idx: Int)(using Context): Type = self.newParamRef(idx) + def MethodType_paramNames(self: MethodType)(using Context): List[String] = self.paramNames.map(_.toString) + def MethodType_paramTypes(self: MethodType)(using Context): List[Type] = self.paramInfos + def MethodType_resType(self: MethodType)(using Context): Type = self.resType type PolyType = Types.PolyType - def PolyType_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, PolyType] = new { + def PolyType_TypeTest(using Context): TypeTest[TypeOrBounds, PolyType] = new { def runtimeClass: Class[?] = classOf[PolyType] override def unapply(x: Any): Option[PolyType] = x match case tpe: Types.PolyType => Some(tpe) case _ => None } - def PolyType_apply(paramNames: List[String])(paramBoundsExp: PolyType => List[TypeBounds], resultTypeExp: PolyType => Type)(using ctx: Context): PolyType = + def PolyType_apply(paramNames: List[String])(paramBoundsExp: PolyType => List[TypeBounds], resultTypeExp: PolyType => Type)(using Context): PolyType = Types.PolyType(paramNames.map(_.toTypeName))(paramBoundsExp, resultTypeExp) - def PolyType_param(self: PolyType, idx: Int)(using ctx: Context): Type = self.newParamRef(idx) - def PolyType_paramNames(self: PolyType)(using ctx: Context): List[String] = self.paramNames.map(_.toString) - def PolyType_paramBounds(self: PolyType)(using ctx: Context): List[TypeBounds] = self.paramInfos - def PolyType_resType(self: PolyType)(using ctx: Context): Type = self.resType + def PolyType_param(self: PolyType, idx: Int)(using Context): Type = self.newParamRef(idx) + def PolyType_paramNames(self: PolyType)(using Context): List[String] = self.paramNames.map(_.toString) + def PolyType_paramBounds(self: PolyType)(using Context): List[TypeBounds] = self.paramInfos + def PolyType_resType(self: PolyType)(using Context): Type = self.resType type TypeLambda = Types.TypeLambda - def TypeLambda_TypeTest(using ctx: Context): TypeTest[TypeOrBounds, TypeLambda] = new { + def TypeLambda_TypeTest(using Context): TypeTest[TypeOrBounds, TypeLambda] = new { def runtimeClass: Class[?] = classOf[TypeLambda] override def unapply(x: Any): Option[TypeLambda] = x match case tpe: Types.TypeLambda => Some(tpe) @@ -1513,11 +1514,11 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend def TypeLambda_apply(paramNames: List[String], boundsFn: TypeLambda => List[TypeBounds], bodyFn: TypeLambda => Type): TypeLambda = Types.HKTypeLambda(paramNames.map(_.toTypeName))(boundsFn, bodyFn) - def TypeLambda_paramNames(self: TypeLambda)(using ctx: Context): List[String] = self.paramNames.map(_.toString) - def TypeLambda_paramBounds(self: TypeLambda)(using ctx: Context): List[TypeBounds] = self.paramInfos - def TypeLambda_param(self: TypeLambda, idx: Int)(using ctx: Context): Type = + def TypeLambda_paramNames(self: TypeLambda)(using Context): List[String] = self.paramNames.map(_.toString) + def TypeLambda_paramBounds(self: TypeLambda)(using Context): List[TypeBounds] = self.paramInfos + def TypeLambda_param(self: TypeLambda, idx: Int)(using Context): Type = self.newParamRef(idx) - def TypeLambda_resType(self: TypeLambda)(using ctx: Context): Type = self.resType + def TypeLambda_resType(self: TypeLambda)(using Context): Type = self.resType ////////////////////// @@ -1528,32 +1529,32 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type SimpleSelector = untpd.ImportSelector - def SimpleSelector_TypeTest(using ctx: Context): TypeTest[ImportSelector, SimpleSelector] = new { + def SimpleSelector_TypeTest(using Context): TypeTest[ImportSelector, SimpleSelector] = new { def runtimeClass: Class[?] = classOf[SimpleSelector] override def unapply(x: Any): Option[SimpleSelector] = x match case x: untpd.ImportSelector if x.renamed.isEmpty => Some(x) case _ => None // TODO: handle import bounds } - def SimpleSelector_selection(self: SimpleSelector)(using ctx: Context): Id = self.imported + def SimpleSelector_selection(self: SimpleSelector)(using Context): Id = self.imported type RenameSelector = untpd.ImportSelector - def RenameSelector_TypeTest(using ctx: Context): TypeTest[ImportSelector, RenameSelector] = new { + def RenameSelector_TypeTest(using Context): TypeTest[ImportSelector, RenameSelector] = new { def runtimeClass: Class[?] = classOf[RenameSelector] override def unapply(x: Any): Option[RenameSelector] = x match case x: untpd.ImportSelector if !x.renamed.isEmpty => Some(x) case _ => None } - def RenameSelector_from(self: RenameSelector)(using ctx: Context): Id = + def RenameSelector_from(self: RenameSelector)(using Context): Id = self.imported - def RenameSelector_to(self: RenameSelector)(using ctx: Context): Id = + def RenameSelector_to(self: RenameSelector)(using Context): Id = self.renamed.asInstanceOf[untpd.Ident] type OmitSelector = untpd.ImportSelector - def OmitSelector_TypeTest(using ctx: Context): TypeTest[ImportSelector, OmitSelector] = new { + def OmitSelector_TypeTest(using Context): TypeTest[ImportSelector, OmitSelector] = new { def runtimeClass: Class[?] = classOf[OmitSelector] override def unapply(x: Any): Option[OmitSelector] = x match { case self: untpd.ImportSelector => @@ -1565,7 +1566,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } - def SimpleSelector_omitted(self: OmitSelector)(using ctx: Context): Id = + def SimpleSelector_omitted(self: OmitSelector)(using Context): Id = self.imported @@ -1575,9 +1576,9 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type Id = untpd.Ident - def Id_pos(self: Id)(using ctx: Context): Position = self.sourcePos + def Id_pos(self: Id)(using Context): Position = self.sourcePos - def Id_name(self: Id)(using ctx: Context): String = self.name.toString + def Id_name(self: Id)(using Context): String = self.name.toString //////////////// @@ -1672,37 +1673,37 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type Symbol = core.Symbols.Symbol - def Symbol_owner(self: Symbol)(using ctx: Context): Symbol = self.owner - def Symbol_maybeOwner(self: Symbol)(using ctx: Context): Symbol = self.maybeOwner + def Symbol_owner(self: Symbol)(using Context): Symbol = self.owner + def Symbol_maybeOwner(self: Symbol)(using Context): Symbol = self.maybeOwner - def Symbol_flags(self: Symbol)(using ctx: Context): Flags = self.flags + def Symbol_flags(self: Symbol)(using Context): Flags = self.flags - def Symbol_tree(self: Symbol)(using ctx: Context): Tree = + def Symbol_tree(self: Symbol)(using Context): Tree = FromSymbol.definitionFromSym(self) - def Symbol_privateWithin(self: Symbol)(using ctx: Context): Option[Type] = { + def Symbol_privateWithin(self: Symbol)(using Context): Option[Type] = { val within = self.privateWithin if (within.exists && !self.is(core.Flags.Protected)) Some(within.typeRef) else None } - def Symbol_protectedWithin(self: Symbol)(using ctx: Context): Option[Type] = { + def Symbol_protectedWithin(self: Symbol)(using Context): Option[Type] = { val within = self.privateWithin if (within.exists && self.is(core.Flags.Protected)) Some(within.typeRef) else None } - def Symbol_name(self: Symbol)(using ctx: Context): String = self.name.toString + def Symbol_name(self: Symbol)(using Context): String = self.name.toString - def Symbol_fullName(self: Symbol)(using ctx: Context): String = self.fullName.toString + def Symbol_fullName(self: Symbol)(using Context): String = self.fullName.toString - def Symbol_pos(self: Symbol)(using ctx: Context): Position = self.sourcePos + def Symbol_pos(self: Symbol)(using Context): Position = self.sourcePos - def Symbol_localContext(self: Symbol)(using ctx: Context): Context = + def Symbol_localContext(self: Symbol)(using Context): Context = if (self.exists) ctx.withOwner(self) else ctx - def Symbol_comment(self: Symbol)(using ctx: Context): Option[Comment] = { + def Symbol_comment(self: Symbol)(using Context): Option[Comment] = { import dotty.tools.dotc.core.Comments.CommentsContext val docCtx = ctx.docCtx.getOrElse { throw new RuntimeException( @@ -1711,129 +1712,129 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } docCtx.docstring(self) } - def Symbol_annots(self: Symbol)(using ctx: Context): List[Term] = + def Symbol_annots(self: Symbol)(using Context): List[Term] = self.annotations.flatMap { case _: core.Annotations.BodyAnnotation => Nil case annot => annot.tree :: Nil } - def Symbol_isDefinedInCurrentRun(self: Symbol)(using ctx: Context): Boolean = + def Symbol_isDefinedInCurrentRun(self: Symbol)(using Context): Boolean = self.topLevelClass.asClass.isDefinedInCurrentRun - def Symbol_isLocalDummy(self: Symbol)(using ctx: Context): Boolean = self.isLocalDummy - def Symbol_isRefinementClass(self: Symbol)(using ctx: Context): Boolean = self.isRefinementClass - def Symbol_isAliasType(self: Symbol)(using ctx: Context): Boolean = self.isAliasType - def Symbol_isAnonymousClass(self: Symbol)(using ctx: Context): Boolean = self.isAnonymousClass - def Symbol_isAnonymousFunction(self: Symbol)(using ctx: Context): Boolean = self.isAnonymousFunction - def Symbol_isAbstractType(self: Symbol)(using ctx: Context): Boolean = self.isAbstractType - def Symbol_isClassConstructor(self: Symbol)(using ctx: Context): Boolean = self.isClassConstructor + def Symbol_isLocalDummy(self: Symbol)(using Context): Boolean = self.isLocalDummy + def Symbol_isRefinementClass(self: Symbol)(using Context): Boolean = self.isRefinementClass + def Symbol_isAliasType(self: Symbol)(using Context): Boolean = self.isAliasType + def Symbol_isAnonymousClass(self: Symbol)(using Context): Boolean = self.isAnonymousClass + def Symbol_isAnonymousFunction(self: Symbol)(using Context): Boolean = self.isAnonymousFunction + def Symbol_isAbstractType(self: Symbol)(using Context): Boolean = self.isAbstractType + def Symbol_isClassConstructor(self: Symbol)(using Context): Boolean = self.isClassConstructor - def Symbol_fields(self: Symbol)(using ctx: Context): List[Symbol] = + def Symbol_fields(self: Symbol)(using Context): List[Symbol] = self.unforcedDecls.filter(isField) - def Symbol_field(self: Symbol)(name: String)(using ctx: Context): Symbol = { + def Symbol_field(self: Symbol)(name: String)(using Context): Symbol = { val sym = self.unforcedDecls.find(sym => sym.name == name.toTermName) if (isField(sym)) sym else core.Symbols.NoSymbol } - def Symbol_classMethod(self: Symbol)(name: String)(using ctx: Context): List[Symbol] = + def Symbol_classMethod(self: Symbol)(name: String)(using Context): List[Symbol] = self.typeRef.decls.iterator.collect { case sym if isMethod(sym) && sym.name.toString == name => sym.asTerm }.toList - def Symbol_typeMembers(self: Symbol)(using ctx: Context): List[Symbol] = + def Symbol_typeMembers(self: Symbol)(using Context): List[Symbol] = self.unforcedDecls.filter(_.isType) - def Symbol_typeMember(self: Symbol)(name: String)(using ctx: Context): Symbol = + def Symbol_typeMember(self: Symbol)(name: String)(using Context): Symbol = self.unforcedDecls.find(sym => sym.name == name.toTypeName) - def Symbol_classMethods(self: Symbol)(using ctx: Context): List[Symbol] = + def Symbol_classMethods(self: Symbol)(using Context): List[Symbol] = self.typeRef.decls.iterator.collect { case sym if isMethod(sym) => sym.asTerm }.toList private def appliedTypeRef(sym: Symbol): Type = sym.typeRef.appliedTo(sym.typeParams.map(_.typeRef)) - def Symbol_method(self: Symbol)(name: String)(using ctx: Context): List[Symbol] = + def Symbol_method(self: Symbol)(name: String)(using Context): List[Symbol] = appliedTypeRef(self).allMembers.iterator.map(_.symbol).collect { case sym if isMethod(sym) && sym.name.toString == name => sym.asTerm }.toList - def Symbol_methods(self: Symbol)(using ctx: Context): List[Symbol] = + def Symbol_methods(self: Symbol)(using Context): List[Symbol] = appliedTypeRef(self).allMembers.iterator.map(_.symbol).collect { case sym if isMethod(sym) => sym.asTerm }.toList - private def isMethod(sym: Symbol)(using ctx: Context): Boolean = + private def isMethod(sym: Symbol)(using Context): Boolean = sym.isTerm && sym.is(Flags.Method) && !sym.isConstructor - def Symbol_paramSymss(self: Symbol)(using ctx: Context): List[List[Symbol]] = + def Symbol_paramSymss(self: Symbol)(using Context): List[List[Symbol]] = self.paramSymss def Symbol_primaryConstructor(self: Symbol)(using Context): Symbol = self.primaryConstructor - def Symbol_caseFields(self: Symbol)(using ctx: Context): List[Symbol] = + def Symbol_caseFields(self: Symbol)(using Context): List[Symbol] = if (!self.isClass) Nil else self.asClass.paramAccessors.collect { case sym if sym.is(Flags.CaseAccessor) => sym.asTerm } - def Symbol_children(self: Symbol)(using ctx: Context): List[Symbol] = + def Symbol_children(self: Symbol)(using Context): List[Symbol] = self.children - private def isField(sym: Symbol)(using ctx: Context): Boolean = sym.isTerm && !sym.is(Flags.Method) + private def isField(sym: Symbol)(using Context): Boolean = sym.isTerm && !sym.is(Flags.Method) - def Symbol_of(fullName: String)(using ctx: Context): Symbol = + def Symbol_of(fullName: String)(using Context): Symbol = requiredClass(fullName) - def Symbol_newMethod(parent: Symbol, name: String, flags: Flags, tpe: Type, privateWithin: Symbol)(using ctx: Context): Symbol = + def Symbol_newMethod(parent: Symbol, name: String, flags: Flags, tpe: Type, privateWithin: Symbol)(using Context): Symbol = newSymbol(parent, name.toTermName, flags | Flags.Method, tpe, privateWithin) - def Symbol_newVal(parent: Symbol, name: String, flags: Flags, tpe: Type, privateWithin: Symbol)(using ctx: Context): Symbol = + def Symbol_newVal(parent: Symbol, name: String, flags: Flags, tpe: Type, privateWithin: Symbol)(using Context): Symbol = newSymbol(parent, name.toTermName, flags, tpe, privateWithin) - def Symbol_newBind(parent: Symbol, name: String, flags: Flags, tpe: Type)(using ctx: Context): Symbol = + def Symbol_newBind(parent: Symbol, name: String, flags: Flags, tpe: Type)(using Context): Symbol = newSymbol(parent, name.toTermName, flags | Case, tpe) - def Symbol_isTypeParam(self: Symbol)(using ctx: Context): Boolean = + def Symbol_isTypeParam(self: Symbol)(using Context): Boolean = self.isTypeParam - def Symbol_isType(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isType(symbol: Symbol)(using Context): Boolean = symbol.isType - def Symbol_isTerm(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isTerm(symbol: Symbol)(using Context): Boolean = symbol.isTerm - def Symbol_isPackageDef(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isPackageDef(symbol: Symbol)(using Context): Boolean = symbol.is(Flags.Package) - def Symbol_isClassDef(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isClassDef(symbol: Symbol)(using Context): Boolean = symbol.isClass - def Symbol_isTypeDef(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isTypeDef(symbol: Symbol)(using Context): Boolean = symbol.isType && !symbol.isClass && !symbol.is(Flags.Case) - def Symbol_isValDef(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isValDef(symbol: Symbol)(using Context): Boolean = symbol.isTerm && !symbol.is(core.Flags.Method) && !symbol.is(core.Flags.Case/*, FIXME add this check and fix sourcecode butNot = Enum | Module*/) - def Symbol_isDefDef(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isDefDef(symbol: Symbol)(using Context): Boolean = symbol.is(core.Flags.Method) - def Symbol_isBind(symbol: Symbol)(using ctx: Context): Boolean = + def Symbol_isBind(symbol: Symbol)(using Context): Boolean = symbol.is(core.Flags.Case, butNot = Enum | Module) && !symbol.isClass - def Symbol_signature(self: Symbol)(using ctx: Context): Signature = + def Symbol_signature(self: Symbol)(using Context): Signature = self.signature - def Symbol_moduleClass(self: Symbol)(using ctx: Context): Symbol = self.moduleClass + def Symbol_moduleClass(self: Symbol)(using Context): Symbol = self.moduleClass - def Symbol_companionClass(self: Symbol)(using ctx: Context): Symbol = self.companionClass + def Symbol_companionClass(self: Symbol)(using Context): Symbol = self.companionClass - def Symbol_companionModule(self: Symbol)(using ctx: Context): Symbol = self.companionModule + def Symbol_companionModule(self: Symbol)(using Context): Symbol = self.companionModule - def Symbol_noSymbol(using ctx: Context): Symbol = core.Symbols.NoSymbol + def Symbol_noSymbol(using Context): Symbol = core.Symbols.NoSymbol /////////// @@ -1979,11 +1980,11 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type ImplicitSearchResult = Tree - def searchImplicit(tpe: Type)(using ctx: Context): ImplicitSearchResult = + def searchImplicit(tpe: Type)(using Context): ImplicitSearchResult = ctx.typer.inferImplicitArg(tpe, rootPosition.span) type ImplicitSearchSuccess = Tree - def ImplicitSearchSuccess_TypeTest(using ctx: Context): TypeTest[ImplicitSearchResult, ImplicitSearchSuccess] = new { + def ImplicitSearchSuccess_TypeTest(using Context): TypeTest[ImplicitSearchResult, ImplicitSearchSuccess] = new { def runtimeClass: Class[?] = classOf[ImplicitSearchSuccess] override def unapply(x: Any): Option[ImplicitSearchSuccess] = x match case x: Tree @unchecked => @@ -1992,10 +1993,10 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => Some(x) case _ => None } - def ImplicitSearchSuccess_tree(self: ImplicitSearchSuccess)(using ctx: Context): Term = self + def ImplicitSearchSuccess_tree(self: ImplicitSearchSuccess)(using Context): Term = self type ImplicitSearchFailure = Tree - def ImplicitSearchFailure_TypeTest(using ctx: Context): TypeTest[ImplicitSearchResult, ImplicitSearchFailure] = new { + def ImplicitSearchFailure_TypeTest(using Context): TypeTest[ImplicitSearchResult, ImplicitSearchFailure] = new { def runtimeClass: Class[?] = classOf[ImplicitSearchFailure] override def unapply(x: Any): Option[ImplicitSearchFailure] = x match case x: Tree @unchecked => @@ -2004,11 +2005,11 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None case _ => None } - def ImplicitSearchFailure_explanation(self: ImplicitSearchFailure)(using ctx: Context): String = + def ImplicitSearchFailure_explanation(self: ImplicitSearchFailure)(using Context): String = self.tpe.asInstanceOf[SearchFailureType].explanation type DivergingImplicit = Tree - def DivergingImplicit_TypeTest(using ctx: Context): TypeTest[ImplicitSearchResult, DivergingImplicit] = new { + def DivergingImplicit_TypeTest(using Context): TypeTest[ImplicitSearchResult, DivergingImplicit] = new { def runtimeClass: Class[?] = classOf[DivergingImplicit] override def unapply(x: Any): Option[DivergingImplicit] = x match case x: Tree @unchecked => @@ -2019,7 +2020,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } type NoMatchingImplicits = Tree - def NoMatchingImplicits_TypeTest(using ctx: Context): TypeTest[ImplicitSearchResult, NoMatchingImplicits] = new { + def NoMatchingImplicits_TypeTest(using Context): TypeTest[ImplicitSearchResult, NoMatchingImplicits] = new { def runtimeClass: Class[?] = classOf[NoMatchingImplicits] override def unapply(x: Any): Option[NoMatchingImplicits] = x match case x: Tree @unchecked => @@ -2030,7 +2031,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend } type AmbiguousImplicits = Tree - def AmbiguousImplicits_TypeTest(using ctx: Context): TypeTest[ImplicitSearchResult, AmbiguousImplicits] = new { + def AmbiguousImplicits_TypeTest(using Context): TypeTest[ImplicitSearchResult, AmbiguousImplicits] = new { def runtimeClass: Class[?] = classOf[AmbiguousImplicits] override def unapply(x: Any): Option[AmbiguousImplicits] = x match case x: Tree @unchecked => @@ -2040,7 +2041,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend case _ => None } - def betaReduce(fn: Term, args: List[Term])(using ctx: Context): Term = { + def betaReduce(fn: Term, args: List[Term])(using Context): Term = { val (argVals0, argRefs0) = args.foldLeft((List.empty[ValDef], List.empty[Tree])) { case ((acc1, acc2), arg) => arg.tpe match { case tpe: SingletonType if isIdempotentExpr(arg) => (acc1, arg :: acc2) case _ => @@ -2056,7 +2057,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend seq(argVals, reducedBody).withSpan(fn.span) } - def lambdaExtractor(fn: Term, paramTypes: List[Type])(using ctx: Context): Option[List[Term] => Term] = { + def lambdaExtractor(fn: Term, paramTypes: List[Type])(using Context): Option[List[Term] => Term] = { def rec(fn: Term, transformBody: Term => Term): Option[List[Term] => Term] = { fn match { case Inlined(call, bindings, expansion) => @@ -2103,7 +2104,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend private def optional[T <: Trees.Tree[?]](tree: T): Option[tree.type] = if (tree.isEmpty) None else Some(tree) - private def withDefaultPos[T <: Tree](fn: Context ?=> T)(using ctx: Context): T = + private def withDefaultPos[T <: Tree](fn: Context ?=> T)(using Context): T = fn(using ctx.withSource(rootPosition.source)).withSpan(rootPosition.span) def compilerId: Int = rootContext.outersIterator.toList.last.hashCode() diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/package.scala b/compiler/src/dotty/tools/dotc/tastyreflect/package.scala index 3db7a3e6b680..3f2f98ed200a 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/package.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/package.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc import dotty.tools.dotc.ast.Trees.{Tree, Untyped} -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Symbols.Symbol import dotty.tools.dotc.core.Types.Type import dotty.tools.dotc.core.SymDenotations.SymDenotation diff --git a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala index 17a7fe241174..b1490bf4ff4a 100644 --- a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala +++ b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc package transform import core._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Flags._ import Names._ diff --git a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala index 11283c0a869f..314236400084 100644 --- a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Types._ import StdNames._ diff --git a/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala b/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala index cbafbe3a206a..6ba4244560ff 100644 --- a/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala +++ b/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Types._ import StdNames._ diff --git a/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala b/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala index 82806fa1095d..af74ba9f1de6 100644 --- a/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala +++ b/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase._ -import Contexts.{Context, ctx} +import Contexts._ import Flags._ import SymUtils._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala b/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala index 7431cc94554d..5c2436cbc7d1 100644 --- a/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala +++ b/compiler/src/dotty/tools/dotc/transform/BetaReduce.scala @@ -35,7 +35,7 @@ class BetaReduce extends MiniPhase: def phaseName: String = "betaReduce" - override def transformApply(app: Apply)(using ctx: Context): Tree = app.fun match + override def transformApply(app: Apply)(using Context): Tree = app.fun match case Select(fn, nme.apply) if defn.isFunctionType(fn.tpe) => val app1 = betaReduce(app, fn, app.args) if app1 ne app then report.log(i"beta reduce $app -> $app1") @@ -43,7 +43,7 @@ class BetaReduce extends MiniPhase: case _ => app - private def betaReduce(tree: Apply, fn: Tree, args: List[Tree])(using ctx: Context): Tree = + private def betaReduce(tree: Apply, fn: Tree, args: List[Tree])(using Context): Tree = fn match case Typed(expr, _) => betaReduce(tree, expr, args) case Block(Nil, expr) => betaReduce(tree, expr, args) @@ -54,7 +54,7 @@ object BetaReduce: import ast.tpd._ /** Beta-reduces a call to `ddef` with arguments `argSyms` */ - def apply(ddef: DefDef, args: List[Tree])(using ctx: Context) = + def apply(ddef: DefDef, args: List[Tree])(using Context) = val bindings = List.newBuilder[ValDef] val vparams = ddef.vparamss.iterator.flatten.toList assert(args.hasSameLengthAs(vparams)) diff --git a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala index e163cfd65250..172e611f260f 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala @@ -4,7 +4,7 @@ package transform import core._ import dotty.tools.dotc.transform.MegaPhase._ import Flags._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Decorators._ diff --git a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala index a8a8dbb4cd9d..75e0fb824ece 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala @@ -4,7 +4,7 @@ package transform import core._ import dotty.tools.dotc.transform.MegaPhase._ import Flags._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import dotty.tools.dotc.ast.tpd import Decorators._ diff --git a/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala b/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala index 452020044ccb..88d0b726dd4b 100644 --- a/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala +++ b/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc.transform import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Symbols.Symbol import dotty.tools.dotc.transform.MegaPhase.MiniPhase diff --git a/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala b/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala index 1a32b42ce8bf..b9cb7ec67e06 100644 --- a/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala +++ b/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala @@ -7,7 +7,7 @@ import StdNames.{nme, tpnme} import Types._ import dotty.tools.dotc.transform.MegaPhase._ import Flags._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Constants._ import Decorators._ diff --git a/compiler/src/dotty/tools/dotc/transform/Constructors.scala b/compiler/src/dotty/tools/dotc/transform/Constructors.scala index 1d7c0f8b7b26..14ac216b556a 100644 --- a/compiler/src/dotty/tools/dotc/transform/Constructors.scala +++ b/compiler/src/dotty/tools/dotc/transform/Constructors.scala @@ -4,7 +4,7 @@ package transform import core._ import MegaPhase._ import dotty.tools.dotc.ast.tpd._ -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.StdNames._ import ast._ import Trees._ diff --git a/compiler/src/dotty/tools/dotc/transform/CookComments.scala b/compiler/src/dotty/tools/dotc/transform/CookComments.scala index 7eeb99c47045..6ef0bdc4c247 100644 --- a/compiler/src/dotty/tools/dotc/transform/CookComments.scala +++ b/compiler/src/dotty/tools/dotc/transform/CookComments.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc.transform import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.ContextOps._ import dotty.tools.dotc.typer.Docstrings diff --git a/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala b/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala index a4c9406cde30..27a7907b266e 100644 --- a/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala +++ b/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase.MiniPhase -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import ast._ import Trees._ import Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala b/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala index 0fc0da4b3e64..55c31612be87 100644 --- a/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala +++ b/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc.transform import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Flags import dotty.tools.dotc.core.Types.AndType import dotty.tools.dotc.transform.MegaPhase._ diff --git a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala index dfc1089ad4ca..808cf928ecc2 100644 --- a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala +++ b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc package transform -import core.Contexts.{Context, ctx} +import core.Contexts._ /** Utility class for lazy values whose evaluation depends on a context. * This should be used whenever the evaluation of a lazy expression diff --git a/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled b/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled index 9117a216515f..13adcf5c3f76 100644 --- a/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled @@ -4,7 +4,7 @@ package transform import core._ import DenotTransformers.SymTransformer import Phases.Phase -import Contexts.{Context, ctx} +import Contexts._ import Flags._ import Symbols._ import SymDenotations.SymDenotation diff --git a/compiler/src/dotty/tools/dotc/transform/DropOuterAccessors.scala b/compiler/src/dotty/tools/dotc/transform/DropOuterAccessors.scala index 30c90b76033e..17b342709e0e 100644 --- a/compiler/src/dotty/tools/dotc/transform/DropOuterAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/DropOuterAccessors.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase.MiniPhase -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import ast._ import Trees._ import Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala b/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala index bb5c7fdc3454..c64486ddf50b 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala @@ -5,7 +5,7 @@ import core._ import dotty.tools.dotc.transform.MegaPhase._ import Flags._ import Types._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Decorators._ import Denotations.{SingleDenotation, NonSymSingleDenotation} diff --git a/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala b/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala index 9d2a5ac9b2be..20a3c3223ea8 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase.MiniPhase -import Contexts.{Context, ctx} +import Contexts._ import Types._ import NameKinds.OuterSelectName diff --git a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala index ddc8c4b91a31..4b48b649f278 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala @@ -178,7 +178,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => * The solution is to add a method that converts its argument from `Array[? <: T]` to `Seq[T]` and * forwards it to `ddef`. */ - private def addVarArgsForwarder(ddef: DefDef, isBridge: Boolean)(using ctx: Context): Tree = + private def addVarArgsForwarder(ddef: DefDef, isBridge: Boolean)(using Context): Tree = val original = ddef.symbol // The java-compatible forwarder symbol diff --git a/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala b/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala index b0e13a7d56cf..8bf188a6a2de 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc package transform import core._ -import Contexts.{Context, ctx} +import Contexts._ import Flags._ import dotty.tools.dotc.ast.tpd import MegaPhase.MiniPhase diff --git a/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala b/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala index 103869d41e9e..301b6b8a3b1c 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala @@ -3,7 +3,7 @@ package transform import core._ import dotty.tools.dotc.core.DenotTransformers.IdentityDenotTransformer -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Flags._ import SymDenotations._ diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala index b8a69397562b..0d28d71ba22a 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc package transform import core._ -import Contexts.{Context, ctx} +import Contexts._ import Types._ import MegaPhase._ import ast.Trees._ diff --git a/compiler/src/dotty/tools/dotc/transform/Flatten.scala b/compiler/src/dotty/tools/dotc/transform/Flatten.scala index a43eb53bba4a..2009076e5846 100644 --- a/compiler/src/dotty/tools/dotc/transform/Flatten.scala +++ b/compiler/src/dotty/tools/dotc/transform/Flatten.scala @@ -3,7 +3,7 @@ package transform import core._ import DenotTransformers.SymTransformer -import Contexts.{Context, ctx, FreshContext} +import Contexts._ import Flags._ import SymDenotations.SymDenotation import collection.mutable diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala index 23959f25f8f0..25bb7a5ce28f 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala @@ -3,7 +3,7 @@ package transform import core._ import Constants.Constant -import Contexts.{Context, ctx} +import Contexts._ import Flags._ import Definitions._ import DenotTransformers._ diff --git a/compiler/src/dotty/tools/dotc/transform/Getters.scala b/compiler/src/dotty/tools/dotc/transform/Getters.scala index a9d30a1f9330..b1d97d412910 100644 --- a/compiler/src/dotty/tools/dotc/transform/Getters.scala +++ b/compiler/src/dotty/tools/dotc/transform/Getters.scala @@ -3,7 +3,7 @@ package transform import core._ import DenotTransformers.SymTransformer -import Contexts.{Context, ctx} +import Contexts._ import SymDenotations.SymDenotation import Types._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala b/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala index eeab8c20b9b2..e86b8e5f3f89 100644 --- a/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala +++ b/compiler/src/dotty/tools/dotc/transform/InlinePatterns.scala @@ -35,7 +35,7 @@ class InlinePatterns extends MiniPhase: // by the pattern matcher but are still not visible in that group of phases. override def runsAfterGroupsOf: Set[String] = Set(PatternMatcher.name) - override def transformApply(app: Apply)(using ctx: Context): Tree = + override def transformApply(app: Apply)(using Context): Tree = if app.symbol.name.isUnapplyName && !app.tpe.isInstanceOf[MethodicType] then app match case App(Select(fn, name), argss) => @@ -52,7 +52,7 @@ class InlinePatterns extends MiniPhase: case Apply(App(fn, argss), args) => (fn, argss :+ args) case _ => (app, Nil) - private def betaReduce(tree: Apply, fn: Tree, name: Name, args: List[Tree])(using ctx: Context): Tree = + private def betaReduce(tree: Apply, fn: Tree, name: Name, args: List[Tree])(using Context): Tree = fn match case Block(TypeDef(_, template: Template) :: Nil, Apply(Select(New(_),_), Nil)) if template.constr.rhs.isEmpty => template.body match diff --git a/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala b/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala index 4d184397bb56..4c38c1119012 100644 --- a/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala +++ b/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc package transform import core._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Flags._ import SymDenotations._ diff --git a/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled b/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled index af37b606d791..68b493a0b9db 100644 --- a/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled @@ -4,7 +4,7 @@ package transform import dotty.tools.dotc.util.Positions._ import MegaPhase.MiniPhase import core._ -import Contexts.{Context, ctx}, Types._, Constants._, Decorators._, Symbols._ +import Contexts._, Types._, Constants._, Decorators._, Symbols._ import TypeUtils._, TypeErasure._, Flags._ /** Implements partial evaluation of `sc.isInstanceOf[Sel]` according to: diff --git a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala index fad15d309625..8ac80b3310d3 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -6,7 +6,7 @@ import java.util.IdentityHashMap import ast.tpd import core.Annotations.Annotation import core.Constants.Constant -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Decorators._ import core.DenotTransformers.IdentityDenotTransformer import core.Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/LetOverApply.scala b/compiler/src/dotty/tools/dotc/transform/LetOverApply.scala index 0d7dfc80f588..cd61c0f5ac82 100644 --- a/compiler/src/dotty/tools/dotc/transform/LetOverApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/LetOverApply.scala @@ -3,7 +3,7 @@ package dotc package transform import core._ -import Contexts.{Context, ctx}, Symbols._, Decorators._ +import Contexts._, Symbols._, Decorators._ import MegaPhase._ import ast.Trees._ diff --git a/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala b/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala index 2f568140fc2f..3a30ae41fc6e 100644 --- a/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala +++ b/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase._ -import Contexts.{Context, ctx} +import Contexts._ import Flags._ import SymUtils._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/Memoize.scala b/compiler/src/dotty/tools/dotc/transform/Memoize.scala index 98231da9fb0b..e8a3c564d16a 100644 --- a/compiler/src/dotty/tools/dotc/transform/Memoize.scala +++ b/compiler/src/dotty/tools/dotc/transform/Memoize.scala @@ -3,7 +3,7 @@ package transform import core._ import DenotTransformers._ -import Contexts.{Context, ctx} +import Contexts._ import Phases.phaseOf import SymDenotations.SymDenotation import Denotations._ diff --git a/compiler/src/dotty/tools/dotc/transform/Mixin.scala b/compiler/src/dotty/tools/dotc/transform/Mixin.scala index 4c8d45e6671f..6cdf54d5d305 100644 --- a/compiler/src/dotty/tools/dotc/transform/Mixin.scala +++ b/compiler/src/dotty/tools/dotc/transform/Mixin.scala @@ -4,7 +4,7 @@ package transform import core._ import MegaPhase._ -import Contexts.{Context, ctx, atPhase} +import Contexts._ import Flags._ import SymUtils._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala b/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala index 345c729f9fbb..6883c5c1086b 100644 --- a/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala +++ b/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc.transform import dotty.tools.dotc.ast.{Trees, tpd} import dotty.tools.dotc.core.Annotations.Annotation -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.DenotTransformers.SymTransformer import dotty.tools.dotc.core.SymDenotations.SymDenotation import dotty.tools.dotc.core.NameOps._ diff --git a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala index f79478b8495c..b7336c17f0ca 100644 --- a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc package transform -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.NameKinds._ import core.Symbols._ import core.Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala index 98aa8fc106d8..07f447d93fb4 100644 --- a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala @@ -327,7 +327,7 @@ class ReifyQuotes extends MacroTransform { val idx = embedded.addTree(body, NoSymbol) /** Remove references to local types that will not be defined in this quote */ - def getTypeHoleType(using ctx: Context) = new TypeMap() { + def getTypeHoleType(using Context) = new TypeMap() { override def apply(tp: Type): Type = tp match case tp: TypeRef if tp.typeSymbol.isSplice => apply(tp.dealias) @@ -341,7 +341,7 @@ class ReifyQuotes extends MacroTransform { } /** Remove references to local types that will not be defined in this quote */ - def getTermHoleType(using ctx: Context) = new TypeMap() { + def getTermHoleType(using Context) = new TypeMap() { override def apply(tp: Type): Type = tp match case tp @ TypeRef(NoPrefix, _) if capturers.contains(tp.symbol) => // reference to term with a type defined in outer quote diff --git a/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala b/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala index 137d4388d574..60327d59be88 100644 --- a/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala +++ b/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala @@ -1,6 +1,6 @@ package dotty.tools.dotc.transform -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.DenotTransformers.SymTransformer import dotty.tools.dotc.core.Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala index 457f824c011a..1f3600b471cd 100644 --- a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala +++ b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala @@ -3,7 +3,7 @@ package transform import core._ import MegaPhase._ -import Contexts.{Context, ctx} +import Contexts._ import Flags._ import SymUtils._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala b/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala index 839d805a1fc3..6fe75ce8a901 100644 --- a/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala +++ b/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala @@ -3,7 +3,7 @@ package transform import core._ import DenotTransformers.IdentityDenotTransformer -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Scopes._ import MegaPhase.MiniPhase diff --git a/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala b/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala index a3b6f0e6fbee..810b7984baf1 100644 --- a/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala @@ -3,7 +3,7 @@ package transform import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.DenotTransformers.IdentityDenotTransformer import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala b/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala index c28e5532eee2..aacf3373dbe0 100644 --- a/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala +++ b/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala @@ -3,7 +3,7 @@ package transform import core._ import dotty.tools.dotc.transform.MegaPhase._ -import Contexts.{Context, ctx} +import Contexts._ /** A transformer that eliminates SeqLiteral's, transforming `SeqLiteral(elems)` to an operation * equivalent to diff --git a/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala b/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala index dfd61315bdcc..06c3d3ffa0eb 100644 --- a/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala +++ b/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc.transform import dotty.tools.dotc.CompilationUnit import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Phases.Phase /** Set the `rootTreeOrProvider` property of class symbols. */ diff --git a/compiler/src/dotty/tools/dotc/transform/TailRec.scala b/compiler/src/dotty/tools/dotc/transform/TailRec.scala index e2e70906adeb..196fccf4c30e 100644 --- a/compiler/src/dotty/tools/dotc/transform/TailRec.scala +++ b/compiler/src/dotty/tools/dotc/transform/TailRec.scala @@ -4,7 +4,7 @@ package transform import ast.Trees._ import ast.{TreeTypeMap, tpd} import config.Printers.tailrec -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Constants.Constant import core.Decorators._ import core.Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala index 701c48712bd4..cab2fa3328a4 100644 --- a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala +++ b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala @@ -7,7 +7,7 @@ import ast.Trees._ import core.Types._ import core.NameKinds.ExceptionBinderName import dotty.tools.dotc.core.Flags -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.transform.MegaPhase.MiniPhase import dotty.tools.dotc.util.Spans.Span diff --git a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala index 4a937565f382..e0d69516fe16 100644 --- a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala +++ b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala @@ -3,7 +3,7 @@ package transform import core._ import Constants.Constant -import Contexts.{Context, ctx} +import Contexts._ import Decorators._ import Flags._ import ast.Trees._ diff --git a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala index 2184591ceb16..09bc9dad9f95 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala @@ -196,7 +196,7 @@ object TypeTestsCasts { def transformIsInstanceOf(expr: Tree, testType: Type, flagUnrelated: Boolean): Tree = { def testCls = effectiveClass(testType.widen) - def unreachable(why: => String)(using ctx: Context): Boolean = { + def unreachable(why: => String)(using Context): Boolean = { if (flagUnrelated) if (inMatch) report.error(em"this case is unreachable since $why", expr.sourcePos) else report.warning(em"this will always yield false since $why", expr.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/transform/init/Checker.scala b/compiler/src/dotty/tools/dotc/transform/init/Checker.scala index f8e36e66f8d6..f604b851a18c 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Checker.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Checker.scala @@ -7,7 +7,7 @@ import dotty.tools.dotc._ import ast.tpd import dotty.tools.dotc.core._ -import Contexts.{Context, ctx} +import Contexts._ import Types._ import dotty.tools.dotc.transform._ diff --git a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala index 8e8ac85886f1..b38fb934e466 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala @@ -5,7 +5,7 @@ package init import scala.collection.mutable import core._ -import Contexts.{Context, ctx} +import Contexts._ import ast.tpd._ import Decorators._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/init/Env.scala b/compiler/src/dotty/tools/dotc/transform/init/Env.scala index f0e83f9e61c9..47ad287b4860 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Env.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Env.scala @@ -3,7 +3,7 @@ package transform package init import core._ -import Contexts.{Context, ctx} +import Contexts._ import Types._ import Symbols._ import Decorators._ diff --git a/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala b/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala index 379f4c5f976d..8b8ceacc053f 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala @@ -4,7 +4,7 @@ package init import MegaPhase._ import ast.tpd -import core.Contexts.{Context, ctx} +import core.Contexts._ /** Set the `defTree` property of symbols */ class SetDefTree extends MiniPhase { diff --git a/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala b/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala index 2ff0e9dc451f..0584971aac97 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala @@ -3,7 +3,7 @@ package transform package init import core._ -import Contexts.{Context, ctx} +import Contexts._ import Decorators._ import StdNames._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/init/Summary.scala b/compiler/src/dotty/tools/dotc/transform/init/Summary.scala index fd62efc1cb4c..35c264751434 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Summary.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Summary.scala @@ -5,7 +5,7 @@ package init import scala.collection.mutable import core._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import reporting.trace import config.Printers.init diff --git a/compiler/src/dotty/tools/dotc/transform/init/Util.scala b/compiler/src/dotty/tools/dotc/transform/init/Util.scala index 6a315f0050c7..ac3d12364d26 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Util.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Util.scala @@ -3,7 +3,7 @@ package transform package init import core._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import config.Printers.Printer diff --git a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala index 127f12f85bbf..ff198f415baa 100644 --- a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala +++ b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala @@ -5,7 +5,7 @@ import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Constants.Constant -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Types.MethodType diff --git a/compiler/src/dotty/tools/dotc/typer/Dynamic.scala b/compiler/src/dotty/tools/dotc/typer/Dynamic.scala index 6139d55652b1..fcce4bb9a45e 100644 --- a/compiler/src/dotty/tools/dotc/typer/Dynamic.scala +++ b/compiler/src/dotty/tools/dotc/typer/Dynamic.scala @@ -6,7 +6,7 @@ import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.tpd import dotty.tools.dotc.ast.untpd import dotty.tools.dotc.core.Constants.Constant -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Names.{Name, TermName} import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Types._ diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index ab98c8c5d72d..c9ba8e2eb383 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -13,7 +13,7 @@ import Constants._ import StagingContext._ import StdNames._ import transform.SymUtils._ -import Contexts.{Context, inContext, ctx} +import Contexts._ import Names.{Name, TermName} import NameKinds.{InlineAccessorName, InlineBinderName, InlineScrutineeName, BodyRetainerName} import ProtoTypes.selectionProto diff --git a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala index 3a53f9399b23..e02aae1e8dbb 100644 --- a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala +++ b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc.util import dotty.tools.dotc.core.Comments.{Comment, CommentsContext} -import dotty.tools.dotc.core.Contexts.{Context, ctx, inContext} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Names.TermName import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.printing.SyntaxHighlighting diff --git a/compiler/src/dotty/tools/dotc/util/Signatures.scala b/compiler/src/dotty/tools/dotc/util/Signatures.scala index 7ea6941c4282..58dde0c590d3 100644 --- a/compiler/src/dotty/tools/dotc/util/Signatures.scala +++ b/compiler/src/dotty/tools/dotc/util/Signatures.scala @@ -4,7 +4,7 @@ package util import ast.Trees._ import ast.tpd import core.Constants.Constant -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Denotations.SingleDenotation import core.Flags.Implicit import core.Names.TermName diff --git a/compiler/src/dotty/tools/dotc/util/SourceFile.scala b/compiler/src/dotty/tools/dotc/util/SourceFile.scala index 3ad9bf07fb17..36ff21c297ab 100644 --- a/compiler/src/dotty/tools/dotc/util/SourceFile.scala +++ b/compiler/src/dotty/tools/dotc/util/SourceFile.scala @@ -9,7 +9,7 @@ import java.io.IOException import scala.internal.Chars._ import Spans._ import scala.io.Codec -import core.Contexts.{Context, ctx} +import core.Contexts._ import scala.annotation.internal.sharable import java.util.concurrent.atomic.AtomicInteger import scala.collection.mutable diff --git a/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala b/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala index 266d1f1528f4..f46b5feed76a 100644 --- a/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala +++ b/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala @@ -2,7 +2,7 @@ package dotty.tools.repl import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.tpd -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Phases.Phase /** A phase that collects user defined top level imports. diff --git a/compiler/src/dotty/tools/repl/JLineTerminal.scala b/compiler/src/dotty/tools/repl/JLineTerminal.scala index 36ed0aa3ea38..916df851cbf9 100644 --- a/compiler/src/dotty/tools/repl/JLineTerminal.scala +++ b/compiler/src/dotty/tools/repl/JLineTerminal.scala @@ -1,6 +1,6 @@ package dotty.tools.repl -import dotty.tools.dotc.core.Contexts.{Context, ctx} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.parsing.Scanners.Scanner import dotty.tools.dotc.parsing.Tokens._ import dotty.tools.dotc.printing.SyntaxHighlighting diff --git a/compiler/src/dotty/tools/repl/ParseResult.scala b/compiler/src/dotty/tools/repl/ParseResult.scala index 06ecd5c4d356..066742ea59e2 100644 --- a/compiler/src/dotty/tools/repl/ParseResult.scala +++ b/compiler/src/dotty/tools/repl/ParseResult.scala @@ -3,7 +3,7 @@ package repl import dotc.CompilationUnit import dotc.ast.untpd -import dotc.core.Contexts.{Context, ctx, inContext} +import dotc.core.Contexts._ import dotc.core.StdNames.str import dotc.parsing.Parsers.Parser import dotc.parsing.Tokens diff --git a/compiler/src/dotty/tools/repl/Rendering.scala b/compiler/src/dotty/tools/repl/Rendering.scala index 0c5874480562..4406dbf1e4fc 100644 --- a/compiler/src/dotty/tools/repl/Rendering.scala +++ b/compiler/src/dotty/tools/repl/Rendering.scala @@ -6,7 +6,7 @@ import java.lang.{ ClassLoader, ExceptionInInitializerError } import java.lang.reflect.InvocationTargetException import dotc.ast.tpd -import dotc.core.Contexts.{Context, ctx} +import dotc.core.Contexts._ import dotc.core.Denotations.Denotation import dotc.core.Flags import dotc.core.Flags._ diff --git a/compiler/src/dotty/tools/repl/ReplFrontEnd.scala b/compiler/src/dotty/tools/repl/ReplFrontEnd.scala index dd4fbc2a6ee7..8e07ccdfe0c3 100644 --- a/compiler/src/dotty/tools/repl/ReplFrontEnd.scala +++ b/compiler/src/dotty/tools/repl/ReplFrontEnd.scala @@ -3,7 +3,7 @@ package repl import dotc.typer.FrontEnd import dotc.CompilationUnit -import dotc.core.Contexts.{Context, ctx} +import dotc.core.Contexts._ /** A customized `FrontEnd` for the REPL * From fc803f21d1b1d91fe60f26c58a7e5196289a852b Mon Sep 17 00:00:00 2001 From: Martin Odersky <odersky@gmail.com> Date: Thu, 16 Jul 2020 12:08:41 +0200 Subject: [PATCH 06/10] Fix rebase breakage --- .../tools/dotc/tastyreflect/ReflectionCompilerInterface.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala index d04226fc139f..b2234be57979 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala @@ -6,7 +6,7 @@ import dotty.tools.dotc.ast.{TreeTypeMap, Trees, tpd, untpd} import dotty.tools.dotc.typer.{Implicits, Typer} import dotty.tools.dotc.core._ import dotty.tools.dotc.core.Flags._ -import dotty.tools.dotc.core.Contexts.{ctx, CState} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.quoted.PickledQuotes import dotty.tools.dotc.core.Symbols._ From 1679663b2dea34b048d8171ed20eb8e7ccc8b1c2 Mon Sep 17 00:00:00 2001 From: Martin Odersky <odersky@gmail.com> Date: Mon, 20 Jul 2020 14:51:25 +0200 Subject: [PATCH 07/10] Move runId, phaseId back to context --- compiler/src/dotty/tools/dotc/Run.scala | 2 +- .../dotty/tools/dotc/core/Annotations.scala | 2 +- .../src/dotty/tools/dotc/core/Contexts.scala | 3 ++ .../dotty/tools/dotc/core/Definitions.scala | 4 +-- .../tools/dotc/core/DenotTransformers.scala | 2 +- .../dotty/tools/dotc/core/Denotations.scala | 16 ++++----- .../src/dotty/tools/dotc/core/Periods.scala | 4 +-- .../src/dotty/tools/dotc/core/Scopes.scala | 2 +- .../tools/dotc/core/SymDenotations.scala | 14 ++++---- .../src/dotty/tools/dotc/core/Symbols.scala | 12 +++---- .../src/dotty/tools/dotc/core/Types.scala | 34 +++++++++---------- .../dotty/tools/dotc/transform/Pickler.scala | 6 ++-- .../tools/dotc/transform/TreeChecker.scala | 2 +- .../tools/dotc/transform/ValueClasses.scala | 2 +- .../src/dotty/tools/dotc/typer/Namer.scala | 6 ++-- 15 files changed, 57 insertions(+), 54 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index c5fc3719f991..cd141101f246 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -85,7 +85,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint /** The context created for this run */ given runContext[Dummy_so_its_a_def] as Context = myCtx - assert(currentRunId(using runContext) <= Periods.MaxPossibleRunId) + assert(runContext.runId <= Periods.MaxPossibleRunId) private var myUnits: List[CompilationUnit] = _ private var myUnitsCached: List[CompilationUnit] = _ diff --git a/compiler/src/dotty/tools/dotc/core/Annotations.scala b/compiler/src/dotty/tools/dotc/core/Annotations.scala index eefdd5c64bd0..20ca963ff4a2 100644 --- a/compiler/src/dotty/tools/dotc/core/Annotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Annotations.scala @@ -59,7 +59,7 @@ object Annotations { case symFn: (Context ?=> Symbol) @unchecked => mySym = null mySym = atPhaseNoLater(picklerPhase)(symFn) - case sym: Symbol if sym.defRunId != currentRunId(using parentCtx) => + case sym: Symbol if sym.defRunId != parentCtx.runId => mySym = sym.denot.current.symbol case _ => } diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index f43a38881368..57e4823d1366 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -369,6 +369,9 @@ object Contexts { /** The current reporter */ def reporter: Reporter = typerState.reporter + final def runId = period.runId + final def phaseId = period.phaseId + /** Is this a context for the members of a class definition? */ def isClassDefContext: Boolean = owner.isClass && (owner ne outer.owner) diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index 6db6eeeb54bc..85eac41dfe9e 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -1356,9 +1356,9 @@ class Definitions { private var current: RunId = NoRunId private var cached: T = _ def apply()(using Context): T = { - if (current != currentRunId) { + if (current != ctx.runId) { cached = generate - current = currentRunId + current = ctx.runId } cached } diff --git a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala index 0cb6432df952..05473da8a03b 100644 --- a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala +++ b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala @@ -24,7 +24,7 @@ object DenotTransformers { /** The validity period of the transformed denotations in the given context */ def validFor(using Context): Period = - Period(currentRunId, id + 1, lastPhaseId) + Period(ctx.runId, id + 1, lastPhaseId) /** The transformation method */ def transform(ref: SingleDenotation)(using Context): SingleDenotation diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index cb0da1a65b39..d76bf0142ae9 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -686,11 +686,11 @@ object Denotations { private def updateValidity()(using Context): this.type = { assert( - currentRunId >= validFor.runId + ctx.runId >= validFor.runId || ctx.settings.YtestPickler.value // mixing test pickler with debug printing can travel back in time || ctx.mode.is(Mode.Printing) // no use to be picky when printing error messages || symbol.isOneOf(ValidForeverFlags), - s"denotation $this invalid in run ${currentRunId}. ValidFor: $validFor") + s"denotation $this invalid in run ${ctx.runId}. ValidFor: $validFor") var d: SingleDenotation = this while ({ d.validFor = Period(currentPeriod.runId, d.validFor.firstPhaseId, d.validFor.lastPhaseId) @@ -720,7 +720,7 @@ object Denotations { case _ => } if (!symbol.exists) return updateValidity() - if (!coveredInterval.containsPhaseId(currentPhaseId)) return NoDenotation + if (!coveredInterval.containsPhaseId(ctx.phaseId)) return NoDenotation if (ctx.debug) traceInvalid(this) staleSymbolError } @@ -842,7 +842,7 @@ object Denotations { } private def demandOutsideDefinedMsg(using Context): String = - s"demanding denotation of $this at phase ${currentPhase}(${currentPhaseId}) outside defined interval: defined periods are${definedPeriodsString}" + s"demanding denotation of $this at phase ${currentPhase}(${ctx.phaseId}) outside defined interval: defined periods are${definedPeriodsString}" /** Install this denotation to be the result of the given denotation transformer. * This is the implementation of the same-named method in SymDenotations. @@ -851,16 +851,16 @@ object Denotations { */ protected def installAfter(phase: DenotTransformer)(using Context): Unit = { val targetId = phase.next.id - if (currentPhaseId != targetId) atPhase(phase.next)(installAfter(phase)) + if (ctx.phaseId != targetId) atPhase(phase.next)(installAfter(phase)) else { val current = symbol.current // println(s"installing $this after $phase/${phase.id}, valid = ${current.validFor}") // printPeriods(current) - this.validFor = Period(currentRunId, targetId, current.validFor.lastPhaseId) + this.validFor = Period(ctx.runId, targetId, current.validFor.lastPhaseId) if (current.validFor.firstPhaseId >= targetId) current.replaceWith(this) else { - current.validFor = Period(currentRunId, current.validFor.firstPhaseId, targetId - 1) + current.validFor = Period(ctx.runId, current.validFor.firstPhaseId, targetId - 1) insertAfter(current) } } @@ -1071,7 +1071,7 @@ object Denotations { class ErrorDenotation(using Context) extends NonSymSingleDenotation(NoSymbol, NoType, NoType) { override def exists: Boolean = false override def hasUniqueSym: Boolean = false - validFor = Period.allInRun(currentRunId) + validFor = Period.allInRun(ctx.runId) protected def newLikeThis(s: Symbol, i: Type, pre: Type): SingleDenotation = this } diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index ae59500d8a1d..6dcb64ee4656 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -11,11 +11,11 @@ object Periods { * we take the next transformer id following the current phase. */ def currentStablePeriod(using Context): Period = - var first = currentPhaseId + var first = ctx.phaseId val nxTrans = ctx.base.nextDenotTransformerId(first) while (first - 1 > NoPhaseId && (ctx.base.nextDenotTransformerId(first - 1) == nxTrans)) first -= 1 - Period(currentRunId, first, nxTrans) + Period(ctx.runId, first, nxTrans) /** Are all base types in the current period guaranteed to be the same as in period `p`? */ def currentHasSameBaseTypesAs(p: Period)(using Context): Boolean = diff --git a/compiler/src/dotty/tools/dotc/core/Scopes.scala b/compiler/src/dotty/tools/dotc/core/Scopes.scala index b9f80c918049..1726b2963e4b 100644 --- a/compiler/src/dotty/tools/dotc/core/Scopes.scala +++ b/compiler/src/dotty/tools/dotc/core/Scopes.scala @@ -265,7 +265,7 @@ object Scopes { /** enter a symbol in this scope. */ final def enter[T <: Symbol](sym: T)(using Context): T = { - if (sym.isType && currentPhaseId <= typerPhase.id) + if (sym.isType && ctx.phaseId <= typerPhase.id) assert(lookup(sym.name) == NoSymbol, s"duplicate ${sym.debugString}; previous was ${lookup(sym.name).debugString}") // !!! DEBUG newScopeEntry(sym) diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index 96f578a50af5..c12b876ca6c4 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -2104,7 +2104,7 @@ object SymDenotations { * `phase.next`, install a new denotation with a cloned scope in `phase.next`. */ def ensureFreshScopeAfter(phase: DenotTransformer)(using Context): Unit = - if (currentPhaseId != phase.next.id) atPhase(phase.next)(ensureFreshScopeAfter(phase)) + if (ctx.phaseId != phase.next.id) atPhase(phase.next)(ensureFreshScopeAfter(phase)) else { val prevClassInfo = atPhase(phase) { current.asInstanceOf[ClassDenotation].classInfo @@ -2154,8 +2154,8 @@ object SymDenotations { /** The package objects in this class */ def packageObjs(using Context): List[ClassDenotation] = { - if (packageObjsRunId != currentRunId) { - packageObjsRunId = currentRunId + if (packageObjsRunId != ctx.runId) { + packageObjsRunId = ctx.runId packageObjsCache = Nil // break cycle in case we are looking for package object itself packageObjsCache = { val pkgObjBuf = new mutable.ListBuffer[ClassDenotation] @@ -2296,7 +2296,7 @@ object SymDenotations { for (sym <- scope.toList.iterator) // We need to be careful to not force the denotation of `sym` here, // otherwise it will be brought forward to the current run. - if (sym.defRunId != currentRunId && sym.isClass && sym.asClass.assocFile == file) + if (sym.defRunId != ctx.runId && sym.isClass && sym.asClass.assocFile == file) scope.unlink(sym, sym.lastKnownDenotation.name) } } @@ -2348,7 +2348,7 @@ object SymDenotations { else { val initial = denot.initial val firstPhaseId = initial.validFor.firstPhaseId.max(typerPhase.id) - if ((initial ne denot) || currentPhaseId != firstPhaseId) + if ((initial ne denot) || ctx.phaseId != firstPhaseId) atPhase(firstPhaseId)(stillValidInOwner(initial)) else stillValidInOwner(denot) @@ -2381,7 +2381,7 @@ object SymDenotations { if (denot.isOneOf(ValidForeverFlags) || denot.isRefinementClass) true else val initial = denot.initial - if ((initial ne denot) || currentPhaseId != initial.validFor.firstPhaseId) + if ((initial ne denot) || ctx.phaseId != initial.validFor.firstPhaseId) atPhase(initial.validFor.firstPhaseId)(traceInvalid(initial)) else try { val owner = denot.owner.denot @@ -2576,7 +2576,7 @@ object SymDenotations { def isValidAt(phase: Phase)(using Context) = checkedPeriod == currentPeriod || - createdAt.runId == currentRunId && + createdAt.runId == ctx.runId && createdAt.phaseId < unfusedPhases.length && sameGroup(unfusedPhases(createdAt.phaseId), phase) && { checkedPeriod = currentPeriod; true } diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index bb484de1951c..be602fd1f75b 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -134,14 +134,14 @@ object Symbols { /** Does this symbol come from a currently compiled source file? */ final def isDefinedInCurrentRun(using Context): Boolean = - span.exists && defRunId == currentRunId && { + span.exists && defRunId == ctx.runId && { val file = associatedFile file != null && ctx.run.files.contains(file) } /** Is symbol valid in current run? */ final def isValidInCurrentRun(using Context): Boolean = - (lastDenot.validFor.runId == currentRunId || stillValid(lastDenot)) && + (lastDenot.validFor.runId == ctx.runId || stillValid(lastDenot)) && (lastDenot.symbol eq this) // the last condition is needed because under ctx.staleOK overwritten // members keep denotations pointing to the new symbol, so the validity @@ -149,9 +149,9 @@ object Symbols { // valid. If the option would be removed, the check would be no longer needed. final def isTerm(using Context): Boolean = - (if (defRunId == currentRunId) lastDenot else denot).isTerm + (if (defRunId == ctx.runId) lastDenot else denot).isTerm final def isType(using Context): Boolean = - (if (defRunId == currentRunId) lastDenot else denot).isType + (if (defRunId == ctx.runId) lastDenot else denot).isType final def asTerm(using Context): TermSymbol = { assert(isTerm, s"asTerm called on not-a-Term $this" ); asInstanceOf[TermSymbol] @@ -204,7 +204,7 @@ object Symbols { * @pre Symbol is a class member */ def enteredAfter(phase: DenotTransformer)(using Context): this.type = - if currentPhaseId != phase.next.id then + if ctx.phaseId != phase.next.id then atPhase(phase.next)(enteredAfter(phase)) else this.owner match { case owner: ClassSymbol => @@ -229,7 +229,7 @@ object Symbols { * @pre Symbol is a class member */ def dropAfter(phase: DenotTransformer)(using Context): Unit = - if currentPhaseId != phase.next.id then + if ctx.phaseId != phase.next.id then atPhase(phase.next)(dropAfter(phase)) else { assert (!this.owner.is(Package)) diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index 2166b565cc6a..d1b77f68ced2 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -677,7 +677,7 @@ object Types { } else val joint = pdenot.meet( - new JointRefDenotation(NoSymbol, rinfo, Period.allInRun(currentRunId), pre), + new JointRefDenotation(NoSymbol, rinfo, Period.allInRun(ctx.runId), pre), pre, safeIntersection = ctx.base.pendingMemberSearches.contains(name)) joint match @@ -1914,7 +1914,7 @@ object Types { * some symbols change their signature at erasure. */ private def currentSignature(using Context): Signature = - if currentRunId == mySignatureRunId then mySignature + if ctx.runId == mySignatureRunId then mySignature else val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) @@ -1948,7 +1948,7 @@ object Types { * current run. */ def denotationIsCurrent(using Context): Boolean = - lastDenotation != null && lastDenotation.validFor.runId == currentRunId + lastDenotation != null && lastDenotation.validFor.runId == ctx.runId /** If the reference is symbolic or the denotation is current, its symbol, otherwise NoDenotation. * @@ -1969,7 +1969,7 @@ object Types { * Used to get the class underlying a ThisType. */ private[Types] def stableInRunSymbol(using Context): Symbol = - if (checkedPeriod.runId == currentRunId) lastSymbol + if (checkedPeriod.runId == ctx.runId) lastSymbol else symbol def info(using Context): Type = denot.info @@ -2008,7 +2008,7 @@ object Types { finish(memberDenot(name, allowPrivate)) case sym: Symbol => val symd = sym.lastKnownDenotation - if (symd.validFor.runId != currentRunId && !stillValid(symd)) + if (symd.validFor.runId != ctx.runId && !stillValid(symd)) finish(memberDenot(symd.initial.name, allowPrivate = false)) else if (prefix.isArgPrefixOf(symd)) finish(argDenot(sym.asType)) @@ -2021,7 +2021,7 @@ object Types { lastDenotation match { case lastd0: SingleDenotation => val lastd = lastd0.skipRemoved - if (lastd.validFor.runId == currentRunId && (checkedPeriod != Nowhere)) finish(lastd.current) + if (lastd.validFor.runId == ctx.runId && (checkedPeriod != Nowhere)) finish(lastd.current) else lastd match { case lastd: SymDenotation => if (stillValid(lastd) && (checkedPeriod != Nowhere)) finish(lastd.current) @@ -2053,9 +2053,9 @@ object Types { if (!d.exists && !allowPrivate && ctx.mode.is(Mode.Interactive)) // In the IDE we might change a public symbol to private, and would still expect to find it. d = memberDenot(prefix, name, true) - if (!d.exists && currentPhaseId > FirstPhaseId && lastDenotation.isInstanceOf[SymDenotation]) + if (!d.exists && ctx.phaseId > FirstPhaseId && lastDenotation.isInstanceOf[SymDenotation]) // name has changed; try load in earlier phase and make current - d = atPhase(currentPhaseId - 1)(memberDenot(name, allowPrivate)).current + d = atPhase(ctx.phaseId - 1)(memberDenot(name, allowPrivate)).current if (d.isOverloaded) d = disambiguate(d) d @@ -2155,7 +2155,7 @@ object Types { s"""data race? overwriting $lastSymbol with $sym in type $this, |last sym id = ${lastSymbol.id}, new sym id = ${sym.id}, |last owner = ${lastSymbol.owner}, new owner = ${sym.owner}, - |period = ${currentPhase} at run ${currentRunId}""") + |period = ${currentPhase} at run ${ctx.runId}""") } /** A reference with the initial symbol in `symd` has an info that @@ -2980,12 +2980,12 @@ object Types { private var myWidened: Type = _ private def ensureAtomsComputed()(using Context): Unit = - if atomsRunId != currentRunId then + if atomsRunId != ctx.runId then myAtoms = tp1.atoms | tp2.atoms val tp1w = tp1.widenSingletons val tp2w = tp2.widenSingletons myWidened = if ((tp1 eq tp1w) && (tp2 eq tp2w)) this else tp1w | tp2w - atomsRunId = currentRunId + atomsRunId = ctx.runId override def atoms(using Context): Atoms = ensureAtomsComputed() @@ -3070,9 +3070,9 @@ object Types { protected[dotc] def computeSignature(using Context): Signature final override def signature(using Context): Signature = { - if (currentRunId != mySignatureRunId) { + if (ctx.runId != mySignatureRunId) { mySignature = computeSignature - if (!mySignature.isUnderDefined) mySignatureRunId = currentRunId + if (!mySignature.isUnderDefined) mySignatureRunId = ctx.runId } mySignature } @@ -4992,14 +4992,14 @@ object Types { derivedSuperType(tp, this(thistp), this(supertp)) case tp: LazyRef => - LazyRef { + LazyRef { (using refCtx) => val ref1 = tp.ref - if currentRunId == currentRunId(using mapCtx) then this(ref1) + if refCtx.runId == mapCtx.runId then this(ref1) else // splice in new run into map context val saved = mapCtx mapCtx = mapCtx.fresh - .setPeriod(Period(currentRunId, currentPhaseId(using mapCtx))) - .setRun(ctx.run) + .setPeriod(Period(refCtx.runId, mapCtx.phaseId)) + .setRun(refCtx.run) try this(ref1) finally mapCtx = saved } diff --git a/compiler/src/dotty/tools/dotc/transform/Pickler.scala b/compiler/src/dotty/tools/dotc/transform/Pickler.scala index 7d7fc0dd0937..1e82218cae11 100644 --- a/compiler/src/dotty/tools/dotc/transform/Pickler.scala +++ b/compiler/src/dotty/tools/dotc/transform/Pickler.scala @@ -47,7 +47,7 @@ class Pickler extends Phase { override def run(using Context): Unit = { val unit = ctx.compilationUnit - pickling.println(i"unpickling in run ${currentRunId}") + pickling.println(i"unpickling in run ${ctx.runId}") for { cls <- dropCompanionModuleClasses(topLevelClasses(unit.tpdTree)) @@ -92,7 +92,7 @@ class Pickler extends Phase { if (ctx.settings.YtestPickler.value) testUnpickler( using ctx.fresh - .setPeriod(Period(currentRunId + 1, FirstPhaseId)) + .setPeriod(Period(ctx.runId + 1, FirstPhaseId)) .setReporter(new ThrowingReporter(ctx.reporter)) .addMode(Mode.ReadPositions) .addMode(Mode.ReadComments) @@ -101,7 +101,7 @@ class Pickler extends Phase { } private def testUnpickler(using Context): Unit = { - pickling.println(i"testing unpickler at run ${currentRunId}") + pickling.println(i"testing unpickler at run ${ctx.runId}") ctx.initialize() val unpicklers = for ((cls, pickler) <- picklers) yield { diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index 1b49c68d82cb..57275080b806 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -89,7 +89,7 @@ class TreeChecker extends Phase with SymTransformer { // Signatures are used to disambiguate overloads and need to stay stable // until erasure, see the comment above `Compiler#phases`. - if (currentPhaseId <= erasurePhase.id) { + if (ctx.phaseId <= erasurePhase.id) { val cur = symd.info val initial = symd.initial.info val curSig = cur match { diff --git a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala index 32925643aeb5..addaa2124233 100644 --- a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala +++ b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala @@ -25,7 +25,7 @@ object ValueClasses { def isMethodWithExtension(sym: Symbol)(using Context): Boolean = atPhaseNoLater(extensionMethodsPhase) { val d = sym.denot - d.validFor.containsPhaseId(currentPhaseId) && + d.validFor.containsPhaseId(ctx.phaseId) && d.isRealMethod && isDerivedValueClass(d.owner) && !d.isConstructor && diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index f7fc45d66213..d21f3155d963 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -703,9 +703,9 @@ class Namer { typer: Typer => else levels(c.outer) + 1 println(s"!!!completing ${denot.symbol.showLocated} in buried typerState, gap = ${levels(ctx)}") } - val creationRunId = currentRunId(using creationContext) - if currentRunId > creationRunId then - assert(ctx.mode.is(Mode.Interactive), s"completing $denot in wrong run ${currentRunId}, was created in $creationRunId") + val creationRunId = creationContext.runId + if ctx.runId > creationRunId then + assert(ctx.mode.is(Mode.Interactive), s"completing $denot in wrong run ${ctx.runId}, was created in $creationRunId") denot.info = UnspecifiedErrorType else try From 2ccebc59d9ba13653e160a585388e146be9f7ec2 Mon Sep 17 00:00:00 2001 From: Martin Odersky <odersky@gmail.com> Date: Mon, 20 Jul 2020 11:01:12 +0200 Subject: [PATCH 08/10] Move phase back to Context --- compiler/src/dotty/tools/dotc/Run.scala | 2 +- compiler/src/dotty/tools/dotc/ast/tpd.scala | 2 +- .../src/dotty/tools/dotc/core/Contexts.scala | 19 +++++++-------- .../dotty/tools/dotc/core/Definitions.scala | 6 ++--- .../tools/dotc/core/DenotTransformers.scala | 2 +- .../dotty/tools/dotc/core/Denotations.scala | 2 +- .../tools/dotc/core/SymDenotations.scala | 12 +++++----- .../dotty/tools/dotc/core/TypeComparer.scala | 6 ++--- .../src/dotty/tools/dotc/core/TypeOps.scala | 2 +- .../src/dotty/tools/dotc/core/Types.scala | 8 +++---- .../dotc/core/classfile/ClassfileParser.scala | 2 +- .../core/unpickleScala2/Scala2Unpickler.scala | 2 +- compiler/src/dotty/tools/dotc/report.scala | 4 ++-- .../dotty/tools/dotc/reporting/messages.scala | 2 +- .../dotty/tools/dotc/transform/Bridges.scala | 2 +- .../dotty/tools/dotc/transform/Erasure.scala | 10 ++++---- .../dotc/transform/ExtensionMethods.scala | 2 +- .../dotty/tools/dotc/transform/Staging.scala | 2 +- .../dotc/transform/SyntheticMembers.scala | 2 +- .../dotc/transform/TransformByNameApply.scala | 2 +- .../tools/dotc/transform/TreeChecker.scala | 24 +++++++++---------- .../dotc/transform/YCheckPositions.scala | 2 +- .../src/dotty/tools/dotc/typer/Checking.scala | 2 +- .../tools/dotc/typer/ErrorReporting.scala | 2 +- .../dotty/tools/dotc/typer/Implicits.scala | 2 +- .../dotty/tools/dotc/typer/TypeAssigner.scala | 4 ++-- .../src/dotty/tools/dotc/typer/Typer.scala | 6 ++--- 27 files changed, 65 insertions(+), 68 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index cd141101f246..1101dec8c15a 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -236,7 +236,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint private def printTree(last: PrintedTree)(using Context): PrintedTree = { val unit = ctx.compilationUnit - val prevPhase = currentPhase.prev // can be a mini-phase + val prevPhase = ctx.phase.prev // can be a mini-phase val squashedPhase = ctx.base.squashed(prevPhase) val treeString = unit.tpdTree.show(using ctx.withProperty(XprintMode, Some(()))) diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 708d4ecc2ded..5f72a4148176 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -828,7 +828,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * owner by `from` to `to`. */ def changeOwnerAfter(from: Symbol, to: Symbol, trans: DenotTransformer)(using Context): ThisTree = - if (currentPhase == trans.next) { + if (ctx.phase == trans.next) { val traverser = new TreeTraverser { def traverse(tree: Tree)(using Context) = tree match { case tree: DefTree => diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 57e4823d1366..9def8a1edee6 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -72,26 +72,20 @@ object Contexts { atPhase(phase.id)(op) inline def atNextPhase[T](inline op: Context ?=> T)(using Context): T = - atPhase(currentPhase.next)(op) + atPhase(ctx.phase.next)(op) inline def atPhaseNoLater[T](limit: Phase)(inline op: Context ?=> T)(using Context): T = - op(using if !limit.exists || currentPhase <= limit then ctx else ctx.withPhase(limit)) + op(using if !limit.exists || ctx.phase <= limit then ctx else ctx.withPhase(limit)) inline def atPhaseNoEarlier[T](limit: Phase)(inline op: Context ?=> T)(using Context): T = - op(using if !limit.exists || limit <= currentPhase then ctx else ctx.withPhase(limit)) + op(using if !limit.exists || limit <= ctx.phase then ctx else ctx.withPhase(limit)) inline def currentPeriod(using ctx: Context): Period = ctx.period - inline def currentPhase(using ctx: Context): Phase = ctx.base.phases(ctx.period.firstPhaseId) - - inline def currentRunId(using ctx: Context): Int = ctx.period.runId - - inline def currentPhaseId(using ctx: Context): Int = ctx.period.phaseId - - def currentlyAfterTyper(using Context): Boolean = ctx.base.isAfterTyper(currentPhase) + def currentlyAfterTyper(using Context): Boolean = ctx.base.isAfterTyper(ctx.phase) /** Does current phase use an erased types interpretation? */ - def currentlyAfterErasure(using Context): Boolean = currentPhase.erasedTypes + def currentlyAfterErasure(using Context): Boolean = ctx.phase.erasedTypes inline def inMode[T](mode: Mode)(inline op: Context ?=> T)(using ctx: Context): T = op(using if mode != ctx.mode then ctx.fresh.setMode(mode) else ctx) @@ -369,8 +363,11 @@ object Contexts { /** The current reporter */ def reporter: Reporter = typerState.reporter + final def phase: Phase = base.phases(period.firstPhaseId) final def runId = period.runId final def phaseId = period.phaseId + final def erasedTypes = phase.erasedTypes + final def isAfterTyper = base.isAfterTyper(phase) /** Is this a context for the members of a class definition? */ def isClassDefContext: Boolean = diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index 85eac41dfe9e..c6826105e3f4 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -867,7 +867,7 @@ class Definitions { def ClassType(arg: Type)(using Context): Type = { val ctype = ClassClass.typeRef - if (currentPhase.erasedTypes) ctype else ctype.appliedTo(arg) + if (ctx.phase.erasedTypes) ctype else ctype.appliedTo(arg) } /** The enumeration type, goven a value of the enumeration */ @@ -1041,13 +1041,13 @@ class Definitions { name.drop(prefix.length).forall(_.isDigit)) def isBottomClass(cls: Symbol): Boolean = - if (ctx.explicitNulls && !currentPhase.erasedTypes) cls == NothingClass + if (ctx.explicitNulls && !ctx.phase.erasedTypes) cls == NothingClass else isBottomClassAfterErasure(cls) def isBottomClassAfterErasure(cls: Symbol): Boolean = cls == NothingClass || cls == NullClass def isBottomType(tp: Type): Boolean = - if (ctx.explicitNulls && !currentPhase.erasedTypes) tp.derivesFrom(NothingClass) + if (ctx.explicitNulls && !ctx.phase.erasedTypes) tp.derivesFrom(NothingClass) else isBottomTypeAfterErasure(tp) def isBottomTypeAfterErasure(tp: Type): Boolean = diff --git a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala index 05473da8a03b..4b08c9442102 100644 --- a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala +++ b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala @@ -43,7 +43,7 @@ object DenotTransformers { if (info1 eq ref.info) ref else ref match { case ref: SymDenotation => - ref.copySymDenotation(info = info1).copyCaches(ref, currentPhase.next) + ref.copySymDenotation(info = info1).copyCaches(ref, ctx.phase.next) case _ => ref.derivedSingleDenotation(ref.symbol, info1) } diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index d76bf0142ae9..c0ae132cf155 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -842,7 +842,7 @@ object Denotations { } private def demandOutsideDefinedMsg(using Context): String = - s"demanding denotation of $this at phase ${currentPhase}(${ctx.phaseId}) outside defined interval: defined periods are${definedPeriodsString}" + s"demanding denotation of $this at phase ${ctx.phase}(${ctx.phaseId}) outside defined interval: defined periods are${definedPeriodsString}" /** Install this denotation to be the result of the given denotation transformer. * This is the implementation of the same-named method in SymDenotations. diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index c12b876ca6c4..d531694e9a42 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -762,7 +762,7 @@ object SymDenotations { /** Is this symbol a class of which `null` is a value? */ final def isNullableClass(using Context): Boolean = - if (ctx.explicitNulls && !currentPhase.erasedTypes) symbol == defn.NullClass || symbol == defn.AnyClass + if (ctx.explicitNulls && !ctx.phase.erasedTypes) symbol == defn.NullClass || symbol == defn.AnyClass else isNullableClassAfterErasure /** Is this symbol a class of which `null` is a value after erasure? @@ -849,7 +849,7 @@ object SymDenotations { || this.is(Protected) && ( superAccess || pre.isInstanceOf[ThisType] - || currentPhase.erasedTypes + || ctx.phase.erasedTypes || isProtectedAccessOK ) ) @@ -1325,7 +1325,7 @@ object SymDenotations { final def accessBoundary(base: Symbol)(using Context): Symbol = if (this.is(Private)) owner else if (this.isAllOf(StaticProtected)) defn.RootClass - else if (privateWithin.exists && !currentPhase.erasedTypes) privateWithin + else if (privateWithin.exists && !ctx.phase.erasedTypes) privateWithin else if (this.is(Protected)) base else defn.RootClass @@ -1451,7 +1451,7 @@ object SymDenotations { val initFlags1 = (if (initFlags != UndefinedFlags) initFlags else this.flags) val info1 = if (info != null) info else this.info if (currentlyAfterTyper && changedClassParents(info, info1, completersMatter = false)) - assert(currentPhase.changesParents, i"undeclared parent change at ${currentPhase} for $this, was: $info, now: $info1") + assert(ctx.phase.changesParents, i"undeclared parent change at ${ctx.phase} for $this, was: $info, now: $info1") val privateWithin1 = if (privateWithin != null) privateWithin else this.privateWithin val annotations1 = if (annotations != null) annotations else this.annotations val rawParamss1 = if rawParamss != null then rawParamss else this.rawParamss @@ -2592,7 +2592,7 @@ object SymDenotations { private var cache: SimpleIdentityMap[NameFilter, Set[Name]] = SimpleIdentityMap.Empty final def isValid(using Context): Boolean = - cache != null && isValidAt(currentPhase) + cache != null && isValidAt(ctx.phase) private var locked = false @@ -2634,7 +2634,7 @@ object SymDenotations { private var locked = false private var provisional = false - final def isValid(using Context): Boolean = valid && isValidAt(currentPhase) + final def isValid(using Context): Boolean = valid && isValidAt(ctx.phase) def invalidate(): Unit = if (valid && !locked) { diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index 9f25389e310c..4d5a74fe756c 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -388,7 +388,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } case tp1: SkolemType => tp2 match { - case tp2: SkolemType if !currentPhase.isTyper && recur(tp1.info, tp2.info) => true + case tp2: SkolemType if !ctx.phase.isTyper && recur(tp1.info, tp2.info) => true case _ => thirdTry } case tp1: TypeVar => @@ -808,7 +808,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w case _ => tp2.isAnyRef } compareJavaArray - case tp1: ExprType if currentPhase.id > gettersPhase.id => + case tp1: ExprType if ctx.phase.id > gettersPhase.id => // getters might have converted T to => T, need to compensate. recur(tp1.widenExpr, tp2) case _ => @@ -1233,7 +1233,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * for equality would give the wrong result, so we should not use the sets * for comparisons. */ - def canCompare(ts: Set[Type]) = currentPhase.isTyper || { + def canCompare(ts: Set[Type]) = ctx.phase.isTyper || { val hasSkolems = new ExistsAccumulator(_.isInstanceOf[SkolemType]) { override def stopAtStatic = true } diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index 47f3aadf6c7b..8e091c788dc5 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -122,7 +122,7 @@ object TypeOps: } def isLegalPrefix(pre: Type)(using Context): Boolean = - pre.isStable || !currentPhase.isTyper + pre.isStable || !ctx.phase.isTyper /** Implementation of Types#simplified */ def simplify(tp: Type, theMap: SimplifyMap)(using Context): Type = { diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index d1b77f68ced2..22cc412a7a33 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -980,7 +980,7 @@ object Types { */ def matches(that: Type)(using Context): Boolean = { record("matches") - ctx.typeComparer.matchesType(this, that, relaxed = !currentPhase.erasedTypes) + ctx.typeComparer.matchesType(this, that, relaxed = !ctx.phase.erasedTypes) } /** This is the same as `matches` except that it also matches => T with T and @@ -2094,7 +2094,7 @@ object Types { else { if (!ctx.reporter.errorsReported) throw new TypeError( - i"""bad parameter reference $this at ${currentPhase} + i"""bad parameter reference $this at ${ctx.phase} |the parameter is ${param.showLocated} but the prefix $prefix |does not define any corresponding arguments.""") NoDenotation @@ -2155,7 +2155,7 @@ object Types { s"""data race? overwriting $lastSymbol with $sym in type $this, |last sym id = ${lastSymbol.id}, new sym id = ${sym.id}, |last owner = ${lastSymbol.owner}, new owner = ${sym.owner}, - |period = ${currentPhase} at run ${ctx.runId}""") + |period = ${ctx.phase} at run ${ctx.runId}""") } /** A reference with the initial symbol in `symd` has an info that @@ -2489,7 +2489,7 @@ object Types { /** Assert current phase does not have erasure semantics */ private def assertUnerased()(using Context) = - if (Config.checkUnerased) assert(!currentPhase.erasedTypes) + if (Config.checkUnerased) assert(!ctx.phase.erasedTypes) /** The designator to be used for a named type creation with given prefix, name, and denotation. * This is the denotation's symbol, if it exists and the prefix is not the this type diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index 6b3ff303c838..e22e3e44a203 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -309,7 +309,7 @@ class ClassfileParser( /** Map direct references to Object to references to Any */ final def objToAny(tp: Type)(using Context): Type = - if (tp.isDirectRef(defn.ObjectClass) && !currentPhase.erasedTypes) defn.AnyType else tp + if (tp.isDirectRef(defn.ObjectClass) && !ctx.phase.erasedTypes) defn.AnyType else tp def constantTagToType(tag: Int)(using Context): Type = (tag: @switch) match { diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index 6a76dbe0ee26..75bb306aebe3 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -986,7 +986,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas protected def deferredAnnot(end: Int)(using Context): Annotation = { val start = readIndex val atp = readTypeRef() - val phase = currentPhase + val phase = ctx.phase Annotation.deferred(atp.typeSymbol)( atReadPos(start, () => atPhase(phase)(readAnnotationContents(end)))) } diff --git a/compiler/src/dotty/tools/dotc/report.scala b/compiler/src/dotty/tools/dotc/report.scala index cc22c1fe11ea..479e8f0af253 100644 --- a/compiler/src/dotty/tools/dotc/report.scala +++ b/compiler/src/dotty/tools/dotc/report.scala @@ -92,8 +92,8 @@ object report: * "contains" here. */ def log(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - if (ctx.settings.Ylog.value.containsPhase(currentPhase)) - echo(s"[log $currentPhase] $msg", pos) + if (ctx.settings.Ylog.value.containsPhase(ctx.phase)) + echo(s"[log $ctx.phase] $msg", pos) def debuglog(msg: => String)(using Context): Unit = if (ctx.debug) log(msg) diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index f14295b64f7e..9de881883848 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -2011,7 +2011,7 @@ import ast.tpd case NoMatch => // If the signatures don't match at all at the current phase, then // they might match after erasure. - if currentPhase.id <= elimErasedValueTypePhase.id then + if ctx.phase.id <= elimErasedValueTypePhase.id then atPhase(elimErasedValueTypePhase.next)(details) else "" // shouldn't be reachable diff --git a/compiler/src/dotty/tools/dotc/transform/Bridges.scala b/compiler/src/dotty/tools/dotc/transform/Bridges.scala index a03585aa02b6..ee6d9dc9e089 100644 --- a/compiler/src/dotty/tools/dotc/transform/Bridges.scala +++ b/compiler/src/dotty/tools/dotc/transform/Bridges.scala @@ -14,7 +14,7 @@ import util.SourcePosition class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { import ast.tpd._ - assert(currentPhase == erasurePhase.next) + assert(ctx.phase == erasurePhase.next) private val preErasureCtx = ctx.withPhase(erasurePhase) private lazy val elimErasedCtx = ctx.withPhase(elimErasedValueTypePhase.next) diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index e011b1fc453c..846dd2ce8c34 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -50,13 +50,13 @@ class Erasure extends Phase with DenotTransformer { case ref: SymDenotation => def isCompacted(symd: SymDenotation) = symd.isAnonymousFunction && { - atPhase(currentPhase.next)(symd.info) match { + atPhase(ctx.phase.next)(symd.info) match { case MethodType(nme.ALLARGS :: Nil) => true case _ => false } } - assert(currentPhase == this, s"transforming $ref at ${currentPhase}") + assert(ctx.phase == this, s"transforming $ref at ${ctx.phase}") if (ref.symbol eq defn.ObjectClass) { // After erasure, all former Any members are now Object members val ClassInfo(pre, _, ps, decls, selfInfo) = ref.info @@ -99,7 +99,7 @@ class Erasure extends Phase with DenotTransformer { then ref else - assert(!ref.is(Flags.PackageClass), s"trans $ref @ ${currentPhase} oldOwner = $oldOwner, newOwner = $newOwner, oldInfo = $oldInfo, newInfo = $newInfo ${oldOwner eq newOwner} ${oldInfo eq newInfo}") + assert(!ref.is(Flags.PackageClass), s"trans $ref @ ${ctx.phase} oldOwner = $oldOwner, newOwner = $newOwner, oldInfo = $oldInfo, newInfo = $newInfo ${oldOwner eq newOwner} ${oldInfo eq newInfo}") ref.copySymDenotation( symbol = newSymbol, owner = newOwner, @@ -166,7 +166,7 @@ class Erasure extends Phase with DenotTransformer { isAllowed(defn.TupleClass, "Tuple.scala") || isAllowed(defn.NonEmptyTupleClass, "Tuple.scala") || isAllowed(defn.PairClass, "Tuple.scala"), - i"The type $tp - ${tp.toString} of class ${tp.getClass} of tree $tree : ${tree.tpe} / ${tree.getClass} is illegal after erasure, phase = ${currentPhase.prev}") + i"The type $tp - ${tp.toString} of class ${tp.getClass} of tree $tree : ${tree.tpe} / ${tree.getClass} is illegal after erasure, phase = ${ctx.phase.prev}") } } @@ -981,7 +981,7 @@ object Erasure { override def adapt(tree: Tree, pt: Type, locked: TypeVars, tryGadtHealing: Boolean)(using Context): Tree = trace(i"adapting ${tree.showSummary}: ${tree.tpe} to $pt", show = true) { - if currentPhase != erasurePhase && currentPhase != erasurePhase.next then + if ctx.phase != erasurePhase && ctx.phase != erasurePhase.next then // this can happen when reading annotations loaded during erasure, // since these are loaded at phase typer. atPhase(erasurePhase.next)(adapt(tree, pt, locked)) diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index d506be0b5365..d2c772e472a5 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -117,7 +117,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete case ClassInfo(pre, cls, _, _, _) if cls is ModuleClass => cls.linkedClass match { case valueClass: ClassSymbol if isDerivedValueClass(valueClass) => - val info1 = atPhase(currentPhase.next)(cls.denot).asClass.classInfo.derivedClassInfo(prefix = pre) + val info1 = atPhase(ctx.phase.next)(cls.denot).asClass.classInfo.derivedClassInfo(prefix = pre) ref.derivedSingleDenotation(ref.symbol, info1) case _ => ref } diff --git a/compiler/src/dotty/tools/dotc/transform/Staging.scala b/compiler/src/dotty/tools/dotc/transform/Staging.scala index eff95b7ad26e..6138ad5b42bb 100644 --- a/compiler/src/dotty/tools/dotc/transform/Staging.scala +++ b/compiler/src/dotty/tools/dotc/transform/Staging.scala @@ -39,7 +39,7 @@ class Staging extends MacroTransform { override def allowsImplicitSearch: Boolean = true override def checkPostCondition(tree: Tree)(using Context): Unit = - if (currentPhase <= reifyQuotesPhase) { + if (ctx.phase <= reifyQuotesPhase) { // Recheck that PCP holds but do not heal any inconsistent types as they should already have been heald tree match { case PackageDef(pid, _) if tree.symbol.owner == defn.RootClass => diff --git a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala index e78ef75a5fd9..065d2ed5ee2a 100644 --- a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala +++ b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala @@ -130,7 +130,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { case nme.productElementName => productElementNameBody(accessors.length, vrefss.head.head) case nme.ordinal => Select(This(clazz), nme.ordinalDollar) } - report.log(s"adding $synthetic to $clazz at ${currentPhase}") + report.log(s"adding $synthetic to $clazz at ${ctx.phase}") synthesizeDef(synthetic, syntheticRHS) } diff --git a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala index 42e3f3d2b801..90f7488b973d 100644 --- a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala @@ -37,7 +37,7 @@ abstract class TransformByNameApply extends MiniPhase { thisPhase: DenotTransfor def mkByNameClosure(arg: Tree, argType: Type)(using Context): Tree = unsupported(i"mkClosure($arg)") override def transformApply(tree: Apply)(using Context): Tree = - trace(s"transforming ${tree.show} at phase ${currentPhase}", show = true) { + trace(s"transforming ${tree.show} at phase ${ctx.phase}", show = true) { def transformArg(arg: Tree, formal: Type): Tree = formal.dealias match { case formalExpr: ExprType => diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index 57275080b806..74432437c4f4 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -58,7 +58,7 @@ class TreeChecker extends Phase with SymTransformer { def checkCompanion(symd: SymDenotation)(using Context): Unit = { val cur = symd.linkedClass - val prev = atPhase(currentPhase.prev) { + val prev = atPhase(ctx.phase.prev) { symd.symbol.linkedClass } @@ -100,7 +100,7 @@ class TreeChecker extends Phase with SymTransformer { cur.signature } assert(curSig == initial.signature, - i"""Signature of ${sym.showLocated} changed at phase ${ctx.base.squashed(currentPhase.prev)} + i"""Signature of ${sym.showLocated} changed at phase ${ctx.base.squashed(ctx.phase.prev)} |Initial info: ${initial} |Initial sig : ${initial.signature} |Current info: ${cur} @@ -114,9 +114,9 @@ class TreeChecker extends Phase with SymTransformer { def phaseName: String = "Ycheck" def run(using Context): Unit = - if (ctx.settings.YtestPickler.value && currentPhase.prev.isInstanceOf[Pickler]) + if (ctx.settings.YtestPickler.value && ctx.phase.prev.isInstanceOf[Pickler]) report.echo("Skipping Ycheck after pickling with -Ytest-pickler, the returned tree contains stale symbols") - else if (currentPhase.prev.isCheckable) + else if (ctx.phase.prev.isCheckable) check(ctx.base.allPhases.toIndexedSeq, ctx) private def previousPhases(phases: List[Phase])(using Context): List[Phase] = phases match { @@ -125,14 +125,14 @@ class TreeChecker extends Phase with SymTransformer { val previousSubPhases = previousPhases(subPhases.toList) if (previousSubPhases.length == subPhases.length) previousSubPhases ::: previousPhases(phases1) else previousSubPhases - case phase :: phases1 if phase ne currentPhase => + case phase :: phases1 if phase ne ctx.phase => phase :: previousPhases(phases1) case _ => Nil } def check(phasesToRun: Seq[Phase], ctx: Context): Tree = { - val prevPhase = currentPhase(using ctx).prev // can be a mini-phase + val prevPhase = ctx.phase.prev // can be a mini-phase val squashedPhase = ctx.base.squashed(prevPhase) report.echo(s"checking ${ctx.compilationUnit} after phase ${squashedPhase}")(using ctx) @@ -152,7 +152,7 @@ class TreeChecker extends Phase with SymTransformer { catch { case NonFatal(ex) => //TODO CHECK. Check that we are bootstrapped inContext(checkingCtx) { - println(i"*** error while checking ${ctx.compilationUnit} after phase ${currentPhase.prev} ***") + println(i"*** error while checking ${ctx.compilationUnit} after phase ${ctx.phase.prev} ***") } throw ex } @@ -237,7 +237,7 @@ class TreeChecker extends Phase with SymTransformer { i"undefined symbol ${sym} at line " + tree.sourcePos.line ) - if (!currentPhase.patternTranslated) + if (!ctx.phase.patternTranslated) assert( !sym.isPatternBound || patBoundSyms.contains(sym), i"sym.isPatternBound => patBoundSyms.contains(sym) is broken, sym = $sym, line " + tree.sourcePos.line @@ -366,7 +366,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedIdent(tree: untpd.Ident, pt: Type)(using Context): Tree = { - assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + currentPhase) + assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + ctx.phase) assert(tree.isType || ctx.mode.is(Mode.Pattern) && untpd.isWildcardArg(tree) || !needsSelect(tree.tpe), i"bad type ${tree.tpe} for $tree # ${tree.uniqueId}") assertDefined(tree) @@ -378,7 +378,7 @@ class TreeChecker extends Phase with SymTransformer { * Approximately means: The two symbols might be different but one still overrides the other. */ override def typedSelect(tree: untpd.Select, pt: Type)(using Context): Tree = { - assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + currentPhase) + assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + ctx.phase) val tpe = tree.typeOpt val sym = tree.symbol val symIsFixed = tpe match { @@ -481,7 +481,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedClosure(tree: untpd.Closure, pt: Type)(using Context): Tree = { - if (!currentPhase.lambdaLifted) nestingBlock match { + if (!ctx.phase.lambdaLifted) nestingBlock match { case block @ Block((meth : untpd.DefDef) :: Nil, closure: untpd.Closure) => assert(meth.symbol == closure.meth.symbol, "closure.meth symbol not equal to method symbol. Block: " + block.show) @@ -531,7 +531,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedWhileDo(tree: untpd.WhileDo)(using Context): Tree = { - assert((tree.cond ne EmptyTree) || currentPhase.refChecked, i"invalid empty condition in while at $tree") + assert((tree.cond ne EmptyTree) || ctx.phase.refChecked, i"invalid empty condition in while at $tree") super.typedWhileDo(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala index 86b851a897ec..6722701ad448 100644 --- a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala +++ b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala @@ -55,7 +55,7 @@ class YCheckPositions extends Phase { } private def isMacro(call: Tree)(using Context) = - if (currentPhase <= postTyperPhase) call.symbol.is(Macro) + if (ctx.phase <= postTyperPhase) call.symbol.is(Macro) else call.isInstanceOf[Select] // The call of a macro after typer is encoded as a Select while other inlines are Ident // TODO remove this distinction once Inline nodes of expanded macros can be trusted (also in Inliner.inlineCallTrace) } diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index 957034ec71fc..fcec37725513 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -740,7 +740,7 @@ trait Checking { tp.underlyingClassRef(refinementOK = false) match { case tref: TypeRef => if (traitReq && !tref.symbol.is(Trait)) report.error(TraitIsExpected(tref.symbol), pos) - if (stablePrefixReq && currentPhase <= refchecksPhase) checkStable(tref.prefix, pos, "class prefix") + if (stablePrefixReq && ctx.phase <= refchecksPhase) checkStable(tref.prefix, pos, "class prefix") tp case _ => report.error(ex"$tp is not a class type", pos) diff --git a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala index b72f29ae1208..04ebd7e83eef 100644 --- a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala +++ b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala @@ -89,7 +89,7 @@ object ErrorReporting { if (tree.tpe.widen.exists) i"${exprStr(tree)} does not take ${kind}parameters" else { - i"undefined: $tree # ${tree.uniqueId}: ${tree.tpe.toString} at ${currentPhase}" + i"undefined: $tree # ${tree.uniqueId}: ${tree.tpe.toString} at ${ctx.phase}" } def patternConstrStr(tree: Tree): String = ??? diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index 17cb75e7e6be..d59a269ed60e 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -970,7 +970,7 @@ trait Implicits { self: Typer => def inferImplicit(pt: Type, argument: Tree, span: Span)(using Context): SearchResult = trace(s"search implicit ${pt.show}, arg = ${argument.show}: ${argument.tpe.show}", implicits, show = true) { record("inferImplicit") - assert(currentPhase.allowsImplicitSearch, + assert(ctx.phase.allowsImplicitSearch, if (argument.isEmpty) i"missing implicit parameter of type $pt after typer" else i"type error: ${argument.tpe} does not conform to $pt${err.whyNoMatchStr(argument.tpe, pt)}") val result0 = diff --git a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala index 9bf13555f4d4..31fa0126ea0c 100644 --- a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala +++ b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala @@ -289,11 +289,11 @@ trait TypeAssigner { def assignType(tree: untpd.Apply, fn: Tree, args: List[Tree])(using Context): Apply = { val ownType = fn.tpe.widen match { case fntpe: MethodType => - if (sameLength(fntpe.paramInfos, args) || currentPhase.prev.relaxedTyping) + if (sameLength(fntpe.paramInfos, args) || ctx.phase.prev.relaxedTyping) if (fntpe.isResultDependent) safeSubstParams(fntpe.resultType, fntpe.paramRefs, args.tpes) else fntpe.resultType else - errorType(i"wrong number of arguments at ${currentPhase.prev} for $fntpe: ${fn.tpe}, expected: ${fntpe.paramInfos.length}, found: ${args.length}", tree.sourcePos) + errorType(i"wrong number of arguments at ${ctx.phase.prev} for $fntpe: ${fn.tpe}, expected: ${fntpe.paramInfos.length}, found: ${args.length}", tree.sourcePos) case t => if (ctx.settings.Ydebug.value) new FatalError("").printStackTrace() errorType(err.takesNoParamsStr(fn, ""), tree.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 0b7c794e2e30..f2506d33a8da 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -2092,7 +2092,7 @@ class Typer extends Namer val cdef1 = assignType(cpy.TypeDef(cdef)(name, impl1), cls) val reportDynamicInheritance = - currentPhase.isTyper && + ctx.phase.isTyper && cdef1.symbol.ne(defn.DynamicClass) && cdef1.tpe.derivesFrom(defn.DynamicClass) && !dynamicsEnabled @@ -2544,7 +2544,7 @@ class Typer extends Namer trace(i"typing $tree, pt = $pt", typr, show = true) { record(s"typed $getClass") record("typed total") - if currentPhase.isTyper then + if ctx.phase.isTyper then assertPositioned(tree) if tree.source != ctx.source && tree.source.exists then typed(tree, pt, locked)(using ctx.withSource(tree.source)) @@ -3614,7 +3614,7 @@ class Typer extends Namer tpd.Block(List(bundleVal), splice(tpd.ref(bundleVal.symbol))).withSpan(call.span) } } - if currentPhase.isTyper then + if ctx.phase.isTyper then call match case untpd.Ident(nme.???) => // Instinsic macros ignored case _ => From 0e42cd838cbce7d929ea3c9e8de3c2f34d4ec1d2 Mon Sep 17 00:00:00 2001 From: Martin Odersky <odersky@gmail.com> Date: Mon, 20 Jul 2020 14:40:10 +0200 Subject: [PATCH 09/10] Move currentPeriod back to Context --- compiler/src/dotty/tools/dotc/ast/tpd.scala | 10 ++--- .../src/dotty/tools/dotc/core/Contexts.scala | 11 ++--- .../dotty/tools/dotc/core/Definitions.scala | 6 +-- .../dotty/tools/dotc/core/Denotations.scala | 16 +++---- .../src/dotty/tools/dotc/core/Periods.scala | 2 +- .../src/dotty/tools/dotc/core/Phases.scala | 2 +- .../tools/dotc/core/SymDenotations.scala | 28 ++++++------ .../src/dotty/tools/dotc/core/Symbols.scala | 4 +- .../tools/dotc/core/TypeApplications.scala | 2 +- .../dotty/tools/dotc/core/TypeComparer.scala | 12 ++--- .../dotty/tools/dotc/core/TypeErasure.scala | 4 +- .../src/dotty/tools/dotc/core/TypeOps.scala | 2 +- .../src/dotty/tools/dotc/core/Types.scala | 44 +++++++++---------- .../transform/ContextFunctionResults.scala | 2 +- .../tools/dotc/transform/TreeChecker.scala | 10 ++--- .../tools/dotc/transform/TypeUtils.scala | 2 +- .../dotty/tools/dotc/typer/Applications.scala | 6 +-- .../src/dotty/tools/dotc/typer/Checking.scala | 6 +-- .../dotty/tools/dotc/typer/EtaExpansion.scala | 2 +- .../dotty/tools/dotc/typer/Implicits.scala | 4 +- .../dotty/tools/dotc/typer/Nullables.scala | 8 ++-- .../tools/dotc/typer/PrepareInlineable.scala | 4 +- .../src/dotty/tools/dotc/typer/ReTyper.scala | 2 +- .../dotty/tools/dotc/typer/TypeAssigner.scala | 6 +-- .../src/dotty/tools/dotc/typer/Typer.scala | 26 +++++------ 25 files changed, 109 insertions(+), 112 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 5f72a4148176..3d55f224265a 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -414,7 +414,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { ref(NamedType(sym.owner.thisType, sym.name, sym.denot)) private def followOuterLinks(t: Tree)(using Context) = t match { - case t: This if currentlyAfterErasure && !(t.symbol == ctx.owner.enclosingClass || t.symbol.isStaticOwner) => + case t: This if ctx.erasedTypes && !(t.symbol == ctx.owner.enclosingClass || t.symbol.isStaticOwner) => // after erasure outer paths should be respected ExplicitOuter.OuterOps(ctx).path(toCls = t.tpe.widen.classSymbol) case t => @@ -458,7 +458,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { def newArr = ref(defn.DottyArraysModule).select(defn.newArrayMethod).withSpan(span) - if (!currentlyAfterErasure) { + if (!ctx.erasedTypes) { assert(!TypeErasure.isGeneric(elemTpe), elemTpe) //needs to be done during typer. See Applications.convertNewGenericArray newArr.appliedToTypeTrees(TypeTree(returnTpe) :: Nil).appliedToArgs(clsOf(elemTpe) :: clsOf(returnTpe) :: dims :: Nil).withSpan(span) } @@ -962,7 +962,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** cast tree to `tp`, assuming no exception is raised, i.e the operation is pure */ def cast(tp: Type)(using Context): Tree = { assert(tp.isValueType, i"bad cast: $tree.asInstanceOf[$tp]") - tree.select(if (currentlyAfterErasure) defn.Any_asInstanceOf else defn.Any_typeCast) + tree.select(if (ctx.erasedTypes) defn.Any_asInstanceOf else defn.Any_typeCast) .appliedToType(tp) } @@ -972,7 +972,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { */ def ensureConforms(tp: Type)(using Context): Tree = if (tree.tpe <:< tp) tree - else if (!currentlyAfterErasure) cast(tp) + else if (!ctx.erasedTypes) cast(tp) else Erasure.Boxing.adaptToType(tree, tp) /** `tree ne null` (might need a cast to be type correct) */ @@ -1156,7 +1156,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** A tree that corresponds to `Predef.classOf[$tp]` in source */ def clsOf(tp: Type)(using Context): Tree = - if currentlyAfterErasure then + if ctx.erasedTypes then def TYPE(module: TermSymbol) = ref(module).select(nme.TYPE_) defn.scalaClassName(tp) match case tpnme.Boolean => TYPE(defn.BoxedBooleanModule) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 9def8a1edee6..d043a6bd1a11 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -80,13 +80,6 @@ object Contexts { inline def atPhaseNoEarlier[T](limit: Phase)(inline op: Context ?=> T)(using Context): T = op(using if !limit.exists || limit <= ctx.phase then ctx else ctx.withPhase(limit)) - inline def currentPeriod(using ctx: Context): Period = ctx.period - - def currentlyAfterTyper(using Context): Boolean = ctx.base.isAfterTyper(ctx.phase) - - /** Does current phase use an erased types interpretation? */ - def currentlyAfterErasure(using Context): Boolean = ctx.phase.erasedTypes - inline def inMode[T](mode: Mode)(inline op: Context ?=> T)(using ctx: Context): T = op(using if mode != ctx.mode then ctx.fresh.setMode(mode) else ctx) @@ -366,7 +359,11 @@ object Contexts { final def phase: Phase = base.phases(period.firstPhaseId) final def runId = period.runId final def phaseId = period.phaseId + + /** Does current phase use an erased types interpretation? */ final def erasedTypes = phase.erasedTypes + + /** Is current phase after FrontEnd? */ final def isAfterTyper = base.isAfterTyper(phase) /** Is this a context for the members of a class definition? */ diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index c6826105e3f4..1f7b51bf78e7 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -905,7 +905,7 @@ class Definitions { object ArrayOf { def apply(elem: Type)(using Context): Type = - if (currentlyAfterErasure) JavaArrayType(elem) + if (ctx.erasedTypes) JavaArrayType(elem) else ArrayType.appliedTo(elem :: Nil) def unapply(tp: Type)(using Context): Option[Type] = tp.dealias match { case AppliedType(at, arg :: Nil) if at.isRef(ArrayType.symbol) => Some(arg) @@ -1020,7 +1020,7 @@ class Definitions { @tu lazy val Function0_apply: Symbol = ImplementedFunctionType(0).symbol.requiredMethod(nme.apply) def FunctionType(n: Int, isContextual: Boolean = false, isErased: Boolean = false)(using Context): TypeRef = - if (n <= MaxImplementedFunctionArity && (!isContextual || currentlyAfterErasure) && !isErased) ImplementedFunctionType(n) + if (n <= MaxImplementedFunctionArity && (!isContextual || ctx.erasedTypes) && !isErased) ImplementedFunctionType(n) else FunctionClass(n, isContextual, isErased).typeRef lazy val PolyFunctionClass = requiredClass("scala.PolyFunction") @@ -1285,7 +1285,7 @@ class Definitions { */ object ContextFunctionType: def unapply(tp: Type)(using Context): Option[(List[Type], Type, Boolean)] = - if currentlyAfterErasure then + if ctx.erasedTypes then atPhase(erasurePhase)(unapply(tp)) else val tp1 = tp.dealias diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index c0ae132cf155..b9f9175e938c 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -131,10 +131,10 @@ object Denotations { /** The denotation with info(s) as seen from prefix type */ final def asSeenFrom(pre: Type)(using Context): AsSeenFromResult = if (Config.cacheAsSeenFrom) { - if ((cachedPrefix ne pre) || currentPeriod != validAsSeenFrom) { + if ((cachedPrefix ne pre) || ctx.period != validAsSeenFrom) { cachedAsSeenFrom = computeAsSeenFrom(pre) cachedPrefix = pre - validAsSeenFrom = if (pre.isProvisional) Nowhere else currentPeriod + validAsSeenFrom = if (pre.isProvisional) Nowhere else ctx.period } cachedAsSeenFrom } @@ -693,7 +693,7 @@ object Denotations { s"denotation $this invalid in run ${ctx.runId}. ValidFor: $validFor") var d: SingleDenotation = this while ({ - d.validFor = Period(currentPeriod.runId, d.validFor.firstPhaseId, d.validFor.lastPhaseId) + d.validFor = Period(ctx.runId, d.validFor.firstPhaseId, d.validFor.lastPhaseId) d.invalidateInheritedInfo() d = d.nextInRun d ne this @@ -746,7 +746,7 @@ object Denotations { if (myValidFor.code <= 0) nextDefined else this /** Produce a denotation that is valid for the given context. - * Usually called when !(validFor contains currentPeriod) + * Usually called when !(validFor contains ctx.period) * (even though this is not a precondition). * If the runId of the context is the same as runId of this denotation, * the right flock member is located, or, if it does not exist yet, @@ -758,7 +758,7 @@ object Denotations { * the symbol is stale, which constitutes an internal error. */ def current(using Context): SingleDenotation = { - val currentPeriod = Contexts.currentPeriod + val currentPeriod = ctx.period val valid = myValidFor if (valid.code <= 0) { // can happen if we sit on a stale denotation which has been replaced @@ -919,7 +919,7 @@ object Denotations { case denot: SymDenotation => s"in ${denot.owner}" case _ => "" } - s"stale symbol; $this#${symbol.id} $ownerMsg, defined in ${myValidFor}, is referred to in run ${currentPeriod}" + s"stale symbol; $this#${symbol.id} $ownerMsg, defined in ${myValidFor}, is referred to in run ${ctx.period}" } /** The period (interval of phases) for which there exists @@ -977,10 +977,10 @@ object Denotations { true case MethodNotAMethodMatch => // Java allows defining both a field and a zero-parameter method with the same name - !currentlyAfterErasure && !(symbol.is(JavaDefined) && other.symbol.is(JavaDefined)) + !ctx.erasedTypes && !(symbol.is(JavaDefined) && other.symbol.is(JavaDefined)) case ParamMatch => // The signatures do not tell us enough to be sure about matching - !currentlyAfterErasure && info.matches(other.info) + !ctx.erasedTypes && info.matches(other.info) case noMatch => false end matches diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index 6dcb64ee4656..d5944beedc2a 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -19,7 +19,7 @@ object Periods { /** Are all base types in the current period guaranteed to be the same as in period `p`? */ def currentHasSameBaseTypesAs(p: Period)(using Context): Boolean = - val period = currentPeriod + val period = ctx.period period == p || period.runId == p.runId && unfusedPhases(period.phaseId).sameBaseTypesStartId == diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index f35dae303e23..d8878ef15a6a 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -308,7 +308,7 @@ object Phases { /** Is this phase the standard typerphase? True for FrontEnd, but * not for other first phases (such as FromTasty). The predicate * is tested in some places that perform checks and corrections. It's - * different from currentlyAfterTyper (and cheaper to test). + * different from ctx.isAfterTyper (and cheaper to test). */ def isTyper: Boolean = false diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index d531694e9a42..340082041d55 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -862,7 +862,7 @@ object SymDenotations { def membersNeedAsSeenFrom(pre: Type)(using Context): Boolean = !( this.isTerm || this.isStaticOwner && !this.seesOpaques - || currentlyAfterErasure + || ctx.erasedTypes || (pre eq NoPrefix) || (pre eq thisType) ) @@ -875,7 +875,7 @@ object SymDenotations { * Default parameters are recognized until erasure. */ def hasDefaultParams(using Context): Boolean = - if currentlyAfterErasure then false + if ctx.erasedTypes then false else if is(HasDefaultParams) then true else if is(NoDefaultParams) then false else @@ -1450,7 +1450,7 @@ object SymDenotations { // simulate default parameters, while also passing implicit context ctx to the default values val initFlags1 = (if (initFlags != UndefinedFlags) initFlags else this.flags) val info1 = if (info != null) info else this.info - if (currentlyAfterTyper && changedClassParents(info, info1, completersMatter = false)) + if (ctx.isAfterTyper && changedClassParents(info, info1, completersMatter = false)) assert(ctx.phase.changesParents, i"undeclared parent change at ${ctx.phase} for $this, was: $info, now: $info1") val privateWithin1 = if (privateWithin != null) privateWithin else this.privateWithin val annotations1 = if (annotations != null) annotations else this.annotations @@ -1567,9 +1567,9 @@ object SymDenotations { private var memberNamesCache: MemberNames = MemberNames.None private def memberCache(using Context): LRUCache[Name, PreDenotation] = { - if (myMemberCachePeriod != currentPeriod) { + if (myMemberCachePeriod != ctx.period) { myMemberCache = new LRUCache - myMemberCachePeriod = currentPeriod + myMemberCachePeriod = ctx.period } myMemberCache } @@ -1577,7 +1577,7 @@ object SymDenotations { private def baseTypeCache(using Context): BaseTypeMap = { if !currentHasSameBaseTypesAs(myBaseTypeCachePeriod) then myBaseTypeCache = new BaseTypeMap - myBaseTypeCachePeriod = currentPeriod + myBaseTypeCachePeriod = ctx.period myBaseTypeCache } @@ -1641,7 +1641,7 @@ object SymDenotations { override final def typeParams(using Context): List[TypeSymbol] = { if (myTypeParams == null) myTypeParams = - if (currentlyAfterErasure || is(Module)) Nil // fast return for modules to avoid scanning package decls + if (ctx.erasedTypes || is(Module)) Nil // fast return for modules to avoid scanning package decls else { val di = initial if (this ne di) di.typeParams @@ -1729,7 +1729,7 @@ object SymDenotations { def computeBaseData(implicit onBehalf: BaseData, ctx: Context): (List[ClassSymbol], BaseClassSet) = { def emptyParentsExpected = - is(Package) || (symbol == defn.AnyClass) || currentlyAfterErasure && (symbol == defn.ObjectClass) + is(Package) || (symbol == defn.AnyClass) || ctx.erasedTypes && (symbol == defn.ObjectClass) if (classParents.isEmpty && !emptyParentsExpected) onBehalf.signalProvisional() val builder = new BaseDataBuilder @@ -1825,7 +1825,7 @@ object SymDenotations { */ def ensureTypeParamsInCorrectOrder()(using Context): Unit = { val tparams = typeParams - if (!currentlyAfterErasure && !typeParamsFromDecls.corresponds(tparams)(_.name == _.name)) { + if (!ctx.erasedTypes && !typeParamsFromDecls.corresponds(tparams)(_.name == _.name)) { val decls = info.decls val decls1 = newScope for (tparam <- typeParams) decls1.enter(decls.lookup(tparam.name)) @@ -2372,7 +2372,7 @@ object SymDenotations { def traceInvalid(denot: Denotation)(using Context): Boolean = { def show(d: Denotation) = s"$d#${d.symbol.id}" def explain(msg: String) = { - println(s"${show(denot)} is invalid at ${currentPeriod} because $msg") + println(s"${show(denot)} is invalid at ${ctx.period} because $msg") false } denot match { @@ -2535,7 +2535,7 @@ object SymDenotations { implicit val None: MemberNames = new InvalidCache with MemberNames { def apply(keepOnly: NameFilter, clsd: ClassDenotation)(implicit onBehalf: MemberNames, ctx: Context) = ??? } - def newCache()(using Context): MemberNames = new MemberNamesImpl(currentPeriod) + def newCache()(using Context): MemberNames = new MemberNamesImpl(ctx.period) } /** A cache for baseclasses, as a sequence in linearization order and as a set that @@ -2552,7 +2552,7 @@ object SymDenotations { def apply(clsd: ClassDenotation)(implicit onBehalf: BaseData, ctx: Context) = ??? def signalProvisional() = () } - def newCache()(using Context): BaseData = new BaseDataImpl(currentPeriod) + def newCache()(using Context): BaseData = new BaseDataImpl(ctx.period) } private abstract class InheritedCacheImpl(val createdAt: Period) extends InheritedCache { @@ -2575,11 +2575,11 @@ object SymDenotations { } def isValidAt(phase: Phase)(using Context) = - checkedPeriod == currentPeriod || + checkedPeriod == ctx.period || createdAt.runId == ctx.runId && createdAt.phaseId < unfusedPhases.length && sameGroup(unfusedPhases(createdAt.phaseId), phase) && - { checkedPeriod = currentPeriod; true } + { checkedPeriod = ctx.period; true } } private class InvalidCache extends InheritedCache { diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index be602fd1f75b..ab3439971a0b 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -102,13 +102,13 @@ object Symbols { final def denot(using Context): SymDenotation = { util.Stats.record("Symbol.denot") val lastd = lastDenot - if (checkedPeriod == currentPeriod) lastd + if (checkedPeriod == ctx.period) lastd else computeDenot(lastd) } private def computeDenot(lastd: SymDenotation)(using Context): SymDenotation = { util.Stats.record("Symbol.computeDenot") - val now = currentPeriod + val now = ctx.period checkedPeriod = now if (lastd.validFor contains now) lastd else recomputeDenot(lastd) } diff --git a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala index 24c2a294f5ea..94c83bd97036 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala @@ -287,7 +287,7 @@ class TypeApplications(val self: Type) extends AnyVal { val typParams = self.typeParams val stripped = self.stripTypeVar val dealiased = stripped.safeDealias - if (args.isEmpty || currentlyAfterErasure) self + if (args.isEmpty || ctx.erasedTypes) self else dealiased match { case dealiased: HKTypeLambda => def tryReduce = diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index 4d5a74fe756c..cab9362009e9 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -261,7 +261,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w // This is safe because X$ self-type is X.type sym1 = sym1.companionModule if ((sym1 ne NoSymbol) && (sym1 eq sym2)) - currentlyAfterErasure || + ctx.erasedTypes || sym1.isStaticOwner || isSubPrefix(tp1.prefix, tp2.prefix) || thirdTryNamed(tp2) @@ -1312,7 +1312,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w */ def compareCaptured(arg1: TypeBounds, arg2: Type) = tparam match { case tparam: Symbol => - if (leftRoot.isStable || (currentlyAfterTyper || ctx.mode.is(Mode.TypevarsMissContext)) + if (leftRoot.isStable || (ctx.isAfterTyper || ctx.mode.is(Mode.TypevarsMissContext)) && leftRoot.member(tparam.name).exists) { val captured = TypeRef(leftRoot, tparam) try isSubArg(captured, arg2) @@ -1862,7 +1862,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w final def glb(tps: List[Type]): Type = tps.foldLeft(AnyType: Type)(glb) def widenInUnions(using Context): Boolean = - migrateTo3 || currentlyAfterErasure + migrateTo3 || ctx.erasedTypes /** The least upper bound of two types * @param canConstrain If true, new constraints might be added to simplify the lub. @@ -2021,7 +2021,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } private def andTypeGen(tp1: Type, tp2: Type, op: (Type, Type) => Type, - original: (Type, Type) => Type = _ & _, isErased: Boolean = currentlyAfterErasure): Type = trace(s"glb(${tp1.show}, ${tp2.show})", subtyping, show = true) { + original: (Type, Type) => Type = _ & _, isErased: Boolean = ctx.erasedTypes): Type = trace(s"glb(${tp1.show}, ${tp2.show})", subtyping, show = true) { val t1 = distributeAnd(tp1, tp2) if (t1.exists) t1 else { @@ -2049,7 +2049,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * Finally, refined types with the same refined name are * opportunistically merged. */ - final def andType(tp1: Type, tp2: Type, isErased: Boolean = currentlyAfterErasure): Type = + final def andType(tp1: Type, tp2: Type, isErased: Boolean = ctx.erasedTypes): Type = andTypeGen(tp1, tp2, AndType(_, _), isErased = isErased) final def simplifyAndTypeWithFallback(tp1: Type, tp2: Type, fallback: Type): Type = @@ -2064,7 +2064,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * @param isErased Apply erasure semantics. If erased is true, instead of creating * an OrType, the lub will be computed using TypeCreator#erasedLub. */ - final def orType(tp1: Type, tp2: Type, isErased: Boolean = currentlyAfterErasure): Type = { + final def orType(tp1: Type, tp2: Type, isErased: Boolean = ctx.erasedTypes): Type = { val t1 = distributeOr(tp1, tp2) if (t1.exists) t1 else { diff --git a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala index ddf0272a1d9d..ecc5b14a2536 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala @@ -132,7 +132,7 @@ object TypeErasure { /** The current context with a phase no later than erasure */ def preErasureCtx(using Context) = - if (currentlyAfterErasure) ctx.withPhase(erasurePhase) else ctx + if (ctx.erasedTypes) ctx.withPhase(erasurePhase) else ctx /** The standard erasure of a Scala type. Value classes are erased as normal classes. * @@ -608,7 +608,7 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean else val cls = normalizeClass(sym.asClass) val fullName = - if !currentlyAfterErasure then + if !ctx.erasedTypes then // It's important to use the initial symbol to compute the full name // because the current symbol might have a different name or owner // and signatures are required to be stable before erasure. diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index 8e091c788dc5..3eca986a973b 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -193,7 +193,7 @@ object TypeOps: val accu1 = if (accu exists (_ derivesFrom c)) accu else c :: accu if (cs == c.baseClasses) accu1 else dominators(rest, accu1) case Nil => // this case can happen because after erasure we do not have a top class anymore - assert(currentlyAfterErasure || ctx.reporter.errorsReported) + assert(ctx.erasedTypes || ctx.reporter.errorsReported) defn.ObjectClass :: Nil } diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index 22cc412a7a33..8564627b4d11 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -1413,7 +1413,7 @@ object Types { TermRef(this, name, member(name)) def select(name: TermName, sig: Signature)(using Context): TermRef = - TermRef(this, name, member(name).atSignature(sig, relaxed = !currentlyAfterErasure)) + TermRef(this, name, member(name).atSignature(sig, relaxed = !ctx.erasedTypes)) // ----- Access to parts -------------------------------------------- @@ -1601,8 +1601,8 @@ object Types { def toFunctionType(dropLast: Int = 0)(using Context): Type = this match { case mt: MethodType if !mt.isParamDependent => val formals1 = if (dropLast == 0) mt.paramInfos else mt.paramInfos dropRight dropLast - val isContextual = mt.isContextualMethod && !currentlyAfterErasure - val isErased = mt.isErasedMethod && !currentlyAfterErasure + val isContextual = mt.isContextualMethod && !ctx.erasedTypes + val isErased = mt.isErasedMethod && !ctx.erasedTypes val result1 = mt.nonDependentResultApprox match { case res: MethodType => res.toFunctionType() case res => res @@ -1904,7 +1904,7 @@ object Types { protected[dotc] def computeSignature(using Context): Signature = val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) - else if currentlyAfterErasure then atPhase(erasurePhase)(computeSignature) + else if ctx.erasedTypes then atPhase(erasurePhase)(computeSignature) else symbol.asSeenFrom(prefix).signature /** The signature computed from the current denotation with `sigFromDenot` if it is @@ -1918,7 +1918,7 @@ object Types { else val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) - else if currentlyAfterErasure then atPhase(erasurePhase)(currentSignature) + else if ctx.erasedTypes then atPhase(erasurePhase)(currentSignature) else val sym = currentSymbol if sym.exists then sym.asSeenFrom(prefix).signature @@ -1934,7 +1934,7 @@ object Types { final def symbol(using Context): Symbol = // We can rely on checkedPeriod (unlike in the definition of `denot` below) // because SymDenotation#installAfter never changes the symbol - if (checkedPeriod == currentPeriod) lastSymbol else computeSymbol + if (checkedPeriod == ctx.period) lastSymbol else computeSymbol private def computeSymbol(using Context): Symbol = designator match { @@ -1977,7 +1977,7 @@ object Types { /** The denotation currently denoted by this type */ final def denot(using Context): Denotation = { util.Stats.record("NamedType.denot") - val now = currentPeriod + val now = ctx.period // Even if checkedPeriod == now we still need to recheck lastDenotation.validFor // as it may have been mutated by SymDenotation#installAfter if (checkedPeriod != Nowhere && lastDenotation.validFor.contains(now)) { @@ -2038,7 +2038,7 @@ object Types { private def disambiguate(d: Denotation, sig: Signature)(using Context): Denotation = if (sig != null) - d.atSignature(sig, relaxed = !currentlyAfterErasure) match { + d.atSignature(sig, relaxed = !ctx.erasedTypes) match { case d1: SingleDenotation => d1 case d1 => d1.atSignature(sig, relaxed = false) match { @@ -2114,7 +2114,7 @@ object Types { lastDenotation = denot lastSymbol = denot.symbol - checkedPeriod = if (prefix.isProvisional) Nowhere else currentPeriod + checkedPeriod = if (prefix.isProvisional) Nowhere else ctx.period designator match { case sym: Symbol if designator ne lastSymbol => designator = lastSymbol.asInstanceOf[Designator{ type ThisName = self.ThisName }] @@ -2451,11 +2451,11 @@ object Types { * based tests. */ def canDropAlias(using Context) = - if myCanDropAliasPeriod != currentPeriod then + if myCanDropAliasPeriod != ctx.period then myCanDropAlias = !symbol.canMatchInheritedSymbols || !prefix.baseClasses.exists(_.info.decls.lookup(name).is(Deferred)) - myCanDropAliasPeriod = currentPeriod + myCanDropAliasPeriod = ctx.period myCanDropAlias override def designator: Designator = myDesignator @@ -2561,7 +2561,7 @@ object Types { } override def underlying(using Context): Type = - if (currentlyAfterErasure) tref + if (ctx.erasedTypes) tref else cls.info match { case cinfo: ClassInfo => cinfo.selfType case _: ErrorType | NoType if ctx.mode.is(Mode.Interactive) => cls.info @@ -2729,7 +2729,7 @@ object Types { else make(RefinedType(parent, names.head, infos.head), names.tail, infos.tail) def apply(parent: Type, name: Name, info: Type)(using Context): RefinedType = { - assert(!currentlyAfterErasure) + assert(!ctx.erasedTypes) unique(new CachedRefinedType(parent, name, info)).checkInst } } @@ -2875,7 +2875,7 @@ object Types { private var myBaseClasses: List[ClassSymbol] = _ /** Base classes of are the merge of the operand base classes. */ override final def baseClasses(using Context): List[ClassSymbol] = { - if (myBaseClassesPeriod != currentPeriod) { + if (myBaseClassesPeriod != ctx.period) { val bcs1 = tp1.baseClasses val bcs1set = BaseClassSet(bcs1) def recur(bcs2: List[ClassSymbol]): List[ClassSymbol] = bcs2 match { @@ -2887,7 +2887,7 @@ object Types { case nil => bcs1 } myBaseClasses = recur(tp2.baseClasses) - myBaseClassesPeriod = currentPeriod + myBaseClassesPeriod = ctx.period } myBaseClasses } @@ -2940,7 +2940,7 @@ object Types { private var myBaseClasses: List[ClassSymbol] = _ /** Base classes of are the intersection of the operand base classes. */ override final def baseClasses(using Context): List[ClassSymbol] = { - if (myBaseClassesPeriod != currentPeriod) { + if (myBaseClassesPeriod != ctx.period) { val bcs1 = tp1.baseClasses val bcs1set = BaseClassSet(bcs1) def recur(bcs2: List[ClassSymbol]): List[ClassSymbol] = bcs2 match { @@ -2953,7 +2953,7 @@ object Types { bcs2 } myBaseClasses = recur(tp2.baseClasses) - myBaseClassesPeriod = currentPeriod + myBaseClassesPeriod = ctx.period } myBaseClasses } @@ -2966,11 +2966,11 @@ object Types { /** Replace or type by the closest non-or type above it */ def join(using Context): Type = { - if (myJoinPeriod != currentPeriod) { + if (myJoinPeriod != ctx.period) { myJoin = TypeOps.orDominator(this) core.println(i"join of $this == $myJoin") assert(myJoin != this) - myJoinPeriod = currentPeriod + myJoinPeriod = ctx.period } myJoin } @@ -3790,14 +3790,14 @@ object Types { override def underlying(using Context): Type = tycon override def superType(using Context): Type = { - if (currentPeriod != validSuper) { + if (ctx.period != validSuper) { cachedSuper = tycon match { case tycon: HKTypeLambda => defn.AnyType case tycon: TypeRef if tycon.symbol.isClass => tycon case tycon: TypeProxy => tycon.superType.applyIfParameterized(args) case _ => defn.AnyType } - validSuper = if (tycon.isProvisional) Nowhere else currentPeriod + validSuper = if (tycon.isProvisional) Nowhere else ctx.period } cachedSuper } @@ -4380,7 +4380,7 @@ object Types { val givenSelf = clsd.givenSelfType if (!givenSelf.isValueType) appliedRef else if (clsd.is(Module)) givenSelf - else if (currentlyAfterErasure) appliedRef + else if (ctx.erasedTypes) appliedRef else AndType(givenSelf, appliedRef) } selfTypeCache diff --git a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala index c3bd96c4f45a..e21a835e2833 100644 --- a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala +++ b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala @@ -120,7 +120,7 @@ object ContextFunctionResults: * @param `n` the select nodes seen in previous recursive iterations of this method */ def integrateSelect(tree: untpd.Tree, n: Int = 0)(using Context): Boolean = - if currentlyAfterErasure then + if ctx.erasedTypes then atPhase(erasurePhase)(integrateSelect(tree, n)) else tree match case Select(qual, name) => diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index 74432437c4f4..5e5ee1b9dd80 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -316,7 +316,7 @@ class TreeChecker extends Phase with SymTransformer { override def typed(tree: untpd.Tree, pt: Type = WildcardType)(using Context): Tree = { val tpdTree = super.typed(tree, pt) Typer.assertPositioned(tree) - if (currentlyAfterErasure) + if (ctx.erasedTypes) // Can't be checked in earlier phases since `checkValue` is only run in // Erasure (because running it in Typer would force too much) checkIdentNotJavaClass(tpdTree) @@ -366,7 +366,7 @@ class TreeChecker extends Phase with SymTransformer { } override def typedIdent(tree: untpd.Ident, pt: Type)(using Context): Tree = { - assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + ctx.phase) + assert(tree.isTerm || !ctx.isAfterTyper, tree.show + " at " + ctx.phase) assert(tree.isType || ctx.mode.is(Mode.Pattern) && untpd.isWildcardArg(tree) || !needsSelect(tree.tpe), i"bad type ${tree.tpe} for $tree # ${tree.uniqueId}") assertDefined(tree) @@ -378,11 +378,11 @@ class TreeChecker extends Phase with SymTransformer { * Approximately means: The two symbols might be different but one still overrides the other. */ override def typedSelect(tree: untpd.Select, pt: Type)(using Context): Tree = { - assert(tree.isTerm || !currentlyAfterTyper, tree.show + " at " + ctx.phase) + assert(tree.isTerm || !ctx.isAfterTyper, tree.show + " at " + ctx.phase) val tpe = tree.typeOpt val sym = tree.symbol val symIsFixed = tpe match { - case tpe: TermRef => currentlyAfterErasure || !tpe.isMemberRef + case tpe: TermRef => ctx.erasedTypes || !tpe.isMemberRef case _ => false } if (sym.exists && !sym.is(Private) && @@ -453,7 +453,7 @@ class TreeChecker extends Phase with SymTransformer { (ddef.tparams :: ddef.vparamss).filter(!_.isEmpty).map(_.map(_.symbol)) def layout(symss: List[List[Symbol]]): String = symss.map(syms => i"($syms%, %)").mkString - assert(currentlyAfterErasure || sym.rawParamss == defParamss, + assert(ctx.erasedTypes || sym.rawParamss == defParamss, i"""param mismatch for ${sym.showLocated}: |defined in tree = ${layout(defParamss)} |stored in symbol = ${layout(sym.rawParamss)}""") diff --git a/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala b/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala index 659c43311c78..d3cec855eafe 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala @@ -23,7 +23,7 @@ object TypeUtils { def ensureMethodic(using Context): Type = self match { case self: MethodicType => self - case _ => if (currentlyAfterErasure) MethodType(Nil, self) else ExprType(self) + case _ => if (ctx.erasedTypes) MethodType(Nil, self) else ExprType(self) } def widenToParents(using Context): Type = self.parents match { diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index 56c1c3a9319c..5329c29ce0b3 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -1048,7 +1048,7 @@ trait Applications extends Compatibility { typedFunPart(tree.fun, PolyProto(typedArgs, pt)) match { case IntegratedTypeArgs(app) => app - case _: TypeApply if !currentlyAfterTyper => + case _: TypeApply if !ctx.isAfterTyper => errorTree(tree, "illegal repeated type application") case typedFn => typedFn.tpe.widen match { @@ -1830,7 +1830,7 @@ trait Applications extends Compatibility { val alts2 = alts.filter(alt => isDirectlyApplicableMethodRef(alt, args, resultType) ) - if (alts2.isEmpty && !currentlyAfterTyper) + if (alts2.isEmpty && !ctx.isAfterTyper) alts.filter(alt => isApplicableMethodRef(alt, args, resultType, keepConstraint = false) ) @@ -2048,7 +2048,7 @@ trait Applications extends Compatibility { case cdef: CaseDef => tpd.cpy.CaseDef(cdef)(body = adaptDeep(cdef.body, pt)) case _ => adapt(tree, pt) } - if (currentlyAfterTyper) trees else harmonizeWith(trees)(_.tpe, adaptDeep) + if (ctx.isAfterTyper) trees else harmonizeWith(trees)(_.tpe, adaptDeep) } /** Apply a transformation `harmonize` on the results of operation `op`, diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index fcec37725513..f216f344cfeb 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -727,7 +727,7 @@ trait Checking { /** Check that `path` is a legal prefix for an import or export clause */ def checkLegalImportPath(path: Tree)(using Context): Unit = { checkStable(path.tpe, path.sourcePos, "import prefix") - if (!currentlyAfterTyper) Checking.checkRealizable(path.tpe, path.posd) + if (!ctx.isAfterTyper) Checking.checkRealizable(path.tpe, path.posd) } /** Check that `tp` is a class type. @@ -868,7 +868,7 @@ trait Checking { /** Check that `tree` can be right hand-side or argument to `inline` value or parameter. */ def checkInlineConformant(tpt: Tree, tree: Tree, sym: Symbol)(using Context): Unit = { - if sym.is(Inline, butNot = DeferredOrTermParamOrAccessor) && !currentlyAfterErasure && !Inliner.inInlineMethod then + if sym.is(Inline, butNot = DeferredOrTermParamOrAccessor) && !ctx.erasedTypes && !Inliner.inInlineMethod then tpt.tpe.widenTermRefExpr.dealias.normalized match case tp: ConstantType => if !(exprPurity(tree) >= Pure) then @@ -917,7 +917,7 @@ trait Checking { } def checkParentCall(call: Tree, caller: ClassSymbol)(using Context): Unit = - if (!currentlyAfterTyper) { + if (!ctx.isAfterTyper) { val called = call.tpe.classSymbol if (caller.is(Trait)) report.error(i"$caller may not call constructor of $called", call.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala index 2d89564f162f..c4936b5a3a9e 100644 --- a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala +++ b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala @@ -223,7 +223,7 @@ object EtaExpansion extends LiftImpure { */ def etaExpand(tree: Tree, mt: MethodType, xarity: Int)(using Context): untpd.Tree = { import untpd._ - assert(!currentlyAfterTyper) + assert(!ctx.isAfterTyper) val defs = new mutable.ListBuffer[tpd.Tree] val lifted: Tree = TypedSplice(liftApp(defs, tree)) val isLastApplication = mt.resultType match { diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index d59a269ed60e..b8ba3396261c 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -730,7 +730,7 @@ trait Implicits { self: Typer => override def viewExists(from: Type, to: Type)(using Context): Boolean = !from.isError && !to.isError - && !currentlyAfterTyper + && !ctx.isAfterTyper && ctx.mode.is(Mode.ImplicitsEnabled) && from.isValueType && ( from.isValueSubType(to) @@ -956,7 +956,7 @@ trait Implicits { self: Typer => /** Check that equality tests between types `ltp` and `rtp` make sense */ def checkCanEqual(ltp: Type, rtp: Type, span: Span)(using Context): Unit = - if (!currentlyAfterTyper && !assumedCanEqual(ltp, rtp)) { + if (!ctx.isAfterTyper && !assumedCanEqual(ltp, rtp)) { val res = implicitArgTree(defn.EqlClass.typeRef.appliedTo(ltp, rtp), span) implicits.println(i"Eql witness found for $ltp / $rtp: $res: ${res.tpe}") } diff --git a/compiler/src/dotty/tools/dotc/typer/Nullables.scala b/compiler/src/dotty/tools/dotc/typer/Nullables.scala index ed8f34249563..514012dbb660 100644 --- a/compiler/src/dotty/tools/dotc/typer/Nullables.scala +++ b/compiler/src/dotty/tools/dotc/typer/Nullables.scala @@ -261,7 +261,7 @@ object Nullables: /* The nullability info of `tree` */ def notNullInfo(using Context): NotNullInfo = stripInlined(tree).getAttachment(NNInfo) match - case Some(info) if !currentlyAfterErasure => info + case Some(info) if !ctx.erasedTypes => info case _ => NotNullInfo.empty /* The nullability info of `tree`, assuming it is a condition that evaluates to `c` */ @@ -276,7 +276,7 @@ object Nullables: */ def notNullConditional(using Context): NotNullConditional = stripBlock(tree).getAttachment(NNConditional) match - case Some(cond) if !currentlyAfterErasure => cond + case Some(cond) if !ctx.erasedTypes => cond case _ => NotNullConditional.empty /** The current context augmented with nullability information of `tree` */ @@ -297,7 +297,7 @@ object Nullables: * of the left argument, if the application is a boolean `&&` or `||`. */ def nullableInArgContext(using Context): Context = tree match - case Select(x, _) if !currentlyAfterErasure => + case Select(x, _) if !ctx.erasedTypes => if tree.symbol == defn.Boolean_&& then x.nullableContextIf(true) else if tree.symbol == defn.Boolean_|| then x.nullableContextIf(false) else ctx @@ -313,7 +313,7 @@ object Nullables: def computeNullable()(using Context): tree.type = def setConditional(ifTrue: Set[TermRef], ifFalse: Set[TermRef]) = tree.putAttachment(NNConditional, NotNullConditional(ifTrue, ifFalse)) - if !currentlyAfterErasure && analyzedOps.contains(tree.symbol.name.toTermName) then + if !ctx.erasedTypes && analyzedOps.contains(tree.symbol.name.toTermName) then tree match case CompareNull(TrackedRef(ref), testEqual) => if testEqual then setConditional(Set(), Set(ref)) diff --git a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala index 83dca707c4a6..73c14dc71838 100644 --- a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala +++ b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala @@ -234,7 +234,7 @@ object PrepareInlineable { case Some(ann: ConcreteBodyAnnotation) => case Some(ann: LazyBodyAnnotation) if ann.isEvaluated || ann.isEvaluating => case _ => - if (!currentlyAfterTyper) { + if (!ctx.isAfterTyper) { val inlineCtx = ctx inlined.updateAnnotation(LazyBodyAnnotation { given ctx as Context = inlineCtx @@ -255,7 +255,7 @@ object PrepareInlineable { if Inliner.inInlineMethod(using ctx.outer) then report.error(ex"Implementation restriction: nested inline methods are not supported", inlined.sourcePos) - if (inlined.is(Macro) && !currentlyAfterTyper) { + if (inlined.is(Macro) && !ctx.isAfterTyper) { def checkMacro(tree: Tree): Unit = tree match { case Spliced(code) => diff --git a/compiler/src/dotty/tools/dotc/typer/ReTyper.scala b/compiler/src/dotty/tools/dotc/typer/ReTyper.scala index 20cb18bad09a..35458aa89af4 100644 --- a/compiler/src/dotty/tools/dotc/typer/ReTyper.scala +++ b/compiler/src/dotty/tools/dotc/typer/ReTyper.scala @@ -122,7 +122,7 @@ class ReTyper extends Typer with ReChecking { try super.typedUnadapted(tree, pt, locked) catch { case NonFatal(ex) => - if (currentlyAfterTyper) + if (ctx.isAfterTyper) println(i"exception while typing $tree of class ${tree.getClass} # ${tree.uniqueId}") throw ex } diff --git a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala index 31fa0126ea0c..43e731bbd791 100644 --- a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala +++ b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala @@ -228,7 +228,7 @@ trait TypeAssigner { value.tag match { case UnitTag => defn.UnitType case NullTag => defn.NullType - case _ => if (currentlyAfterErasure) value.tpe else ConstantType(value) + case _ => if (ctx.erasedTypes) value.tpe else ConstantType(value) } } @@ -256,7 +256,7 @@ trait TypeAssigner { val owntype = if (mixinClass.exists) mixinClass.appliedRef else if (!mix.isEmpty) findMixinSuper(cls.info) - else if (currentlyAfterErasure) cls.info.firstParent.typeConstructor + else if (ctx.erasedTypes) cls.info.firstParent.typeConstructor else { val ps = cls.classInfo.parents if (ps.isEmpty) defn.AnyType else ps.reduceLeft((x: Type, y: Type) => x & y) @@ -431,7 +431,7 @@ trait TypeAssigner { def assignType(tree: untpd.SeqLiteral, elems: List[Tree], elemtpt: Tree)(using Context): SeqLiteral = { val ownType = tree match { case tree: untpd.JavaSeqLiteral => defn.ArrayOf(elemtpt.tpe) - case _ => if (currentlyAfterErasure) defn.SeqType else defn.SeqType.appliedTo(elemtpt.tpe) + case _ => if (ctx.erasedTypes) defn.SeqType else defn.SeqType.appliedTo(elemtpt.tpe) } tree.withType(ownType) } diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index f2506d33a8da..03c4cb29d0f2 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -766,7 +766,7 @@ class Typer extends Namer def typedTpt = checkSimpleKinded(typedType(tree.tpt)) def handlePattern: Tree = { val tpt1 = typedTpt - if (!currentlyAfterTyper && pt != defn.ImplicitScrutineeTypeRef) + if (!ctx.isAfterTyper && pt != defn.ImplicitScrutineeTypeRef) withMode(Mode.GadtConstraintInference)(ctx.typeComparer.constrainPatternType(tpt1.tpe, pt)) // special case for an abstract type that comes with a class tag tryWithClassTag(ascription(tpt1, isWildcard = true), pt) @@ -783,7 +783,7 @@ class Typer extends Namer * @pre We are in pattern-matching mode (Mode.Pattern) */ def tryWithClassTag(tree: Typed, pt: Type)(using Context): Tree = tree.tpt.tpe.dealias match { - case tref: TypeRef if !tref.symbol.isClass && !currentlyAfterTyper && !(tref =:= pt) => + case tref: TypeRef if !tref.symbol.isClass && !ctx.isAfterTyper && !(tref =:= pt) => require(ctx.mode.is(Mode.Pattern)) withoutMode(Mode.Pattern)( inferImplicit(defn.ClassTagClass.typeRef.appliedTo(tref), EmptyTree, tree.tpt.span) @@ -1391,7 +1391,7 @@ class Typer extends Namer if (sym.name != tpnme.WILDCARD) if (ctx.scope.lookup(b.name) == NoSymbol) ctx.enter(sym) else report.error(new DuplicateBind(b, cdef), b.sourcePos) - if (!currentlyAfterTyper) { + if (!ctx.isAfterTyper) { val bounds = ctx.gadt.fullBounds(sym) if (bounds != null) sym.info = bounds } @@ -1515,7 +1515,7 @@ class Typer extends Namer else { val from = tree.from.asInstanceOf[tpd.Tree] val proto = - if (currentlyAfterErasure) from.symbol.info.finalResultType + if (ctx.erasedTypes) from.symbol.info.finalResultType else WildcardType // We cannot reliably detect the internal type view of polymorphic or dependent methods // because we do not know the internal type params and method params. // Hence no adaptation is possible, and we assume WildcardType as prototype. @@ -1789,7 +1789,7 @@ class Typer extends Namer // are eliminated once the enclosing pattern has been typechecked; see `indexPattern` // in `typedCase`. //val ptt = if (lo.isEmpty && hi.isEmpty) pt else - if (currentlyAfterTyper) tree1 + if (ctx.isAfterTyper) tree1 else { val wildcardSym = newPatternBoundSymbol(tpnme.WILDCARD, tree1.tpe & pt, tree.span) untpd.Bind(tpnme.WILDCARD, tree1).withType(wildcardSym.typeRef) @@ -2008,7 +2008,7 @@ class Typer extends Namer case cinfo @ MethodType(Nil) if !cinfo.resultType.isInstanceOf[MethodType] => ref case cinfo: MethodType => - if (!currentlyAfterErasure) { // after constructors arguments are passed in super call. + if (!ctx.erasedTypes) { // after constructors arguments are passed in super call. typr.println(i"constr type: $cinfo") report.error(ParameterizedTypeLacksArguments(psym), ref.sourcePos) } @@ -2034,7 +2034,7 @@ class Typer extends Namer if (!tree.span.isSourceDerived) return EmptyTree - if (!currentlyAfterTyper) report.error(i"$psym is extended twice", tree.sourcePos) + if (!ctx.isAfterTyper) report.error(i"$psym is extended twice", tree.sourcePos) } else seenParents += psym if (tree.isType) { @@ -2083,7 +2083,7 @@ class Typer extends Namer checkNoDoubleDeclaration(cls) val impl1 = cpy.Template(impl)(constr1, parents1, Nil, self1, body1) .withType(dummy.termRef) - if (!cls.isOneOf(AbstractOrTrait) && !currentlyAfterTyper) + if (!cls.isOneOf(AbstractOrTrait) && !ctx.isAfterTyper) checkRealizableBounds(cls, cdef.sourcePos.withSpan(cdef.nameSpan)) if (cls.derivesFrom(defn.EnumClass)) { val firstParent = parents1.head.tpe.dealias.typeSymbol @@ -2205,7 +2205,7 @@ class Typer extends Namer case pid1: RefTree if pkg.is(Package) => val packageCtx = ctx.packageContext(tree, pkg) var stats1 = typedStats(tree.stats, pkg.moduleClass)(using packageCtx)._1 - if (!currentlyAfterTyper) + if (!ctx.isAfterTyper) stats1 = stats1 ++ typedBlockStats(MainProxies.mainProxies(stats1))(using packageCtx)._1 cpy.PackageDef(tree)(pid1, stats1).withType(pkg.termRef) case _ => @@ -2475,7 +2475,7 @@ class Typer extends Namer && xtree.isTerm && !untpd.isContextualClosure(xtree) && !ctx.mode.is(Mode.Pattern) - && !currentlyAfterTyper + && !ctx.isAfterTyper && !ctx.isInlineContext then makeContextualFunction(xtree, ifpt) @@ -3201,7 +3201,7 @@ class Typer extends Namer !isApplyProto(pt) && pt != AssignProto && !ctx.mode.is(Mode.Pattern) && - !currentlyAfterTyper && + !ctx.isAfterTyper && !ctx.isInlineContext) { typr.println(i"insert apply on implicit $tree") typed(untpd.Select(untpd.TypedSplice(tree), nme.apply), pt, locked) @@ -3556,7 +3556,7 @@ class Typer extends Namer } // Overridden in InlineTyper - def suppressInline(using Context): Boolean = currentlyAfterTyper + def suppressInline(using Context): Boolean = ctx.isAfterTyper /** Does the "contextuality" of the method type `methType` match the one of the prototype `pt`? * This is the case if @@ -3593,7 +3593,7 @@ class Typer extends Namer } private def checkStatementPurity(tree: tpd.Tree)(original: untpd.Tree, exprOwner: Symbol)(using Context): Unit = - if (!tree.tpe.isErroneous && !currentlyAfterTyper && isPureExpr(tree) && + if (!tree.tpe.isErroneous && !ctx.isAfterTyper && isPureExpr(tree) && !tree.tpe.isRef(defn.UnitClass) && !isSelfOrSuperConstrCall(tree)) report.warning(PureExpressionInStatementPosition(original, exprOwner), original.sourcePos) From 0e0f686d32d9e0f602af5da6c822874ca5d07fae Mon Sep 17 00:00:00 2001 From: Martin Odersky <odersky@gmail.com> Date: Mon, 20 Jul 2020 13:29:02 +0200 Subject: [PATCH 10/10] Remove all mixin traits from Contexts. In particular: - `newSymbol`, `requiredSymbol` etc, now are available from Symbols, no `ctx.` prefix needed - All reporing methods are available from `report` object. Also: - Change functions from Context to context functions. - Add atPhase, atPhaseNoLater, addPhaseNoEarlier and have them replace most uss of `withPhase`... - Add inMode, withMode, withoutMode utility wrappers - Move error messages directly into reporting: this avoids an annoying import - Convert old style implicit parameters to `(using Context)` - Reorganize TyperState.test: Instead of overwriting fields of TyperState, keep test contexts in an explicit stack, so that they can be re-used. This is simpler and since there is more decoupling between tests. Usage is now `Contexts.explore(...)` instead of `ctx.test(...)`. # Conflicts: # compiler/src/dotty/tools/dotc/core/Definitions.scala # Conflicts: # compiler/src/dotty/tools/dotc/Run.scala # compiler/src/dotty/tools/dotc/core/Annotations.scala # compiler/src/dotty/tools/dotc/core/Contexts.scala # compiler/src/dotty/tools/dotc/core/Definitions.scala # compiler/src/dotty/tools/dotc/core/Phases.scala # compiler/src/dotty/tools/dotc/core/TyperState.scala # compiler/src/dotty/tools/dotc/core/Types.scala # compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala # compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala # compiler/src/dotty/tools/dotc/transform/TreeChecker.scala # compiler/src/dotty/tools/dotc/typer/Namer.scala --- compiler/src/dotty/tools/dotc/Run.scala | 10 ++++----- .../dotty/tools/dotc/core/Annotations.scala | 5 +++++ .../src/dotty/tools/dotc/core/Contexts.scala | 20 +++++++----------- .../src/dotty/tools/dotc/core/Phases.scala | 10 ++++----- .../dotty/tools/dotc/core/TyperState.scala | 13 ++---------- .../tools/dotc/core/tasty/TreeUnpickler.scala | 16 +++++++------- .../dotc/reporting/ExploringReporter.scala | 21 +++++++++++++++++++ .../tools/dotc/transform/ExplicitOuter.scala | 17 ++++++++------- .../tools/dotc/transform/TreeChecker.scala | 6 +++--- .../src/dotty/tools/dotc/typer/Namer.scala | 8 +++---- 10 files changed, 70 insertions(+), 56 deletions(-) create mode 100644 compiler/src/dotty/tools/dotc/reporting/ExploringReporter.scala diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 1101dec8c15a..53c4be27d8ce 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -131,7 +131,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint throw ex } - /** TODO: There's a fundamental design problem here: We assemble phases using `squash` + /** TODO: There's a fundamental design problem here: We assemble phases using `fusePhases` * when we first build the compiler. But we modify them with -Yskip, -Ystop * on each run. That modification needs to either transform the tree structure, * or we need to assemble phases on each run, and take -Yskip, -Ystop into @@ -237,10 +237,10 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint private def printTree(last: PrintedTree)(using Context): PrintedTree = { val unit = ctx.compilationUnit val prevPhase = ctx.phase.prev // can be a mini-phase - val squashedPhase = ctx.base.squashed(prevPhase) + val fusedPhase = ctx.base.fusedContaining(prevPhase) val treeString = unit.tpdTree.show(using ctx.withProperty(XprintMode, Some(()))) - report.echo(s"result of $unit after $squashedPhase:") + report.echo(s"result of $unit after $fusedPhase:") last match { case SomePrintedTree(phase, lastTreeSting) if lastTreeSting != treeString => @@ -248,7 +248,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint if (!ctx.settings.XprintDiff.value && !ctx.settings.XprintDiffDel.value) treeString else DiffUtil.mkColoredCodeDiff(treeString, lastTreeSting, ctx.settings.XprintDiffDel.value) report.echo(msg) - SomePrintedTree(squashedPhase.toString, treeString) + SomePrintedTree(fusedPhase.toString, treeString) case SomePrintedTree(phase, lastTreeSting) => report.echo(" Unchanged since " + phase) @@ -256,7 +256,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint case NoPrintedTree => report.echo(treeString) - SomePrintedTree(squashedPhase.toString, treeString) + SomePrintedTree(fusedPhase.toString, treeString) } } diff --git a/compiler/src/dotty/tools/dotc/core/Annotations.scala b/compiler/src/dotty/tools/dotc/core/Annotations.scala index 20ca963ff4a2..52b515ad0ae8 100644 --- a/compiler/src/dotty/tools/dotc/core/Annotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Annotations.scala @@ -59,6 +59,11 @@ object Annotations { case symFn: (Context ?=> Symbol) @unchecked => mySym = null mySym = atPhaseNoLater(picklerPhase)(symFn) + // We should always produce the same annotation tree, no matter when the + // annotation is evaluated. Setting the phase to a pre-transformation phase + // seems to be enough to ensure this (note that after erasure, `ctx.typer` + // will be the Erasure typer, but that doesn't seem to affect the annotation + // trees we create, so we leave it as is) case sym: Symbol if sym.defRunId != parentCtx.runId => mySym = sym.denot.current.symbol case _ => diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index d043a6bd1a11..3b30bb0cbebf 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -305,7 +305,7 @@ object Contexts { private var phasedCtxs: Array[Context] = null /** This context at given phase. - * This method will always return a phase period equal to phaseId, thus will never return squashed phases + * This method will always return a phase period equal to phaseId, thus will never return a fused phase */ final def withPhase(phaseId: PhaseId): Context = if (this.period.phaseId == phaseId) this @@ -324,12 +324,6 @@ object Contexts { final def withPhase(phase: Phase): Context = withPhase(phase.id) - final def withPhaseNoLater(phase: Phase): Context = - if (phase.exists && period.phaseId > phase.id) withPhase(phase) else this - - final def withPhaseNoEarlier(phase: Phase): Context = - if (phase.exists && period.phaseId < phase.id) withPhase(phase) else this - // `creationTrace`-related code. To enable, uncomment the code below and the // call to `setCreationTrace()` in this file. /* @@ -662,8 +656,8 @@ object Contexts { def updateStore[T](loc: Store.Location[T], value: T): this.type = setStore(store.updated(loc, value)) - def setPhase(pid: PhaseId): this.type = setPeriod(Period(period.runId, pid)) - def setPhase(phase: Phase): this.type = setPeriod(Period(period.runId, phase.start, phase.end)) + def setPhase(pid: PhaseId): this.type = setPeriod(Period(runId, pid)) + def setPhase(phase: Phase): this.type = setPeriod(Period(runId, phase.start, phase.end)) def setSetting[T](setting: Setting[T], value: T): this.type = setSettings(setting.updateIn(settingsState, value)) @@ -709,7 +703,7 @@ object Contexts { testContexts(testsInUse).reuseIn(ctx) else val ts = TyperState() - .setReporter(TestingReporter()) + .setReporter(ExploringReporter()) .setCommittable(false) val c = FreshContext(ctx.base).init(ctx, ctx).setTyperState(ts) testContexts += c @@ -720,7 +714,7 @@ object Contexts { val result = try op(using nestedCtx) finally - nestedTS.reporter.asInstanceOf[TestingReporter].reset() + nestedTS.reporter.asInstanceOf[ExploringReporter].reset() testsInUse -= 1 result end explore @@ -796,7 +790,7 @@ object Contexts { definitions.init() } - def squashed(p: Phase): Phase = + def fusedContaining(p: Phase): Phase = allPhases.find(_.period.containsPhaseId(p.id)).getOrElse(NoPhase) } @@ -864,7 +858,7 @@ object Contexts { /** Phases by id */ private[dotc] var phases: Array[Phase] = _ - /** Phases with consecutive Transforms grouped into a single phase, Empty array if squashing is disabled */ + /** Phases with consecutive Transforms grouped into a single phase, Empty array if fusion is disabled */ private[core] var fusedPhases: Array[Phase] = Array.empty[Phase] /** Next denotation transformer id */ diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index d8878ef15a6a..994cc3ff05a3 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -92,13 +92,13 @@ object Phases { s"${phase.phaseName} requires ${unmetRequirements.mkString(", ")} to be in different TreeTransformer") case _ => - assert(false, s"Only tree transforms can be squashed, ${phase.phaseName} can not be squashed") + assert(false, s"Only tree transforms can be fused, ${phase.phaseName} can not be fused") } val superPhase = new MegaPhase(filteredPhaseBlock.asInstanceOf[List[MiniPhase]].toArray) prevPhases ++= filteredPhaseBlock.map(_.phaseName) superPhase } - else { // block of a single phase, no squashing + else { // block of a single phase, no fusion val phase = filteredPhaseBlock.head prevPhases += phase.phaseName phase @@ -118,9 +118,9 @@ object Phases { /** Use the following phases in the order they are given. * The list should never contain NoPhase. - * if squashing is enabled, phases in same subgroup will be squashed to single phase. + * if fusion is enabled, phases in same subgroup will be fused to single phase. */ - final def usePhases(phasess: List[Phase], squash: Boolean = true): Unit = { + final def usePhases(phasess: List[Phase], fuse: Boolean = true): Unit = { val flatPhases = collection.mutable.ListBuffer[Phase]() @@ -183,7 +183,7 @@ object Phases { nextDenotTransformerId(i) = lastTransformerId } - if (squash) + if (fuse) this.fusedPhases = (NoPhase :: phasess).toArray else this.fusedPhases = this.phases diff --git a/compiler/src/dotty/tools/dotc/core/TyperState.scala b/compiler/src/dotty/tools/dotc/core/TyperState.scala index 168e415b1d43..ccb1cfd29648 100644 --- a/compiler/src/dotty/tools/dotc/core/TyperState.scala +++ b/compiler/src/dotty/tools/dotc/core/TyperState.scala @@ -29,7 +29,7 @@ class TyperState() { private var myId: Int = _ def id: Int = myId - private var previous: TyperState = _ + private var previous: TyperState /* | Null */ = _ private var myReporter: Reporter = _ @@ -69,7 +69,7 @@ class TyperState() { /** Initializes all fields except reporter, isCommittable, which need to be * set separately. */ - private[core] def init(previous: TyperState, constraint: Constraint): this.type = + private[core] def init(previous: TyperState /* | Null */, constraint: Constraint): this.type = this.myId = TyperState.nextId TyperState.nextId += 1 this.previous = previous @@ -79,15 +79,6 @@ class TyperState() { this.isCommitted = false this - def disable() = - previous = null - myConstraint = null - previousConstraint = null - myOwnedVars = null - isCommitted = false - myReporter = null - myIsCommittable = true - /** A fresh typer state with the same constraint as this one. */ def fresh(reporter: Reporter = StoreReporter(this.reporter)): TyperState = util.Stats.record("TyperState.fresh") diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index 0057ab275ae7..b5bf7128d552 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -116,9 +116,10 @@ class TreeUnpickler(reader: TastyReader, val owner = ctx.owner val source = ctx.source def complete(denot: SymDenotation)(using Context): Unit = - treeAtAddr(currentAddr) = + treeAtAddr(currentAddr) = atPhaseNoLater(picklerPhase) { new TreeReader(reader).readIndexedDef()( - using ctx.withPhaseNoLater(picklerPhase).withOwner(owner).withSource(source)) + using ctx.withOwner(owner).withSource(source)) + } } class TreeReader(val reader: TastyReader) { @@ -1375,11 +1376,12 @@ class TreeUnpickler(reader: TastyReader, op: TreeReader => Context ?=> T) extends Trees.Lazy[T] { def complete(using Context): T = { pickling.println(i"starting to read at ${reader.reader.currentAddr} with owner $owner") - op(reader)(using ctx - .withPhaseNoLater(picklerPhase) - .withOwner(owner) - .withModeBits(mode) - .withSource(source)) + atPhaseNoLater(picklerPhase) { + op(reader)(using ctx + .withOwner(owner) + .withModeBits(mode) + .withSource(source)) + } } } diff --git a/compiler/src/dotty/tools/dotc/reporting/ExploringReporter.scala b/compiler/src/dotty/tools/dotc/reporting/ExploringReporter.scala new file mode 100644 index 000000000000..e7b636cddf02 --- /dev/null +++ b/compiler/src/dotty/tools/dotc/reporting/ExploringReporter.scala @@ -0,0 +1,21 @@ +package dotty.tools +package dotc +package reporting + +import collection.mutable +import core.Contexts.Context +import Diagnostic._ + +/** A re-usable Reporter used in Contexts#test */ +class ExploringReporter extends StoreReporter(null): + infos = new mutable.ListBuffer[Diagnostic] + + override def hasUnreportedErrors: Boolean = + infos.exists(_.isInstanceOf[Error]) + + override def removeBufferedMessages(using Context): List[Diagnostic] = + try infos.toList finally reset() + + def reset(): Unit = infos.clear() + +end ExploringReporter \ No newline at end of file diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index 6c85145faa5c..5ab591ca1e68 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -397,16 +397,19 @@ object ExplicitOuter { try @tailrec def loop(tree: Tree, count: Int): Tree = val treeCls = tree.tpe.widen.classSymbol - val outerAccessorCtx = ctx.withPhaseNoLater(lambdaLiftPhase) // lambdalift mangles local class names, which means we cannot reliably find outer acessors anymore - report.log(i"outer to $toCls of $tree: ${tree.tpe}, looking for ${outerAccName(treeCls.asClass)(using outerAccessorCtx)} in $treeCls") + report.log(i"outer to $toCls of $tree: ${tree.tpe}, looking for ${atPhaseNoLater(lambdaLiftPhase)(outerAccName(treeCls.asClass))} in $treeCls") if (count == 0 || count < 0 && treeCls == toCls) tree else val enclClass = ctx.owner.lexicallyEnclosingClass.asClass - val outerAcc = tree match - case tree: This if tree.symbol == enclClass && !enclClass.is(Trait) => - outerParamAccessor(enclClass)(using outerAccessorCtx) - case _ => - outerAccessor(treeCls.asClass)(using outerAccessorCtx) + val outerAcc = atPhaseNoLater(lambdaLiftPhase) { + // lambdalift mangles local class names, which means we cannot + // reliably find outer acessors anymore + tree match + case tree: This if tree.symbol == enclClass && !enclClass.is(Trait) => + outerParamAccessor(enclClass) + case _ => + outerAccessor(treeCls.asClass) + } assert(outerAcc.exists, i"failure to construct path from ${ctx.owner.ownersIterator.toList}%/% to `this` of ${toCls.showLocated};\n${treeCls.showLocated} does not have an outer accessor") loop(tree.select(outerAcc).ensureApplied, count - 1) diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index 5e5ee1b9dd80..df1ec46bb4f6 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -100,7 +100,7 @@ class TreeChecker extends Phase with SymTransformer { cur.signature } assert(curSig == initial.signature, - i"""Signature of ${sym.showLocated} changed at phase ${ctx.base.squashed(ctx.phase.prev)} + i"""Signature of ${sym.showLocated} changed at phase ${ctx.base.fusedContaining(ctx.phase.prev)} |Initial info: ${initial} |Initial sig : ${initial.signature} |Current info: ${cur} @@ -133,8 +133,8 @@ class TreeChecker extends Phase with SymTransformer { def check(phasesToRun: Seq[Phase], ctx: Context): Tree = { val prevPhase = ctx.phase.prev // can be a mini-phase - val squashedPhase = ctx.base.squashed(prevPhase) - report.echo(s"checking ${ctx.compilationUnit} after phase ${squashedPhase}")(using ctx) + val fusedPhase = ctx.base.fusedContaining(prevPhase) + report.echo(s"checking ${ctx.compilationUnit} after phase ${fusedPhase}")(using ctx) inContext(ctx) { assertSelectWrapsNew(ctx.compilationUnit.tpdTree) diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index d21f3155d963..368b9024e7a2 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -672,7 +672,7 @@ class Namer { typer: Typer => given creationContext as Context = ictx // make sure testing contexts are not captured by completers - assert(!ictx.reporter.isInstanceOf[TestingReporter]) + assert(!ictx.reporter.isInstanceOf[ExploringReporter]) protected def typeSig(sym: Symbol): Type = original match { case original: ValDef => @@ -1216,10 +1216,8 @@ class Namer { typer: Typer => } def typedAheadType(tree: Tree, pt: Type = WildcardType)(using Context): tpd.Tree = - withoutMode(Mode.PatternOrTypeBits) { - withMode(Mode.Type) { - typedAhead(tree, typer.typed(_, pt)) - } + inMode(ctx.mode &~ Mode.PatternOrTypeBits | Mode.Type) { + typedAhead(tree, typer.typed(_, pt)) } def typedAheadExpr(tree: Tree, pt: Type = WildcardType)(using Context): tpd.Tree =