From d8cd2bbc777a2cfe9d06f35327c76ea0154f1799 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 10:06:37 +0200 Subject: [PATCH 01/41] Convert to using clauses --- .../src/dotty/tools/dotc/core/Contexts.scala | 1 - .../dotty/tools/dotc/core/Substituters.scala | 42 +- .../tools/dotc/core/TypeApplications.scala | 2 +- .../src/dotty/tools/dotc/core/Types.scala | 801 +++++++++--------- .../tools/dotc/sbt/ExtractDependencies.scala | 2 +- .../tools/dotc/transform/ExplicitOuter.scala | 2 +- 6 files changed, 425 insertions(+), 425 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 232a893072ff..f97e8bd6eece 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -78,7 +78,6 @@ object Contexts { */ abstract class Context(val base: ContextBase) extends Periods - with Substituters with Phases with Printers with Symbols diff --git a/compiler/src/dotty/tools/dotc/core/Substituters.scala b/compiler/src/dotty/tools/dotc/core/Substituters.scala index bd70216ba390..e34f4495b648 100644 --- a/compiler/src/dotty/tools/dotc/core/Substituters.scala +++ b/compiler/src/dotty/tools/dotc/core/Substituters.scala @@ -5,9 +5,9 @@ import Types._, Symbols._, Contexts._ /** Substitution operations on types. See the corresponding `subst` and * `substThis` methods on class Type for an explanation. */ -trait Substituters { this: Context => +object Substituters: - final def subst(tp: Type, from: BindingType, to: BindingType, theMap: SubstBindingMap): Type = + final def subst(tp: Type, from: BindingType, to: BindingType, theMap: SubstBindingMap)(using Context): Type = tp match { case tp: BoundType => if (tp.binder eq from) tp.copyBoundType(to.asInstanceOf[tp.BT]) else tp @@ -21,7 +21,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def subst1(tp: Type, from: Symbol, to: Type, theMap: Subst1Map): Type = + final def subst1(tp: Type, from: Symbol, to: Type, theMap: Subst1Map)(using Context): Type = tp match { case tp: NamedType => val sym = tp.symbol @@ -35,7 +35,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def subst2(tp: Type, from1: Symbol, to1: Type, from2: Symbol, to2: Type, theMap: Subst2Map): Type = + final def subst2(tp: Type, from1: Symbol, to1: Type, from2: Symbol, to2: Type, theMap: Subst2Map)(using Context): Type = tp match { case tp: NamedType => val sym = tp.symbol @@ -50,7 +50,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def subst(tp: Type, from: List[Symbol], to: List[Type], theMap: SubstMap): Type = + final def subst(tp: Type, from: List[Symbol], to: List[Type], theMap: SubstMap)(using Context): Type = tp match { case tp: NamedType => val sym = tp.symbol @@ -70,7 +70,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def substSym(tp: Type, from: List[Symbol], to: List[Symbol], theMap: SubstSymMap): Type = + final def substSym(tp: Type, from: List[Symbol], to: List[Symbol], theMap: SubstSymMap)(using Context): Type = tp match { case tp: NamedType => val sym = tp.symbol @@ -101,7 +101,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def substThis(tp: Type, from: ClassSymbol, to: Type, theMap: SubstThisMap): Type = + final def substThis(tp: Type, from: ClassSymbol, to: Type, theMap: SubstThisMap)(using Context): Type = tp match { case tp: ThisType => if (tp.cls eq from) to else tp @@ -115,7 +115,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def substRecThis(tp: Type, from: Type, to: Type, theMap: SubstRecThisMap): Type = + final def substRecThis(tp: Type, from: Type, to: Type, theMap: SubstRecThisMap)(using Context): Type = tp match { case tp @ RecThis(binder) => if (binder eq from) to else tp @@ -129,7 +129,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def substParam(tp: Type, from: ParamRef, to: Type, theMap: SubstParamMap): Type = + final def substParam(tp: Type, from: ParamRef, to: Type, theMap: SubstParamMap)(using Context): Type = tp match { case tp: BoundType => if (tp == from) to else tp @@ -143,7 +143,7 @@ trait Substituters { this: Context => .mapOver(tp) } - final def substParams(tp: Type, from: BindingType, to: List[Type], theMap: SubstParamsMap): Type = + final def substParams(tp: Type, from: BindingType, to: List[Type], theMap: SubstParamsMap)(using Context): Type = tp match { case tp: ParamRef => if (tp.binder == from) to(tp.paramNum) else tp @@ -157,44 +157,44 @@ trait Substituters { this: Context => .mapOver(tp) } - final class SubstBindingMap(from: BindingType, to: BindingType) extends DeepTypeMap { + final class SubstBindingMap(from: BindingType, to: BindingType)(using Context) extends DeepTypeMap { def apply(tp: Type): Type = subst(tp, from, to, this) } - final class Subst1Map(from: Symbol, to: Type) extends DeepTypeMap { + final class Subst1Map(from: Symbol, to: Type)(using Context) extends DeepTypeMap { def apply(tp: Type): Type = subst1(tp, from, to, this) } - final class Subst2Map(from1: Symbol, to1: Type, from2: Symbol, to2: Type) extends DeepTypeMap { + final class Subst2Map(from1: Symbol, to1: Type, from2: Symbol, to2: Type)(using Context) extends DeepTypeMap { def apply(tp: Type): Type = subst2(tp, from1, to1, from2, to2, this) } - final class SubstMap(from: List[Symbol], to: List[Type]) extends DeepTypeMap { + final class SubstMap(from: List[Symbol], to: List[Type])(using Context) extends DeepTypeMap { def apply(tp: Type): Type = subst(tp, from, to, this) } - final class SubstSymMap(from: List[Symbol], to: List[Symbol]) extends DeepTypeMap { + final class SubstSymMap(from: List[Symbol], to: List[Symbol])(using Context) extends DeepTypeMap { def apply(tp: Type): Type = substSym(tp, from, to, this) } - final class SubstThisMap(from: ClassSymbol, to: Type) extends DeepTypeMap { + final class SubstThisMap(from: ClassSymbol, to: Type)(using Context) extends DeepTypeMap { def apply(tp: Type): Type = substThis(tp, from, to, this) } - final class SubstRecThisMap(from: Type, to: Type) extends DeepTypeMap { + final class SubstRecThisMap(from: Type, to: Type)(using Context) extends DeepTypeMap { def apply(tp: Type): Type = substRecThis(tp, from, to, this) } - final class SubstParamMap(from: ParamRef, to: Type) extends DeepTypeMap { + final class SubstParamMap(from: ParamRef, to: Type)(using Context) extends DeepTypeMap { def apply(tp: Type): Type = substParam(tp, from, to, this) } - final class SubstParamsMap(from: BindingType, to: List[Type]) extends DeepTypeMap { + final class SubstParamsMap(from: BindingType, to: List[Type])(using Context) extends DeepTypeMap { def apply(tp: Type): Type = substParams(tp, from, to, this) } /** An approximating substitution that can handle wildcards in the `to` list */ - final class SubstApproxMap(from: List[Symbol], to: List[Type])(implicit ctx: Context) extends ApproximatingTypeMap { + final class SubstApproxMap(from: List[Symbol], to: List[Type])(using Context) extends ApproximatingTypeMap { def apply(tp: Type): Type = tp match { case tp: NamedType => val sym = tp.symbol @@ -216,4 +216,4 @@ trait Substituters { this: Context => mapOver(tp) } } -} +end Substituters diff --git a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala index b4ff6f9974d8..597a8e76ff03 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala @@ -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(c).appliedTo(args)(using c)) + LazyRef(c => dealiased.ref(using c).appliedTo(args)(using c)) 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/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index 30ca0146f638..d4d961baab27 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -108,9 +108,9 @@ object Types { * uninstantiated type variables or type symbols that have the Provisional flag set. * This is an antimonotonic property - once a type is not provisional, it stays so forever. */ - def isProvisional(implicit ctx: Context): Boolean = mightBeProvisional && testProvisional + def isProvisional(using Context): Boolean = mightBeProvisional && testProvisional - private def testProvisional(implicit ctx: Context) = { + private def testProvisional(using Context) = { val accu = new TypeAccumulator[Boolean] { override def apply(x: Boolean, t: Type) = x || t.mightBeProvisional && { @@ -158,7 +158,7 @@ object Types { * Like in isStableMember, "stability" means idempotence. * Rationale: If an expression has a stable type, the expression must be idempotent, so stable types * must be singleton types of stable expressions. */ - final def isStable(implicit ctx: Context): Boolean = stripTypeVar match { + final def isStable(using Context): Boolean = stripTypeVar match { case tp: TermRef => tp.symbol.isStableMember && tp.prefix.isStable || tp.info.isStable case _: SingletonType | NoPrefix => true case tp: RefinedOrRecType => tp.parent.isStable @@ -176,7 +176,7 @@ object Types { * It makes no sense for it to be an alias type because isRef would always * return false in that case. */ - def isRef(sym: Symbol, skipRefined: Boolean = true)(implicit ctx: Context): Boolean = stripAnnots.stripTypeVar match { + def isRef(sym: Symbol, skipRefined: Boolean = true)(using Context): Boolean = stripAnnots.stripTypeVar match { case this1: TypeRef => this1.info match { // see comment in Namer#typeDefSig case TypeAlias(tp) => tp.isRef(sym, skipRefined) @@ -192,7 +192,7 @@ object Types { } /** Is this type a (neither aliased nor applied) reference to class `sym`? */ - def isDirectRef(sym: Symbol)(implicit ctx: Context): Boolean = stripTypeVar match { + def isDirectRef(sym: Symbol)(using Context): Boolean = stripTypeVar match { case this1: TypeRef => this1.name == sym.name && // avoid forcing info if names differ (this1.symbol eq sym) @@ -207,7 +207,7 @@ object Types { /** Does this type refer exactly to class symbol `sym`, instead of to a subclass of `sym`? * Implemented like `isRef`, but follows more types: all type proxies as well as and- and or-types */ - private[Types] def isTightPrefix(sym: Symbol)(implicit ctx: Context): Boolean = stripTypeVar match { + private[Types] def isTightPrefix(sym: Symbol)(using Context): Boolean = stripTypeVar match { case tp: NamedType => tp.info.isTightPrefix(sym) case tp: ClassInfo => tp.cls eq sym case tp: Types.ThisType => tp.cls eq sym @@ -218,7 +218,7 @@ object Types { } /** Is this type an instance of a non-bottom subclass of the given class `cls`? */ - final def derivesFrom(cls: Symbol)(implicit ctx: Context): Boolean = { + final def derivesFrom(cls: Symbol)(using Context): Boolean = { def loop(tp: Type): Boolean = tp match { case tp: TypeRef => val sym = tp.symbol @@ -245,7 +245,7 @@ object Types { * ` . ` is an actual argument reference, i.e. `this` is different * from the ThisType of `symd`'s owner. */ - def isArgPrefixOf(symd: SymDenotation)(implicit ctx: Context): Boolean = + def isArgPrefixOf(symd: SymDenotation)(using Context): Boolean = symd.exists && !symd.owner.is(Package) && // Early exit if possible because the next check would force SymbolLoaders symd.isAllOf(ClassTypeParam) && { this match { @@ -255,22 +255,22 @@ object Types { } /** Is this type exactly Nothing (no vars, aliases, refinements etc allowed)? */ - def isBottomType(implicit ctx: Context): Boolean = this match { + def isBottomType(using Context): Boolean = this match { case tp: TypeRef => tp.symbol eq defn.NothingClass case _ => false } /** Is this type exactly Any (no vars, aliases, refinements etc allowed)? */ - def isTopType(implicit ctx: Context): Boolean = this match { + def isTopType(using Context): Boolean = this match { case tp: TypeRef => tp.symbol eq defn.AnyClass case _ => false } /** Is this type a (possibly aliased) singleton type? */ - def isSingleton(implicit ctx: Context): Boolean = dealias.isInstanceOf[SingletonType] + def isSingleton(using Context): Boolean = dealias.isInstanceOf[SingletonType] /** Is this type of kind `AnyKind`? */ - def hasAnyKind(implicit ctx: Context): Boolean = { + def hasAnyKind(using Context): Boolean = { @tailrec def loop(tp: Type): Boolean = tp match { case tp: TypeRef => val sym = tp.symbol @@ -284,7 +284,7 @@ object Types { } /** Is this type guaranteed not to have `null` as a value? */ - final def isNotNull(implicit ctx: Context): Boolean = this match { + final def isNotNull(using Context): Boolean = this match { case tp: ConstantType => tp.value.value != null case tp: ClassInfo => !tp.cls.isNullableClass && tp.cls != defn.NothingClass case tp: TypeBounds => tp.lo.isNotNull @@ -295,20 +295,20 @@ object Types { } /** Is this type produced as a repair for an error? */ - final def isError(implicit ctx: Context): Boolean = stripTypeVar.isInstanceOf[ErrorType] + final def isError(using Context): Boolean = stripTypeVar.isInstanceOf[ErrorType] /** Is some part of the widened version of this type produced as a repair for an error? */ - def isErroneous(implicit ctx: Context): Boolean = + def isErroneous(using Context): Boolean = widen.existsPart(_.isError, forceLazy = false) /** Does the type carry an annotation that is an instance of `cls`? */ - @tailrec final def hasAnnotation(cls: ClassSymbol)(implicit ctx: Context): Boolean = stripTypeVar match { + @tailrec final def hasAnnotation(cls: ClassSymbol)(using Context): Boolean = stripTypeVar match { case AnnotatedType(tp, annot) => (annot matches cls) || (tp hasAnnotation cls) case _ => false } /** Does this type have a supertype with an annotation satisfying given predicate `p`? */ - def derivesAnnotWith(p: Annotation => Boolean)(implicit ctx: Context): Boolean = this match { + def derivesAnnotWith(p: Annotation => Boolean)(using Context): Boolean = this match { case tp: AnnotatedType => p(tp.annot) || tp.parent.derivesAnnotWith(p) case tp: TypeProxy => tp.superType.derivesAnnotWith(p) case AndType(l, r) => l.derivesAnnotWith(p) || r.derivesAnnotWith(p) @@ -317,28 +317,28 @@ object Types { } /** Does this type occur as a part of type `that`? */ - def occursIn(that: Type)(implicit ctx: Context): Boolean = + def occursIn(that: Type)(using Context): Boolean = that.existsPart(this == _) /** Does this type not refer to TypeParamRefs or uninstantiated TypeVars? */ - final def isGround(implicit ctx: Context): Boolean = + final def isGround(using Context): Boolean = (new isGroundAccumulator).apply(true, this) /** Is this a type of a repeated parameter? */ - def isRepeatedParam(implicit ctx: Context): Boolean = + def isRepeatedParam(using Context): Boolean = typeSymbol eq defn.RepeatedParamClass /** Is this the type of a method that has a repeated parameter type as * last parameter type? */ - def isVarArgsMethod(implicit ctx: Context): Boolean = stripPoly match { + def isVarArgsMethod(using Context): Boolean = stripPoly match { case mt: MethodType => mt.paramInfos.nonEmpty && mt.paramInfos.last.isRepeatedParam case _ => false } /** Is this the type of a method with a leading empty parameter list? */ - def isNullaryMethod(implicit ctx: Context): Boolean = stripPoly match { + def isNullaryMethod(using Context): Boolean = stripPoly match { case MethodType(Nil) => true case _ => false } @@ -360,7 +360,7 @@ object Types { /** Is this a match type or a higher-kinded abstraction of one? */ - def isMatch(implicit ctx: Context): Boolean = stripTypeVar.stripAnnots match { + def isMatch(using Context): Boolean = stripTypeVar.stripAnnots match { case _: MatchType => true case tp: HKTypeLambda => tp.resType.isMatch case _ => false @@ -373,20 +373,20 @@ object Types { /** Returns true if there is a part of this type that satisfies predicate `p`. */ - final def existsPart(p: Type => Boolean, forceLazy: Boolean = true)(implicit ctx: Context): Boolean = + final def existsPart(p: Type => Boolean, forceLazy: Boolean = true)(using Context): Boolean = new ExistsAccumulator(p, forceLazy).apply(false, this) /** Returns true if all parts of this type satisfy predicate `p`. */ - final def forallParts(p: Type => Boolean)(implicit ctx: Context): Boolean = + final def forallParts(p: Type => Boolean)(using Context): Boolean = !existsPart(!p(_)) /** Performs operation on all parts of this type */ - final def foreachPart(p: Type => Unit, stopAtStatic: Boolean = false)(implicit ctx: Context): Unit = + final def foreachPart(p: Type => Unit, stopAtStatic: Boolean = false)(using Context): Unit = new ForeachAccumulator(p, stopAtStatic).apply((), this) /** The parts of this type which are type or term refs */ - final def namedParts(implicit ctx: Context): collection.Set[NamedType] = + final def namedParts(using Context): collection.Set[NamedType] = namedPartsWith(alwaysTrue) /** The parts of this type which are type or term refs and which @@ -397,17 +397,17 @@ object Types { * types will be ignored. */ def namedPartsWith(p: NamedType => Boolean, excludeLowerBounds: Boolean = false) - (implicit ctx: Context): collection.Set[NamedType] = + (using Context): collection.Set[NamedType] = new NamedPartsAccumulator(p, excludeLowerBounds).apply(mutable.LinkedHashSet(), this) /** Map function `f` over elements of an AndType, rebuilding with function `g` */ - def mapReduceAnd[T](f: Type => T)(g: (T, T) => T)(implicit ctx: Context): T = stripTypeVar match { + def mapReduceAnd[T](f: Type => T)(g: (T, T) => T)(using Context): T = stripTypeVar match { case AndType(tp1, tp2) => g(tp1.mapReduceAnd(f)(g), tp2.mapReduceAnd(f)(g)) case _ => f(this) } /** Map function `f` over elements of an OrType, rebuilding with function `g` */ - final def mapReduceOr[T](f: Type => T)(g: (T, T) => T)(implicit ctx: Context): T = stripTypeVar match { + final def mapReduceOr[T](f: Type => T)(g: (T, T) => T)(using Context): T = stripTypeVar match { case OrType(tp1, tp2) => g(tp1.mapReduceOr(f)(g), tp2.mapReduceOr(f)(g)) case _ => f(this) } @@ -415,7 +415,7 @@ object Types { // ----- Associated symbols ---------------------------------------------- /** The type symbol associated with the type */ - @tailrec final def typeSymbol(implicit ctx: Context): Symbol = this match { + @tailrec final def typeSymbol(using Context): Symbol = this match { case tp: TypeRef => tp.symbol case tp: ClassInfo => tp.cls case tp: SingletonType => NoSymbol @@ -428,7 +428,7 @@ object Types { * instance, or NoSymbol if none exists (either because this type is not a * value type, or because superclasses are ambiguous). */ - final def classSymbol(implicit ctx: Context): Symbol = this match { + final def classSymbol(using Context): Symbol = this match { case ConstantType(constant) => constant.tpe.classSymbol case tp: TypeRef => @@ -456,7 +456,7 @@ object Types { /** The least (wrt <:<) set of symbols satisfying the `include` predicate of which this type is a subtype */ - final def parentSymbols(include: Symbol => Boolean)(implicit ctx: Context): List[Symbol] = this match { + final def parentSymbols(include: Symbol => Boolean)(using Context): List[Symbol] = this match { case tp: ClassInfo => tp.cls :: Nil case tp: TypeRef => @@ -474,11 +474,11 @@ object Types { /** The least (wrt <:<) set of class symbols of which this type is a subtype */ - final def classSymbols(implicit ctx: Context): List[ClassSymbol] = + final def classSymbols(using Context): List[ClassSymbol] = parentSymbols(_.isClass).asInstanceOf /** The term symbol associated with the type */ - @tailrec final def termSymbol(implicit ctx: Context): Symbol = this match { + @tailrec final def termSymbol(using Context): Symbol = this match { case tp: TermRef => tp.symbol case tp: TypeProxy => tp.underlying.termSymbol case _ => NoSymbol @@ -489,13 +489,13 @@ object Types { * Inherited by all type proxies. Overridden for And and Or types. * `Nil` for all other types. */ - def baseClasses(implicit ctx: Context): List[ClassSymbol] = { + def baseClasses(using Context): List[ClassSymbol] = { record("baseClasses") this match { case tp: TypeProxy => tp.underlying.baseClasses case tp: ClassInfo => - tp.cls.baseClasses + tp.cls.classDenot.baseClasses case _ => Nil } } @@ -506,7 +506,7 @@ object Types { * Defined by ClassInfo, inherited by type proxies. * Empty scope for all other types. */ - @tailrec final def decls(implicit ctx: Context): Scope = this match { + @tailrec final def decls(using Context): Scope = this match { case tp: ClassInfo => tp.decls case tp: TypeProxy => @@ -519,20 +519,20 @@ object Types { * The result is either a SymDenotation or a MultiDenotation of SymDenotations. * The info(s) are the original symbol infos, no translation takes place. */ - final def decl(name: Name)(implicit ctx: Context): Denotation = { + final def decl(name: Name)(using Context): Denotation = { record("decl") findDecl(name, EmptyFlags) } /** A denotation containing the non-private declaration(s) in this type with the given name */ - final def nonPrivateDecl(name: Name)(implicit ctx: Context): Denotation = + final def nonPrivateDecl(name: Name)(using Context): Denotation = findDecl(name, Private) /** A denotation containing the declaration(s) in this type with the given * name, as seen from prefix type `pre`. Declarations that have a flag * in `excluded` are omitted. */ - @tailrec final def findDecl(name: Name, excluded: FlagSet)(implicit ctx: Context): Denotation = this match { + @tailrec final def findDecl(name: Name, excluded: FlagSet)(using Context): Denotation = this match { case tp: ClassInfo => tp.decls.denotsNamed(name).filterWithFlags(EmptyFlags, excluded).toDenot(NoPrefix) case tp: TypeProxy => @@ -544,19 +544,19 @@ object Types { } /** The member of this type with the given name */ - final def member(name: Name)(implicit ctx: Context): Denotation = { + final def member(name: Name)(using Context): Denotation = { record("member") memberBasedOnFlags(name, required = EmptyFlags, excluded = EmptyFlags) } /** The non-private member of this type with the given name. */ - final def nonPrivateMember(name: Name)(implicit ctx: Context): Denotation = { + final def nonPrivateMember(name: Name)(using Context): Denotation = { record("nonPrivateMember") memberBasedOnFlags(name, required = EmptyFlags, excluded = Flags.Private) } /** The member with given `name` and required and/or excluded flags */ - final def memberBasedOnFlags(name: Name, required: FlagSet = EmptyFlags, excluded: FlagSet = EmptyFlags)(implicit ctx: Context): Denotation = { + final def memberBasedOnFlags(name: Name, required: FlagSet = EmptyFlags, excluded: FlagSet = EmptyFlags)(using Context): Denotation = { // We need a valid prefix for `asSeenFrom` val pre = this match { case tp: ClassInfo => tp.appliedRef @@ -569,7 +569,7 @@ object Types { * flags and no `excluded` flag and produce a denotation that contains * the type of the member as seen from given prefix `pre`. */ - final def findMember(name: Name, pre: Type, required: FlagSet = EmptyFlags, excluded: FlagSet = EmptyFlags)(implicit ctx: Context): Denotation = { + final def findMember(name: Name, pre: Type, required: FlagSet = EmptyFlags, excluded: FlagSet = EmptyFlags)(using Context): Denotation = { @tailrec def go(tp: Type): Denotation = tp match { case tp: TermRef => go (tp.underlying match { @@ -752,7 +752,7 @@ object Types { case ex: Throwable => core.println(s"findMember exception for $this member $name, pre = $pre, recCount = $recCount") - def showPrefixSafely(pre: Type)(implicit ctx: Context): String = pre.stripTypeVar match { + def showPrefixSafely(pre: Type)(using Context): String = pre.stripTypeVar match { case pre: TermRef => i"${pre.termSymbol.name}." case pre: TypeRef => i"${pre.typeSymbol.name}#" case pre: TypeProxy => showPrefixSafely(pre.underlying) @@ -774,9 +774,9 @@ object Types { * @note: OK to use a Set[Name] here because Name hashcodes are replayable, * hence the Set will always give the same names in the same order. */ - final def memberNames(keepOnly: NameFilter, pre: Type = this)(implicit ctx: Context): Set[Name] = this match { + final def memberNames(keepOnly: NameFilter, pre: Type = this)(using Context): Set[Name] = this match { case tp: ClassInfo => - tp.cls.memberNames(keepOnly) filter (keepOnly(pre, _)) + tp.cls.classDenot.memberNames(keepOnly) filter (keepOnly(pre, _)) case tp: RefinedType => val ns = tp.parent.memberNames(keepOnly, pre) if (keepOnly(pre, tp.refinedName)) ns + tp.refinedName else ns @@ -790,14 +790,14 @@ object Types { Set() } - def memberDenots(keepOnly: NameFilter, f: (Name, mutable.Buffer[SingleDenotation]) => Unit)(implicit ctx: Context): Seq[SingleDenotation] = { + def memberDenots(keepOnly: NameFilter, f: (Name, mutable.Buffer[SingleDenotation]) => Unit)(using Context): Seq[SingleDenotation] = { val buf = mutable.ListBuffer[SingleDenotation]() for (name <- memberNames(keepOnly)) f(name, buf) buf.toList } /** The set of abstract term members of this type. */ - final def abstractTermMembers(implicit ctx: Context): Seq[SingleDenotation] = { + final def abstractTermMembers(using Context): Seq[SingleDenotation] = { record("abstractTermMembers") memberDenots(abstractTermNameFilter, (name, buf) => buf ++= nonPrivateMember(name).altsWith(_.is(Deferred))) @@ -817,35 +817,35 @@ object Types { * @return the set of methods that are abstract and do not match any of [[java.lang.Object]] * */ - final def possibleSamMethods(implicit ctx: Context): Seq[SingleDenotation] = { + final def possibleSamMethods(using Context): Seq[SingleDenotation] = { record("possibleSamMethods") abstractTermMembers .filterNot(m => m.symbol.matchingMember(defn.ObjectType).exists || m.symbol.isSuperAccessor) } /** The set of abstract type members of this type. */ - final def abstractTypeMembers(implicit ctx: Context): Seq[SingleDenotation] = { + final def abstractTypeMembers(using Context): Seq[SingleDenotation] = { record("abstractTypeMembers") memberDenots(abstractTypeNameFilter, (name, buf) => buf += nonPrivateMember(name).asSingleDenotation) } /** The set of abstract type members of this type. */ - final def nonClassTypeMembers(implicit ctx: Context): Seq[SingleDenotation] = { + final def nonClassTypeMembers(using Context): Seq[SingleDenotation] = { record("nonClassTypeMembers") memberDenots(nonClassTypeNameFilter, (name, buf) => buf += member(name).asSingleDenotation) } /** The set of type alias members of this type */ - final def typeAliasMembers(implicit ctx: Context): Seq[SingleDenotation] = { + final def typeAliasMembers(using Context): Seq[SingleDenotation] = { record("typeAliasMembers") memberDenots(typeAliasNameFilter, (name, buf) => buf += member(name).asSingleDenotation) } /** The set of type members of this type */ - final def typeMembers(implicit ctx: Context): Seq[SingleDenotation] = { + final def typeMembers(using Context): Seq[SingleDenotation] = { record("typeMembers") memberDenots(typeNameFilter, (name, buf) => buf += member(name).asSingleDenotation) @@ -855,7 +855,7 @@ object Types { * @param kind A subset of {Implicit, Given} that specifies what kind of implicit should * be returned */ - final def implicitMembers(implicit ctx: Context): List[TermRef] = { + final def implicitMembers(using Context): List[TermRef] = { record("implicitMembers") memberDenots(implicitFilter, (name, buf) => buf ++= member(name).altsWith(_.isOneOf(GivenOrImplicitVal))) @@ -863,39 +863,39 @@ object Types { } /** The set of member classes of this type */ - final def memberClasses(implicit ctx: Context): Seq[SingleDenotation] = { + final def memberClasses(using Context): Seq[SingleDenotation] = { record("memberClasses") memberDenots(typeNameFilter, (name, buf) => buf ++= member(name).altsWith(x => x.isClass)) } - final def fields(implicit ctx: Context): Seq[SingleDenotation] = { + final def fields(using Context): Seq[SingleDenotation] = { record("fields") memberDenots(fieldFilter, (name, buf) => buf ++= member(name).altsWith(x => !x.is(Method))) } /** The set of members of this type that have all of `required` flags but none of `excluded` flags set. */ - final def membersBasedOnFlags(required: FlagSet, excluded: FlagSet)(implicit ctx: Context): Seq[SingleDenotation] = { + final def membersBasedOnFlags(required: FlagSet, excluded: FlagSet)(using Context): Seq[SingleDenotation] = { record("membersBasedOnFlags") memberDenots(takeAllFilter, (name, buf) => buf ++= memberBasedOnFlags(name, required, excluded).alternatives) } /** All members of this type. Warning: this can be expensive to compute! */ - final def allMembers(implicit ctx: Context): Seq[SingleDenotation] = { + final def allMembers(using Context): Seq[SingleDenotation] = { record("allMembers") memberDenots(takeAllFilter, (name, buf) => buf ++= member(name).alternatives) } /** The info of `sym`, seen as a member of this type. */ - final def memberInfo(sym: Symbol)(implicit ctx: Context): Type = + final def memberInfo(sym: Symbol)(using Context): Type = sym.info.asSeenFrom(this, sym.owner) /** This type seen as if it were the type of a member of prefix type `pre` * declared in class `cls`. */ - final def asSeenFrom(pre: Type, cls: Symbol)(implicit ctx: Context): Type = { + final def asSeenFrom(pre: Type, cls: Symbol)(using Context): Type = { record("asSeenFrom") if (!cls.membersNeedAsSeenFrom(pre)) this else TypeOps.asSeenFrom(this, pre, cls) @@ -904,13 +904,13 @@ object Types { // ----- Subtype-related -------------------------------------------- /** Is this type a subtype of that type? */ - final def <:<(that: Type)(implicit ctx: Context): Boolean = { + final def <:<(that: Type)(using Context): Boolean = { record("<:<") ctx.typeComparer.topLevelSubType(this, that) } /** Is this type a subtype of that type? */ - final def frozen_<:<(that: Type)(implicit ctx: Context): Boolean = { + final def frozen_<:<(that: Type)(using Context): Boolean = { record("frozen_<:<") ctx.typeComparer.isSubTypeWhenFrozen(this, that) } @@ -918,16 +918,16 @@ object Types { /** Is this type the same as that type? * This is the case iff `this <:< that` and `that <:< this`. */ - final def =:=(that: Type)(implicit ctx: Context): Boolean = { + final def =:=(that: Type)(using Context): Boolean = { record("=:=") ctx.typeComparer.isSameType(this, that) } - final def frozen_=:=(that: Type)(implicit ctx: Context): Boolean = + final def frozen_=:=(that: Type)(using Context): Boolean = ctx.typeComparer.isSameTypeWhenFrozen(this, that) /** Is this type a primitive value type which can be widened to the primitive value type `that`? */ - def isValueSubType(that: Type)(implicit ctx: Context): Boolean = widen match { + def isValueSubType(that: Type)(using Context): Boolean = widen match { case self: TypeRef if self.symbol.isPrimitiveValueClass => that.widenExpr match { case that: TypeRef if that.symbol.isPrimitiveValueClass => @@ -939,7 +939,7 @@ object Types { false } - def relaxed_<:<(that: Type)(implicit ctx: Context): Boolean = + def relaxed_<:<(that: Type)(using Context): Boolean = (this <:< that) || (this isValueSubType that) /** Is this type a legal type for member `sym1` that overrides another @@ -947,7 +947,7 @@ object Types { * @param matchLoosely if true the types `=> T` and `()T` are seen as overriding each other. * @param checkClassInfo if true we check that ClassInfos are within bounds of abstract types */ - final def overrides(that: Type, matchLoosely: => Boolean, checkClassInfo: Boolean = true)(implicit ctx: Context): Boolean = { + final def overrides(that: Type, matchLoosely: => Boolean, checkClassInfo: Boolean = true)(using Context): Boolean = { def widenNullary(tp: Type) = tp match { case tp @ MethodType(Nil) => tp.resultType case _ => tp @@ -977,7 +977,7 @@ object Types { * (*) when matching with a Java method, we also regard Any and Object as equivalent * parameter types. */ - def matches(that: Type)(implicit ctx: Context): Boolean = { + def matches(that: Type)(using Context): Boolean = { record("matches") ctx.typeComparer.matchesType(this, that, relaxed = !ctx.phase.erasedTypes) } @@ -985,7 +985,7 @@ object Types { /** This is the same as `matches` except that it also matches => T with T and * vice versa. */ - def matchesLoosely(that: Type)(implicit ctx: Context): Boolean = + def matchesLoosely(that: Type)(using Context): Boolean = (this matches that) || { val thisResult = this.widenExpr val thatResult = that.widenExpr @@ -993,7 +993,7 @@ object Types { } /** The basetype of this type with given class symbol, NoType if `base` is not a class. */ - final def baseType(base: Symbol)(implicit ctx: Context): Type = { + final def baseType(base: Symbol)(using Context): Type = { record("baseType") base.denot match { case classd: ClassDenotation => classd.baseTypeOf(this) @@ -1001,7 +1001,7 @@ object Types { } } - def & (that: Type)(implicit ctx: Context): Type = { + def & (that: Type)(using Context): Type = { record("&") ctx.typeComparer.glb(this, that) } @@ -1015,7 +1015,7 @@ object Types { * (which will be masked unless `-Yno-deep-subtypes` is enabled). * pos/i536 demonstrates that the infinite loop can also involve lower bounds. */ - def safe_& (that: Type)(implicit ctx: Context): Type = (this, that) match { + def safe_& (that: Type)(using Context): Type = (this, that) match { case (TypeBounds(lo1, hi1), TypeBounds(lo2, hi2)) => TypeBounds(OrType(lo1.stripLazyRef, lo2.stripLazyRef), AndType(hi1.stripLazyRef, hi2.stripLazyRef)) case _ => this & that @@ -1023,7 +1023,7 @@ object Types { /** `this & that`, but handle CyclicReferences by falling back to `safe_&`. */ - def recoverable_&(that: Type)(implicit ctx: Context): Type = + def recoverable_&(that: Type)(using Context): Type = try this & that catch { case ex: CyclicReference => this safe_& that @@ -1032,7 +1032,7 @@ object Types { // superclass. } - def | (that: Type)(implicit ctx: Context): Type = { + def | (that: Type)(using Context): Type = { record("|") ctx.typeComparer.lub(this, that) } @@ -1042,19 +1042,19 @@ object Types { /** Map a TypeVar to either its instance if it is instantiated, or its origin, * if not, until the result is no longer a TypeVar. Identity on all other types. */ - def stripTypeVar(implicit ctx: Context): Type = this + def stripTypeVar(using Context): Type = this /** Remove all AnnotatedTypes wrapping this type. */ - def stripAnnots(implicit ctx: Context): Type = this + def stripAnnots(using Context): Type = this - def rewrapAnnots(tp: Type)(implicit ctx: Context): Type = tp.stripTypeVar match { + def rewrapAnnots(tp: Type)(using Context): Type = tp.stripTypeVar match { case AnnotatedType(tp1, annot) => AnnotatedType(rewrapAnnots(tp1), annot) case _ => this } /** Strip PolyType prefixes */ - def stripPoly(implicit ctx: Context): Type = this match { + def stripPoly(using Context): Type = this match { case tp: PolyType => tp.resType.stripPoly case _ => this } @@ -1073,7 +1073,7 @@ object Types { * def o: Outer * .widen = o.C */ - final def widen(implicit ctx: Context): Type = widenSingleton match { + final def widen(using Context): Type = widenSingleton match { case tp: ExprType => tp.resultType.widen case tp => tp } @@ -1081,7 +1081,7 @@ object Types { /** Widen from singleton type to its underlying non-singleton * base type by applying one or more `underlying` dereferences. */ - final def widenSingleton(implicit ctx: Context): Type = stripTypeVar.stripAnnots match { + final def widenSingleton(using Context): Type = stripTypeVar.stripAnnots match { case tp: SingletonType if !tp.isOverloaded => tp.underlying.widenSingleton case _ => this } @@ -1089,7 +1089,7 @@ object Types { /** Widen from TermRef to its underlying non-termref * base type, while also skipping Expr types. */ - final def widenTermRefExpr(implicit ctx: Context): Type = stripTypeVar match { + final def widenTermRefExpr(using Context): Type = stripTypeVar match { case tp: TermRef if !tp.isOverloaded => tp.underlying.widenExpr.widenTermRefExpr case _ => this } @@ -1103,14 +1103,14 @@ object Types { } /** Widen type if it is unstable (i.e. an ExprType, or TermRef to unstable symbol */ - final def widenIfUnstable(implicit ctx: Context): Type = stripTypeVar match { + final def widenIfUnstable(using Context): Type = stripTypeVar match { case tp: ExprType => tp.resultType.widenIfUnstable case tp: TermRef if tp.symbol.exists && !tp.symbol.isStableMember => tp.underlying.widenIfUnstable case _ => this } /** If this is a skolem, its underlying type, otherwise the type itself */ - final def widenSkolem(implicit ctx: Context): Type = this match { + final def widenSkolem(using Context): Type = this match { case tp: SkolemType => tp.underlying case _ => this } @@ -1132,7 +1132,7 @@ object Types { * Exception (if `-YexplicitNulls` is set): if this type is a nullable union (i.e. of the form `T | Null`), * then the top-level union isn't widened. This is needed so that type inference can infer nullable types. */ - def widenUnion(implicit ctx: Context): Type = widen match { + def widenUnion(using Context): Type = widen match { case tp @ OrNull(tp1): OrType => // Don't widen `T|Null`, since otherwise we wouldn't be able to infer nullable unions. val tp1Widen = tp1.widenUnionWithoutNull @@ -1142,7 +1142,7 @@ object Types { tp.widenUnionWithoutNull } - def widenUnionWithoutNull(implicit ctx: Context): Type = widen match { + def widenUnionWithoutNull(using Context): Type = widen match { case tp @ OrType(lhs, rhs) => ctx.typeComparer.lub(lhs.widenUnionWithoutNull, rhs.widenUnionWithoutNull, canConstrain = true) match { case union: OrType => union.join @@ -1162,7 +1162,7 @@ object Types { * and going to the operands of & and |. * Overridden and cached in OrType. */ - def widenSingletons(implicit ctx: Context): Type = dealias match { + def widenSingletons(using Context): Type = dealias match { case tp: SingletonType => tp.widen case tp: OrType => @@ -1208,7 +1208,7 @@ object Types { case Atoms.Unknown => Atoms.Unknown case _ => Atoms.Unknown - private def dealias1(keep: AnnotatedType => Context => Boolean)(implicit ctx: 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 { @@ -1234,21 +1234,21 @@ object Types { * TypeVars until type is no longer alias type, annotated type, LazyRef, * or instantiated type variable. */ - final def dealias(implicit ctx: Context): Type = dealias1(keepNever) + final def dealias(using Context): Type = dealias1(keepNever) /** Follow aliases and dereferences LazyRefs and instantiated TypeVars until type * is no longer alias type, LazyRef, or instantiated type variable. * Goes through annotated types and rewraps annotations on the result. */ - final def dealiasKeepAnnots(implicit ctx: Context): Type = dealias1(keepAlways) + final def dealiasKeepAnnots(using Context): Type = dealias1(keepAlways) /** Like `dealiasKeepAnnots`, but keeps only refining annotations */ - final def dealiasKeepRefiningAnnots(implicit ctx: Context): Type = dealias1(keepIfRefining) + final def dealiasKeepRefiningAnnots(using Context): Type = dealias1(keepIfRefining) /** The result of normalization using `tryNormalize`, or the type itself if * tryNormlize yields NoType */ - final def normalized(implicit ctx: Context): Type = { + final def normalized(using Context): Type = { val normed = tryNormalize if (normed.exists) normed else this } @@ -1257,38 +1257,38 @@ object Types { * of S[n] types, the result after applying all toplevel normalizations, * otherwise NoType */ - def tryNormalize(implicit ctx: Context): Type = NoType + def tryNormalize(using Context): Type = NoType - private def widenDealias1(keep: AnnotatedType => Context => Boolean)(implicit ctx: 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) } /** Perform successive widenings and dealiasings until none can be applied anymore */ - final def widenDealias(implicit ctx: Context): Type = widenDealias1(keepNever) + final def widenDealias(using Context): Type = widenDealias1(keepNever) /** Perform successive widenings and dealiasings while rewrapping annotations, until none can be applied anymore */ - final def widenDealiasKeepAnnots(implicit ctx: Context): Type = widenDealias1(keepAlways) + final def widenDealiasKeepAnnots(using Context): Type = widenDealias1(keepAlways) /** Perform successive widenings and dealiasings while rewrapping refining annotations, until none can be applied anymore */ - final def widenDealiasKeepRefiningAnnots(implicit ctx: Context): Type = widenDealias1(keepIfRefining) + final def widenDealiasKeepRefiningAnnots(using Context): Type = widenDealias1(keepIfRefining) /** Widen from constant type to its underlying non-constant * base type. */ - final def deconst(implicit ctx: Context): Type = stripTypeVar match { + final def deconst(using Context): Type = stripTypeVar match { case tp: ConstantType => tp.value.tpe case _ => this } /** Dealias, and if result is a dependent function type, drop the `apply` refinement. */ - final def dropDependentRefinement(implicit ctx: Context): Type = dealias match { + final def dropDependentRefinement(using Context): Type = dealias match { case RefinedType(parent, nme.apply, _) => parent case tp => tp } /** The type constructor of an applied type, otherwise the type itself */ - final def typeConstructor(implicit ctx: Context): Type = this match { + final def typeConstructor(using Context): Type = this match { case AppliedType(tycon, _) => tycon case _ => this } @@ -1297,7 +1297,7 @@ object Types { * a class, the class type ref, otherwise NoType. * @param refinementOK If `true` we also skip refinements. */ - def underlyingClassRef(refinementOK: Boolean)(implicit ctx: Context): Type = dealias match { + def underlyingClassRef(refinementOK: Boolean)(using Context): Type = dealias match { case tp: TypeRef => if (tp.symbol.isClass) tp else if (tp.symbol.isAliasType) tp.underlying.underlyingClassRef(refinementOK) @@ -1318,7 +1318,7 @@ object Types { /** The iterator of underlying types as long as type is a TypeProxy. * Useful for diagnostics */ - def underlyingIterator(implicit ctx: Context): Iterator[Type] = new Iterator[Type] { + def underlyingIterator(using Context): Iterator[Type] = new Iterator[Type] { var current = Type.this var hasNext = true def next = { @@ -1332,19 +1332,19 @@ object Types { /** A prefix-less refined this or a termRef to a new skolem symbol * that has the given type as info. */ - def narrow(implicit ctx: Context): TermRef = + def narrow(using Context): TermRef = TermRef(NoPrefix, ctx.newSkolem(this)) /** Useful for diagnostics: The underlying type if this type is a type proxy, * otherwise NoType */ - def underlyingIfProxy(implicit ctx: Context): Type = this match { + def underlyingIfProxy(using Context): Type = this match { case this1: TypeProxy => this1.underlying case _ => NoType } /** If this is a repeated type, its element type, otherwise the type itself */ - def repeatedToSingle(implicit ctx: Context): Type = this match { + def repeatedToSingle(using Context): Type = this match { case tp @ ExprType(tp1) => tp.derivedExprType(tp1.repeatedToSingle) case _ => if (isRepeatedParam) this.argTypesHi.head else this } @@ -1366,7 +1366,7 @@ object Types { * * (*) normalizes means: follow instantiated typevars and aliases. */ - def lookupRefined(name: Name)(implicit ctx: Context): Type = { + def lookupRefined(name: Name)(using Context): Type = { @tailrec def loop(pre: Type): Type = pre.stripTypeVar match { case pre: RefinedType => pre.refinedInfo match { @@ -1397,21 +1397,21 @@ object Types { } /** The type , reduced if possible */ - def select(name: Name)(implicit ctx: Context): Type = + def select(name: Name)(using Context): Type = NamedType(this, name, member(name)).reduceProjection /** The type with given denotation, reduced if possible. */ - def select(name: Name, denot: Denotation)(implicit ctx: Context): Type = + def select(name: Name, denot: Denotation)(using Context): Type = NamedType(this, name, denot).reduceProjection /** The type , reduced if possible */ - def select(sym: Symbol)(implicit ctx: Context): Type = + def select(sym: Symbol)(using Context): Type = NamedType(this, sym).reduceProjection - def select(name: TermName)(implicit ctx: Context): TermRef = + def select(name: TermName)(using Context): TermRef = TermRef(this, name, member(name)) - def select(name: TermName, sig: Signature)(implicit ctx: Context): TermRef = + def select(name: TermName, sig: Signature)(using Context): TermRef = TermRef(this, name, member(name).atSignature(sig, relaxed = !ctx.erasedTypes)) // ----- Access to parts -------------------------------------------- @@ -1422,7 +1422,7 @@ object Types { * Inherited by all other type proxies. * `NoType` for all other types. */ - @tailrec final def normalizedPrefix(implicit ctx: Context): Type = this match { + @tailrec final def normalizedPrefix(using Context): Type = this match { case tp: NamedType => if (tp.symbol.info.isTypeAlias) tp.info.normalizedPrefix else tp.prefix case tp: ClassInfo => @@ -1434,7 +1434,7 @@ object Types { } /** The full parent types, including all type arguments */ - def parents(implicit ctx: Context): List[Type] = this match { + def parents(using Context): List[Type] = this match { case tp @ AppliedType(tycon, args) if tycon.typeSymbol.isClass => tycon.parents.map(_.subst(tycon.typeSymbol.typeParams, args)) case tp: TypeRef => @@ -1449,32 +1449,32 @@ object Types { } /** The first parent of this type, AnyRef if list of parents is empty */ - def firstParent(implicit ctx: Context): Type = parents match { + def firstParent(using Context): Type = parents match { case p :: _ => p case _ => defn.AnyType } /** The parameter types of a PolyType or MethodType, Empty list for others */ - final def paramInfoss(implicit ctx: Context): List[List[Type]] = stripPoly match { + final def paramInfoss(using Context): List[List[Type]] = stripPoly match { case mt: MethodType => mt.paramInfos :: mt.resultType.paramInfoss case _ => Nil } /** The parameter names of a PolyType or MethodType, Empty list for others */ - final def paramNamess(implicit ctx: Context): List[List[TermName]] = stripPoly match { + final def paramNamess(using Context): List[List[TermName]] = stripPoly match { case mt: MethodType => mt.paramNames :: mt.resultType.paramNamess case _ => Nil } /** The parameter types in the first parameter section of a generic type or MethodType, Empty list for others */ - final def firstParamTypes(implicit ctx: Context): List[Type] = stripPoly match { + final def firstParamTypes(using Context): List[Type] = stripPoly match { case mt: MethodType => mt.paramInfos case _ => Nil } /** Is this either not a method at all, or a parameterless method? */ - final def isParameterless(implicit ctx: Context): Boolean = stripPoly match { + final def isParameterless(using Context): Boolean = stripPoly match { case mt: MethodType => false case _ => true } @@ -1483,18 +1483,18 @@ object Types { final def isNullType(using Context) = isRef(defn.NullClass) /** The resultType of a LambdaType, or ExprType, the type itself for others */ - def resultType(implicit ctx: Context): Type = this + def resultType(using Context): Type = this /** The final result type of a PolyType, MethodType, or ExprType, after skipping * all parameter sections, the type itself for all others. */ - def finalResultType(implicit ctx: Context): Type = resultType.stripPoly match { + def finalResultType(using Context): Type = resultType.stripPoly match { case mt: MethodType => mt.resultType.finalResultType case _ => resultType } /** This type seen as a TypeBounds */ - final def bounds(implicit ctx: Context): TypeBounds = this match { + final def bounds(using Context): TypeBounds = this match { case tp: TypeBounds => tp case ci: ClassInfo => TypeAlias(ci.appliedRef) case wc: WildcardType => @@ -1521,13 +1521,13 @@ object Types { * in order not to provoke a cycle by forcing the info. If that yields * no symbol it tries `member` as an alternative. */ - def typeParamNamed(name: TypeName)(implicit ctx: Context): Symbol = + def typeParamNamed(name: TypeName)(using Context): Symbol = classSymbol.unforcedDecls.lookup(name) orElse member(name).symbol /** If this is a prototype with some ignored component, reveal one more * layer of it. Otherwise the type itself. */ - def deepenProto(implicit ctx: Context): Type = this + def deepenProto(using Context): Type = this /** If this is an ignored proto type, its underlying type, otherwise the type itself */ def revealIgnored: Type = this @@ -1540,55 +1540,55 @@ object Types { /** Substitute all types that refer in their symbol attribute to * one of the symbols in `from` by the corresponding types in `to`. */ - final def subst(from: List[Symbol], to: List[Type])(implicit ctx: Context): Type = + final def subst(from: List[Symbol], to: List[Type])(using Context): Type = if (from.isEmpty) this else { val from1 = from.tail - if (from1.isEmpty) ctx.subst1(this, from.head, to.head, null) + if (from1.isEmpty) Substituters.subst1(this, from.head, to.head, null) else { val from2 = from1.tail - if (from2.isEmpty) ctx.subst2(this, from.head, to.head, from1.head, to.tail.head, null) - else ctx.subst(this, from, to, null) + if (from2.isEmpty) Substituters.subst2(this, from.head, to.head, from1.head, to.tail.head, null) + else Substituters.subst(this, from, to, null) } } /** Substitute all types of the form `TypeParamRef(from, N)` by * `TypeParamRef(to, N)`. */ - final def subst(from: BindingType, to: BindingType)(implicit ctx: Context): Type = - ctx.subst(this, from, to, null) + final def subst(from: BindingType, to: BindingType)(using Context): Type = + Substituters.subst(this, from, to, null) /** Substitute all occurrences of `This(cls)` by `tp` */ - final def substThis(cls: ClassSymbol, tp: Type)(implicit ctx: Context): Type = - ctx.substThis(this, cls, tp, null) + final def substThis(cls: ClassSymbol, tp: Type)(using Context): Type = + Substituters.substThis(this, cls, tp, null) /** As substThis, but only is class is a static owner (i.e. a globally accessible object) */ - final def substThisUnlessStatic(cls: ClassSymbol, tp: Type)(implicit ctx: Context): Type = - if (cls.isStaticOwner) this else ctx.substThis(this, cls, tp, null) + final def substThisUnlessStatic(cls: ClassSymbol, tp: Type)(using Context): Type = + if (cls.isStaticOwner) this else Substituters.substThis(this, cls, tp, null) /** Substitute all occurrences of `RecThis(binder)` by `tp` */ - final def substRecThis(binder: RecType, tp: Type)(implicit ctx: Context): Type = - ctx.substRecThis(this, binder, tp, null) + final def substRecThis(binder: RecType, tp: Type)(using Context): Type = + Substituters.substRecThis(this, binder, tp, null) /** Substitute a bound type by some other type */ - final def substParam(from: ParamRef, to: Type)(implicit ctx: Context): Type = - ctx.substParam(this, from, to, null) + final def substParam(from: ParamRef, to: Type)(using Context): Type = + Substituters.substParam(this, from, to, null) /** Substitute bound types by some other types */ - final def substParams(from: BindingType, to: List[Type])(implicit ctx: Context): Type = - ctx.substParams(this, from, to, null) + final def substParams(from: BindingType, to: List[Type])(using Context): Type = + Substituters.substParams(this, from, to, null) /** Substitute all occurrences of symbols in `from` by references to corresponding symbols in `to` */ - final def substSym(from: List[Symbol], to: List[Symbol])(implicit ctx: Context): Type = - ctx.substSym(this, from, to, null) + final def substSym(from: List[Symbol], to: List[Symbol])(using Context): Type = + Substituters.substSym(this, from, to, null) /** Substitute all occurrences of symbols in `from` by corresponding types in `to`. * Unlike for `subst`, the `to` types can be type bounds. A TypeBounds target * will be replaced by range that gets absorbed in an approximating type map. */ - final def substApprox(from: List[Symbol], to: List[Type])(implicit ctx: Context): Type = - new ctx.SubstApproxMap(from, to).apply(this) + final def substApprox(from: List[Symbol], to: List[Type])(using Context): Type = + new Substituters.SubstApproxMap(from, to).apply(this) // ----- misc ----------------------------------------------------------- @@ -1597,7 +1597,7 @@ object Types { * @param dropLast The number of trailing parameters that should be dropped * when forming the function type. */ - def toFunctionType(dropLast: Int = 0)(implicit ctx: Context): Type = this match { + 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 @@ -1619,10 +1619,10 @@ object Types { * pattern is that method signatures use caching, so encapsulation * is improved using an OO scheme). */ - def signature(implicit ctx: Context): Signature = Signature.NotAMethod + def signature(using Context): Signature = Signature.NotAMethod /** Drop annotation of given `cls` from this type */ - def dropAnnot(cls: Symbol)(implicit ctx: Context): Type = stripTypeVar match { + def dropAnnot(cls: Symbol)(using Context): Type = stripTypeVar match { case self @ AnnotatedType(pre, annot) => if (annot.symbol eq cls) pre else self.derivedAnnotatedType(pre.dropAnnot(cls), annot) @@ -1630,9 +1630,9 @@ object Types { this } - def dropRepeatedAnnot(implicit ctx: Context): Type = dropAnnot(defn.RepeatedAnnot) + def dropRepeatedAnnot(using Context): Type = dropAnnot(defn.RepeatedAnnot) - def annotatedToRepeated(implicit ctx: Context): Type = this match { + def annotatedToRepeated(using Context): Type = this match { case tp @ ExprType(tp1) => tp.derivedExprType(tp1.annotatedToRepeated) case AnnotatedType(tp, annot) if annot matches defn.RepeatedAnnot => val typeSym = tp.typeSymbol.asClass @@ -1642,11 +1642,11 @@ object Types { } /** The set of distinct symbols referred to by this type, after all aliases are expanded */ - def coveringSet(implicit ctx: Context): Set[Symbol] = + def coveringSet(using Context): Set[Symbol] = (new CoveringSetAccumulator).apply(Set.empty[Symbol], this) /** The number of applications and refinements in this type, after all aliases are expanded */ - def typeSize(implicit ctx: Context): Int = + def typeSize(using Context): Int = (new TypeSizeAccumulator).apply(0, this) /** Convert to text */ @@ -1655,7 +1655,7 @@ object Types { /** Utility method to show the underlying type of a TypeProxy chain together * with the proxy type itself. */ - def showWithUnderlying(n: Int = 1)(implicit ctx: Context): String = this match { + def showWithUnderlying(n: Int = 1)(using Context): String = this match { case tp: TypeProxy if n > 0 => s"$show with underlying ${tp.underlying.showWithUnderlying(n - 1)}" case _ => show } @@ -1675,7 +1675,7 @@ object Types { * lead to a different `signature`. Since this isn't very useful anyway, * this method handles this by never simplifying inside a `MethodicType`. */ - def simplified(implicit ctx: Context): Type = TypeOps.simplify(this, null) + def simplified(using Context): Type = TypeOps.simplify(this, null) /** Compare `this == that`, assuming corresponding binders in `bs` are equal. * The normal `equals` should be equivalent to `equals(that, null`)`. @@ -1721,20 +1721,20 @@ object Types { abstract class TypeProxy extends Type { /** The type to which this proxy forwards operations. */ - def underlying(implicit ctx: Context): Type + def underlying(using Context): Type /** The closest supertype of this type. This is the same as `underlying`, * except that * - instead of a TyperBounds type it returns its upper bound, and * - for applied types it returns the upper bound of the constructor re-applied to the arguments. */ - def superType(implicit ctx: Context): Type = underlying match { + def superType(using Context): Type = underlying match { case TypeBounds(_, hi) => hi case st => st } /** Same as superType, except that opaque types are treated as transparent aliases */ - def translucentSuperType(implicit ctx: Context): Type = superType + def translucentSuperType(using Context): Type = superType } // Every type has to inherit one of the following four abstract type classes., @@ -1808,7 +1808,7 @@ object Types { * single non-null value (they might contain null in addition). */ trait SingletonType extends TypeProxy with ValueType { - def isOverloaded(implicit ctx: Context): Boolean = false + def isOverloaded(using Context): Boolean = false } /** A trait for types that bind other types that refer to them. @@ -1835,9 +1835,9 @@ object Types { /** A trait for proto-types, used as expected types in typer */ trait ProtoType extends Type { - def isMatchedBy(tp: Type, keepConstraint: Boolean = false)(implicit ctx: Context): Boolean - def fold[T](x: T, ta: TypeAccumulator[T])(implicit ctx: Context): T - def map(tm: TypeMap)(implicit ctx: Context): ProtoType + def isMatchedBy(tp: Type, keepConstraint: Boolean = false)(using Context): Boolean + def fold[T](x: T, ta: TypeAccumulator[T])(using Context): T + def map(tm: TypeMap)(using Context): ProtoType /** If this prototype captures a context, the same prototype except that the result * captures the given context `ctx`. @@ -1850,7 +1850,7 @@ object Types { /** Implementations of this trait cache the results of `narrow`. */ trait NarrowCached extends Type { private var myNarrow: TermRef = null - override def narrow(implicit ctx: Context): TermRef = { + override def narrow(using Context): TermRef = { if (myNarrow eq null) myNarrow = super.narrow myNarrow } @@ -1886,7 +1886,7 @@ object Types { /** If designator is a name, this name. Otherwise, the original name * of the designator symbol. */ - final def name(implicit ctx: Context): ThisName = { + final def name(using Context): ThisName = { if (myName == null) myName = computeName myName.asInstanceOf[ThisName] } @@ -1900,7 +1900,7 @@ object Types { * or if there is none, the signature of the symbol. Signatures are always * computed before erasure, since some symbols change their signature at erasure. */ - protected[dotc] def computeSignature(implicit ctx: Context): Signature = + protected[dotc] def computeSignature(using Context): Signature = val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) else if ctx.erasedTypes then computeSignature(using ctx.withPhase(ctx.erasurePhase)) @@ -1912,7 +1912,7 @@ object Types { * Otherwise NotAMethod. Signatures are always computed before erasure, since * some symbols change their signature at erasure. */ - private def currentSignature(implicit ctx: Context): Signature = + private def currentSignature(using Context): Signature = if ctx.runId == mySignatureRunId then mySignature else val lastd = lastDenotation @@ -1930,12 +1930,12 @@ object Types { case lastd: SingleDenotation => lastd.initial.signature case _ => Signature.OverloadedSignature - final def symbol(implicit ctx: Context): Symbol = + 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 - private def computeSymbol(implicit ctx: Context): Symbol = + private def computeSymbol(using Context): Symbol = designator match { case sym: Symbol => if (sym.isValidInCurrentRun) sym else denot.symbol @@ -1946,7 +1946,7 @@ object Types { /** There is a denotation computed which is valid (somewhere in) the * current run. */ - def denotationIsCurrent(implicit ctx: Context): Boolean = + def denotationIsCurrent(using Context): Boolean = lastDenotation != null && lastDenotation.validFor.runId == ctx.runId /** If the reference is symbolic or the denotation is current, its symbol, otherwise NoDenotation. @@ -1958,7 +1958,7 @@ object Types { * type accumulators, as well as to be safe in diagnostic printing. * Normally, it's better to use `symbol`, not `currentSymbol`. */ - final def currentSymbol(implicit ctx: Context): Symbol = designator match { + final def currentSymbol(using Context): Symbol = designator match { case sym: Symbol => sym case _ => if (denotationIsCurrent) lastDenotation.symbol else NoSymbol } @@ -1967,14 +1967,14 @@ object Types { * Assumes that symbols do not change between periods in the same run. * Used to get the class underlying a ThisType. */ - private[Types] def stableInRunSymbol(implicit ctx: Context): Symbol = + private[Types] def stableInRunSymbol(using Context): Symbol = if (checkedPeriod.runId == ctx.runId) lastSymbol else symbol - def info(implicit ctx: Context): Type = denot.info + def info(using Context): Type = denot.info /** The denotation currently denoted by this type */ - final def denot(implicit ctx: Context): Denotation = { + final def denot(using Context): Denotation = { val now = ctx.period // Even if checkedPeriod == now we still need to recheck lastDenotation.validFor // as it may have been mutated by SymDenotation#installAfter @@ -1985,7 +1985,7 @@ object Types { else computeDenot } - private def computeDenot(implicit ctx: Context): Denotation = { + private def computeDenot(using Context): Denotation = { def finish(d: Denotation) = { if (d.exists) @@ -2030,10 +2030,10 @@ object Types { } } - private def disambiguate(d: Denotation)(implicit ctx: Context): Denotation = + private def disambiguate(d: Denotation)(using Context): Denotation = disambiguate(d, currentSignature) - private def disambiguate(d: Denotation, sig: Signature)(implicit ctx: Context): Denotation = + private def disambiguate(d: Denotation, sig: Signature)(using Context): Denotation = if (sig != null) d.atSignature(sig, relaxed = !ctx.erasedTypes) match { case d1: SingleDenotation => d1 @@ -2045,23 +2045,23 @@ object Types { } else d - private def memberDenot(name: Name, allowPrivate: Boolean)(implicit ctx: Context): Denotation = { + private def memberDenot(name: Name, allowPrivate: Boolean)(using Context): Denotation = { var d = memberDenot(prefix, name, allowPrivate) 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]) // name has changed; try load in earlier phase and make current - d = memberDenot(name, allowPrivate)(ctx.withPhase(ctx.phaseId - 1)).current + d = memberDenot(name, allowPrivate)(using ctx.withPhase(ctx.phaseId - 1)).current if (d.isOverloaded) d = disambiguate(d) d } - private def memberDenot(prefix: Type, name: Name, allowPrivate: Boolean)(implicit ctx: Context): Denotation = + private def memberDenot(prefix: Type, name: Name, allowPrivate: Boolean)(using Context): Denotation = if (allowPrivate) prefix.member(name) else prefix.nonPrivateMember(name) - private def argDenot(param: TypeSymbol)(implicit ctx: Context): Denotation = { + private def argDenot(param: TypeSymbol)(using Context): Denotation = { val cls = param.owner val args = prefix.baseType(cls).argInfos val typeParams = cls.typeParams @@ -2101,10 +2101,10 @@ object Types { /** Reload denotation by computing the member with the reference's name as seen * from the reference's prefix. */ - def recomputeDenot()(implicit ctx: Context): Unit = + def recomputeDenot()(using Context): Unit = setDenot(memberDenot(name, allowPrivate = !symbol.exists || symbol.is(Private))) - private def setDenot(denot: Denotation)(implicit ctx: Context): Unit = { + private def setDenot(denot: Denotation)(using Context): Unit = { if (Config.checkNoDoubleBindings) if (ctx.settings.YnoDoubleBindings.value) checkSymAssign(denot.symbol) @@ -2120,9 +2120,9 @@ object Types { checkDenot() } - private def checkDenot()(implicit ctx: Context) = {} + private def checkDenot()(using Context) = {} - private def checkSymAssign(sym: Symbol)(implicit ctx: Context) = { + private def checkSymAssign(sym: Symbol)(using Context) = { def selfTypeOf(sym: Symbol) = if (sym.isClass) sym.asClass.givenSelfType else NoType assert( @@ -2158,11 +2158,11 @@ object Types { /** A reference with the initial symbol in `symd` has an info that * might depend on the given prefix. */ - private def infoDependsOnPrefix(symd: SymDenotation, prefix: Type)(implicit ctx: Context): Boolean = + private def infoDependsOnPrefix(symd: SymDenotation, prefix: Type)(using Context): Boolean = symd.maybeOwner.membersNeedAsSeenFrom(prefix) && !symd.is(NonMember) /** Is this a reference to a class or object member? */ - def isMemberRef(implicit ctx: Context): Boolean = designator match { + def isMemberRef(using Context): Boolean = designator match { case sym: Symbol => infoDependsOnPrefix(sym, prefix) case _ => true } @@ -2174,7 +2174,7 @@ object Types { * provided `U` does not refer with a RecThis to the * refinement type `T { X = U; ... }` */ - def reduceProjection(implicit ctx: Context): Type = + def reduceProjection(using Context): Type = if (isType) { val reduced = prefix.lookupRefined(name) if (reduced.exists) reduced else this @@ -2191,7 +2191,7 @@ object Types { * These are errors but we have to make sure that operations do * not loop before the error is detected. */ - final def controlled[T](op: => T)(implicit ctx: Context): T = try { + final def controlled[T](op: => T)(using Context): T = try { ctx.base.underlyingRecursions += 1 if (ctx.base.underlyingRecursions < Config.LogPendingUnderlyingThreshold) op @@ -2212,7 +2212,7 @@ object Types { * prefix `pre`. Can produce a TypeBounds type in case prefix is an & or | type * and parameter is non-variant. */ - def argForParam(pre: Type)(implicit ctx: Context): Type = { + def argForParam(pre: Type)(using Context): Type = { val tparam = symbol val cls = tparam.owner val base = pre.baseType(cls) @@ -2261,7 +2261,7 @@ object Types { * --> S#A & T#A otherwise * (S | T)#A --> S#A | T#A */ - def derivedSelect(prefix: Type)(implicit ctx: Context): Type = + def derivedSelect(prefix: Type)(using Context): Type = if (prefix eq this.prefix) this else if (prefix.isBottomType) prefix else { @@ -2295,7 +2295,7 @@ object Types { } /** A reference like this one, but with the given symbol, if it exists */ - final def withSym(sym: Symbol)(implicit ctx: Context): ThisType = + final def withSym(sym: Symbol)(using Context): ThisType = if ((designator ne sym) && sym.exists) NamedType(prefix, sym).asInstanceOf[ThisType] else this @@ -2318,7 +2318,7 @@ object Types { * references often recompute their info directly from the symbol's info). * A test case is neg/opaque-self-encoding.scala. */ - final def withDenot(denot: Denotation)(implicit ctx: Context): ThisType = + final def withDenot(denot: Denotation)(using Context): ThisType = if (denot.exists) { val adapted = withSym(denot.symbol) val result = @@ -2335,7 +2335,7 @@ object Types { this /** A reference like this one, but with the given prefix. */ - final def withPrefix(prefix: Type)(implicit ctx: Context): NamedType = { + final def withPrefix(prefix: Type)(using Context): NamedType = { def reload(): NamedType = { val allowPrivate = !lastSymbol.exists || lastSymbol.is(Private) && prefix.classSymbol == this.prefix.classSymbol var d = memberDenot(prefix, name, allowPrivate) @@ -2387,7 +2387,7 @@ object Types { * Implicits.RenamedImplicitRef. */ trait ImplicitRef { - def implicitName(implicit ctx: Context): TermName + def implicitName(using Context): TermName def underlyingRef: TermRef } @@ -2404,20 +2404,20 @@ object Types { override protected def designator_=(d: Designator): Unit = myDesignator = d //assert(name.toString != "") - override def underlying(implicit ctx: Context): Type = { + override def underlying(using Context): Type = { val d = denot if (d.isOverloaded) NoType else d.info } - override def isOverloaded(implicit ctx: Context): Boolean = denot.isOverloaded + override def isOverloaded(using Context): Boolean = denot.isOverloaded - def alternatives(implicit ctx: Context): List[TermRef] = + def alternatives(using Context): List[TermRef] = denot.alternatives.map(withDenot(_)) - def altsWith(p: Symbol => Boolean)(implicit ctx: Context): List[TermRef] = + def altsWith(p: Symbol => Boolean)(using Context): List[TermRef] = denot.altsWith(p).map(withDenot(_)) - def implicitName(implicit ctx: Context): TermName = name + def implicitName(using Context): TermName = name def underlyingRef: TermRef = this } @@ -2458,9 +2458,9 @@ object Types { override def designator: Designator = myDesignator override protected def designator_=(d: Designator): Unit = myDesignator = d - override def underlying(implicit ctx: Context): Type = info + override def underlying(using Context): Type = info - override def translucentSuperType(implicit ctx: Context) = info match { + override def translucentSuperType(using Context) = info match { case TypeAlias(aliased) => aliased case TypeBounds(_, hi) => if (symbol.isOpaqueAlias) @@ -2470,7 +2470,7 @@ object Types { } /** Hook that can be called from creation methods in TermRef and TypeRef */ - def validated(implicit ctx: Context): this.type = + def validated(using Context): this.type = this } @@ -2485,7 +2485,7 @@ object Types { } /** Assert current phase does not have erasure semantics */ - private def assertUnerased()(implicit ctx: Context) = + private def assertUnerased()(using Context) = if (Config.checkUnerased) assert(!ctx.phase.erasedTypes) /** The designator to be used for a named type creation with given prefix, name, and denotation. @@ -2497,7 +2497,7 @@ object Types { * a reference with a name as designator so that the denotation will be correctly updated in * the future. See also NamedType#withDenot. Test case is neg/opaque-self-encoding.scala. */ - private def designatorFor(prefix: Type, name: Name, denot: Denotation)(implicit ctx: Context): Designator = { + private def designatorFor(prefix: Type, name: Name, denot: Denotation)(using Context): Designator = { val sym = denot.symbol if (sym.exists && (prefix.eq(NoPrefix) || prefix.ne(sym.owner.thisType))) sym @@ -2506,14 +2506,14 @@ object Types { } object NamedType { - def isType(desig: Designator)(implicit ctx: Context): Boolean = desig match { + def isType(desig: Designator)(using Context): Boolean = desig match { case sym: Symbol => sym.isType case name: Name => name.isTypeName } - def apply(prefix: Type, designator: Designator)(implicit ctx: Context): NamedType = + def apply(prefix: Type, designator: Designator)(using Context): NamedType = if (isType(designator)) TypeRef.apply(prefix, designator) else TermRef.apply(prefix, designator) - def apply(prefix: Type, designator: Name, denot: Denotation)(implicit ctx: Context): NamedType = + def apply(prefix: Type, designator: Name, denot: Denotation)(using Context): NamedType = if (designator.isTermName) TermRef.apply(prefix, designator.asTermName, denot) else TypeRef.apply(prefix, designator.asTypeName, denot) } @@ -2521,26 +2521,26 @@ object Types { object TermRef { /** Create a term ref with given designator */ - def apply(prefix: Type, desig: Designator)(implicit ctx: Context): TermRef = + def apply(prefix: Type, desig: Designator)(using Context): TermRef = ctx.uniqueNamedTypes.enterIfNew(prefix, desig, isTerm = true).asInstanceOf[TermRef] /** Create a term ref with given initial denotation. The name of the reference is taken * from the denotation's symbol if the latter exists, or else it is the given name. */ - def apply(prefix: Type, name: TermName, denot: Denotation)(implicit ctx: Context): TermRef = + def apply(prefix: Type, name: TermName, denot: Denotation)(using Context): TermRef = apply(prefix, designatorFor(prefix, name, denot)).withDenot(denot) } object TypeRef { /** Create a type ref with given prefix and name */ - def apply(prefix: Type, desig: Designator)(implicit ctx: Context): TypeRef = + def apply(prefix: Type, desig: Designator)(using Context): TypeRef = ctx.uniqueNamedTypes.enterIfNew(prefix, desig, isTerm = false).asInstanceOf[TypeRef] /** Create a type ref with given initial denotation. The name of the reference is taken * from the denotation's symbol if the latter exists, or else it is the given name. */ - def apply(prefix: Type, name: TypeName, denot: Denotation)(implicit ctx: Context): TypeRef = + def apply(prefix: Type, name: TypeName, denot: Denotation)(using Context): TypeRef = apply(prefix, designatorFor(prefix, name, denot)).withDenot(denot) } @@ -2552,12 +2552,12 @@ object Types { * do not survive runs whereas typerefs do. */ abstract case class ThisType(tref: TypeRef) extends CachedProxyType with SingletonType { - def cls(implicit ctx: Context): ClassSymbol = tref.stableInRunSymbol match { + def cls(using Context): ClassSymbol = tref.stableInRunSymbol match { case cls: ClassSymbol => cls case _ if ctx.mode.is(Mode.Interactive) => defn.AnyClass // was observed to happen in IDE mode } - override def underlying(implicit ctx: Context): Type = + override def underlying(using Context): Type = if (ctx.erasedTypes) tref else cls.info match { case cinfo: ClassInfo => cinfo.selfType @@ -2577,7 +2577,7 @@ object Types { object ThisType { /** Normally one should use ClassSymbol#thisType instead */ - def raw(tref: TypeRef)(implicit ctx: Context): CachedThisType = + def raw(tref: TypeRef)(using Context): CachedThisType = unique(new CachedThisType(tref)) } @@ -2586,10 +2586,10 @@ object Types { * by `super`. */ abstract case class SuperType(thistpe: Type, supertpe: Type) extends CachedProxyType with SingletonType { - override def underlying(implicit ctx: Context): Type = supertpe - override def superType(implicit ctx: Context): Type = + override def underlying(using Context): Type = supertpe + override def superType(using Context): Type = thistpe.baseType(supertpe.typeSymbol) - def derivedSuperType(thistpe: Type, supertpe: Type)(implicit ctx: Context): Type = + def derivedSuperType(thistpe: Type, supertpe: Type)(using Context): Type = if ((thistpe eq this.thistpe) && (supertpe eq this.supertpe)) this else SuperType(thistpe, supertpe) @@ -2604,7 +2604,7 @@ object Types { final class CachedSuperType(thistpe: Type, supertpe: Type) extends SuperType(thistpe, supertpe) object SuperType { - def apply(thistpe: Type, supertpe: Type)(implicit ctx: Context): SuperType = { + def apply(thistpe: Type, supertpe: Type)(using Context): SuperType = { assert(thistpe != NoPrefix) unique(new CachedSuperType(thistpe, supertpe)) } @@ -2612,7 +2612,7 @@ object Types { /** A constant type with single `value`. */ abstract case class ConstantType(value: Constant) extends CachedProxyType with SingletonType { - override def underlying(implicit ctx: Context): Type = value.tpe + override def underlying(using Context): Type = value.tpe override def computeHash(bs: Binders): Int = doHash(value) } @@ -2620,7 +2620,7 @@ object Types { final class CachedConstantType(value: Constant) extends ConstantType(value) object ConstantType { - def apply(value: Constant)(implicit ctx: Context): ConstantType = { + def apply(value: Constant)(using Context): ConstantType = { assertUnerased() unique(new CachedConstantType(value)) } @@ -2630,7 +2630,7 @@ object Types { private var myRef: Type = null private var computed = false - def ref(implicit ctx: Context): Type = + def ref(using Context): Type = if computed then if myRef == null then // if errors were reported previously handle this by throwing a CyclicReference @@ -2656,7 +2656,7 @@ object Types { def evaluating: Boolean = computed && myRef == null def completed: Boolean = myRef != null - override def underlying(implicit ctx: Context): Type = ref + override def underlying(using Context): Type = ref override def toString: String = s"LazyRef(${if (computed) myRef else "..."})" override def equals(other: Any): Boolean = this.eq(other.asInstanceOf[AnyRef]) override def hashCode: Int = System.identityHashCode(this) @@ -2679,19 +2679,19 @@ object Types { else assert(refinedInfo.isInstanceOf[TypeType], this) assert(!refinedName.is(NameKinds.ExpandedName), this) - override def underlying(implicit ctx: Context): Type = parent + override def underlying(using Context): Type = parent private def badInst = throw new AssertionError(s"bad instantiation: $this") - def checkInst(implicit ctx: Context): this.type = this // debug hook + def checkInst(using Context): this.type = this // debug hook - def derivedRefinedType(parent: Type, refinedName: Name, refinedInfo: Type)(implicit ctx: Context): Type = + def derivedRefinedType(parent: Type, refinedName: Name, refinedInfo: Type)(using Context): Type = if ((parent eq this.parent) && (refinedName eq this.refinedName) && (refinedInfo eq this.refinedInfo)) this else RefinedType(parent, refinedName, refinedInfo) /** Add this refinement to `parent`, provided `refinedName` is a member of `parent`. */ - def wrapIfMember(parent: Type)(implicit ctx: Context): Type = + def wrapIfMember(parent: Type)(using Context): Type = if (parent.member(refinedName).exists) derivedRefinedType(parent, refinedName, refinedInfo) else parent @@ -2721,11 +2721,11 @@ object Types { extends RefinedType(parent, refinedName, refinedInfo) object RefinedType { - @tailrec def make(parent: Type, names: List[Name], infos: List[Type])(implicit ctx: Context): Type = + @tailrec def make(parent: Type, names: List[Name], infos: List[Type])(using Context): Type = if (names.isEmpty) parent else make(RefinedType(parent, names.head, infos.head), names.tail, infos.tail) - def apply(parent: Type, name: Name, info: Type)(implicit ctx: Context): RefinedType = { + def apply(parent: Type, name: Name, info: Type)(using Context): RefinedType = { assert(!ctx.erasedTypes) unique(new CachedRefinedType(parent, name, info)).checkInst } @@ -2771,17 +2771,17 @@ object Types { myRecThis } - override def underlying(implicit ctx: Context): Type = parent + override def underlying(using Context): Type = parent - def derivedRecType(parent: Type)(implicit ctx: Context): RecType = + def derivedRecType(parent: Type)(using Context): RecType = if (parent eq this.parent) this else RecType(rt => parent.substRecThis(this, rt.recThis)) - def rebind(parent: Type)(implicit ctx: Context): Type = + def rebind(parent: Type)(using Context): Type = if (parent eq this.parent) this else RecType.closeOver(rt => parent.substRecThis(this, rt.recThis)) - def isReferredToBy(tp: Type)(implicit ctx: Context): Boolean = { + def isReferredToBy(tp: Type)(using Context): Boolean = { val refacc = new TypeAccumulator[Boolean] { override def apply(x: Boolean, tp: Type) = x || { tp match { @@ -2814,7 +2814,7 @@ object Types { override def toString: String = s"RecType($parent | $hashCode)" - private def checkInst(implicit ctx: Context): this.type = this // debug hook + private def checkInst(using Context): this.type = this // debug hook } object RecType { @@ -2829,7 +2829,7 @@ object Types { * TODO: Figure out how to guarantee absence of cycles * of length > 1 */ - def apply(parentExp: RecType => Type)(implicit ctx: Context): RecType = { + def apply(parentExp: RecType => Type)(using Context): RecType = { val rt = new RecType(parentExp) def normalize(tp: Type): Type = tp.stripTypeVar match { case tp: RecType => @@ -2847,7 +2847,7 @@ object Types { } /** Create a `RecType`, but only if the type generated by `parentExp` is indeed recursive. */ - def closeOver(parentExp: RecType => Type)(implicit ctx: Context): Type = { + def closeOver(parentExp: RecType => Type)(using Context): Type = { val rt = this(parentExp) if (rt.isReferredToBy(rt.parent)) rt else rt.parent } @@ -2860,7 +2860,7 @@ object Types { def tp1: Type def tp2: Type - def derivedAndOrType(tp1: Type, tp2: Type)(implicit ctx: Context) = + def derivedAndOrType(tp1: Type, tp2: Type)(using Context) = if ((tp1 eq this.tp1) && (tp2 eq this.tp2)) this else if (isAnd) AndType.make(tp1, tp2, checkValid = true) else OrType.make(tp1, tp2) @@ -2871,7 +2871,7 @@ object Types { private var myBaseClassesPeriod: Period = Nowhere private var myBaseClasses: List[ClassSymbol] = _ /** Base classes of are the merge of the operand base classes. */ - override final def baseClasses(implicit ctx: Context): List[ClassSymbol] = { + override final def baseClasses(using Context): List[ClassSymbol] = { if (myBaseClassesPeriod != ctx.period) { val bcs1 = tp1.baseClasses val bcs1set = BaseClassSet(bcs1) @@ -2889,11 +2889,11 @@ object Types { myBaseClasses } - def derivedAndType(tp1: Type, tp2: Type)(implicit ctx: Context): Type = + def derivedAndType(tp1: Type, tp2: Type)(using Context): Type = if ((tp1 eq this.tp1) && (tp2 eq this.tp2)) this else AndType.make(tp1, tp2, checkValid = true) - def derived_& (tp1: Type, tp2: Type)(implicit ctx: Context): Type = + def derived_& (tp1: Type, tp2: Type)(using Context): Type = if ((tp1 eq this.tp1) && (tp2 eq this.tp2)) this else tp1 & tp2 @@ -2908,13 +2908,13 @@ object Types { final class CachedAndType(tp1: Type, tp2: Type) extends AndType(tp1, tp2) object AndType { - def apply(tp1: Type, tp2: Type)(implicit ctx: Context): AndType = { + def apply(tp1: Type, tp2: Type)(using Context): AndType = { assert(tp1.isValueTypeOrWildcard && tp2.isValueTypeOrWildcard, i"$tp1 & $tp2 / " + s"$tp1 & $tp2") unchecked(tp1, tp2) } - def unchecked(tp1: Type, tp2: Type)(implicit ctx: Context): AndType = { + def unchecked(tp1: Type, tp2: Type)(using Context): AndType = { assertUnerased() unique(new CachedAndType(tp1, tp2)) } @@ -2922,7 +2922,7 @@ object Types { /** Make an AndType using `op` unless clearly unnecessary (i.e. without * going through `&`). */ - def make(tp1: Type, tp2: Type, checkValid: Boolean = false)(implicit ctx: Context): Type = + def make(tp1: Type, tp2: Type, checkValid: Boolean = false)(using Context): Type = if ((tp1 eq tp2) || (tp2 eq defn.AnyType)) tp1 else if (tp1 eq defn.AnyType) @@ -2936,7 +2936,7 @@ object Types { private var myBaseClassesPeriod: Period = Nowhere private var myBaseClasses: List[ClassSymbol] = _ /** Base classes of are the intersection of the operand base classes. */ - override final def baseClasses(implicit ctx: Context): List[ClassSymbol] = { + override final def baseClasses(using Context): List[ClassSymbol] = { if (myBaseClassesPeriod != ctx.period) { val bcs1 = tp1.baseClasses val bcs1set = BaseClassSet(bcs1) @@ -2962,7 +2962,7 @@ object Types { private var myJoinPeriod: Period = Nowhere /** Replace or type by the closest non-or type above it */ - def join(implicit ctx: Context): Type = { + def join(using Context): Type = { if (myJoinPeriod != ctx.period) { myJoin = TypeOps.orDominator(this) core.println(i"join of $this == $myJoin") @@ -2976,7 +2976,7 @@ object Types { private var myAtoms: Atoms = _ private var myWidened: Type = _ - private def ensureAtomsComputed()(implicit ctx: Context): Unit = + private def ensureAtomsComputed()(using Context): Unit = if atomsRunId != ctx.runId then myAtoms = tp1.atoms | tp2.atoms val tp1w = tp1.widenSingletons @@ -2988,12 +2988,12 @@ object Types { ensureAtomsComputed() myAtoms - override def widenSingletons(implicit ctx: Context): Type = { + override def widenSingletons(using Context): Type = { ensureAtomsComputed() myWidened } - def derivedOrType(tp1: Type, tp2: Type)(implicit ctx: Context): Type = + def derivedOrType(tp1: Type, tp2: Type)(using Context): Type = if ((tp1 eq this.tp1) && (tp2 eq this.tp2)) this else OrType.make(tp1, tp2) @@ -3008,11 +3008,11 @@ object Types { final class CachedOrType(tp1: Type, tp2: Type) extends OrType(tp1, tp2) object OrType { - def apply(tp1: Type, tp2: Type)(implicit ctx: Context): OrType = { + def apply(tp1: Type, tp2: Type)(using Context): OrType = { assertUnerased() unique(new CachedOrType(tp1, tp2)) } - def make(tp1: Type, tp2: Type)(implicit ctx: Context): Type = + def make(tp1: Type, tp2: Type)(using Context): Type = if (tp1 eq tp2) tp1 else apply(tp1, tp2) } @@ -3064,9 +3064,9 @@ object Types { protected var mySignature: Signature = _ protected var mySignatureRunId: Int = NoRunId - protected[dotc] def computeSignature(implicit ctx: Context): Signature + protected[dotc] def computeSignature(using Context): Signature - final override def signature(implicit ctx: Context): Signature = { + final override def signature(using Context): Signature = { if (ctx.runId != mySignatureRunId) { mySignature = computeSignature if (!mySignature.isUnderDefined) mySignatureRunId = ctx.runId @@ -3076,7 +3076,7 @@ object Types { } trait MethodicType extends TermType { - protected def resultSignature(implicit ctx: Context): Signature = try resultType match { + protected def resultSignature(using Context): Signature = try resultType match { case rtp: MethodicType => rtp.signature case tp => if (tp.isRef(defn.UnitClass)) Signature(Nil, defn.UnitClass.fullName.asTypeName) @@ -3092,12 +3092,12 @@ object Types { /** A by-name parameter type of the form `=> T`, or the type of a method with no parameter list. */ abstract case class ExprType(resType: Type) extends CachedProxyType with TermType with MethodicType { - override def resultType(implicit ctx: Context): Type = resType - override def underlying(implicit ctx: Context): Type = resType + override def resultType(using Context): Type = resType + override def underlying(using Context): Type = resType - override def signature(implicit ctx: Context): Signature = Signature.NotAMethod + override def signature(using Context): Signature = Signature.NotAMethod - def derivedExprType(resType: Type)(implicit ctx: Context): ExprType = + def derivedExprType(resType: Type)(using Context): ExprType = if (resType eq this.resType) this else ExprType(resType) override def computeHash(bs: Binders): Int = doHash(bs, resType) @@ -3119,7 +3119,7 @@ object Types { final class CachedExprType(resultType: Type) extends ExprType(resultType) object ExprType { - def apply(resultType: Type)(implicit ctx: Context): ExprType = { + def apply(resultType: Type)(using Context): ExprType = { assertUnerased() unique(new CachedExprType(resultType)) } @@ -3143,10 +3143,10 @@ object Types { def resType: Type protected def newParamRef(n: Int): ParamRefType - override def resultType(implicit ctx: Context): Type = resType + override def resultType(using Context): Type = resType - def isResultDependent(implicit ctx: Context): Boolean - def isParamDependent(implicit ctx: Context): Boolean + def isResultDependent(using Context): Boolean + def isParamDependent(using Context): Boolean final def isTermLambda: Boolean = isInstanceOf[TermLambda] final def isTypeLambda: Boolean = isInstanceOf[TypeLambda] @@ -3160,12 +3160,12 @@ object Types { } /** Like `paramInfos` but substitute parameter references with the given arguments */ - final def instantiateParamInfos(argTypes: => List[Type])(implicit ctx: Context): List[Type] = + final def instantiateParamInfos(argTypes: => List[Type])(using Context): List[Type] = if (isParamDependent) paramInfos.mapConserve(_.substParams(this, argTypes)) else paramInfos /** Like `resultType` but substitute parameter references with the given arguments */ - final def instantiate(argTypes: => List[Type])(implicit ctx: Context): Type = + final def instantiate(argTypes: => List[Type])(using Context): Type = if (isResultDependent) resultType.substParams(this, argTypes) else resultType @@ -3174,7 +3174,7 @@ object Types { /** The type `[tparams := paramRefs] tp`, where `tparams` can be * either a list of type parameter symbols or a list of lambda parameters */ - def integrate(tparams: List[ParamInfo], tp: Type)(implicit ctx: Context): Type = + def integrate(tparams: List[ParamInfo], tp: Type)(using Context): Type = (tparams: @unchecked) match { case LambdaParam(lam, _) :: _ => tp.subst(lam, this) case params: List[Symbol @unchecked] => tp.subst(params, paramRefs) @@ -3182,11 +3182,11 @@ object Types { final def derivedLambdaType(paramNames: List[ThisName] = this.paramNames, paramInfos: List[PInfo] = this.paramInfos, - resType: Type = this.resType)(implicit ctx: Context): LambdaType = + resType: Type = this.resType)(using Context): LambdaType = if ((paramNames eq this.paramNames) && (paramInfos eq this.paramInfos) && (resType eq this.resType)) this else newLikeThis(paramNames, paramInfos, resType) - def newLikeThis(paramNames: List[ThisName], paramInfos: List[PInfo], resType: Type)(implicit ctx: Context): This = + def newLikeThis(paramNames: List[ThisName], paramInfos: List[PInfo], resType: Type)(using Context): This = companion(paramNames)( x => paramInfos.mapConserve(_.subst(this, x).asInstanceOf[PInfo]), x => resType.subst(this, x)) @@ -3196,7 +3196,7 @@ object Types { } abstract class HKLambda extends CachedProxyType with LambdaType { - final override def underlying(implicit ctx: Context): Type = resType + final override def underlying(using Context): Type = resType final override def hashIsStable: Boolean = resType.hashIsStable && paramInfos.hashIsStable final override def equals(that: Any): Boolean = equals(that, null) } @@ -3228,7 +3228,7 @@ object Types { type This <: TermLambda type ParamRefType = TermParamRef - override def resultType(implicit ctx: Context): Type = + override def resultType(using Context): Type = if (dependencyStatus == FalseDeps) { // dealias all false dependencies val dealiasMap = new TypeMap { def apply(tp: Type) = tp match { @@ -3248,7 +3248,7 @@ object Types { private var myDependencyStatus: DependencyStatus = Unknown private var myParamDependencyStatus: DependencyStatus = Unknown - private def depStatus(initial: DependencyStatus, tp: Type)(implicit ctx: Context): DependencyStatus = { + private def depStatus(initial: DependencyStatus, tp: Type)(using Context): DependencyStatus = { def combine(x: DependencyStatus, y: DependencyStatus) = { val status = (x & StatusMask) max (y & StatusMask) val provisional = (x | y) & Provisional @@ -3283,7 +3283,7 @@ object Types { * def f(x: C)(y: x.T) // dependencyStatus = FalseDeps, i.e. * // dependency can be eliminated by dealiasing. */ - private def dependencyStatus(implicit ctx: Context): DependencyStatus = + private def dependencyStatus(using Context): DependencyStatus = if (myDependencyStatus != Unknown) myDependencyStatus else { val result = depStatus(NoDeps, resType) @@ -3294,7 +3294,7 @@ object Types { /** The parameter dependency status of this method. Analogous to `dependencyStatus`, * but tracking dependencies in same parameter list. */ - private def paramDependencyStatus(implicit ctx: Context): DependencyStatus = + private def paramDependencyStatus(using Context): DependencyStatus = if (myParamDependencyStatus != Unknown) myParamDependencyStatus else { val result = @@ -3307,17 +3307,17 @@ object Types { /** Does result type contain references to parameters of this method type, * which cannot be eliminated by de-aliasing? */ - def isResultDependent(implicit ctx: Context): Boolean = dependencyStatus == TrueDeps + def isResultDependent(using Context): Boolean = dependencyStatus == TrueDeps /** Does one of the parameter types contain references to earlier parameters * of this method type which cannot be eliminated by de-aliasing? */ - def isParamDependent(implicit ctx: Context): Boolean = paramDependencyStatus == TrueDeps + def isParamDependent(using Context): Boolean = paramDependencyStatus == TrueDeps def newParamRef(n: Int): TermParamRef = new TermParamRefImpl(this, n) /** The least supertype of `resultType` that does not contain parameter dependencies */ - def nonDependentResultApprox(implicit ctx: Context): Type = + def nonDependentResultApprox(using Context): Type = if (isResultDependent) { val dropDependencies = new ApproximatingTypeMap { def apply(tp: Type) = tp match { @@ -3357,7 +3357,7 @@ object Types { companion.eq(ContextualMethodType) || companion.eq(ErasedContextualMethodType) - protected[dotc] def computeSignature(implicit ctx: Context): Signature = { + protected[dotc] def computeSignature(using Context): Signature = { val params = if (isErasedMethod) Nil else paramInfos resultSignature.prependTermParams(params, isJavaMethod) } @@ -3376,17 +3376,17 @@ object Types { memoizedNames.getOrElseUpdate(n, (0 until n).map(syntheticParamName).toList) } - def apply(paramNames: List[N])(paramInfosExp: LT => List[PInfo], resultTypeExp: LT => Type)(implicit ctx: Context): LT - def apply(paramNames: List[N], paramInfos: List[PInfo], resultType: Type)(implicit ctx: Context): LT = + def apply(paramNames: List[N])(paramInfosExp: LT => List[PInfo], resultTypeExp: LT => Type)(using Context): LT + def apply(paramNames: List[N], paramInfos: List[PInfo], resultType: Type)(using Context): LT = apply(paramNames)(_ => paramInfos, _ => resultType) - def apply(paramInfos: List[PInfo])(resultTypeExp: LT => Type)(implicit ctx: Context): LT = + def apply(paramInfos: List[PInfo])(resultTypeExp: LT => Type)(using Context): LT = apply(syntheticParamNames(paramInfos.length))(_ => paramInfos, resultTypeExp) - def apply(paramInfos: List[PInfo], resultType: Type)(implicit ctx: Context): LT = + def apply(paramInfos: List[PInfo], resultType: Type)(using Context): LT = apply(syntheticParamNames(paramInfos.length), paramInfos, resultType) - protected def toPInfo(tp: Type)(implicit ctx: Context): PInfo + protected def toPInfo(tp: Type)(using Context): PInfo - def fromParams[PI <: ParamInfo.Of[N]](params: List[PI], resultType: Type)(implicit ctx: Context): Type = + def fromParams[PI <: ParamInfo.Of[N]](params: List[PI], resultType: Type)(using Context): Type = if (params.isEmpty) resultType else apply(params.map(_.paramName))( tl => params.map(param => toPInfo(tl.integrate(params, param.paramInfo))), @@ -3395,13 +3395,13 @@ object Types { abstract class TermLambdaCompanion[LT <: TermLambda] extends LambdaTypeCompanion[TermName, Type, LT] { - def toPInfo(tp: Type)(implicit ctx: Context): Type = tp + def toPInfo(tp: Type)(using Context): Type = tp def syntheticParamName(n: Int): TermName = nme.syntheticParamName(n) } abstract class TypeLambdaCompanion[LT <: TypeLambda] extends LambdaTypeCompanion[TypeName, TypeBounds, LT] { - def toPInfo(tp: Type)(implicit ctx: Context): TypeBounds = (tp: @unchecked) match { + def toPInfo(tp: Type)(using Context): TypeBounds = (tp: @unchecked) match { case tp: TypeBounds => tp case tp: ErrorType => TypeAlias(tp) } @@ -3415,7 +3415,7 @@ object Types { * - replace @repeated annotations on Seq or Array types by types * - add @inlineParam to inline parameters */ - def fromSymbols(params: List[Symbol], resultType: Type)(implicit ctx: Context): MethodType = { + def fromSymbols(params: List[Symbol], resultType: Type)(using Context): MethodType = { def translateInline(tp: Type): Type = tp match { case ExprType(resType) => ExprType(AnnotatedType(resType, Annotation(defn.InlineParamAnnot))) case _ => AnnotatedType(tp, Annotation(defn.InlineParamAnnot)) @@ -3430,10 +3430,10 @@ object Types { tl => tl.integrate(params, resultType)) } - final def apply(paramNames: List[TermName])(paramInfosExp: MethodType => List[Type], resultTypeExp: MethodType => Type)(implicit ctx: Context): MethodType = + final def apply(paramNames: List[TermName])(paramInfosExp: MethodType => List[Type], resultTypeExp: MethodType => Type)(using Context): MethodType = checkValid(unique(new CachedMethodType(paramNames)(paramInfosExp, resultTypeExp, self))) - def checkValid(mt: MethodType)(implicit ctx: Context): mt.type = { + def checkValid(mt: MethodType)(using Context): mt.type = { if (Config.checkMethodTypes) for ((paramInfo, idx) <- mt.paramInfos.zipWithIndex) paramInfo.foreachPart { @@ -3468,7 +3468,7 @@ object Types { /** A ternary extractor for MethodType */ object MethodTpe { - def unapply(mt: MethodType)(implicit ctx: Context): Some[(List[TermName], List[Type], Type)] = + def unapply(mt: MethodType)(using Context): Some[(List[TermName], List[Type], Type)] = Some((mt.paramNames, mt.paramInfos, mt.resultType)) } @@ -3478,15 +3478,15 @@ object Types { type This <: TypeLambda type ParamRefType = TypeParamRef - def isResultDependent(implicit ctx: Context): Boolean = true - def isParamDependent(implicit ctx: Context): Boolean = true + def isResultDependent(using Context): Boolean = true + def isParamDependent(using Context): Boolean = true def newParamRef(n: Int): TypeParamRef = new TypeParamRefImpl(this, n) @threadUnsafe lazy val typeParams: List[LambdaParam] = paramNames.indices.toList.map(new LambdaParam(this, _)) - def derivedLambdaAbstraction(paramNames: List[TypeName], paramInfos: List[TypeBounds], resType: Type)(implicit ctx: Context): Type = + def derivedLambdaAbstraction(paramNames: List[TypeName], paramInfos: List[TypeBounds], resType: Type)(using Context): Type = resType match { case resType: AliasingBounds => resType.derivedAlias(newLikeThis(paramNames, paramInfos, resType.alias)) @@ -3558,15 +3558,15 @@ object Types { false } - override def newLikeThis(paramNames: List[ThisName], paramInfos: List[PInfo], resType: Type)(implicit ctx: Context): This = + override def newLikeThis(paramNames: List[ThisName], paramInfos: List[PInfo], resType: Type)(using Context): This = newLikeThis(paramNames, declaredVariances, paramInfos, resType) - def newLikeThis(paramNames: List[ThisName], variances: List[Variance], paramInfos: List[PInfo], resType: Type)(implicit ctx: Context): This = + def newLikeThis(paramNames: List[ThisName], variances: List[Variance], paramInfos: List[PInfo], resType: Type)(using Context): This = HKTypeLambda(paramNames, variances)( x => paramInfos.mapConserve(_.subst(this, x).asInstanceOf[PInfo]), x => resType.subst(this, x)) - def withVariances(variances: List[Variance])(implicit ctx: Context): This = + def withVariances(variances: List[Variance])(using Context): This = newLikeThis(paramNames, variances, paramInfos, resType) protected def prefixString: String = "HKTypeLambda" @@ -3592,7 +3592,7 @@ object Types { assert(resType.isInstanceOf[TermType], this) assert(paramNames.nonEmpty) - protected[dotc] def computeSignature(implicit ctx: Context): Signature = + protected[dotc] def computeSignature(using Context): Signature = resultSignature.prependTypeParams(paramNames.length) override def isContextualMethod = resType.isContextualMethod @@ -3601,7 +3601,7 @@ object Types { /** Merge nested polytypes into one polytype. nested polytypes are normally not supported * but can arise as temporary data structures. */ - def flatten(implicit ctx: Context): PolyType = resType match { + def flatten(using Context): PolyType = resType match { case that: PolyType => val shiftedSubst = (x: PolyType) => new TypeMap { def apply(t: Type) = t match { @@ -3622,22 +3622,22 @@ object Types { object HKTypeLambda extends TypeLambdaCompanion[HKTypeLambda] { def apply(paramNames: List[TypeName])( paramInfosExp: HKTypeLambda => List[TypeBounds], - resultTypeExp: HKTypeLambda => Type)(implicit ctx: Context): HKTypeLambda = + resultTypeExp: HKTypeLambda => Type)(using Context): HKTypeLambda = apply(paramNames, Nil)(paramInfosExp, resultTypeExp) def apply(paramNames: List[TypeName], variances: List[Variance])( paramInfosExp: HKTypeLambda => List[TypeBounds], - resultTypeExp: HKTypeLambda => Type)(implicit ctx: Context): HKTypeLambda = + resultTypeExp: HKTypeLambda => Type)(using Context): HKTypeLambda = unique(new HKTypeLambda(paramNames, variances)(paramInfosExp, resultTypeExp)) def unapply(tl: HKTypeLambda): Some[(List[LambdaParam], Type)] = Some((tl.typeParams, tl.resType)) - def any(n: Int)(implicit ctx: Context): HKTypeLambda = + def any(n: Int)(using Context): HKTypeLambda = apply(syntheticParamNames(n))( pt => List.fill(n)(TypeBounds.empty), pt => defn.AnyType) - override def fromParams[PI <: ParamInfo.Of[TypeName]](params: List[PI], resultType: Type)(implicit ctx: Context): Type = + override def fromParams[PI <: ParamInfo.Of[TypeName]](params: List[PI], resultType: Type)(using Context): Type = resultType match case bounds: TypeBounds => boundsFromParams(params, bounds) case _ => super.fromParams(params, resultType) @@ -3666,7 +3666,7 @@ object Types { * type T[A, B] = A => B // A is contravariant, B is covariant (determined structurally) * type T[A, +B] = A => B // A is invariant, B is covariant */ - def boundsFromParams[PI <: ParamInfo.Of[TypeName]](params: List[PI], bounds: TypeBounds)(implicit ctx: Context): TypeBounds = { + def boundsFromParams[PI <: ParamInfo.Of[TypeName]](params: List[PI], bounds: TypeBounds)(using Context): TypeBounds = { def expand(tp: Type, useVariances: Boolean) = if params.nonEmpty && useVariances then apply(params.map(_.paramName), params.map(_.paramVariance))( @@ -3694,13 +3694,13 @@ object Types { object PolyType extends TypeLambdaCompanion[PolyType] { def apply(paramNames: List[TypeName])( paramInfosExp: PolyType => List[TypeBounds], - resultTypeExp: PolyType => Type)(implicit ctx: Context): PolyType = + resultTypeExp: PolyType => Type)(using Context): PolyType = unique(new PolyType(paramNames)(paramInfosExp, resultTypeExp)) def unapply(tl: PolyType): Some[(List[LambdaParam], Type)] = Some((tl.typeParams, tl.resType)) - def any(n: Int)(implicit ctx: Context): PolyType = + def any(n: Int)(using Context): PolyType = apply(syntheticParamNames(n))( pt => List.fill(n)(TypeBounds.empty), pt => defn.AnyType) } @@ -3721,12 +3721,12 @@ object Types { case class LambdaParam(tl: TypeLambda, n: Int) extends ParamInfo { type ThisName = TypeName - def isTypeParam(implicit ctx: Context): Boolean = tl.paramNames.head.isTypeName - def paramName(implicit ctx: Context): tl.ThisName = tl.paramNames(n) - def paramInfo(implicit ctx: Context): tl.PInfo = tl.paramInfos(n) - def paramInfoAsSeenFrom(pre: Type)(implicit ctx: Context): tl.PInfo = paramInfo - def paramInfoOrCompleter(implicit ctx: Context): Type = paramInfo - def paramRef(implicit ctx: Context): Type = tl.paramRefs(n) + def isTypeParam(using Context): Boolean = tl.paramNames.head.isTypeName + def paramName(using Context): tl.ThisName = tl.paramNames(n) + def paramInfo(using Context): tl.PInfo = tl.paramInfos(n) + def paramInfoAsSeenFrom(pre: Type)(using Context): tl.PInfo = paramInfo + def paramInfoOrCompleter(using Context): Type = paramInfo + def paramRef(using Context): Type = tl.paramRefs(n) private var myVariance: FlagSet = UndefinedFlags @@ -3755,7 +3755,7 @@ object Types { myVariance /** The declared or structural variance of this parameter. */ - def paramVariance(implicit ctx: Context): Variance = + def paramVariance(using Context): Variance = if myVariance == UndefinedFlags then tl match case tl: HKTypeLambda => @@ -3776,7 +3776,7 @@ object Types { private var isGroundKnown: Boolean = false private var isGroundCache: Boolean = _ - def isGround(acc: TypeAccumulator[Boolean])(implicit ctx: Context): Boolean = { + def isGround(acc: TypeAccumulator[Boolean])(using Context): Boolean = { if (!isGroundKnown) { isGroundCache = acc.foldOver(true, this) isGroundKnown = true @@ -3784,9 +3784,9 @@ object Types { isGroundCache } - override def underlying(implicit ctx: Context): Type = tycon + override def underlying(using Context): Type = tycon - override def superType(implicit ctx: Context): Type = { + override def superType(using Context): Type = { if (ctx.period != validSuper) { cachedSuper = tycon match { case tycon: HKTypeLambda => defn.AnyType @@ -3799,14 +3799,14 @@ object Types { cachedSuper } - override def translucentSuperType(implicit ctx: Context): Type = tycon match { + override def translucentSuperType(using Context): Type = tycon match { case tycon: TypeRef if tycon.symbol.isOpaqueAlias => tycon.translucentSuperType.applyIfParameterized(args) case _ => superType } - override def tryNormalize(implicit ctx: Context): Type = tycon match { + override def tryNormalize(using Context): Type = tycon match { case tycon: TypeRef => def tryMatchAlias = tycon.info match { case MatchAlias(alias) => @@ -3823,7 +3823,7 @@ object Types { NoType } - def tryCompiletimeConstantFold(implicit ctx: Context): Type = tycon match { + def tryCompiletimeConstantFold(using Context): Type = tycon match { case tycon: TypeRef if defn.isCompiletimeAppliedType(tycon.symbol) => def constValue(tp: Type): Option[Any] = tp.dealias match { case ConstantType(Constant(n)) => Some(n) @@ -3913,7 +3913,7 @@ object Types { case _ => NoType } - def lowerBound(implicit ctx: Context): Type = tycon.stripTypeVar match { + def lowerBound(using Context): Type = tycon.stripTypeVar match { case tycon: TypeRef => tycon.info match { case TypeBounds(lo, hi) => @@ -3927,14 +3927,14 @@ object Types { NoType } - def tyconTypeParams(implicit ctx: Context): List[ParamInfo] = { + def tyconTypeParams(using Context): List[ParamInfo] = { val tparams = tycon.typeParams if (tparams.isEmpty) HKTypeLambda.any(args.length).typeParams else tparams } - def hasWildcardArg(implicit ctx: Context): Boolean = args.exists(isBounds) + def hasWildcardArg(using Context): Boolean = args.exists(isBounds) - def derivedAppliedType(tycon: Type, args: List[Type])(implicit ctx: Context): Type = + def derivedAppliedType(tycon: Type, args: List[Type])(using Context): Type = if ((tycon eq this.tycon) && (args eq this.args)) this else tycon.appliedTo(args) @@ -3960,7 +3960,7 @@ object Types { } object AppliedType { - def apply(tycon: Type, args: List[Type])(implicit ctx: Context): AppliedType = { + def apply(tycon: Type, args: List[Type])(using Context): AppliedType = { assertUnerased() ctx.base.uniqueAppliedTypes.enterIfNew(tycon, args) } @@ -3980,7 +3980,7 @@ object Types { def paramNum: Int def paramName: binder.ThisName = binder.paramNames(paramNum) - override def underlying(implicit ctx: Context): Type = { + override def underlying(using Context): Type = { val infos = binder.paramInfos if (infos == null) NoType // this can happen if the referenced generic type is not initialized yet else infos(paramNum) @@ -4026,13 +4026,13 @@ object Types { /** Optimized version of occursIn, avoid quadratic blowup when solving * constraints over large ground types. */ - override def occursIn(that: Type)(implicit ctx: Context): Boolean = !that.isGround && super.occursIn(that) + override def occursIn(that: Type)(using Context): Boolean = !that.isGround && super.occursIn(that) /** Looking only at the structure of `bound`, is one of the following true? * - fromBelow and param <:< bound * - !fromBelow and param >:> bound */ - def occursIn(bound: Type, fromBelow: Boolean)(implicit ctx: Context): Boolean = bound.stripTypeVar match { + def occursIn(bound: Type, fromBelow: Boolean)(using Context): Boolean = bound.stripTypeVar match { case bound: ParamRef => bound == this case bound: AndType => occursIn(bound.tp1, fromBelow) && occursIn(bound.tp2, fromBelow) case bound: OrType => occursIn(bound.tp1, fromBelow) || occursIn(bound.tp2, fromBelow) @@ -4047,7 +4047,7 @@ object Types { */ abstract case class RecThis(binder: RecType) extends BoundType with SingletonType { type BT = RecType - override def underlying(implicit ctx: Context): RecType = binder + override def underlying(using Context): RecType = binder def copyBoundType(bt: BT): RecThis = bt.recThis // need to customize hashCode and equals to prevent infinite recursion @@ -4079,8 +4079,8 @@ object Types { * A skolem is equal to itself and no other type. */ case class SkolemType(info: Type) extends UncachedProxyType with ValueType with SingletonType { - override def underlying(implicit ctx: Context): Type = info - def derivedSkolemType(info: Type)(implicit ctx: Context): SkolemType = + override def underlying(using Context): Type = info + def derivedSkolemType(info: Type)(using Context): SkolemType = if (info eq this.info) this else SkolemType(info) override def hashCode: Int = System.identityHashCode(this) override def equals(that: Any): Boolean = this.eq(that.asInstanceOf[AnyRef]) @@ -4088,7 +4088,7 @@ object Types { def withName(name: Name): this.type = { myRepr = name; this } private var myRepr: Name = null - def repr(implicit ctx: Context): Name = { + def repr(using Context): Name = { if (myRepr == null) myRepr = SkolemName.fresh() myRepr } @@ -4104,7 +4104,7 @@ object Types { * see its implementation for more details. */ class QualSkolemType(info: Type) extends SkolemType(info) { - override def derivedSkolemType(info: Type)(implicit ctx: Context): SkolemType = + override def derivedSkolemType(info: Type)(using Context): SkolemType = if (info eq this.info) this else QualSkolemType(info) } object QualSkolemType { @@ -4159,11 +4159,11 @@ object Types { /** The instance type of this variable, or NoType if the variable is currently * uninstantiated */ - def instanceOpt(implicit ctx: Context): Type = + def instanceOpt(using Context): Type = if (inst.exists) inst else ctx.typeComparer.instType(this) /** Is the variable already instantiated? */ - def isInstantiated(implicit ctx: Context): Boolean = instanceOpt.exists + def isInstantiated(using Context): Boolean = instanceOpt.exists /** Avoid term references in `tp` to parameters or local variables that * are nested more deeply than the type variable itself. @@ -4196,7 +4196,7 @@ object Types { // To do this, we need first test cases for that situation. /** Instantiate variable with given type */ - def instantiateWith(tp: Type)(implicit ctx: Context): Type = { + def instantiateWith(tp: Type)(using Context): Type = { assert(tp ne this, s"self instantiation of ${tp.show}, constraint = ${ctx.typerState.constraint.show}") typr.println(s"instantiating ${this.show} with ${tp.show}") if ((ctx.typerState eq owningState.get) && !ctx.typeComparer.subtypeCheckInProgress) @@ -4212,27 +4212,27 @@ object Types { * instantiation can be a singleton type only if the upper bound * is also a singleton type. */ - def instantiate(fromBelow: Boolean)(implicit ctx: Context): Type = + def instantiate(fromBelow: Boolean)(using Context): Type = instantiateWith(avoidCaptures(ctx.typeComparer.instanceType(origin, fromBelow))) /** For uninstantiated type variables: Is the lower bound different from Nothing? */ - def hasLowerBound(implicit ctx: Context): Boolean = + def hasLowerBound(using Context): Boolean = !ctx.typerState.constraint.entry(origin).loBound.isBottomType /** For uninstantiated type variables: Is the upper bound different from Any? */ - def hasUpperBound(implicit ctx: Context): Boolean = + def hasUpperBound(using Context): Boolean = !ctx.typerState.constraint.entry(origin).hiBound.isRef(defn.AnyClass) /** Unwrap to instance (if instantiated) or origin (if not), until result * is no longer a TypeVar */ - override def stripTypeVar(implicit ctx: Context): Type = { + override def stripTypeVar(using Context): Type = { val inst = instanceOpt if (inst.exists) inst.stripTypeVar else origin } /** If the variable is instantiated, its instance, otherwise its origin */ - override def underlying(implicit ctx: Context): Type = { + override def underlying(using Context): Type = { val inst = instanceOpt if (inst.exists) inst else origin } @@ -4262,24 +4262,24 @@ object Types { * and `X_1,...X_n` are the type variables bound in `patternType` */ abstract case class MatchType(bound: Type, scrutinee: Type, cases: List[Type]) extends CachedProxyType with ValueType { - def derivedMatchType(bound: Type, scrutinee: Type, cases: List[Type])(implicit ctx: Context): MatchType = + def derivedMatchType(bound: Type, scrutinee: Type, cases: List[Type])(using Context): MatchType = if (bound.eq(this.bound) && scrutinee.eq(this.scrutinee) && cases.eqElements(this.cases)) this else MatchType(bound, scrutinee, cases) - def caseType(tp: Type)(implicit ctx: Context): Type = tp match { + def caseType(tp: Type)(using Context): Type = tp match { case tp: HKTypeLambda => caseType(tp.resType) case defn.MatchCase(_, body) => body } - def alternatives(implicit ctx: Context): List[Type] = cases.map(caseType) - def underlying(implicit ctx: Context): Type = bound + def alternatives(using Context): List[Type] = cases.map(caseType) + def underlying(using Context): Type = bound private var myReduced: Type = null private var reductionContext: mutable.Map[Type, Type] = null - override def tryNormalize(implicit ctx: Context): Type = reduced.normalized + override def tryNormalize(using Context): Type = reduced.normalized - def reduced(implicit ctx: Context): Type = { + def reduced(using Context): Type = { val trackingCtx = ctx.fresh.setTypeComparerFn(new TrackingTypeComparer(_)) val typeComparer = trackingCtx.typeComparer.asInstanceOf[TrackingTypeComparer] @@ -4337,7 +4337,7 @@ object Types { class CachedMatchType(bound: Type, scrutinee: Type, cases: List[Type]) extends MatchType(bound, scrutinee, cases) object MatchType { - def apply(bound: Type, scrutinee: Type, cases: List[Type])(implicit ctx: Context): MatchType = + def apply(bound: Type, scrutinee: Type, cases: List[Type])(using Context): MatchType = unique(new CachedMatchType(bound, scrutinee, cases)) } @@ -4370,29 +4370,30 @@ object Types { * - the explicit self type if given (or the info of a given self symbol), and * - the fully applied reference to the class itself. */ - def selfType(implicit ctx: Context): Type = { + def selfType(using Context): Type = { + val clsd = cls.classDenot if (selfTypeCache == null) selfTypeCache = { - val givenSelf = cls.givenSelfType + val givenSelf = clsd.givenSelfType if (!givenSelf.isValueType) appliedRef - else if (cls.is(Module)) givenSelf + else if (clsd.is(Module)) givenSelf else if (ctx.erasedTypes) appliedRef else AndType(givenSelf, appliedRef) } selfTypeCache } - def appliedRef(implicit ctx: Context): Type = { + def appliedRef(using Context): Type = { if (appliedRefCache == null) appliedRefCache = - TypeRef(prefix, cls).appliedTo(cls.typeParams.map(_.typeRef)) + TypeRef(prefix, cls).appliedTo(cls.classDenot.typeParams.map(_.typeRef)) appliedRefCache } // cached because baseType needs parents private var parentsCache: List[Type] = null - override def parents(implicit ctx: Context): List[Type] = { + override def parents(using Context): List[Type] = { if (parentsCache == null) parentsCache = classParents.mapConserve(_.asSeenFrom(prefix, cls.owner)) parentsCache @@ -4401,11 +4402,11 @@ object Types { protected def newLikeThis(prefix: Type, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol)(using Context): ClassInfo = ClassInfo(prefix, cls, classParents, decls, selfInfo) - def derivedClassInfo(prefix: Type)(implicit ctx: Context): ClassInfo = + def derivedClassInfo(prefix: Type)(using Context): ClassInfo = if (prefix eq this.prefix) this else newLikeThis(prefix, classParents, decls, selfInfo) - def derivedClassInfo(prefix: Type = this.prefix, classParents: List[Type] = this.classParents, decls: Scope = this.decls, selfInfo: TypeOrSymbol = this.selfInfo)(implicit ctx: Context): ClassInfo = + def derivedClassInfo(prefix: Type = this.prefix, classParents: List[Type] = this.classParents, decls: Scope = this.decls, selfInfo: TypeOrSymbol = this.selfInfo)(using Context): ClassInfo = if ((prefix eq this.prefix) && (classParents eq this.classParents) && (decls eq this.decls) && (selfInfo eq this.selfInfo)) this else newLikeThis(prefix, classParents, decls, selfInfo) @@ -4476,7 +4477,7 @@ object Types { extends CachedClassInfo(prefix, cls, Nil, decls, selfInfo) { /** Convert to classinfo with known parents */ - def finalized(parents: List[Type])(implicit ctx: Context): ClassInfo = + def finalized(parents: List[Type])(using Context): ClassInfo = ClassInfo(prefix, cls, parents, decls, selfInfo) override def newLikeThis(prefix: Type, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol)(using Context): ClassInfo = @@ -4486,7 +4487,7 @@ object Types { } object ClassInfo { - def apply(prefix: Type, cls: ClassSymbol, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol = NoType)(implicit ctx: Context): ClassInfo = + def apply(prefix: Type, cls: ClassSymbol, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol = NoType)(using Context): ClassInfo = unique(new CachedClassInfo(prefix, cls, classParents, decls, selfInfo)) } @@ -4496,14 +4497,14 @@ object Types { assert(lo.isInstanceOf[TermType], lo) assert(hi.isInstanceOf[TermType], hi) - override def underlying(implicit ctx: Context): Type = hi + override def underlying(using Context): Type = hi /** The non-alias type bounds type with given bounds */ - def derivedTypeBounds(lo: Type, hi: Type)(implicit ctx: Context): TypeBounds = + def derivedTypeBounds(lo: Type, hi: Type)(using Context): TypeBounds = if ((lo eq this.lo) && (hi eq this.hi)) this else TypeBounds(lo, hi) - def contains(tp: Type)(implicit ctx: Context): Boolean = tp match { + def contains(tp: Type)(using Context): Boolean = tp match { case tp: TypeBounds => lo <:< tp.lo && tp.hi <:< hi case tp: ClassInfo => val cls = tp.cls @@ -4516,22 +4517,22 @@ object Types { lo <:< tp && tp <:< hi } - def & (that: TypeBounds)(implicit ctx: Context): TypeBounds = + def & (that: TypeBounds)(using Context): TypeBounds = if ((this.lo frozen_<:< that.lo) && (that.hi frozen_<:< this.hi)) that else if ((that.lo frozen_<:< this.lo) && (this.hi frozen_<:< that.hi)) this else TypeBounds(this.lo | that.lo, this.hi & that.hi) - def | (that: TypeBounds)(implicit ctx: Context): TypeBounds = + def | (that: TypeBounds)(using Context): TypeBounds = if ((this.lo frozen_<:< that.lo) && (that.hi frozen_<:< this.hi)) this else if ((that.lo frozen_<:< this.lo) && (this.hi frozen_<:< that.hi)) that else TypeBounds(this.lo & that.lo, this.hi | that.hi) - override def & (that: Type)(implicit ctx: Context): Type = that match { + override def & (that: Type)(using Context): Type = that match { case that: TypeBounds => this & that case _ => super.& (that) } - override def | (that: Type)(implicit ctx: Context): Type = that match { + override def | (that: Type)(using Context): Type = that match { case that: TypeBounds => this | that case _ => super.| (that) } @@ -4559,7 +4560,7 @@ object Types { /** Common supertype of `TypeAlias` and `MatchAlias` */ abstract class AliasingBounds(val alias: Type) extends TypeBounds(alias, alias) { - def derivedAlias(alias: Type)(implicit ctx: Context): AliasingBounds + def derivedAlias(alias: Type)(using Context): AliasingBounds override def computeHash(bs: Binders): Int = doHash(bs, alias) override def hashIsStable: Boolean = alias.hashIsStable @@ -4580,7 +4581,7 @@ object Types { /** = T */ class TypeAlias(alias: Type) extends AliasingBounds(alias) { - def derivedAlias(alias: Type)(implicit ctx: Context): AliasingBounds = + def derivedAlias(alias: Type)(using Context): AliasingBounds = if (alias eq this.alias) this else TypeAlias(alias) } @@ -4592,26 +4593,26 @@ object Types { * aliases (or else take the jump and allow full recursive types). */ class MatchAlias(alias: Type) extends AliasingBounds(alias) { - def derivedAlias(alias: Type)(implicit ctx: Context): AliasingBounds = + def derivedAlias(alias: Type)(using Context): AliasingBounds = if (alias eq this.alias) this else MatchAlias(alias) } object TypeBounds { - def apply(lo: Type, hi: Type)(implicit ctx: Context): TypeBounds = + def apply(lo: Type, hi: Type)(using Context): TypeBounds = unique(new RealTypeBounds(lo, hi)) - def empty(implicit ctx: Context): TypeBounds = apply(defn.NothingType, defn.AnyType) - def emptyPolyKind(implicit ctx: Context): TypeBounds = apply(defn.NothingType, defn.AnyKindType) - def upper(hi: Type)(implicit ctx: Context): TypeBounds = apply(defn.NothingType, hi) - def lower(lo: Type)(implicit ctx: Context): TypeBounds = apply(lo, defn.AnyType) + def empty(using Context): TypeBounds = apply(defn.NothingType, defn.AnyType) + def emptyPolyKind(using Context): TypeBounds = apply(defn.NothingType, defn.AnyKindType) + def upper(hi: Type)(using Context): TypeBounds = apply(defn.NothingType, hi) + def lower(lo: Type)(using Context): TypeBounds = apply(lo, defn.AnyType) } object TypeAlias { - def apply(alias: Type)(implicit ctx: Context): TypeAlias = unique(new TypeAlias(alias)) + def apply(alias: Type)(using Context): TypeAlias = unique(new TypeAlias(alias)) def unapply(tp: TypeAlias): Option[Type] = Some(tp.alias) } object MatchAlias { - def apply(alias: Type)(implicit ctx: Context): MatchAlias = unique(new MatchAlias(alias)) + def apply(alias: Type)(using Context): MatchAlias = unique(new MatchAlias(alias)) def unapply(tp: MatchAlias): Option[Type] = Some(tp.alias) } @@ -4621,21 +4622,21 @@ object Types { case class AnnotatedType(parent: Type, annot: Annotation) extends UncachedProxyType with ValueType { // todo: cache them? but this makes only sense if annotations and trees are also cached. - override def underlying(implicit ctx: Context): Type = parent + override def underlying(using Context): Type = parent def derivedAnnotatedType(parent: Type, annot: Annotation): AnnotatedType = if ((parent eq this.parent) && (annot eq this.annot)) this else AnnotatedType(parent, annot) - override def stripTypeVar(implicit ctx: Context): Type = + override def stripTypeVar(using Context): Type = derivedAnnotatedType(parent.stripTypeVar, annot) - override def stripAnnots(implicit ctx: Context): Type = parent.stripAnnots + override def stripAnnots(using Context): Type = parent.stripAnnots private var isRefiningKnown = false private var isRefiningCache: Boolean = _ - def isRefining(implicit ctx: Context): Boolean = { + def isRefining(using Context): Boolean = { if (!isRefiningKnown) { isRefiningCache = annot.symbol.derivesFrom(defn.RefiningAnnotationClass) isRefiningKnown = true @@ -4660,7 +4661,7 @@ object Types { /** The type of an erased array */ abstract case class JavaArrayType(elemType: Type) extends CachedGroundType with ValueType { - def derivedJavaArrayType(elemtp: Type)(implicit ctx: Context): JavaArrayType = + def derivedJavaArrayType(elemtp: Type)(using Context): JavaArrayType = if (elemtp eq this.elemType) this else JavaArrayType(elemtp) override def computeHash(bs: Binders): Int = doHash(bs, elemType) @@ -4673,7 +4674,7 @@ object Types { } final class CachedJavaArrayType(elemType: Type) extends JavaArrayType(elemType) object JavaArrayType { - def apply(elemType: Type)(implicit ctx: Context): JavaArrayType = unique(new CachedJavaArrayType(elemType)) + def apply(elemType: Type)(using Context): JavaArrayType = unique(new CachedJavaArrayType(elemType)) } /** The type of an import clause tree */ @@ -4695,7 +4696,7 @@ object Types { abstract class FlexType extends UncachedGroundType with ValueType abstract class ErrorType extends FlexType { - def msg(implicit ctx: Context): Message + def msg(using Context): Message } object ErrorType: @@ -4710,7 +4711,7 @@ object Types { end ErrorType object UnspecifiedErrorType extends ErrorType { - override def msg(implicit ctx: Context): Message = "unspecified error" + override def msg(using Context): Message = "unspecified error" } /* Type used to track Select nodes that could not resolve a member and their qualifier is a scala.Dynamic. */ @@ -4718,7 +4719,7 @@ object Types { /** Wildcard type, possibly with bounds */ abstract case class WildcardType(optBounds: Type) extends CachedGroundType with TermType { - def derivedWildcardType(optBounds: Type)(implicit ctx: Context): WildcardType = + def derivedWildcardType(optBounds: Type)(using Context): WildcardType = if (optBounds eq this.optBounds) this else if (!optBounds.exists) WildcardType else WildcardType(optBounds.asInstanceOf[TypeBounds]) @@ -4742,7 +4743,7 @@ object Types { final class CachedWildcardType(optBounds: Type) extends WildcardType(optBounds) @sharable object WildcardType extends WildcardType(NoType) { - def apply(bounds: TypeBounds)(implicit ctx: Context): WildcardType = unique(new CachedWildcardType(bounds)) + def apply(bounds: TypeBounds)(using Context): WildcardType = unique(new CachedWildcardType(bounds)) } /** An extractor for single abstract method types. @@ -4756,7 +4757,7 @@ object Types { * type of the single abstract method. */ object SAMType { - def zeroParamClass(tp: Type)(implicit ctx: Context): Type = tp match { + def zeroParamClass(tp: Type)(using Context): Type = tp match { case tp: ClassInfo => def zeroParams(tp: Type): Boolean = tp.stripPoly match { case mt: MethodType => mt.paramInfos.isEmpty && !mt.resultType.isInstanceOf[MethodType] @@ -4782,14 +4783,14 @@ object Types { case _ => NoType } - def isInstantiatable(tp: Type)(implicit ctx: Context): Boolean = zeroParamClass(tp) match { + def isInstantiatable(tp: Type)(using Context): Boolean = zeroParamClass(tp) match { case cinfo: ClassInfo => val selfType = cinfo.selfType.asSeenFrom(tp, cinfo.cls) tp <:< selfType case _ => false } - def unapply(tp: Type)(implicit ctx: Context): Option[MethodType] = + def unapply(tp: Type)(using Context): Option[MethodType] = if (isInstantiatable(tp)) { val absMems = tp.possibleSamMethods if (absMems.size == 1) @@ -5072,7 +5073,7 @@ object Types { } /** A type map that maps also parents and self type of a ClassInfo */ - abstract class DeepTypeMap(implicit ctx: Context) extends TypeMap { + abstract class DeepTypeMap(using Context) extends TypeMap { override def mapClassInfo(tp: ClassInfo): ClassInfo = { val prefix1 = this(tp.prefix) val parents1 = tp.parents mapConserve this @@ -5095,7 +5096,7 @@ object Types { * variance < 0 : approximate by lower bound * variance = 0 : propagate bounds to next outer level */ - abstract class ApproximatingTypeMap(implicit ctx: Context) extends TypeMap { thisMap => + abstract class ApproximatingTypeMap(using Context) extends TypeMap { thisMap => protected def range(lo: Type, hi: Type): Type = if (variance > 0) hi @@ -5449,19 +5450,19 @@ object Types { } } - abstract class TypeTraverser(implicit ctx: Context) extends TypeAccumulator[Unit] { + abstract class TypeTraverser(using Context) extends TypeAccumulator[Unit] { def traverse(tp: Type): Unit def apply(x: Unit, tp: Type): Unit = traverse(tp) protected def traverseChildren(tp: Type): Unit = foldOver((), tp) } - class ExistsAccumulator(p: Type => Boolean, forceLazy: Boolean = true)(implicit ctx: Context) extends TypeAccumulator[Boolean] { + class ExistsAccumulator(p: Type => Boolean, forceLazy: Boolean = true)(using Context) extends TypeAccumulator[Boolean] { override def stopAtStatic: Boolean = false def apply(x: Boolean, tp: Type): Boolean = x || p(tp) || (forceLazy || !tp.isInstanceOf[LazyRef]) && foldOver(x, tp) } - class ForeachAccumulator(p: Type => Unit, override val stopAtStatic: Boolean)(implicit ctx: Context) extends TypeAccumulator[Unit] { + class ForeachAccumulator(p: Type => Unit, override val stopAtStatic: Boolean)(using Context) extends TypeAccumulator[Unit] { def apply(x: Unit, tp: Type): Unit = foldOver(p(tp), tp) } @@ -5470,7 +5471,7 @@ object Types { override def isEqual(x: Type, y: Type) = x.eq(y) class NamedPartsAccumulator(p: NamedType => Boolean, excludeLowerBounds: Boolean = false) - (implicit ctx: Context) extends TypeAccumulator[mutable.Set[NamedType]] { + (using Context) extends TypeAccumulator[mutable.Set[NamedType]] { override def stopAtStatic: Boolean = false def maybeAdd(x: mutable.Set[NamedType], tp: NamedType): mutable.Set[NamedType] = if (p(tp)) x += tp else x val seen = TypeHashSet() @@ -5502,7 +5503,7 @@ object Types { } } - class isGroundAccumulator(implicit ctx: Context) extends TypeAccumulator[Boolean] { + class isGroundAccumulator(using Context) extends TypeAccumulator[Boolean] { def apply(x: Boolean, tp: Type): Boolean = x && { tp match { case _: TypeParamRef => false @@ -5513,7 +5514,7 @@ object Types { } } - class TypeSizeAccumulator(implicit ctx: Context) extends TypeAccumulator[Int] { + class TypeSizeAccumulator(using Context) extends TypeAccumulator[Int] { val seen = new java.util.IdentityHashMap[Type, Type] def apply(n: Int, tp: Type): Int = if (seen.get(tp) != null) n @@ -5534,7 +5535,7 @@ object Types { } } - class CoveringSetAccumulator(implicit ctx: Context) extends TypeAccumulator[Set[Symbol]] { + class CoveringSetAccumulator(using Context) extends TypeAccumulator[Set[Symbol]] { val seen = new java.util.IdentityHashMap[Type, Type] def apply(cs: Set[Symbol], tp: Type): Set[Symbol] = if (seen.get(tp) != null) cs @@ -5572,12 +5573,12 @@ object Types { * keep(pre, name) implies keep(C.this, name) */ abstract class NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean + def apply(pre: Type, name: Name)(using Context): Boolean } /** A filter for names of abstract types of a given type */ object abstractTypeNameFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = + def apply(pre: Type, name: Name)(using Context): Boolean = name.isTypeName && { val mbr = pre.nonPrivateMember(name) mbr.symbol.is(Deferred) && mbr.info.isInstanceOf[RealTypeBounds] @@ -5586,7 +5587,7 @@ object Types { /** A filter for names of abstract types of a given type */ object nonClassTypeNameFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = + def apply(pre: Type, name: Name)(using Context): Boolean = name.isTypeName && { val mbr = pre.member(name) mbr.symbol.isType && !mbr.symbol.isClass @@ -5595,13 +5596,13 @@ object Types { /** A filter for names of deferred term definitions of a given type */ object abstractTermNameFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = + def apply(pre: Type, name: Name)(using Context): Boolean = name.isTermName && pre.nonPrivateMember(name).hasAltWith(_.symbol.is(Deferred)) } /** A filter for names of type aliases of a given type */ object typeAliasNameFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = + def apply(pre: Type, name: Name)(using Context): Boolean = name.isTypeName && { val mbr = pre.nonPrivateMember(name) mbr.symbol.isAliasType @@ -5609,16 +5610,16 @@ object Types { } object typeNameFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = name.isTypeName + def apply(pre: Type, name: Name)(using Context): Boolean = name.isTypeName } object fieldFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = + def apply(pre: Type, name: Name)(using Context): Boolean = name.isTermName && (pre member name).hasAltWith(!_.symbol.is(Method)) } object takeAllFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = true + def apply(pre: Type, name: Name)(using Context): Boolean = true } object implicitFilter extends NameFilter { @@ -5626,7 +5627,7 @@ object Types { * Implicit filtering is handled specially in computeMemberNames, so * no post-filtering is needed. */ - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = true + def apply(pre: Type, name: Name)(using Context): Boolean = true } // ----- Debug --------------------------------------------------------- @@ -5636,7 +5637,7 @@ object Types { val watchList: List[TypeName] = List[String]( ) map (_.toTypeName) - def isWatched(tp: Type)(implicit ctx: Context): Boolean = tp match { + def isWatched(tp: Type)(using Context): Boolean = tp match { case ref: TypeRef => watchList contains ref.name case _ => false } @@ -5657,7 +5658,7 @@ 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(ctx) + private val keepIfRefining: AnnotatedType => Context => Boolean = tp => ctx => tp.isRefining(using ctx) val isBounds: Type => Boolean = _.isInstanceOf[TypeBounds] } diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala index f9857f581411..afc077753b47 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala @@ -415,7 +415,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT * The tests in sbt `types-in-used-names-a`, `types-in-used-names-b`, * `as-seen-from-a` and `as-seen-from-b` rely on this. */ - private abstract class TypeDependencyTraverser(implicit ctx: Context) extends TypeTraverser()(ctx) { + private abstract class TypeDependencyTraverser(implicit ctx: Context) extends TypeTraverser()(using ctx) { protected def addDependency(symbol: Symbol): Unit val seen = new mutable.HashSet[Type] diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index bfe26e4953f6..c88cd872a6a8 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -298,7 +298,7 @@ object ExplicitOuter { else tpe.prefix case _ => // Need to be careful to dealias before erasure, otherwise we lose prefixes. - outerPrefix(tpe.underlying(ctx.withPhaseNoLater(ctx.erasurePhase))) + outerPrefix(tpe.underlying(using ctx.withPhaseNoLater(ctx.erasurePhase))) } case tpe: TypeProxy => outerPrefix(tpe.underlying) From 717bce779436b38ad5ad075ed54465bccd54319f Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 8 Jul 2020 23:02:32 +0200 Subject: [PATCH 02/41] Convert Symbols to using clauses --- .../tools/backend/jvm/BTypesFromSymbols.scala | 8 +- .../backend/jvm/DottyBackendInterface.scala | 10 +- compiler/src/dotty/tools/dotc/ast/tpd.scala | 2 +- .../src/dotty/tools/dotc/core/Symbols.scala | 110 +++++++++--------- .../core/unpickleScala2/Scala2Unpickler.scala | 4 +- .../tools/dotc/transform/CapturedVars.scala | 4 +- .../dotc/transform/ExtensionMethods.scala | 2 +- .../dotc/transform/TransformByNameApply.scala | 2 +- .../dotc/transform/init/Summarization.scala | 2 +- .../dotty/tools/dotc/typer/RefChecks.scala | 2 +- tests/pos-with-compiler/i143.scala | 2 +- tests/pos/inlinetuple.scala | 7 ++ 12 files changed, 84 insertions(+), 71 deletions(-) create mode 100644 tests/pos/inlinetuple.scala diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index 9bf597ce99fb..0ad9911cc4f5 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala @@ -8,6 +8,7 @@ import scala.collection.mutable import scala.collection.generic.Clearable import dotty.tools.dotc.core.Flags._ +import dotty.tools.dotc.core.Contexts.inContext import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Phases.Phase import dotty.tools.dotc.transform.SymUtils._ @@ -228,8 +229,9 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { // After lambdalift (which is where we are), the rawowoner field contains the enclosing class. val enclosingClassSym = { if (innerClassSym.isClass) { - val ct = ctx.withPhase(ctx.flattenPhase.prev) - toDenot(innerClassSym)(ct).owner.enclosingClass(ct) + inContext(ctx.withPhase(ctx.flattenPhase.prev)) { + toDenot(innerClassSym).owner.enclosingClass + } } else innerClassSym.enclosingClass(ctx.withPhase(ctx.flattenPhase.prev)) } //todo is handled specially for JavaDefined symbols in scalac @@ -255,7 +257,7 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { if (innerClassSym.isAnonymousClass || innerClassSym.isAnonymousFunction) None else { val original = innerClassSym.initial - Some(innerClassSym.name(ctx.withPhase(original.validFor.phaseId)).mangledString) // moduleSuffix for module classes + Some(innerClassSym.name(using ctx.withPhase(original.validFor.phaseId)).mangledString) // moduleSuffix for module classes } } diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index 467d25d0ab83..b39e68646250 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -137,8 +137,9 @@ object DottyBackendInterface { // for example by specialization val original = toDenot(sym).initial val validity = original.validFor - val shiftedContext = ctx.withPhase(validity.phaseId) - toDenot(sym)(shiftedContext).isStatic(shiftedContext) + inContext(ctx.withPhase(validity.phaseId)) { + toDenot(sym).isStatic + } } @@ -148,8 +149,9 @@ object DottyBackendInterface { // it is very tricky in presence of classes(and annonymous classes) defined inside supper calls. if (sym.exists) { val validity = toDenot(sym).initial.validFor - val shiftedContext = ctx.withPhase(validity.phaseId) - toDenot(sym)(shiftedContext).lexicallyEnclosingClass(shiftedContext) + inContext(ctx.withPhase(validity.phaseId)) { + toDenot(sym).lexicallyEnclosingClass + } } else NoSymbol /** diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 24f4ba55a6df..129c31ff1874 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -833,7 +833,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { def traverse(tree: Tree)(implicit ctx: Context) = tree match { case tree: DefTree => val sym = tree.symbol - val prevDenot = sym.denot(ctx.withPhase(trans)) + val prevDenot = sym.denot(using ctx.withPhase(trans)) if (prevDenot.effectiveOwner == from.skipWeakOwner) { val d = sym.copySymDenotation(owner = to) d.installAfter(trans) diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index 7b82ec25a368..721cdf5543a5 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -44,11 +44,11 @@ trait Symbols { thisCtx: Context => * 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)(implicit ctx: Context): Symbol { type ThisName = N } = + def newNakedSymbol[N <: Name](coord: Coord = NoCoord)(using Context): Symbol { type ThisName = N } = new Symbol(coord, ctx.nextSymId).asInstanceOf[Symbol { type ThisName = N }] /** Create a class symbol without a denotation. */ - def newNakedClassSymbol(coord: Coord = NoCoord, assocFile: AbstractFile = null)(implicit ctx: Context): ClassSymbol = + def newNakedClassSymbol(coord: Coord = NoCoord, assocFile: AbstractFile = null)(using Context): ClassSymbol = new ClassSymbol(coord, assocFile, ctx.nextSymId) // ---- Symbol creation methods ---------------------------------- @@ -122,7 +122,7 @@ trait Symbols { thisCtx: Context => coord: Coord = NoCoord, assocFile: AbstractFile = null): ClassSymbol = { def completer = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + 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) @@ -336,7 +336,7 @@ trait Symbols { thisCtx: Context => } val completer = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + 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 @@ -455,14 +455,14 @@ object Symbols { if (myDefTree == null) tpd.EmptyTree else myDefTree /** Set defining tree if this symbol retains its definition tree */ - def defTree_=(tree: Tree)(implicit ctx: Context): Unit = + def defTree_=(tree: Tree)(using Context): Unit = if (retainsDefTree) myDefTree = tree /** Does this symbol retain its definition tree? * A good policy for this needs to balance costs and benefits, where * costs are mainly memoty leaks, in particular across runs. */ - def retainsDefTree(implicit ctx: Context): Boolean = + def retainsDefTree(using Context): Boolean = ctx.settings.YretainTrees.value || denot.owner.isTerm || // no risk of leaking memory after a run for these denot.isOneOf(InlineOrProxy) || // need to keep inline info @@ -481,20 +481,20 @@ object Symbols { } /** The current denotation of this symbol */ - final def denot(implicit ctx: Context): SymDenotation = { + final def denot(using Context): SymDenotation = { val lastd = lastDenot if (checkedPeriod == ctx.period) lastd else computeDenot(lastd) } - private def computeDenot(lastd: SymDenotation)(implicit ctx: Context): SymDenotation = { + private def computeDenot(lastd: SymDenotation)(using Context): SymDenotation = { val now = ctx.period checkedPeriod = now if (lastd.validFor contains now) lastd else recomputeDenot(lastd) } /** Overridden in NoSymbol */ - protected def recomputeDenot(lastd: SymDenotation)(implicit ctx: Context): SymDenotation = { + protected def recomputeDenot(lastd: SymDenotation)(using Context): SymDenotation = { val newd = lastd.current.asInstanceOf[SymDenotation] lastDenot = newd newd @@ -512,14 +512,14 @@ object Symbols { if (lastDenot == null) NoRunId else lastDenot.validFor.runId /** Does this symbol come from a currently compiled source file? */ - final def isDefinedInCurrentRun(implicit ctx: Context): Boolean = + final def isDefinedInCurrentRun(using Context): Boolean = span.exists && defRunId == ctx.runId && { val file = associatedFile file != null && ctx.run.files.contains(file) } /** Is symbol valid in current run? */ - final def isValidInCurrentRun(implicit ctx: Context): Boolean = + final def isValidInCurrentRun(using Context): Boolean = (lastDenot.validFor.runId == ctx.runId || ctx.stillValid(lastDenot)) && (lastDenot.symbol eq this) // the last condition is needed because under ctx.staleOK overwritten @@ -527,15 +527,15 @@ object Symbols { // periods check out OK. But once a package member is overridden it is not longer // valid. If the option would be removed, the check would be no longer needed. - final def isTerm(implicit ctx: Context): Boolean = + final def isTerm(using Context): Boolean = (if (defRunId == ctx.runId) lastDenot else denot).isTerm - final def isType(implicit ctx: Context): Boolean = + final def isType(using Context): Boolean = (if (defRunId == ctx.runId) lastDenot else denot).isType - final def asTerm(implicit ctx: Context): TermSymbol = { + final def asTerm(using Context): TermSymbol = { assert(isTerm, s"asTerm called on not-a-Term $this" ); asInstanceOf[TermSymbol] } - final def asType(implicit ctx: Context): TypeSymbol = { + final def asType(using Context): TypeSymbol = { assert(isType, s"isType called on not-a-Type $this"); asInstanceOf[TypeSymbol] } @@ -547,29 +547,29 @@ object Symbols { * conservatively returns `false` if symbol does not yet have a denotation, or denotation * is a class that is not yet read. */ - final def isPrivate(implicit ctx: Context): Boolean = { + final def isPrivate(using Context): Boolean = { val d = lastDenot d != null && d.flagsUNSAFE.is(Private) } /** Is the symbol a pattern bound symbol? */ - final def isPatternBound(implicit ctx: Context): Boolean = + final def isPatternBound(using Context): Boolean = !isClass && this.is(Case, butNot = Enum | Module) /** The symbol's signature if it is completed or a method, NotAMethod otherwise. */ - final def signature(implicit ctx: Context): Signature = + final def signature(using Context): Signature = if (lastDenot != null && (lastDenot.isCompleted || lastDenot.is(Method))) denot.signature else Signature.NotAMethod /** Special cased here, because it may be used on naked symbols in substituters */ - final def isStatic(implicit ctx: Context): Boolean = + final def isStatic(using Context): Boolean = lastDenot != null && lastDenot.initial.isStatic /** This symbol entered into owner's scope (owner must be a class). */ - final def entered(implicit ctx: Context): this.type = { + final def entered(using Context): this.type = { if (this.owner.isClass) { this.owner.asClass.enter(this) if (this.is(Module)) this.owner.asClass.enter(this.moduleClass) @@ -582,8 +582,9 @@ object Symbols { * that starts being valid after `phase`. * @pre Symbol is a class member */ - def enteredAfter(phase: DenotTransformer)(implicit ctx: Context): this.type = - if (ctx.phaseId != phase.next.id) enteredAfter(phase)(ctx.withPhase(phase.next)) + def enteredAfter(phase: DenotTransformer)(using Context): this.type = + if ctx.phaseId != phase.next.id then + enteredAfter(phase)(using ctx.withPhase(phase.next)) else this.owner match { case owner: ClassSymbol => if (owner.is(Package)) { @@ -597,7 +598,7 @@ object Symbols { } /** Remove symbol from scope of owning class */ - final def drop()(implicit ctx: Context): Unit = { + final def drop()(using Context): Unit = { this.owner.asClass.delete(this) if (this.is(Module)) this.owner.asClass.delete(this.moduleClass) } @@ -606,8 +607,9 @@ object Symbols { * denotation for its owner class if the class has not yet already one that starts being valid after `phase`. * @pre Symbol is a class member */ - def dropAfter(phase: DenotTransformer)(implicit ctx: Context): Unit = - if (ctx.phaseId != phase.next.id) dropAfter(phase)(ctx.withPhase(phase.next)) + def dropAfter(phase: DenotTransformer)(using Context): Unit = + if ctx.phaseId != phase.next.id then + dropAfter(phase)(using ctx.withPhase(phase.next)) else { assert (!this.owner.is(Package)) this.owner.asClass.ensureFreshScopeAfter(phase) @@ -616,24 +618,24 @@ object Symbols { } /** This symbol, if it exists, otherwise the result of evaluating `that` */ - def orElse(that: => Symbol)(implicit ctx: Context): Symbol = + def orElse(that: => Symbol)(using Context): Symbol = if (this.exists) this else that /** If this symbol satisfies predicate `p` this symbol, otherwise `NoSymbol` */ def filter(p: Symbol => Boolean): Symbol = if (p(this)) this else NoSymbol /** The current name of this symbol */ - final def name(implicit ctx: Context): ThisName = denot.name.asInstanceOf[ThisName] + final def name(using Context): ThisName = denot.name.asInstanceOf[ThisName] /** The source or class file from which this class or * the class containing this symbol was generated, null if not applicable. * Overridden in ClassSymbol */ - def associatedFile(implicit ctx: Context): AbstractFile = + def associatedFile(using Context): AbstractFile = if (lastDenot == null) null else lastDenot.topLevelClass.associatedFile /** The class file from which this class was generated, null if not applicable. */ - final def binaryFile(implicit ctx: Context): AbstractFile = { + final def binaryFile(using Context): AbstractFile = { val file = associatedFile if (file != null && file.extension == "class") file else null } @@ -646,7 +648,7 @@ object Symbols { final def symbol(implicit ev: DontUseSymbolOnSymbol): Nothing = unsupported("symbol") type DontUseSymbolOnSymbol - final def source(implicit ctx: Context): SourceFile = { + final def source(using Context): SourceFile = { def valid(src: SourceFile): SourceFile = if (src.exists && src.file.extension != "class") src else NoSource @@ -672,7 +674,7 @@ object Symbols { * * @see enclosingSourceSymbols */ - @annotation.tailrec final def sourceSymbol(implicit ctx: Context): Symbol = + @annotation.tailrec final def sourceSymbol(using Context): Symbol = if (!denot.exists) this else if (denot.is(ModuleVal)) @@ -693,7 +695,7 @@ object Symbols { */ final def span: Span = if (coord.isSpan) coord.toSpan else NoSpan - final def sourcePos(implicit ctx: Context): SourcePosition = { + final def sourcePos(using Context): SourcePosition = { val src = source (if (src.exists) src else ctx.source).atSpan(span) } @@ -718,12 +720,12 @@ object Symbols { def toText(printer: Printer): Text = printer.toText(this) - def showLocated(implicit ctx: Context): String = ctx.printer.locatedText(this).show - def showExtendedLocation(implicit ctx: Context): String = ctx.printer.extendedLocationText(this).show - def showDcl(implicit ctx: Context): String = ctx.printer.dclText(this).show - def showKind(implicit ctx: Context): String = ctx.printer.kindString(this) - def showName(implicit ctx: Context): String = ctx.printer.nameString(this) - def showFullName(implicit ctx: Context): String = ctx.printer.fullNameString(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. } @@ -744,13 +746,13 @@ object Symbols { * Returns the TypeDef tree (possibly wrapped inside PackageDefs) for this class, otherwise EmptyTree. * This will force the info of the class. */ - def rootTree(implicit ctx: Context): Tree = rootTreeContaining("") + 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)(implicit ctx: Context): Tree = { + def rootTreeContaining(id: String)(using Context): Tree = { denot.infoOrCompleter match { case _: NoCompleter => case _ => denot.ensureCompleted() @@ -770,10 +772,10 @@ object Symbols { def rootTreeOrProvider: TreeOrProvider = myTree - private[dotc] def rootTreeOrProvider_=(t: TreeOrProvider)(implicit ctx: Context): Unit = + private[dotc] def rootTreeOrProvider_=(t: TreeOrProvider)(using Context): Unit = myTree = t - private def mightContain(tree: Tree, id: String)(implicit ctx: Context): Boolean = { + private def mightContain(tree: Tree, id: String)(using Context): Boolean = { val ids = tree.getAttachment(Ids) match { case Some(ids) => ids case None => @@ -791,20 +793,20 @@ object Symbols { } /** The source or class file from which this class was generated, null if not applicable. */ - override def associatedFile(implicit ctx: Context): AbstractFile = + 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(implicit ctx: Context): SourceFile = { + 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(implicit ctx: Context) = + 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) @@ -812,26 +814,26 @@ object Symbols { } case none => NoSource } - sourceFromTopLevel(ctx.withPhaseNoLater(ctx.flattenPhase)) + sourceFromTopLevel(using ctx.withPhaseNoLater(ctx.flattenPhase)) } } mySource } - final def classDenot(implicit ctx: Context): ClassDenotation = + 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(implicit ctx: Context): AbstractFile = NoSource.file - override def recomputeDenot(lastd: SymDenotation)(implicit ctx: Context): SymDenotation = NoDenotation + 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 })(implicit ctx: Context) { + 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`. @@ -856,16 +858,16 @@ object Symbols { } /** Makes all denotation operations available on symbols */ - implicit def toDenot(sym: Symbol)(implicit ctx: Context): SymDenotation = sym.denot + implicit def toDenot(sym: Symbol)(using Context): SymDenotation = sym.denot /** Makes all class denotation operations available on class symbols */ - implicit def toClassDenot(cls: ClassSymbol)(implicit ctx: Context): ClassDenotation = cls.classDenot + implicit def toClassDenot(cls: ClassSymbol)(using Context): ClassDenotation = cls.classDenot /** The Definitions object */ - def defn(implicit ctx: Context): Definitions = ctx.definitions + def defn(using Context): Definitions = ctx.definitions /** The current class */ - def currentClass(implicit ctx: Context): ClassSymbol = ctx.owner.enclosingClass.asClass + 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 { diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index 17280667cb6f..dbaf5ee66185 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -147,12 +147,12 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas import Scala2Unpickler._ - val moduleRoot: SymDenotation = moduleClassRoot.sourceModule(ictx).denot(ictx) + val moduleRoot: SymDenotation = inContext(ictx) { moduleClassRoot.sourceModule.denot } assert(moduleRoot.isTerm) checkVersion(ictx) - private val loadingMirror = defn(ictx) // was: mirrorThatLoaded(classRoot) + private val loadingMirror = defn(using ictx) // was: mirrorThatLoaded(classRoot) /** A map from entry numbers to array offsets */ private val index = createIndex diff --git a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala index 5d639c82704a..e32c2e981a13 100644 --- a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala +++ b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala @@ -93,7 +93,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = override def prepareForValDef(vdef: ValDef)(implicit ctx: Context): Context = { val sym = vdef.symbol(ctx.withPhase(thisPhase)) if (captured contains sym) { - val newd = sym.denot(ctx.withPhase(thisPhase)).copySymDenotation( + val newd = sym.denot(using ctx.withPhase(thisPhase)).copySymDenotation( info = refClass(sym.info.classSymbol, sym.hasAnnotation(defn.VolatileAnnot)).typeRef, initFlags = sym.flags &~ Mutable) newd.removeAnnotation(defn.VolatileAnnot) @@ -117,7 +117,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = override def transformIdent(id: Ident)(implicit ctx: Context): Tree = { val vble = id.symbol if (captured.contains(vble)) - id.select(nme.elem).ensureConforms(vble.denot(ctx.withPhase(thisPhase)).info) + id.select(nme.elem).ensureConforms(vble.denot(using ctx.withPhase(thisPhase)).info) else id } diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index c6b53b158123..3b8cdad45230 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 = cls.denot(ctx.withPhase(ctx.phase.next)).asClass.classInfo.derivedClassInfo(prefix = pre) + val info1 = cls.denot(using ctx.withPhase(ctx.phase.next)).asClass.classInfo.derivedClassInfo(prefix = pre) ref.derivedSingleDenotation(ref.symbol, info1) case _ => ref } diff --git a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala index 1835012e8d7a..d96a9fe49a2d 100644 --- a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala @@ -23,7 +23,7 @@ abstract class TransformByNameApply extends MiniPhase { thisPhase: DenotTransfor /** The info of the tree's symbol before it is potentially transformed in this phase */ private def originalDenotation(tree: Tree)(implicit ctx: Context) = - tree.symbol.denot(ctx.withPhase(thisPhase)) + tree.symbol.denot(using ctx.withPhase(thisPhase)) /** If denotation had an ExprType before, it now gets a function type */ protected def exprBecomesFunction(symd: SymDenotation)(implicit ctx: Context): Boolean = diff --git a/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala b/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala index 64f1312652bb..924f23444804 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Summarization.scala @@ -327,7 +327,7 @@ object Summarization { cls.info match { case cinfo: ClassInfo => val source = { - implicit val ctx2: Context = theCtx.withSource(cls.source(theCtx)) + implicit val ctx2: Context = theCtx.withSource(cls.source(using theCtx)) TypeTree(cls.typeRef).withSpan(cls.span) } diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index f0d8cb4e6e4f..5a834820c0fc 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -534,7 +534,7 @@ object RefChecks { // Give a specific error message for abstract vars based on why it fails: // It could be unimplemented, have only one accessor, or be uninitialized. if (underlying.is(Mutable)) { - val isMultiple = grouped.getOrElse(underlying.name(ctx), Nil).size > 1 + val isMultiple = grouped.getOrElse(underlying.name, Nil).size > 1 // If both getter and setter are missing, squelch the setter error. if (member.isSetter && isMultiple) () diff --git a/tests/pos-with-compiler/i143.scala b/tests/pos-with-compiler/i143.scala index 1cbccc281d42..c7863d45b90f 100644 --- a/tests/pos-with-compiler/i143.scala +++ b/tests/pos-with-compiler/i143.scala @@ -7,6 +7,6 @@ import dotty.tools.dotc.core.Contexts._ class TC5(val ctx: Context) extends AnyVal { def candidates(mbr: SingleDenotation): Boolean = { - mbr.symbol.denot(ctx).exists + mbr.symbol.denot(using ctx).exists } } diff --git a/tests/pos/inlinetuple.scala b/tests/pos/inlinetuple.scala new file mode 100644 index 000000000000..62680108e161 --- /dev/null +++ b/tests/pos/inlinetuple.scala @@ -0,0 +1,7 @@ +object Test: + + def g(x: Int, y: Int) = x + y + inline def f(inline x: (Int, Int)) = g(x._1, x._2) + + val x = f((1, 2)) + From 7330e7f07730a3427790fc5d031c8c5d19b57a2f Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Wed, 8 Jul 2020 23:28:58 +0200 Subject: [PATCH 03/41] Convert Denotations to using clauses --- .../tools/backend/jvm/BTypesFromSymbols.scala | 2 +- .../dotty/tools/dotc/core/Denotations.scala | 158 +++---- .../tools/dotc/core/SymDenotations.scala | 411 +++++++++--------- .../dotc/core/classfile/ClassfileParser.scala | 2 +- .../dotty/tools/dotc/transform/Erasure.scala | 2 +- .../dotc/transform/ExtensionMethods.scala | 2 +- 6 files changed, 289 insertions(+), 288 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index 0ad9911cc4f5..02bb27f7234d 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala @@ -233,7 +233,7 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { toDenot(innerClassSym).owner.enclosingClass } } - else innerClassSym.enclosingClass(ctx.withPhase(ctx.flattenPhase.prev)) + else innerClassSym.enclosingClass(using ctx.withPhase(ctx.flattenPhase.prev)) } //todo is handled specially for JavaDefined symbols in scalac val enclosingClass: ClassBType = classBTypeFromSymbol(enclosingClassSym) diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index 37c487f64982..465101fe3f5f 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -3,7 +3,7 @@ package dotc package core import SymDenotations.{ SymDenotation, ClassDenotation, NoDenotation, LazyType } -import Contexts.{Context, ContextBase} +import Contexts.{Context, Ctx, ctx, ContextBase} import Names._ import NameKinds._ import StdNames._ @@ -86,13 +86,13 @@ object Denotations { def last: Denotation /** Convert to full denotation by &-ing all elements */ - def toDenot(pre: Type)(implicit ctx: Context): Denotation + def toDenot(pre: Type)(using Context): Denotation /** Group contains a denotation that refers to given symbol */ def containsSym(sym: Symbol): Boolean /** Group contains a denotation with the same signature as `other` */ - def matches(other: SingleDenotation)(implicit ctx: Context): Boolean + def matches(other: SingleDenotation)(using Context): Boolean /** Keep only those denotations in this group which satisfy predicate `p`. */ def filterWithPredicate(p: SingleDenotation => Boolean): PreDenotation @@ -100,7 +100,7 @@ object Denotations { /** Keep only those denotations in this group which have a signature * that's not already defined by `denots`. */ - def filterDisjoint(denots: PreDenotation)(implicit ctx: Context): PreDenotation + def filterDisjoint(denots: PreDenotation)(using Context): PreDenotation /** Keep only those inherited members M of this predenotation for which the following is true * - M is not marked Private @@ -112,12 +112,12 @@ object Denotations { * `prevDenots` are the denotations that are defined in the class or inherited from * a base type which comes earlier in the linearization. */ - def mapInherited(ownDenots: PreDenotation, prevDenots: PreDenotation, pre: Type)(implicit ctx: Context): PreDenotation + def mapInherited(ownDenots: PreDenotation, prevDenots: PreDenotation, pre: Type)(using Context): PreDenotation /** Keep only those denotations in this group that have all of the flags in `required`, * but none of the flags in `excluded`. */ - def filterWithFlags(required: FlagSet, excluded: FlagSet)(implicit ctx: Context): PreDenotation + def filterWithFlags(required: FlagSet, excluded: FlagSet)(using Context): PreDenotation /** Map `f` over all single denotations and aggregate the results with `g`. */ def aggregate[T](f: SingleDenotation => T, g: (T, T) => T): T @@ -129,7 +129,7 @@ object Denotations { type AsSeenFromResult <: PreDenotation /** The denotation with info(s) as seen from prefix type */ - final def asSeenFrom(pre: Type)(implicit ctx: Context): AsSeenFromResult = + final def asSeenFrom(pre: Type)(using Context): AsSeenFromResult = if (Config.cacheAsSeenFrom) { if ((cachedPrefix ne pre) || ctx.period != validAsSeenFrom) { cachedAsSeenFrom = computeAsSeenFrom(pre) @@ -140,7 +140,7 @@ object Denotations { } else computeAsSeenFrom(pre) - protected def computeAsSeenFrom(pre: Type)(implicit ctx: Context): AsSeenFromResult + protected def computeAsSeenFrom(pre: Type)(using Context): AsSeenFromResult /** The union of two groups. */ def union(that: PreDenotation): PreDenotation = @@ -183,7 +183,7 @@ object Denotations { * The info is an instance of TypeType iff this is a type denotation * Uncompleted denotations set myInfo to a LazyType. */ - final def info(implicit ctx: Context): Type = { + final def info(using Context): Type = { def completeInfo = { // Written this way so that `info` is small enough to be inlined this.asInstanceOf[SymDenotation].completeFrom(myInfo.asInstanceOf[LazyType]); info } @@ -213,28 +213,28 @@ object Denotations { def hasUniqueSym: Boolean /** The name of the denotation */ - def name(implicit ctx: Context): Name + def name(using Context): Name /** The signature of the denotation. */ - def signature(implicit ctx: Context): Signature + def signature(using Context): Signature /** Resolve overloaded denotation to pick the ones with the given signature * when seen from prefix `site`. * @param relaxed When true, consider only parameter signatures for a match. */ - def atSignature(sig: Signature, site: Type = NoPrefix, relaxed: Boolean = false)(implicit ctx: Context): Denotation + def atSignature(sig: Signature, site: Type = NoPrefix, relaxed: Boolean = false)(using Context): Denotation /** The variant of this denotation that's current in the given context. * If no such denotation exists, returns the denotation with each alternative * at its first point of definition. */ - def current(implicit ctx: Context): Denotation + def current(using Context): Denotation /** Is this denotation different from NoDenotation or an ErrorDenotation? */ def exists: Boolean = true /** A denotation with the info of this denotation transformed using `f` */ - def mapInfo(f: Type => Type)(implicit ctx: Context): Denotation + def mapInfo(f: Type => Type)(using Context): Denotation /** If this denotation does not exist, fallback to alternative */ final def orElse(that: => Denotation): Denotation = if (this.exists) this else that @@ -249,12 +249,12 @@ object Denotations { * or NoDenotation if no satisfying alternative exists. * @throws TypeError if there is at more than one alternative that satisfies `p`. */ - def suchThat(p: Symbol => Boolean)(implicit ctx: Context): SingleDenotation + def suchThat(p: Symbol => Boolean)(using Context): SingleDenotation override def filterWithPredicate(p: SingleDenotation => Boolean): Denotation /** If this is a SingleDenotation, return it, otherwise throw a TypeError */ - def checkUnique(implicit ctx: Context): SingleDenotation = suchThat(alwaysTrue) + def checkUnique(using Context): SingleDenotation = suchThat(alwaysTrue) /** Does this denotation have an alternative that satisfies the predicate `p`? */ def hasAltWith(p: SingleDenotation => Boolean): Boolean @@ -262,13 +262,13 @@ object Denotations { /** The denotation made up from the alternatives of this denotation that * are accessible from prefix `pre`, or NoDenotation if no accessible alternative exists. */ - def accessibleFrom(pre: Type, superAccess: Boolean = false)(implicit ctx: Context): Denotation + def accessibleFrom(pre: Type, superAccess: Boolean = false)(using Context): Denotation /** Find member of this denotation with given `name`, all `required` * flags and no `excluded` flag, and produce a denotation that contains the type of the member * as seen from given prefix `pre`. */ - def findMember(name: Name, pre: Type, required: FlagSet, excluded: FlagSet)(implicit ctx: Context): Denotation = + def findMember(name: Name, pre: Type, required: FlagSet, excluded: FlagSet)(using Context): Denotation = info.findMember(name, pre, required, excluded) /** If this denotation is overloaded, filter with given predicate. @@ -277,7 +277,7 @@ object Denotations { * single-denotations that do not satisfy the predicate are left alone * (whereas suchThat would map them to NoDenotation). */ - def disambiguate(p: Symbol => Boolean)(implicit ctx: Context): SingleDenotation = this match { + def disambiguate(p: Symbol => Boolean)(using Context): SingleDenotation = this match { case sdenot: SingleDenotation => sdenot case mdenot => suchThat(p) orElse NoQualifyingRef(alternatives) } @@ -293,7 +293,7 @@ object Denotations { source: AbstractFile = null, generateStubs: Boolean = true) (p: Symbol => Boolean) - (implicit ctx: Context): Symbol = + (using Context): Symbol = disambiguate(p) match { case m @ MissingRef(ownerd, name) => if (generateStubs) { @@ -311,14 +311,14 @@ object Denotations { denot.symbol } - def requiredMethod(pname: PreName)(implicit ctx: Context): TermSymbol = { + def requiredMethod(pname: PreName)(using Context): TermSymbol = { val name = pname.toTermName info.member(name).requiredSymbol("method", name, this)(_.is(Method)).asTerm } - def requiredMethodRef(name: PreName)(implicit ctx: Context): TermRef = + def requiredMethodRef(name: PreName)(using Context): TermRef = requiredMethod(name).termRef - def requiredMethod(pname: PreName, argTypes: List[Type])(implicit ctx: Context): TermSymbol = { + def requiredMethod(pname: PreName, argTypes: List[Type])(using Context): TermSymbol = { val name = pname.toTermName info.member(name).requiredSymbol(i"method", name, this, argTypes) { x => x.is(Method) && { @@ -329,22 +329,22 @@ object Denotations { } }.asTerm } - def requiredMethodRef(name: PreName, argTypes: List[Type])(implicit ctx: Context): TermRef = + def requiredMethodRef(name: PreName, argTypes: List[Type])(using Context): TermRef = requiredMethod(name, argTypes).termRef - def requiredValue(pname: PreName)(implicit ctx: Context): TermSymbol = { + def requiredValue(pname: PreName)(using Context): TermSymbol = { val name = pname.toTermName info.member(name).requiredSymbol("field or getter", name, this)(_.info.isParameterless).asTerm } - def requiredValueRef(name: PreName)(implicit ctx: Context): TermRef = + def requiredValueRef(name: PreName)(using Context): TermRef = requiredValue(name).termRef - def requiredClass(pname: PreName)(implicit ctx: Context): ClassSymbol = { + def requiredClass(pname: PreName)(using Context): ClassSymbol = { val name = pname.toTypeName info.member(name).requiredSymbol("class", name, this)(_.isClass).asClass } - def requiredType(pname: PreName)(implicit ctx: Context): TypeSymbol = { + def requiredType(pname: PreName)(using Context): TypeSymbol = { val name = pname.toTypeName info.member(name).requiredSymbol("type", name, this)(_.isType).asType } @@ -352,7 +352,7 @@ object Denotations { /** The alternative of this denotation that has a type matching `targetType` when seen * as a member of type `site`, `NoDenotation` if none exists. */ - def matchingDenotation(site: Type, targetType: Type)(implicit ctx: Context): SingleDenotation = { + def matchingDenotation(site: Type, targetType: Type)(using Context): SingleDenotation = { def qualifies(sym: Symbol) = site.memberInfo(sym).matchesLoosely(targetType) if (isOverloaded) atSignature(targetType.signature, site, relaxed = true) match { @@ -392,7 +392,7 @@ object Denotations { * 5. The symbol's visibility is strictly greater than the other one's. * 6. The symbol is a method, but the other one is not. */ - def meet(that: Denotation, pre: Type, safeIntersection: Boolean = false)(implicit ctx: Context): Denotation = { + def meet(that: Denotation, pre: Type, safeIntersection: Boolean = false)(using Context): Denotation = { /** Try to merge denot1 and denot2 without adding a new signature. */ def mergeDenot(denot1: Denotation, denot2: SingleDenotation): Denotation = denot1 match { case denot1 @ MultiDenotation(denot11, denot12) => @@ -505,7 +505,7 @@ object Denotations { // ------ PreDenotation ops ---------------------------------------------- - final def toDenot(pre: Type)(implicit ctx: Context): Denotation = this + final def toDenot(pre: Type)(using Context): Denotation = this final def containsSym(sym: Symbol): Boolean = hasUniqueSym && (symbol eq sym) } @@ -523,7 +523,7 @@ object Denotations { * the possibility of returning NoType. Special handling of ExprTypes, where mixed * intersections widen the ExprType away. */ - def infoMeet(tp1: Type, tp2: Type, safeIntersection: Boolean)(implicit ctx: Context): Type = + def infoMeet(tp1: Type, tp2: Type, safeIntersection: Boolean)(using Context): Type = if tp1 eq tp2 then tp1 else tp1 match case tp1: TypeBounds => @@ -572,14 +572,14 @@ object Denotations { abstract class SingleDenotation(symbol: Symbol, initInfo: Type) extends Denotation(symbol, initInfo) { protected def newLikeThis(symbol: Symbol, info: Type, pre: Type): SingleDenotation - final def name(implicit ctx: Context): Name = symbol.name + final def name(using Context): Name = symbol.name /** If this is not a SymDenotation: The prefix under which the denotation was constructed. * NoPrefix for SymDenotations. */ def prefix: Type = NoPrefix - final def signature(implicit ctx: Context): Signature = + final def signature(using Context): Signature = if (isType) Signature.NotAMethod // don't force info if this is a type SymDenotation else info match { case info: MethodicType => @@ -592,11 +592,11 @@ object Denotations { case _ => Signature.NotAMethod } - def derivedSingleDenotation(symbol: Symbol, info: Type, pre: Type = this.prefix)(implicit ctx: Context): SingleDenotation = + def derivedSingleDenotation(symbol: Symbol, info: Type, pre: Type = this.prefix)(using Context): SingleDenotation = if ((symbol eq this.symbol) && (info eq this.info) && (pre eq this.prefix)) this else newLikeThis(symbol, info, pre) - def mapInfo(f: Type => Type)(implicit ctx: Context): SingleDenotation = + def mapInfo(f: Type => Type)(using Context): SingleDenotation = derivedSingleDenotation(symbol, f(info)) def orElse(that: => SingleDenotation): SingleDenotation = if (this.exists) this else that @@ -604,16 +604,16 @@ object Denotations { def altsWith(p: Symbol => Boolean): List[SingleDenotation] = if (exists && p(symbol)) this :: Nil else Nil - def suchThat(p: Symbol => Boolean)(implicit ctx: Context): SingleDenotation = + def suchThat(p: Symbol => Boolean)(using Context): SingleDenotation = if (exists && p(symbol)) this else NoDenotation def hasAltWith(p: SingleDenotation => Boolean): Boolean = exists && p(this) - def accessibleFrom(pre: Type, superAccess: Boolean)(implicit ctx: Context): Denotation = + def accessibleFrom(pre: Type, superAccess: Boolean)(using Context): Denotation = if (!symbol.exists || symbol.isAccessibleFrom(pre, superAccess)) this else NoDenotation - def atSignature(sig: Signature, site: Type, relaxed: Boolean)(implicit ctx: Context): SingleDenotation = + def atSignature(sig: Signature, site: Type, relaxed: Boolean)(using Context): SingleDenotation = val situated = if site == NoPrefix then this else asSeenFrom(site) val matches = sig.matchDegree(situated.signature) match case FullMatch => @@ -627,7 +627,7 @@ object Denotations { false if matches then this else NoDenotation - def matchesImportBound(bound: Type)(implicit ctx: Context): Boolean = + def matchesImportBound(bound: Type)(using Context): Boolean = if bound.isRef(defn.NothingClass) then false else if bound.isAny then true else NoViewsAllowed.normalizedCompatible(info, bound, keepConstraint = false) @@ -684,7 +684,7 @@ object Denotations { /** Invalidate all caches and fields that depend on base classes and their contents */ def invalidateInheritedInfo(): Unit = () - private def updateValidity()(implicit ctx: Context): this.type = { + private def updateValidity()(using Context): this.type = { assert( ctx.runId >= validFor.runId || ctx.settings.YtestPickler.value // mixing test pickler with debug printing can travel back in time @@ -712,7 +712,7 @@ object Denotations { * - If the symbol did not have a denotation that was defined at the current phase * return a NoDenotation instead. */ - private def bringForward()(implicit ctx: Context): SingleDenotation = { + private def bringForward()(using Context): SingleDenotation = { this match { case symd: SymDenotation => if (ctx.stillValid(symd)) return updateValidity() @@ -742,7 +742,7 @@ object Denotations { /** Skip any denotations that have been removed by an installAfter or that * are otherwise undefined. */ - def skipRemoved(implicit ctx: Context): SingleDenotation = + def skipRemoved(using Context): SingleDenotation = if (myValidFor.code <= 0) nextDefined else this /** Produce a denotation that is valid for the given context. @@ -757,7 +757,7 @@ object Denotations { * is brought forward to be valid in the new runId. Otherwise * the symbol is stale, which constitutes an internal error. */ - def current(implicit ctx: Context): SingleDenotation = { + def current(using Context): SingleDenotation = { val currentPeriod = ctx.period val valid = myValidFor if (valid.code <= 0) { @@ -834,14 +834,14 @@ object Denotations { // 10 times. Best out of 10: 18154ms with `prev` field, 17777ms without. cnt += 1 if (cnt > MaxPossiblePhaseId) - return current(ctx.withPhase(coveredInterval.firstPhaseId)) + return current(using ctx.withPhase(coveredInterval.firstPhaseId)) } cur } } } - private def demandOutsideDefinedMsg(implicit ctx: Context): String = + private def demandOutsideDefinedMsg(using Context): String = 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. @@ -849,9 +849,9 @@ object Denotations { * It's placed here because it needs access to private fields of SingleDenotation. * @pre Can only be called in `phase.next`. */ - protected def installAfter(phase: DenotTransformer)(implicit ctx: Context): Unit = { + protected def installAfter(phase: DenotTransformer)(using Context): Unit = { val targetId = phase.next.id - if (ctx.phaseId != targetId) installAfter(phase)(ctx.withPhase(phase.next)) + if (ctx.phaseId != targetId) installAfter(phase)(using ctx.withPhase(phase.next)) else { val current = symbol.current // println(s"installing $this after $phase/${phase.id}, valid = ${current.validFor}") @@ -870,7 +870,7 @@ object Denotations { /** Apply a transformation `f` to all denotations in this group that start at or after * given phase. Denotations are replaced while keeping the same validity periods. */ - protected def transformAfter(phase: DenotTransformer, f: SymDenotation => SymDenotation)(implicit ctx: Context): Unit = { + protected def transformAfter(phase: DenotTransformer, f: SymDenotation => SymDenotation)(using Context): Unit = { var current = symbol.current while (current.validFor.firstPhaseId < phase.id && (current.nextInRun.validFor.code > current.validFor.code)) current = current.nextInRun @@ -911,10 +911,10 @@ object Denotations { nextInRun = newd } - def staleSymbolError(implicit ctx: Context): Nothing = + def staleSymbolError(using Context): Nothing = throw new StaleSymbol(staleSymbolMsg) - def staleSymbolMsg(implicit ctx: Context): String = { + def staleSymbolMsg(using Context): String = { def ownerMsg = this match { case denot: SymDenotation => s"in ${denot.owner}" case _ => "" @@ -925,7 +925,7 @@ object Denotations { /** The period (interval of phases) for which there exists * a valid denotation in this flock. */ - def coveredInterval(implicit ctx: Context): Period = { + def coveredInterval(using Context): Period = { var cur = this var cnt = 0 var interval = validFor @@ -943,7 +943,7 @@ object Denotations { /** Show declaration string; useful for showing declarations * as seen from subclasses. */ - def showDcl(implicit ctx: Context): String = ctx.printer.dclText(this).show + def showDcl(using Context): String = ctx.printer.dclText(this).show override def toString: String = if (symbol == NoSymbol) symbol.toString @@ -969,7 +969,7 @@ object Denotations { final def first: SingleDenotation = this final def last: SingleDenotation = this - final def matches(other: SingleDenotation)(implicit ctx: Context): Boolean = + final def matches(other: SingleDenotation)(using Context): Boolean = val d = signature.matchDegree(other.signature) d match @@ -985,21 +985,21 @@ object Denotations { false end matches - def mapInherited(ownDenots: PreDenotation, prevDenots: PreDenotation, pre: Type)(implicit ctx: Context): SingleDenotation = + def mapInherited(ownDenots: PreDenotation, prevDenots: PreDenotation, pre: Type)(using Context): SingleDenotation = if (hasUniqueSym && prevDenots.containsSym(symbol)) NoDenotation else if (isType) filterDisjoint(ownDenots).asSeenFrom(pre) else asSeenFrom(pre).filterDisjoint(ownDenots) final def filterWithPredicate(p: SingleDenotation => Boolean): SingleDenotation = if (p(this)) this else NoDenotation - final def filterDisjoint(denots: PreDenotation)(implicit ctx: Context): SingleDenotation = + final def filterDisjoint(denots: PreDenotation)(using Context): SingleDenotation = if (denots.exists && denots.matches(this)) NoDenotation else this - def filterWithFlags(required: FlagSet, excluded: FlagSet)(implicit ctx: Context): SingleDenotation = + def filterWithFlags(required: FlagSet, excluded: FlagSet)(using Context): SingleDenotation = if (required.isEmpty && excluded.isEmpty || compatibleWith(required, excluded)) this else NoDenotation def aggregate[T](f: SingleDenotation => T, g: (T, T) => T): T = f(this) type AsSeenFromResult = SingleDenotation - protected def computeAsSeenFrom(pre: Type)(implicit ctx: Context): SingleDenotation = { + protected def computeAsSeenFrom(pre: Type)(using Context): SingleDenotation = { val symbol = this.symbol val owner = this match { case thisd: SymDenotation => thisd.owner @@ -1032,7 +1032,7 @@ object Denotations { /** Does this denotation have all the `required` flags but none of the `excluded` flags? */ - private def compatibleWith(required: FlagSet, excluded: FlagSet)(implicit ctx: Context): Boolean = { + private def compatibleWith(required: FlagSet, excluded: FlagSet)(using Context): Boolean = { val symd: SymDenotation = this match { case symd: SymDenotation => symd case _ => symbol.denot @@ -1068,7 +1068,7 @@ object Denotations { new JointRefDenotation(s, i, validFor, pre) } - class ErrorDenotation(implicit ctx: Context) extends NonSymSingleDenotation(NoSymbol, NoType, NoType) { + class ErrorDenotation(using Context) extends NonSymSingleDenotation(NoSymbol, NoType, NoType) { override def exists: Boolean = false override def hasUniqueSym: Boolean = false validFor = Period.allInRun(ctx.runId) @@ -1079,7 +1079,7 @@ object Denotations { /** An error denotation that provides more info about the missing reference. * Produced by staticRef, consumed by requiredSymbol. */ - case class MissingRef(val owner: SingleDenotation, name: Name)(implicit ctx: Context) extends ErrorDenotation { + case class MissingRef(val owner: SingleDenotation, name: Name)(using Context) extends ErrorDenotation { val ex: Exception = new Exception // DEBUG } @@ -1087,11 +1087,11 @@ object Denotations { * that were found but that do not qualify. * Produced by staticRef, consumed by requiredSymbol. */ - case class NoQualifyingRef(alts: List[SingleDenotation])(implicit ctx: Context) extends ErrorDenotation + case class NoQualifyingRef(alts: List[SingleDenotation])(using Context) extends ErrorDenotation /** A double definition */ - def isDoubleDef(sym1: Symbol, sym2: Symbol)(implicit ctx: Context): Boolean = + def isDoubleDef(sym1: Symbol, sym2: Symbol)(using Context): Boolean = (sym1.exists && sym2.exists && (sym1 `ne` sym2) && (sym1.effectiveOwner `eq` sym2.effectiveOwner) && !sym1.is(Bridge) && !sym2.is(Bridge)) @@ -1105,15 +1105,15 @@ object Denotations { assert(denot1.exists && denot2.exists, s"Union of non-existing denotations ($denot1) and ($denot2)") def first: Denotation = denot1.first def last: Denotation = denot2.last - def matches(other: SingleDenotation)(implicit ctx: Context): Boolean = + def matches(other: SingleDenotation)(using Context): Boolean = denot1.matches(other) || denot2.matches(other) - def mapInherited(owndenot: PreDenotation, prevdenot: PreDenotation, pre: Type)(implicit ctx: Context): PreDenotation = + def mapInherited(owndenot: PreDenotation, prevdenot: PreDenotation, pre: Type)(using Context): PreDenotation = derivedUnion(denot1.mapInherited(owndenot, prevdenot, pre), denot2.mapInherited(owndenot, prevdenot, pre)) def filterWithPredicate(p: SingleDenotation => Boolean): PreDenotation = derivedUnion(denot1 filterWithPredicate p, denot2 filterWithPredicate p) - def filterDisjoint(denot: PreDenotation)(implicit ctx: Context): PreDenotation = + def filterDisjoint(denot: PreDenotation)(using Context): PreDenotation = derivedUnion(denot1 filterDisjoint denot, denot2 filterDisjoint denot) - def filterWithFlags(required: FlagSet, excluded: FlagSet)(implicit ctx: Context): PreDenotation = + def filterWithFlags(required: FlagSet, excluded: FlagSet)(using Context): PreDenotation = derivedUnion(denot1.filterWithFlags(required, excluded), denot2.filterWithFlags(required, excluded)) def aggregate[T](f: SingleDenotation => T, g: (T, T) => T): T = g(denot1.aggregate(f, g), denot2.aggregate(f, g)) @@ -1124,12 +1124,12 @@ object Denotations { final case class DenotUnion(denot1: PreDenotation, denot2: PreDenotation) extends MultiPreDenotation { def exists: Boolean = true - def toDenot(pre: Type)(implicit ctx: Context): Denotation = + def toDenot(pre: Type)(using Context): Denotation = denot1.toDenot(pre).meet(denot2.toDenot(pre), pre) def containsSym(sym: Symbol): Boolean = (denot1 containsSym sym) || (denot2 containsSym sym) type AsSeenFromResult = PreDenotation - def computeAsSeenFrom(pre: Type)(implicit ctx: Context): PreDenotation = + def computeAsSeenFrom(pre: Type)(using Context): PreDenotation = derivedUnion(denot1.asSeenFrom(pre), denot2.asSeenFrom(pre)) } @@ -1140,16 +1140,16 @@ object Denotations { final def validFor: Period = denot1.validFor & denot2.validFor final def isType: Boolean = false final def hasUniqueSym: Boolean = false - final def name(implicit ctx: Context): Name = denot1.name - final def signature(implicit ctx: Context): Signature = Signature.OverloadedSignature - def atSignature(sig: Signature, site: Type, relaxed: Boolean)(implicit ctx: Context): Denotation = + final def name(using Context): Name = denot1.name + final def signature(using Context): Signature = Signature.OverloadedSignature + def atSignature(sig: Signature, site: Type, relaxed: Boolean)(using Context): Denotation = if (sig eq Signature.OverloadedSignature) this else derivedUnionDenotation(denot1.atSignature(sig, site, relaxed), denot2.atSignature(sig, site, relaxed)) - def current(implicit ctx: Context): Denotation = + def current(using Context): Denotation = derivedUnionDenotation(denot1.current, denot2.current) def altsWith(p: Symbol => Boolean): List[SingleDenotation] = denot1.altsWith(p) ++ denot2.altsWith(p) - def suchThat(p: Symbol => Boolean)(implicit ctx: Context): SingleDenotation = { + def suchThat(p: Symbol => Boolean)(using Context): SingleDenotation = { val sd1 = denot1.suchThat(p) val sd2 = denot2.suchThat(p) if sd1.exists then @@ -1165,14 +1165,14 @@ object Denotations { derivedUnionDenotation(denot1.filterWithPredicate(p), denot2.filterWithPredicate(p)) def hasAltWith(p: SingleDenotation => Boolean): Boolean = denot1.hasAltWith(p) || denot2.hasAltWith(p) - def accessibleFrom(pre: Type, superAccess: Boolean)(implicit ctx: Context): Denotation = { + def accessibleFrom(pre: Type, superAccess: Boolean)(using Context): Denotation = { val d1 = denot1 accessibleFrom (pre, superAccess) val d2 = denot2 accessibleFrom (pre, superAccess) if (!d1.exists) d2 else if (!d2.exists) d1 else derivedUnionDenotation(d1, d2) } - def mapInfo(f: Type => Type)(implicit ctx: Context): Denotation = + def mapInfo(f: Type => Type)(using Context): Denotation = derivedUnionDenotation(denot1.mapInfo(f), denot2.mapInfo(f)) def derivedUnionDenotation(d1: Denotation, d2: Denotation): Denotation = if ((d1 eq denot1) && (d2 eq denot2)) this @@ -1180,7 +1180,7 @@ object Denotations { else if (!d2.exists) d1 else MultiDenotation(d1, d2) type AsSeenFromResult = Denotation - def computeAsSeenFrom(pre: Type)(implicit ctx: Context): Denotation = + def computeAsSeenFrom(pre: Type)(using Context): Denotation = derivedUnionDenotation(denot1.asSeenFrom(pre), denot2.asSeenFrom(pre)) override def toString: String = alternatives.mkString(" ") @@ -1197,7 +1197,7 @@ object Denotations { * 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)(implicit ctx: Context): Denotation = { + 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 = @@ -1248,7 +1248,7 @@ object Denotations { * assume it is a package for which we do not have a directory and * enter it. */ - def missingHook(owner: Symbol, name: Name)(implicit ctx: Context): Symbol = + def missingHook(owner: Symbol, name: Name)(using Context): Symbol = if (owner.is(Package) && name.isTermName) ctx.newCompletePackageSymbol(owner, name.asTermName).entered else diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index e5e5c1cad574..d38657ad5616 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -39,7 +39,7 @@ trait SymDenotations { thisCtx: Context => name: Name, initFlags: FlagSet, initInfo: Type, - initPrivateWithin: Symbol = NoSymbol)(implicit ctx: Context): SymDenotation = { + initPrivateWithin: Symbol = NoSymbol)(using Context): SymDenotation = { val result = if (symbol.isClass) if (initFlags.is(Package)) new PackageClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin) @@ -155,14 +155,14 @@ object SymDenotations { def owner: Symbol = maybeOwner /** The flag set */ - final def flags(implicit ctx: Context): FlagSet = { ensureCompleted(); myFlags } + final def flags(using Context): FlagSet = { ensureCompleted(); myFlags } /** The flag set without forcing symbol completion. * Should be used only for printing. */ private[dotc] final def flagsUNSAFE: FlagSet = myFlags - final def flagsString(implicit ctx: Context): String = flags.flagsString + final def flagsString(using Context): String = flags.flagsString /** Adapt flag set to this denotation's term or type nature */ private def adaptFlags(flags: FlagSet) = if (isType) flags.toTypeFlags else flags.toTermFlags @@ -191,37 +191,37 @@ object SymDenotations { if (myInfo.isInstanceOf[SymbolLoader]) FromStartFlags else AfterLoadFlags) - final def relevantFlagsFor(fs: FlagSet)(implicit ctx: Context) = + final def relevantFlagsFor(fs: FlagSet)(using Context) = if (isCurrent(fs)) myFlags else flags /** Has this denotation one of given flag set? */ - final def is(flag: Flag)(implicit ctx: Context): Boolean = + final def is(flag: Flag)(using Context): Boolean = (if (isCurrent(flag)) myFlags else flags).is(flag) /** Has this denotation one of the flags in `fs` set? */ - final def isOneOf(fs: FlagSet)(implicit ctx: Context): Boolean = + final def isOneOf(fs: FlagSet)(using Context): Boolean = (if (isCurrent(fs)) myFlags else flags).isOneOf(fs) /** Has this denotation the given flag set, whereas none of the flags * in `butNot` are set? */ - final def is(flag: Flag, butNot: FlagSet)(implicit ctx: Context): Boolean = + final def is(flag: Flag, butNot: FlagSet)(using Context): Boolean = (if (isCurrent(flag) && isCurrent(butNot)) myFlags else flags).is(flag, butNot) /** Has this denotation one of the flags in `fs` set, whereas none of the flags * in `butNot` are set? */ - final def isOneOf(fs: FlagSet, butNot: FlagSet)(implicit ctx: Context): Boolean = + final def isOneOf(fs: FlagSet, butNot: FlagSet)(using Context): Boolean = (if (isCurrent(fs) && isCurrent(butNot)) myFlags else flags).isOneOf(fs, butNot) /** Has this denotation all of the flags in `fs` set? */ - final def isAllOf(fs: FlagSet)(implicit ctx: Context): Boolean = + final def isAllOf(fs: FlagSet)(using Context): Boolean = (if (isCurrent(fs)) myFlags else flags).isAllOf(fs) /** Has this denotation all of the flags in `fs` set, whereas none of the flags * in `butNot` are set? */ - final def isAllOf(fs: FlagSet, butNot: FlagSet)(implicit ctx: Context): Boolean = + final def isAllOf(fs: FlagSet, butNot: FlagSet)(using Context): Boolean = (if (isCurrent(fs) && isCurrent(butNot)) myFlags else flags).isAllOf(fs, butNot) /** The type info, or, if symbol is not yet completed, the completer */ @@ -233,7 +233,7 @@ object SymDenotations { case _ => Some(myInfo) } - final def completeFrom(completer: LazyType)(implicit ctx: Context): Unit = + final def completeFrom(completer: LazyType)(using Context): Unit = if (Config.showCompletions) { println(i"${" " * indent}completing ${if (isType) "type" else "val"} $name") indent += 1 @@ -242,7 +242,7 @@ object SymDenotations { myFlags |= Touched // completions.println(s"completing ${this.debugString}") - try completer.complete(this)(ctx.withPhase(validFor.firstPhaseId)) + try completer.complete(this)(using ctx.withPhase(validFor.firstPhaseId)) catch { case ex: CyclicReference => println(s"error while completing ${this.debugString}") @@ -256,7 +256,7 @@ object SymDenotations { else { if (myFlags.is(Touched)) throw CyclicReference(this) myFlags |= Touched - completer.complete(this)(ctx.withPhase(validFor.firstPhaseId)) + completer.complete(this)(using ctx.withPhase(validFor.firstPhaseId)) } protected[dotc] def info_=(tp: Type): Unit = { @@ -279,14 +279,14 @@ object SymDenotations { * - if this is a companion object with a clash-avoiding name, strip the * "avoid clash" suffix */ - def effectiveName(implicit ctx: Context): Name = + def effectiveName(using Context): Name = if (this.is(ModuleClass)) name.stripModuleClassSuffix else name /** The privateWithin boundary, NoSymbol if no boundary is given. */ @tailrec - final def privateWithin(implicit ctx: Context): Symbol = myInfo match { + final def privateWithin(using Context): Symbol = myInfo match { case myInfo: ModuleCompleter => // Instead of completing the ModuleCompleter, we can get `privateWithin` // directly from the module class, which might require less completions. @@ -304,7 +304,7 @@ object SymDenotations { * possible. * @pre `isCompleting` is false, or this is a ModuleCompleter or SymbolLoader */ - protected[dotc] final def setPrivateWithin(pw: Symbol)(implicit ctx: Context): Unit = { + protected[dotc] final def setPrivateWithin(pw: Symbol)(using Context): Unit = { if (isCompleting) assert(myInfo.isInstanceOf[ModuleCompleter | SymbolLoader], s"Illegal call to `setPrivateWithin($pw)` while completing $this using completer $myInfo") @@ -312,7 +312,7 @@ object SymDenotations { } /** The annotations of this denotation */ - final def annotations(implicit ctx: Context): List[Annotation] = { + final def annotations(using Context): List[Annotation] = { ensureCompleted(); myAnnotations } @@ -321,19 +321,19 @@ object SymDenotations { myAnnotations = annots /** Does this denotation have an annotation matching the given class symbol? */ - final def hasAnnotation(cls: Symbol)(implicit ctx: Context): Boolean = + final def hasAnnotation(cls: Symbol)(using Context): Boolean = dropOtherAnnotations(annotations, cls).nonEmpty /** Apply transform `f` to all annotations of this denotation */ - final def transformAnnotations(f: Annotation => Annotation)(implicit ctx: Context): Unit = + final def transformAnnotations(f: Annotation => Annotation)(using Context): Unit = annotations = annotations.mapConserve(f) /** Keep only those annotations that satisfy `p` */ - final def filterAnnotations(p: Annotation => Boolean)(implicit ctx: Context): Unit = + final def filterAnnotations(p: Annotation => Boolean)(using Context): Unit = annotations = annotations.filterConserve(p) /** Optionally, the annotation matching the given class symbol */ - final def getAnnotation(cls: Symbol)(implicit ctx: Context): Option[Annotation] = + final def getAnnotation(cls: Symbol)(using Context): Option[Annotation] = dropOtherAnnotations(annotations, cls) match { case annot :: _ => Some(annot) case nil => None @@ -342,7 +342,7 @@ object SymDenotations { /** The same as getAnnotation, but without ensuring * that the symbol carrying the annotation is completed */ - final def unforcedAnnotation(cls: Symbol)(implicit ctx: Context): Option[Annotation] = + final def unforcedAnnotation(cls: Symbol)(using Context): Option[Annotation] = dropOtherAnnotations(myAnnotations, cls) match { case annot :: _ => Some(annot) case nil => None @@ -353,21 +353,21 @@ object SymDenotations { annotations = annot :: myAnnotations /** Remove annotation with given class from this denotation */ - final def removeAnnotation(cls: Symbol)(implicit ctx: Context): Unit = + final def removeAnnotation(cls: Symbol)(using Context): Unit = annotations = myAnnotations.filterNot(_ matches cls) /** Remove any annotations with same class as `annot`, and add `annot` */ - final def updateAnnotation(annot: Annotation)(implicit ctx: Context): Unit = { + final def updateAnnotation(annot: Annotation)(using Context): Unit = { removeAnnotation(annot.symbol) addAnnotation(annot) } /** Add all given annotations to this symbol */ - final def addAnnotations(annots: TraversableOnce[Annotation])(implicit ctx: Context): Unit = + final def addAnnotations(annots: TraversableOnce[Annotation])(using Context): Unit = annots.iterator.foreach(addAnnotation) @tailrec - private def dropOtherAnnotations(anns: List[Annotation], cls: Symbol)(implicit ctx: Context): List[Annotation] = anns match { + private def dropOtherAnnotations(anns: List[Annotation], cls: Symbol)(using Context): List[Annotation] = anns match { case ann :: rest => if (ann matches cls) anns else dropOtherAnnotations(rest, cls) case Nil => Nil } @@ -432,7 +432,7 @@ object SymDenotations { * * @see ensureCompleted */ - final def completeOnce()(implicit ctx: Context): Unit = myInfo match { + final def completeOnce()(using Context): Unit = myInfo match { case myInfo: LazyType => completeFrom(myInfo) case _ => @@ -442,7 +442,7 @@ object SymDenotations { * * @see completeOnce */ - final def ensureCompleted()(implicit ctx: Context): Unit = info + final def ensureCompleted()(using Context): Unit = info /** The symbols defined in this class or object. * Careful! This does not force the type, so is compilation order dependent. @@ -454,7 +454,7 @@ object SymDenotations { * 3. When playing it safe in order not to raise CylicReferences, e.g. for printing things * or taking more efficient shortcuts (e.g. the stillValid test). */ - final def unforcedDecls(implicit ctx: Context): Scope = myInfo match { + final def unforcedDecls(using Context): Scope = myInfo match { case cinfo: LazyType => val knownDecls = cinfo.decls if (knownDecls ne EmptyScope) knownDecls @@ -467,7 +467,7 @@ object SymDenotations { * aliases such as AnyRef into a package class without forcing it. * Right now, the only usage is for the AnyRef alias in Definitions. */ - final private[core] def currentPackageDecls(implicit ctx: Context): MutableScope = myInfo match { + final private[core] def currentPackageDecls(using Context): MutableScope = myInfo match { case pinfo: SymbolLoaders.PackageLoader => pinfo.currentDecls case _ => unforcedDecls.openForMutations } @@ -518,30 +518,30 @@ object SymDenotations { // ------ Names ---------------------------------------------- /** The expanded name of this denotation. */ - final def expandedName(implicit ctx: Context): Name = + final def expandedName(using Context): Name = if (name.is(ExpandedName) || isConstructor) name else name.expandedName(initial.owner) // need to use initial owner to disambiguate, as multiple private symbols with the same name // might have been moved from different origins into the same class /** The effective name with which the denoting symbol was created */ - final def originalName(implicit ctx: Context): Name = initial.effectiveName + final def originalName(using Context): Name = initial.effectiveName /** The owner with which the denoting symbol was created. */ - final def originalOwner(implicit ctx: Context): Symbol = initial.maybeOwner + final def originalOwner(using Context): Symbol = initial.maybeOwner /** The encoded full path name of this denotation, where outer names and inner names * are separated by `separator` strings as indicated by the given name kind. * Drops package objects. Represents each term in the owner chain by a simple `_$`. */ - def fullNameSeparated(kind: QualifiedNameKind)(implicit ctx: Context): Name = + def fullNameSeparated(kind: QualifiedNameKind)(using Context): Name = maybeOwner.fullNameSeparated(kind, kind, name) /** The encoded full path name of this denotation (separated by `prefixKind`), * followed by the separator implied by `kind` and the given `name`. * Drops package objects. Represents each term in the owner chain by a simple `_$`. */ - def fullNameSeparated(prefixKind: QualifiedNameKind, kind: QualifiedNameKind, name: Name)(implicit ctx: Context): Name = + def fullNameSeparated(prefixKind: QualifiedNameKind, kind: QualifiedNameKind, name: Name)(using Context): Name = if (symbol == NoSymbol || isEffectiveRoot || kind == FlatName && is(PackageClass)) name else { @@ -565,13 +565,13 @@ object SymDenotations { } /** The encoded flat name of this denotation, where joined names are separated by `separator` characters. */ - def flatName(implicit ctx: Context): Name = fullNameSeparated(FlatName) + def flatName(using Context): Name = fullNameSeparated(FlatName) /** `fullName` where `.' is the separator character */ - def fullName(implicit ctx: Context): Name = fullNameSeparated(QualifiedName) + def fullName(using Context): Name = fullNameSeparated(QualifiedName) /** The name given in an `@alpha` annotation if one is present, `name` otherwise */ - final def erasedName(implicit ctx: Context): Name = + final def erasedName(using Context): Name = getAnnotation(defn.AlphaAnnot) match { case Some(ann) => ann.arguments match { @@ -597,7 +597,7 @@ object SymDenotations { final def isClass: Boolean = isInstanceOf[ClassDenotation] /** Is this denotation a non-trait class? */ - final def isRealClass(implicit ctx: Context): Boolean = isClass && !is(Trait) + final def isRealClass(using Context): Boolean = isClass && !is(Trait) /** Cast to class denotation */ final def asClass: ClassDenotation = asInstanceOf[ClassDenotation] @@ -608,7 +608,7 @@ object SymDenotations { /** Make denotation not exist. * @pre `isCompleting` is false, or this is a ModuleCompleter or SymbolLoader */ - final def markAbsent()(implicit ctx: Context): Unit = { + final def markAbsent()(using Context): Unit = { if (isCompleting) assert(myInfo.isInstanceOf[ModuleCompleter | SymbolLoader], s"Illegal call to `markAbsent()` while completing $this using completer $myInfo") @@ -619,7 +619,7 @@ object SymDenotations { * @param canForce If this is true, the info may be forced to avoid a false-negative result */ @tailrec - final def isAbsent(canForce: Boolean = true)(implicit ctx: Context): Boolean = myInfo match { + final def isAbsent(canForce: Boolean = true)(using Context): Boolean = myInfo match { case myInfo: ModuleCompleter => // Instead of completing the ModuleCompleter, we can check whether // the module class is absent, which might require less completions. @@ -639,50 +639,50 @@ object SymDenotations { (maybeOwner eq NoSymbol) && (name.toTermName == nme.ROOT || name == nme.ROOTPKG) /** Is this symbol the empty package class or its companion object? */ - final def isEmptyPackage(implicit ctx: Context): Boolean = + final def isEmptyPackage(using Context): Boolean = name.toTermName == nme.EMPTY_PACKAGE && owner.isRoot /** Is this symbol the empty package class or its companion object? */ - final def isEffectiveRoot(implicit ctx: Context): Boolean = isRoot || isEmptyPackage + final def isEffectiveRoot(using Context): Boolean = isRoot || isEmptyPackage /** Is this symbol an anonymous class? */ - final def isAnonymousClass(implicit ctx: Context): Boolean = + final def isAnonymousClass(using Context): Boolean = isClass && initial.name.isAnonymousClassName - final def isAnonymousFunction(implicit ctx: Context): Boolean = + final def isAnonymousFunction(using Context): Boolean = this.symbol.is(Method) && initial.name.isAnonymousFunctionName - final def isAnonymousModuleVal(implicit ctx: Context): Boolean = + final def isAnonymousModuleVal(using Context): Boolean = this.symbol.is(ModuleVal) && initial.name.isAnonymousClassName /** Is this a synthetic method that represents conversions between representations of a value class * These methods are generated in ExtensionMethods * and used in ElimErasedValueType. */ - final def isValueClassConvertMethod(implicit ctx: Context): Boolean = + final def isValueClassConvertMethod(using Context): Boolean = name.toTermName == nme.U2EVT || name.toTermName == nme.EVT2U /** Is symbol a primitive value class? */ - def isPrimitiveValueClass(implicit ctx: Context): Boolean = + def isPrimitiveValueClass(using Context): Boolean = maybeOwner == defn.ScalaPackageClass && defn.ScalaValueClasses().contains(symbol) /** Is symbol a primitive numeric value class? */ - def isNumericValueClass(implicit ctx: Context): Boolean = + def isNumericValueClass(using Context): Boolean = maybeOwner == defn.ScalaPackageClass && defn.ScalaNumericValueClasses().contains(symbol) /** Is symbol a class for which no runtime representation exists? */ - def isNotRuntimeClass(implicit ctx: Context): Boolean = defn.NotRuntimeClasses contains symbol + def isNotRuntimeClass(using Context): Boolean = defn.NotRuntimeClasses contains symbol /** Is this symbol a class representing a refinement? These classes * are used only temporarily in Typer and Unpickler as an intermediate * step for creating Refinement types. */ - final def isRefinementClass(implicit ctx: Context): Boolean = + final def isRefinementClass(using Context): Boolean = name == tpnme.REFINE_CLASS /** Is this symbol a package object or its module class? */ - def isPackageObject(implicit ctx: Context): Boolean = + def isPackageObject(using Context): Boolean = name.isPackageObjectName && owner.is(Package) && this.is(Module) /** Is this symbol a toplevel definition in a package object? */ @@ -690,24 +690,24 @@ object SymDenotations { !isConstructor && owner.isPackageObject /** Is this symbol an abstract type? */ - final def isAbstractType(implicit ctx: Context): Boolean = this.is(DeferredType) + final def isAbstractType(using Context): Boolean = this.is(DeferredType) /** Is this symbol an alias type? */ - final def isAliasType(implicit ctx: Context): Boolean = isAbstractOrAliasType && !this.is(Deferred) + final def isAliasType(using Context): Boolean = isAbstractOrAliasType && !this.is(Deferred) /** Is this symbol an abstract or alias type? */ final def isAbstractOrAliasType: Boolean = isType & !isClass /** Is this symbol an abstract type or type parameter? */ - final def isAbstractOrParamType(implicit ctx: Context): Boolean = this.isOneOf(DeferredOrTypeParam) + final def isAbstractOrParamType(using Context): Boolean = this.isOneOf(DeferredOrTypeParam) /** Is this symbol a user-defined opaque alias type? */ - def isOpaqueAlias(implicit ctx: Context): Boolean = is(Opaque) && !isClass + def isOpaqueAlias(using Context): Boolean = is(Opaque) && !isClass /** Is this symbol a module that contains opaque aliases? */ - def containsOpaques(implicit ctx: Context): Boolean = is(Opaque) && isClass + def containsOpaques(using Context): Boolean = is(Opaque) && isClass - def seesOpaques(implicit ctx: Context): Boolean = + def seesOpaques(using Context): Boolean = containsOpaques || is(Module, butNot = Package) && owner.seesOpaques @@ -721,7 +721,7 @@ object SymDenotations { * TODO: Find a more robust way to characterize self symbols, maybe by * spending a Flag on them? */ - final def isSelfSym(implicit ctx: Context): Boolean = owner.infoOrCompleter match { + final def isSelfSym(using Context): Boolean = owner.infoOrCompleter match { case ClassInfo(_, _, _, _, selfInfo) => selfInfo == symbol || selfInfo.isInstanceOf[Type] && name == nme.WILDCARD @@ -731,7 +731,7 @@ object SymDenotations { /** Is this definition contained in `boundary`? * Same as `ownersIterator contains boundary` but more efficient. */ - final def isContainedIn(boundary: Symbol)(implicit ctx: Context): Boolean = { + final def isContainedIn(boundary: Symbol)(using Context): Boolean = { def recur(sym: Symbol): Boolean = if (sym eq boundary) true else if (sym eq NoSymbol) false @@ -740,20 +740,20 @@ object SymDenotations { recur(symbol) } - final def isProperlyContainedIn(boundary: Symbol)(implicit ctx: Context): Boolean = + final def isProperlyContainedIn(boundary: Symbol)(using Context): Boolean = symbol != boundary && isContainedIn(boundary) /** Is this denotation static (i.e. with no outer instance)? */ - final def isStatic(implicit ctx: Context): Boolean = + final def isStatic(using Context): Boolean = (if (maybeOwner eq NoSymbol) isRoot else maybeOwner.originDenotation.isStaticOwner) || myFlags.is(JavaStatic) /** Is this a package class or module class that defines static symbols? */ - final def isStaticOwner(implicit ctx: Context): Boolean = + final def isStaticOwner(using Context): Boolean = myFlags.is(ModuleClass) && (myFlags.is(PackageClass) || isStatic) /** Is this denotation defined in the same scope and compilation unit as that symbol? */ - final def isCoDefinedWith(other: Symbol)(implicit ctx: Context): Boolean = + final def isCoDefinedWith(other: Symbol)(using Context): Boolean = (this.effectiveOwner == other.effectiveOwner) && ( !this.effectiveOwner.is(PackageClass) || this.isAbsent(canForce = false) || other.isAbsent(canForce = false) @@ -778,7 +778,7 @@ object SymDenotations { * However, a stable member might not yet be initialized (if it is an object or anyhow lazy). * So the first call to a stable member might fail and/or produce side effects. */ - final def isStableMember(implicit ctx: Context): Boolean = { + final def isStableMember(using Context): Boolean = { def isUnstableValue = isOneOf(UnstableValueFlags) || info.isInstanceOf[ExprType] isType || is(StableRealizable) || exists && !isUnstableValue } @@ -786,7 +786,7 @@ object SymDenotations { /** Is this a denotation of a class that does not have - either direct or inherited - * initialization code? */ - def isNoInitsClass(implicit ctx: Context): Boolean = + def isNoInitsClass(using Context): Boolean = isClass && (asClass.baseClasses.forall(_.is(NoInits)) || defn.isAssuredNoInits(symbol)) @@ -794,15 +794,15 @@ object SymDenotations { * - not an accessor * - not an anonymous function */ - final def isRealMethod(implicit ctx: Context): Boolean = + final def isRealMethod(using Context): Boolean = this.is(Method, butNot = Accessor) && !isAnonymousFunction /** Is this a getter? */ - final def isGetter(implicit ctx: Context): Boolean = + final def isGetter(using Context): Boolean = this.is(Accessor) && !originalName.isSetterName && !originalName.isScala2LocalSuffix /** Is this a setter? */ - final def isSetter(implicit ctx: Context): Boolean = + final def isSetter(using Context): Boolean = this.is(Accessor) && originalName.isSetterName && (!isCompleted || info.firstParamTypes.nonEmpty) // to avoid being fooled by var x_= : Unit = ... @@ -820,42 +820,42 @@ object SymDenotations { final def isLocalDummy: Boolean = name.isLocalDummyName /** Does this symbol denote the primary constructor of its enclosing class? */ - final def isPrimaryConstructor(implicit ctx: Context): Boolean = + final def isPrimaryConstructor(using Context): Boolean = isConstructor && owner.primaryConstructor == symbol /** Does this symbol denote the static constructor of its enclosing class? */ - final def isStaticConstructor(implicit ctx: Context): Boolean = + final def isStaticConstructor(using Context): Boolean = name.isStaticConstructorName /** Is this a subclass of the given class `base`? */ - def isSubClass(base: Symbol)(implicit ctx: Context): Boolean = false + def isSubClass(base: Symbol)(using Context): Boolean = false /** Is this a subclass of `base`, * and is the denoting symbol also different from `Null` or `Nothing`? * @note erroneous classes are assumed to derive from all other classes * and all classes derive from them. */ - def derivesFrom(base: Symbol)(implicit ctx: Context): Boolean = false + def derivesFrom(base: Symbol)(using Context): Boolean = false /** Is this a Scala or Java annotation ? */ - def isAnnotation(implicit ctx: Context): Boolean = + def isAnnotation(using Context): Boolean = isClass && derivesFrom(defn.AnnotationClass) /** Is this symbol a class that extends `java.io.Serializable` ? */ - def isSerializable(implicit ctx: Context): Boolean = + def isSerializable(using Context): Boolean = isClass && derivesFrom(defn.JavaSerializableClass) /** Is this symbol a class that extends `AnyVal`? */ - final def isValueClass(implicit ctx: Context): Boolean = { + final def isValueClass(using Context): Boolean = { val di = initial di.isClass && - di.derivesFrom(defn.AnyValClass)(ctx.withPhase(di.validFor.firstPhaseId)) + di.derivesFrom(defn.AnyValClass)(using ctx.withPhase(di.validFor.firstPhaseId)) // We call derivesFrom at the initial phase both because AnyVal does not exist // after Erasure and to avoid cyclic references caused by forcing denotations } /** Is this symbol a class of which `null` is a value? */ - final def isNullableClass(implicit ctx: Context): Boolean = + final def isNullableClass(using Context): Boolean = if (ctx.explicitNulls && !ctx.phase.erasedTypes) symbol == defn.NullClass || symbol == defn.AnyClass else isNullableClassAfterErasure @@ -863,7 +863,7 @@ object SymDenotations { * For example, if `-Yexplicit-nulls` is set, `String` is not nullable before erasure, * but it becomes nullable after erasure. */ - final def isNullableClassAfterErasure(implicit ctx: Context): Boolean = + final def isNullableClassAfterErasure(using Context): Boolean = isClass && !isValueClass && !is(ModuleClass) && symbol != defn.NothingClass /** Is this definition accessible as a member of tree with type `pre`? @@ -875,7 +875,7 @@ object SymDenotations { * As a side effect, drop Local flags of members that are not accessed via the ThisType * of their owner. */ - final def isAccessibleFrom(pre: Type, superAccess: Boolean = false, whyNot: StringBuffer = null)(implicit ctx: Context): Boolean = { + final def isAccessibleFrom(pre: Type, superAccess: Boolean = false, whyNot: StringBuffer = null)(using Context): Boolean = { /** Are we inside definition of `boundary`? */ def accessWithin(boundary: Symbol) = ctx.owner.isContainedIn(boundary) @@ -953,7 +953,7 @@ object SymDenotations { /** Do members of this symbol need translation via asSeenFrom when * accessed via prefix `pre`? */ - def membersNeedAsSeenFrom(pre: Type)(implicit ctx: Context): Boolean = + def membersNeedAsSeenFrom(pre: Type)(using Context): Boolean = !( this.isTerm || this.isStaticOwner && !this.seesOpaques || ctx.erasedTypes @@ -962,13 +962,13 @@ object SymDenotations { ) /** Is this symbol concrete, or that symbol deferred? */ - def isAsConcrete(that: Symbol)(implicit ctx: Context): Boolean = + def isAsConcrete(that: Symbol)(using Context): Boolean = !this.is(Deferred) || that.is(Deferred) /** Does this symbol have defined or inherited default parameters? * Default parameters are recognized until erasure. */ - def hasDefaultParams(implicit ctx: Context): Boolean = + def hasDefaultParams(using Context): Boolean = if ctx.erasedTypes then false else if is(HasDefaultParams) then true else if is(NoDefaultParams) then false @@ -983,13 +983,13 @@ object SymDenotations { * - package objects * - non-lazy valdefs */ - def isWeakOwner(implicit ctx: Context): Boolean = + def isWeakOwner(using Context): Boolean = isPackageObject || isTerm && !isOneOf(MethodOrLazy) && !isLocalDummy def isSkolem: Boolean = name == nme.SKOLEM - def isInlineMethod(implicit ctx: Context): Boolean = + def isInlineMethod(using Context): Boolean = isAllOf(InlineMethod, butNot = Accessor) /** Does this method or field need to be retained at runtime */ @@ -1002,15 +1002,15 @@ object SymDenotations { is(Method, butNot = Accessor) && isRetainedInline /** Is this a Scala 2 macro */ - final def isScala2Macro(implicit ctx: Context): Boolean = + final def isScala2Macro(using Context): Boolean = isScala2MacroInScala3 || (is(Macro) && symbol.owner.is(Scala2x)) /** Is this a Scala 2 macro defined */ - final def isScala2MacroInScala3(implicit ctx: Context): Boolean = + final def isScala2MacroInScala3(using Context): Boolean = is(Macro, butNot = Inline) && is(Erased) /** An erased value or an erased inline method or field */ - def isEffectivelyErased(implicit ctx: Context): Boolean = + def isEffectivelyErased(using Context): Boolean = is(Erased) || is(Inline) && !isRetainedInline && !hasAnnotation(defn.ScalaStaticAnnot) /** ()T and => T types should be treated as equivalent for this symbol. @@ -1018,7 +1018,7 @@ object SymDenotations { * because the Scala library does not always follow the right conventions. * Examples are: isWhole(), toInt(), toDouble() in BigDecimal, Numeric, RichInt, ScalaNumberProxy. */ - def matchNullaryLoosely(implicit ctx: Context): Boolean = { + def matchNullaryLoosely(using Context): Boolean = { def test(sym: Symbol) = sym.is(JavaDefined) || sym.owner == defn.AnyClass || @@ -1042,7 +1042,7 @@ object SymDenotations { /** If this a module, return the corresponding class, if this is a module, return itself, * otherwise NoSymbol */ - final def moduleClass(implicit ctx: Context): Symbol = { + final def moduleClass(using Context): Symbol = { def notFound = { if (Config.showCompletions) println(s"missing module class for $name: $myInfo") NoSymbol @@ -1068,7 +1068,7 @@ object SymDenotations { /** If this a module class, return the corresponding module, if this is a module, return itself, * otherwise NoSymbol */ - final def sourceModule(implicit ctx: Context): Symbol = + final def sourceModule(using Context): Symbol = if (this.is(ModuleClass)) myInfo match { case ClassInfo(_, _, _, _, selfType) => @@ -1089,7 +1089,7 @@ object SymDenotations { NoSymbol /** The field accessed by this getter or setter, or if it does not exist, the getter */ - def accessedFieldOrGetter(implicit ctx: Context): Symbol = { + def accessedFieldOrGetter(using Context): Symbol = { val fieldName = if (isSetter) name.asTermName.getterName else name val d = owner.info.decl(fieldName) val field = d.suchThat(!_.is(Method)).symbol @@ -1101,11 +1101,11 @@ object SymDenotations { * if it does not exists, the getter of a setter, or * if that does not exist the symbol itself. */ - def underlyingSymbol(implicit ctx: Context): Symbol = + def underlyingSymbol(using Context): Symbol = if (is(Accessor)) accessedFieldOrGetter orElse symbol else symbol /** The chain of owners of this denotation, starting with the denoting symbol itself */ - final def ownersIterator(implicit ctx: Context): Iterator[Symbol] = new Iterator[Symbol] { + final def ownersIterator(using Context): Iterator[Symbol] = new Iterator[Symbol] { private var current = symbol def hasNext = current.exists def next: Symbol = { @@ -1116,11 +1116,11 @@ object SymDenotations { } /** If this is a weak owner, its owner, otherwise the denoting symbol. */ - final def skipWeakOwner(implicit ctx: Context): Symbol = + final def skipWeakOwner(using Context): Symbol = if (isWeakOwner) owner.skipWeakOwner else symbol /** The owner, skipping package objects and non-lazy valdefs. */ - final def effectiveOwner(implicit ctx: Context): Symbol = owner.skipWeakOwner + final def effectiveOwner(using Context): Symbol = owner.skipWeakOwner /** The class containing this denotation. * If this denotation is already a class, return itself @@ -1133,7 +1133,7 @@ object SymDenotations { * Note, that as packages have ClassSymbols, top level classes will have an `enclosingClass` * with Package flag set. */ - final def enclosingClass(implicit ctx: Context): Symbol = { + final def enclosingClass(using Context): Symbol = { def enclClass(sym: Symbol, skip: Boolean): Symbol = { def newSkip = sym.is(JavaStaticTerm) if (!sym.exists) @@ -1147,7 +1147,7 @@ object SymDenotations { } /** A class that in source code would be lexically enclosing */ - final def lexicallyEnclosingClass(implicit ctx: Context): Symbol = + final def lexicallyEnclosingClass(using Context): Symbol = if (!exists || isClass) symbol else owner.lexicallyEnclosingClass /** A class is extensible if it is not final, nor a module class, @@ -1157,7 +1157,7 @@ object SymDenotations { isClass && !isOneOf(FinalOrModuleClass) && !isAnonymousClass /** A symbol is effectively final if it cannot be overridden in a subclass */ - final def isEffectivelyFinal(implicit ctx: Context): Boolean = + final def isEffectivelyFinal(using Context): Boolean = isOneOf(EffectivelyFinalFlags) || is(Inline, butNot = Deferred) || is(JavaDefinedVal, butNot = Method) @@ -1176,7 +1176,7 @@ object SymDenotations { || hasAnnotation(defn.SuperTraitAnnot)) /** The class containing this denotation which has the given effective name. */ - final def enclosingClassNamed(name: Name)(implicit ctx: Context): Symbol = { + final def enclosingClassNamed(name: Name)(using Context): Symbol = { val cls = enclosingClass if (cls.effectiveName == name || !cls.exists) cls else cls.owner.enclosingClassNamed(name) } @@ -1184,7 +1184,7 @@ object SymDenotations { /** The closest enclosing method containing this definition. * A local dummy owner is mapped to the primary constructor of the class. */ - final def enclosingMethod(implicit ctx: Context): Symbol = + final def enclosingMethod(using Context): Symbol = if (this.is(Method)) symbol else if (this.isClass) primaryConstructor else if (this.exists) owner.enclosingMethod @@ -1202,7 +1202,7 @@ object SymDenotations { /** The top-level class containing this denotation, * except for a toplevel module, where its module class is returned. */ - final def topLevelClass(implicit ctx: Context): Symbol = { + final def topLevelClass(using Context): Symbol = { @tailrec def topLevel(d: SymDenotation): Symbol = if (d.isTopLevelClass) d.symbol else topLevel(d.owner) @@ -1211,29 +1211,29 @@ object SymDenotations { if (sym.isClass) sym else sym.moduleClass } - final def isTopLevelClass(implicit ctx: Context): Boolean = + final def isTopLevelClass(using Context): Boolean = !this.exists || this.isEffectiveRoot || this.is(PackageClass) || this.owner.is(PackageClass) /** The package class containing this denotation */ - final def enclosingPackageClass(implicit ctx: Context): Symbol = + final def enclosingPackageClass(using Context): Symbol = if (this.is(PackageClass)) symbol else owner.enclosingPackageClass /** Register target as a companion; overridden in ClassDenotation */ - def registerCompanion(target: Symbol)(implicit ctx: Context) = () + def registerCompanion(target: Symbol)(using Context) = () /** The registered companion; overridden in ClassDenotation */ - def registeredCompanion(implicit ctx: Context): Symbol = NoSymbol + def registeredCompanion(using Context): Symbol = NoSymbol def registeredCompanion_=(c: Symbol): Unit = () /** The module object with the same (term-) name as this class or module class, * and which is also defined in the same scope and compilation unit. * NoSymbol if this module does not exist. */ - final def companionModule(implicit ctx: Context): Symbol = + final def companionModule(using Context): Symbol = if (is(Module)) sourceModule else registeredCompanion.sourceModule - private def companionType(implicit ctx: Context): Symbol = + private def companionType(using Context): Symbol = if (is(Package)) NoSymbol else if (is(ModuleVal)) moduleClass.denot.companionType else registeredCompanion @@ -1242,10 +1242,10 @@ object SymDenotations { * and which is also defined in the same scope and compilation unit. * NoSymbol if this class does not exist. */ - final def companionClass(implicit ctx: Context): Symbol = + final def companionClass(using Context): Symbol = companionType.suchThat(_.isClass).symbol - final def scalacLinkedClass(implicit ctx: Context): Symbol = + final def scalacLinkedClass(using Context): Symbol = if (this.is(ModuleClass)) companionNamed(effectiveName.toTypeName) else if (this.isClass) companionNamed(effectiveName.moduleClassName).sourceModule.moduleClass else NoSymbol @@ -1258,7 +1258,7 @@ object SymDenotations { * 3. If context has an enclosing scope which defines this symbol, * lookup its companion in the same scope. */ - private def companionNamed(name: TypeName)(implicit ctx: Context): Symbol = + private def companionNamed(name: TypeName)(using Context): Symbol = if (owner.isClass) owner.unforcedDecls.lookup(name).suchThat(_.isCoDefinedWith(symbol)).symbol else if (!owner.exists || ctx.compilationUnit == null) @@ -1273,17 +1273,17 @@ object SymDenotations { else if (ctx.scope.lookup(this.name) == symbol) ctx.scope.lookup(name) else - companionNamed(name)(ctx.outersIterator.dropWhile(_.scope eq ctx.scope).next()) + companionNamed(name)(using ctx.outersIterator.dropWhile(_.scope eq ctx.scope).next()) /** Is this symbol the same or a linked class of `sym`? */ - final def isLinkedWith(sym: Symbol)(implicit ctx: Context): Boolean = + final def isLinkedWith(sym: Symbol)(using Context): Boolean = (symbol eq sym) || (linkedClass eq sym) /** If this is a class, the module class of its companion object. * If this is a module class, its companion class. * NoSymbol otherwise. */ - final def linkedClass(implicit ctx: Context): Symbol = + final def linkedClass(using Context): Symbol = if (this.is(ModuleClass)) companionClass else if (this.isClass) companionModule.moduleClass else NoSymbol @@ -1291,13 +1291,13 @@ object SymDenotations { /** The class that encloses the owner of the current context * and that is a subclass of this class. NoSymbol if no such class exists. */ - final def enclosingSubClass(implicit ctx: Context): Symbol = + final def enclosingSubClass(using Context): Symbol = ctx.owner.ownersIterator.findSymbol(_.isSubClass(symbol)) /** The alias of an opaque type alias that's stored in the self type of the * containing object. */ - def opaqueAlias(implicit ctx: Context): Type = { + def opaqueAlias(using Context): Type = { def recur(tp: Type): Type = tp match { case RefinedType(parent, rname, TypeAlias(alias)) => if rname == name then alias.stripLazyRef else recur(parent) @@ -1316,7 +1316,7 @@ object SymDenotations { * * site: Subtype of both inClass and C */ - final def matchingDecl(inClass: Symbol, site: Type)(implicit ctx: Context): Symbol = { + final def matchingDecl(inClass: Symbol, site: Type)(using Context): Symbol = { var denot = inClass.info.nonPrivateDecl(name) if (denot.isTerm) // types of the same name always match denot = denot.matchingDenotation(site, site.memberInfo(symbol)) @@ -1325,7 +1325,7 @@ object SymDenotations { /** The non-private member of `site` whose name and type matches the type of this symbol */ - final def matchingMember(site: Type)(implicit ctx: Context): Symbol = { + final def matchingMember(site: Type)(using Context): Symbol = { var denot = site.nonPrivateMember(name) if (denot.isTerm) // types of the same name always match denot = denot.matchingDenotation(site, site.memberInfo(symbol)) @@ -1335,27 +1335,27 @@ object SymDenotations { /** If false, this symbol cannot possibly participate in an override, * either as overrider or overridee. */ - final def canMatchInheritedSymbols(implicit ctx: Context): Boolean = + final def canMatchInheritedSymbols(using Context): Boolean = maybeOwner.isClass && memberCanMatchInheritedSymbols /** If false, this class member cannot possibly participate in an override, * either as overrider or overridee. */ - final def memberCanMatchInheritedSymbols(implicit ctx: Context): Boolean = + final def memberCanMatchInheritedSymbols(using Context): Boolean = !isConstructor && !is(Private) /** The symbol, in class `inClass`, that is overridden by this denotation in class `siteClass`.*/ - final def overriddenSymbol(inClass: ClassSymbol, siteClass: ClassSymbol = owner.asClass)(implicit ctx: Context): Symbol = + final def overriddenSymbol(inClass: ClassSymbol, siteClass: ClassSymbol = owner.asClass)(using Context): Symbol = if (!canMatchInheritedSymbols && (owner ne inClass)) NoSymbol else matchingDecl(inClass, siteClass.thisType) /** All symbols overridden by this denotation. */ - final def allOverriddenSymbols(implicit ctx: Context): Iterator[Symbol] = + final def allOverriddenSymbols(using Context): Iterator[Symbol] = if (!canMatchInheritedSymbols) Iterator.empty else overriddenFromType(owner.info) /** Equivalent to `allOverriddenSymbols.headOption.getOrElse(NoSymbol)` but more efficient. */ - final def nextOverriddenSymbol(implicit ctx: Context): Symbol = { + final def nextOverriddenSymbol(using Context): Symbol = { val overridden = allOverriddenSymbols if (overridden.hasNext) overridden.next @@ -1364,11 +1364,11 @@ object SymDenotations { } /** Returns all matching symbols defined in parents of the selftype. */ - final def extendedOverriddenSymbols(implicit ctx: Context): Iterator[Symbol] = + final def extendedOverriddenSymbols(using Context): Iterator[Symbol] = if (!canMatchInheritedSymbols) Iterator.empty else overriddenFromType(owner.asClass.classInfo.selfType) - private def overriddenFromType(tp: Type)(implicit ctx: Context): Iterator[Symbol] = + private def overriddenFromType(tp: Type)(using Context): Iterator[Symbol] = tp.baseClasses match { case _ :: inherited => inherited.iterator.map(overriddenSymbol(_)).filter(_.exists) case Nil => Iterator.empty @@ -1378,7 +1378,7 @@ object SymDenotations { * * @param ofclazz is a subclass of this symbol's owner */ - final def overridingSymbol(inClass: ClassSymbol)(implicit ctx: Context): Symbol = + final def overridingSymbol(inClass: ClassSymbol)(using Context): Symbol = if (canMatchInheritedSymbols) matchingDecl(inClass, inClass.thisType) else NoSymbol @@ -1386,7 +1386,7 @@ object SymDenotations { * seen from class `base`. This symbol is always concrete. * pre: `this.owner` is in the base class sequence of `base`. */ - final def superSymbolIn(base: Symbol)(implicit ctx: Context): Symbol = { + final def superSymbolIn(base: Symbol)(using Context): Symbol = { @tailrec def loop(bcs: List[ClassSymbol]): Symbol = bcs match { case bc :: bcs1 => val sym = matchingDecl(bcs.head, base.thisType) @@ -1403,7 +1403,7 @@ object SymDenotations { * (2) it is abstract override and its super symbol in `base` is * nonexistent or incomplete. */ - @tailrec final def isIncompleteIn(base: Symbol)(implicit ctx: Context): Boolean = + @tailrec final def isIncompleteIn(base: Symbol)(using Context): Boolean = this.is(Deferred) || this.is(AbsOverride) && { val supersym = superSymbolIn(base) @@ -1416,23 +1416,23 @@ object SymDenotations { * as public. * @param base The access boundary to assume if this symbol is protected */ - final def accessBoundary(base: Symbol)(implicit ctx: Context): Symbol = + 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 (this.is(Protected)) base else defn.RootClass - final def isPublic(implicit ctx: Context): Boolean = + final def isPublic(using Context): Boolean = accessBoundary(owner) == defn.RootClass /** The primary constructor of a class or trait, NoSymbol if not applicable. */ - def primaryConstructor(implicit ctx: Context): Symbol = NoSymbol + def primaryConstructor(using Context): Symbol = NoSymbol /** The current declaration in this symbol's class owner that has the same name * as this one, and, if there are several, also has the same signature. */ - def currentSymbol(implicit ctx: Context): Symbol = { + def currentSymbol(using Context): Symbol = { val candidates = owner.info.decls.lookupAll(name) def test(sym: Symbol): Symbol = if (sym == symbol || sym.signature == signature) sym @@ -1448,31 +1448,31 @@ object SymDenotations { // ----- type-related ------------------------------------------------ /** The type parameters of a class symbol, Nil for all other symbols */ - def typeParams(implicit ctx: Context): List[TypeSymbol] = Nil + def typeParams(using Context): List[TypeSymbol] = Nil /** The type This(cls), where cls is this class, NoPrefix for all other symbols */ - def thisType(implicit ctx: Context): Type = NoPrefix + def thisType(using Context): Type = NoPrefix - def typeRef(implicit ctx: Context): TypeRef = + def typeRef(using Context): TypeRef = TypeRef(owner.thisType, symbol) - def termRef(implicit ctx: Context): TermRef = + def termRef(using Context): TermRef = TermRef(owner.thisType, symbol) /** The typeRef applied to its own type parameters */ - def appliedRef(implicit ctx: Context): Type = + def appliedRef(using Context): Type = typeRef.appliedTo(symbol.typeParams.map(_.typeRef)) /** The NamedType representing this denotation at its original location. * Same as either `typeRef` or `termRef` depending whether this denotes a type or not. */ - def namedType(implicit ctx: Context): NamedType = + def namedType(using Context): NamedType = if (isType) typeRef else termRef /** The variance of this type parameter or type member as a subset of * {Covariant, Contravariant} */ - final def variance(implicit ctx: Context): Variance = + final def variance(using Context): Variance = if is(Covariant) then Covariant else if is(Contravariant) then Contravariant else EmptyFlags @@ -1559,7 +1559,7 @@ object SymDenotations { /** Copy mamberNames and baseData caches from given denotation, provided * they are valid at given `phase`. */ - def copyCaches(from: SymDenotation, phase: Phase)(implicit ctx: Context): this.type = this + def copyCaches(from: SymDenotation, phase: Phase)(using Context): this.type = this /** Are `info1` and `info2` ClassInfo types with different parents? * @param completersMatter if `true`, consider parents changed if `info1` or `info2 `is a type completer @@ -1577,13 +1577,13 @@ object SymDenotations { override def initial: SymDenotation = super.initial.asSymDenotation /** Install this denotation as the result of the given denotation transformer. */ - override def installAfter(phase: DenotTransformer)(implicit ctx: Context): Unit = + override def installAfter(phase: DenotTransformer)(using Context): Unit = super.installAfter(phase) /** Apply a transformation `f` to all denotations in this group that start at or after * given phase. Denotations are replaced while keeping the same validity periods. */ - override def transformAfter(phase: DenotTransformer, f: SymDenotation => SymDenotation)(implicit ctx: Context): Unit = + override def transformAfter(phase: DenotTransformer, f: SymDenotation => SymDenotation)(using Context): Unit = super.transformAfter(phase, f) /** Set flag `flags` in current phase and in all phases that follow */ @@ -1592,7 +1592,7 @@ object SymDenotations { transformAfter(phase, sd => { sd.setFlag(flags); sd }) /** If denotation is private, remove the Private flag and expand the name if necessary */ - def ensureNotPrivate(implicit ctx: Context): SymDenotation = + def ensureNotPrivate(using Context): SymDenotation = if (is(Private)) copySymDenotation(name = expandedName, initFlags = this.flags &~ Private) else this @@ -1660,7 +1660,7 @@ object SymDenotations { private var baseDataCache: BaseData = BaseData.None private var memberNamesCache: MemberNames = MemberNames.None - private def memberCache(implicit ctx: Context): LRUCache[Name, PreDenotation] = { + private def memberCache(using Context): LRUCache[Name, PreDenotation] = { if (myMemberCachePeriod != ctx.period) { myMemberCache = new LRUCache myMemberCachePeriod = ctx.period @@ -1668,7 +1668,7 @@ object SymDenotations { myMemberCache } - private def baseTypeCache(implicit ctx: Context): BaseTypeMap = { + private def baseTypeCache(using Context): BaseTypeMap = { if (!ctx.hasSameBaseTypesAs(myBaseTypeCachePeriod)) { myBaseTypeCache = new BaseTypeMap myBaseTypeCachePeriod = ctx.period @@ -1699,7 +1699,7 @@ object SymDenotations { val outerCache = sym.owner.owner.asClass.classDenot.myMemberCache if outerCache != null then outerCache.invalidate(sym.name) - override def copyCaches(from: SymDenotation, phase: Phase)(implicit ctx: Context): this.type = { + override def copyCaches(from: SymDenotation, phase: Phase)(using Context): this.type = { from match { case from: ClassDenotation => if (from.memberNamesCache.isValidAt(phase)) memberNamesCache = from.memberNamesCache @@ -1721,19 +1721,19 @@ object SymDenotations { def classSymbol: ClassSymbol = symbol.asInstanceOf[ClassSymbol] /** The info asserted to have type ClassInfo */ - def classInfo(implicit ctx: Context): ClassInfo = info.asInstanceOf[ClassInfo] + def classInfo(using Context): ClassInfo = info.asInstanceOf[ClassInfo] /** The type parameters in this class, in the order they appear in the current * scope `decls`. This might be temporarily the incorrect order when * reading Scala2 pickled info. The problem is fixed by `ensureTypeParamsInCorrectOrder`, * which is called once an unpickled symbol has been completed. */ - private def typeParamsFromDecls(implicit ctx: Context) = + private def typeParamsFromDecls(using Context) = unforcedDecls.filter(sym => sym.is(TypeParam) && sym.owner == symbol).asInstanceOf[List[TypeSymbol]] /** The type parameters of this class */ - override final def typeParams(implicit ctx: Context): List[TypeSymbol] = { + 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 @@ -1756,13 +1756,13 @@ object SymDenotations { super.info_=(tp) } - def classParents(implicit ctx: Context): List[Type] = info match { + def classParents(using Context): List[Type] = info match { case classInfo: ClassInfo => classInfo.parents case _ => Nil } /** The symbol of the superclass, NoSymbol if no superclass exists */ - def superClass(implicit ctx: Context): Symbol = classParents match { + def superClass(using Context): Symbol = classParents match { case parent :: _ => val cls = parent.classSymbol if (cls.is(Trait)) NoSymbol else cls @@ -1773,7 +1773,7 @@ object SymDenotations { /** The explicitly given self type (self types of modules are assumed to be * explcitly given here). */ - def givenSelfType(implicit ctx: Context): Type = classInfo.selfInfo match { + def givenSelfType(using Context): Type = classInfo.selfInfo match { case tp: Type => tp case self: Symbol => self.info } @@ -1787,12 +1787,12 @@ object SymDenotations { * - for a module class `m`: A term ref to m's source module. * - for all other classes `c` with owner `o`: ThisType(TypeRef(o.thisType, c)) */ - override def thisType(implicit ctx: Context): Type = { + override def thisType(using Context): Type = { if (myThisType == null) myThisType = computeThisType myThisType } - private def computeThisType(implicit ctx: Context): Type = { + private def computeThisType(using Context): Type = { val cls = symbol.asType val pre = if (this.is(Package)) NoPrefix else owner.thisType ThisType.raw(TypeRef(pre, cls)) @@ -1800,12 +1800,12 @@ object SymDenotations { private var myTypeRef: TypeRef = null - override def typeRef(implicit ctx: Context): TypeRef = { + override def typeRef(using Context): TypeRef = { if (myTypeRef == null) myTypeRef = super.typeRef myTypeRef } - override def appliedRef(implicit ctx: Context): Type = classInfo.appliedRef + override def appliedRef(using Context): Type = classInfo.appliedRef private def baseData(implicit onBehalf: BaseData, ctx: Context): (List[ClassSymbol], BaseClassSet) = { if (!baseDataCache.isValid) baseDataCache = BaseData.newCache() @@ -1841,14 +1841,14 @@ object SymDenotations { (classSymbol :: builder.baseClasses, builder.baseClassSet) } - final override def derivesFrom(base: Symbol)(implicit ctx: Context): Boolean = + final override def derivesFrom(base: Symbol)(using Context): Boolean = !isAbsent() && base.isClass && ( (symbol eq base) || (baseClassSet contains base) ) - final override def isSubClass(base: Symbol)(implicit ctx: Context): Boolean = + final override def isSubClass(base: Symbol)(using Context): Boolean = derivesFrom(base) || base.isClass && ( (symbol eq defn.NothingClass) || @@ -1861,14 +1861,14 @@ object SymDenotations { * * @return The result may contain false positives, but never false negatives. */ - final def mayHaveCommonChild(that: ClassSymbol)(implicit ctx: Context): Boolean = + final def mayHaveCommonChild(that: ClassSymbol)(using Context): Boolean = !this.is(Final) && !that.is(Final) && (this.is(Trait) || that.is(Trait)) || this.derivesFrom(that) || that.derivesFrom(this.symbol) final override def typeParamCreationFlags: FlagSet = ClassTypeParamCreationFlags /** Hook to do a pre-enter test. Overridden in PackageDenotation */ - protected def proceedWithEnter(sym: Symbol, mscope: MutableScope)(implicit ctx: Context): Boolean = true + protected def proceedWithEnter(sym: Symbol, mscope: MutableScope)(using Context): Boolean = true /** Enter a symbol in current scope, and future scopes of same denotation. * Note: We require that this does not happen after the first time @@ -1876,7 +1876,7 @@ object SymDenotations { * @param scope The scope in which symbol should be entered. * If this is EmptyScope, the scope is `decls`. */ - def enter(sym: Symbol, scope: Scope = EmptyScope)(implicit ctx: Context): Unit = { + def enter(sym: Symbol, scope: Scope = EmptyScope)(using Context): Unit = { val mscope = scope match { case scope: MutableScope => scope case _ => unforcedDecls.openForMutations @@ -1900,7 +1900,7 @@ object SymDenotations { * If `prev` is not defined in current class, do nothing. * @pre `prev` and `replacement` have the same name. */ - def replace(prev: Symbol, replacement: Symbol)(implicit ctx: Context): Unit = { + def replace(prev: Symbol, replacement: Symbol)(using Context): Unit = { unforcedDecls.openForMutations.replace(prev, replacement) if (myMemberCache != null) myMemberCache.invalidate(replacement.name) } @@ -1909,7 +1909,7 @@ object SymDenotations { * Note: We require that this does not happen after the first time * someone does a findMember on a subclass. */ - def delete(sym: Symbol)(implicit ctx: Context): Unit = { + def delete(sym: Symbol)(using Context): Unit = { info.decls.openForMutations.unlink(sym) if (myMemberCache != null) myMemberCache.invalidate(sym.name) if (!sym.flagsUNSAFE.is(Private)) invalidateMemberNamesCache() @@ -1918,7 +1918,7 @@ object SymDenotations { /** Make sure the type parameters of this class appear in the order given * by `typeParams` in the scope of the class. Reorder definitions in scope if necessary. */ - def ensureTypeParamsInCorrectOrder()(implicit ctx: Context): Unit = { + def ensureTypeParamsInCorrectOrder()(using Context): Unit = { val tparams = typeParams if (!ctx.erasedTypes && !typeParamsFromDecls.corresponds(tparams)(_.name == _.name)) { val decls = info.decls @@ -1934,7 +1934,7 @@ object SymDenotations { * The elements of the returned pre-denotation all * have existing symbols. */ - final def membersNamed(name: Name)(implicit ctx: Context): PreDenotation = { + final def membersNamed(name: Name)(using Context): PreDenotation = { val privates = info.decls.denotsNamed(name, selectPrivate) privates union nonPrivateMembersNamed(name).filterDisjoint(privates) } @@ -1944,7 +1944,7 @@ object SymDenotations { * have existing symbols. * @param inherited The method is called on a parent class from computeNPMembersNamed */ - final def nonPrivateMembersNamed(name: Name)(implicit ctx: Context): PreDenotation = { + final def nonPrivateMembersNamed(name: Name)(using Context): PreDenotation = { Stats.record("nonPrivateMembersNamed") if (Config.cacheMembersNamed) { var denots: PreDenotation = memberCache lookup name @@ -1961,7 +1961,7 @@ object SymDenotations { else computeNPMembersNamed(name) } - private[core] def computeNPMembersNamed(name: Name)(implicit ctx: Context): PreDenotation = { + private[core] def computeNPMembersNamed(name: Name)(using Context): PreDenotation = { Stats.record("computeNPMembersNamed after fingerprint") ensureCompleted() val ownDenots = info.decls.denotsNamed(name, selectNonPrivate) @@ -1985,13 +1985,13 @@ object SymDenotations { else collect(ownDenots, classParents) } - override final def findMember(name: Name, pre: Type, required: FlagSet, excluded: FlagSet)(implicit ctx: Context): Denotation = { + override final def findMember(name: Name, pre: Type, required: FlagSet, excluded: FlagSet)(using Context): Denotation = { val raw = if (excluded.is(Private)) nonPrivateMembersNamed(name) else membersNamed(name) raw.filterWithFlags(required, excluded).asSeenFrom(pre).toDenot(pre) } /** Compute tp.baseType(this) */ - final def baseTypeOf(tp: Type)(implicit ctx: Context): Type = { + final def baseTypeOf(tp: Type)(using Context): Type = { val btrCache = baseTypeCache def inCache(tp: Type) = btrCache.get(tp) != null def record(tp: CachedType, baseTp: Type) = { @@ -2169,7 +2169,7 @@ object SymDenotations { } } - override final def fullNameSeparated(kind: QualifiedNameKind)(implicit ctx: Context): Name = { + override final def fullNameSeparated(kind: QualifiedNameKind)(using Context): Name = { val cached = fullNameCache(kind) if (cached != null) cached else { @@ -2180,9 +2180,9 @@ object SymDenotations { } // to avoid overloading ambiguities - override def fullName(implicit ctx: Context): Name = super.fullName + override def fullName(using Context): Name = super.fullName - override def primaryConstructor(implicit ctx: Context): Symbol = { + override def primaryConstructor(using Context): Symbol = { def constrNamed(cname: TermName) = info.decls.denotsNamed(cname).last.symbol // denotsNamed returns Symbols in reverse order of occurrence if (this.is(Package)) NoSymbol @@ -2192,17 +2192,18 @@ object SymDenotations { /** The term parameter accessors of this class. * Both getters and setters are returned in this list. */ - def paramAccessors(implicit ctx: Context): List[Symbol] = + def paramAccessors(using Context): List[Symbol] = unforcedDecls.filter(_.is(ParamAccessor)) /** If this class has the same `decls` scope reference in `phase` and * `phase.next`, install a new denotation with a cloned scope in `phase.next`. */ - def ensureFreshScopeAfter(phase: DenotTransformer)(implicit ctx: Context): Unit = - if (ctx.phaseId != phase.next.id) ensureFreshScopeAfter(phase)(ctx.withPhase(phase.next)) + def ensureFreshScopeAfter(phase: DenotTransformer)(using Context): Unit = + if (ctx.phaseId != phase.next.id) ensureFreshScopeAfter(phase)(using ctx.withPhase(phase.next)) else { - val prevCtx = ctx.withPhase(phase) - val prevClassInfo = current(prevCtx).asInstanceOf[ClassDenotation].classInfo(prevCtx) + val prevClassInfo = inContext(ctx.withPhase(phase)) { + current.asInstanceOf[ClassDenotation].classInfo + } val ClassInfo(pre, _, ps, decls, selfInfo) = classInfo if (prevClassInfo.decls eq decls) copySymDenotation(info = ClassInfo(pre, classSymbol, ps, decls.cloneScope, selfInfo)) @@ -2213,11 +2214,11 @@ object SymDenotations { private var myCompanion: Symbol = NoSymbol /** Register companion class */ - override def registerCompanion(companion: Symbol)(implicit ctx: Context) = + override def registerCompanion(companion: Symbol)(using Context) = if (companion.isClass && !isAbsent(canForce = false) && !companion.isAbsent(canForce = false)) myCompanion = companion - override def registeredCompanion(implicit ctx: Context) = + override def registeredCompanion(using Context) = if !myCompanion.exists then ensureCompleted() myCompanion @@ -2247,7 +2248,7 @@ object SymDenotations { private var ambiguityWarningIssued: Boolean = false /** The package objects in this class */ - def packageObjs(implicit ctx: Context): List[ClassDenotation] = { + def packageObjs(using Context): List[ClassDenotation] = { if (packageObjsRunId != ctx.runId) { packageObjsRunId = ctx.runId packageObjsCache = Nil // break cycle in case we are looking for package object itself @@ -2267,7 +2268,7 @@ object SymDenotations { /** The package object (as a term symbol) in this package that might contain * `sym` as a member. */ - def packageObjFor(sym: Symbol)(implicit ctx: Context): Symbol = { + def packageObjFor(sym: Symbol)(using Context): Symbol = { val owner = sym.maybeOwner if (owner.is(Package)) NoSymbol else if (owner.isPackageObject) owner.sourceModule @@ -2291,7 +2292,7 @@ object SymDenotations { * object that hides a class or object in the scala package of the same name, because * the behavior would then be unintuitive for such members. */ - override def computeNPMembersNamed(name: Name)(implicit ctx: Context): PreDenotation = { + override def computeNPMembersNamed(name: Name)(using Context): PreDenotation = { def recur(pobjs: List[ClassDenotation], acc: PreDenotation): PreDenotation = pobjs match { case pcls :: pobjs1 => if (pcls.isCompleting) recur(pobjs1, acc) @@ -2374,7 +2375,7 @@ object SymDenotations { * If symbol is a package object, invalidate the packageObj cache. * @return `sym` is not already entered */ - override def proceedWithEnter(sym: Symbol, mscope: MutableScope)(implicit ctx: Context): Boolean = { + override def proceedWithEnter(sym: Symbol, mscope: MutableScope)(using Context): Boolean = { val entry = mscope.lookupEntry(sym.name) if (entry != null) { if (entry.sym == sym) return false @@ -2385,7 +2386,7 @@ object SymDenotations { } /** Unlink all package members defined in `file` in a previous run. */ - def unlinkFromFile(file: AbstractFile)(implicit ctx: Context): Unit = { + def unlinkFromFile(file: AbstractFile)(using Context): Unit = { val scope = unforcedDecls.openForMutations for (sym <- scope.toList.iterator) // We need to be careful to not force the denotation of `sym` here, @@ -2401,8 +2402,8 @@ object SymDenotations { override def isTerm: Boolean = false override def exists: Boolean = false override def owner: Symbol = throw new AssertionError("NoDenotation.owner") - override def computeAsSeenFrom(pre: Type)(implicit ctx: Context): SingleDenotation = this - override def mapInfo(f: Type => Type)(implicit ctx: Context): SingleDenotation = this + override def computeAsSeenFrom(pre: Type)(using Context): SingleDenotation = this + override def mapInfo(f: Type => Type)(using Context): SingleDenotation = this NoSymbol.denot = this validFor = Period.allInRun(NoRunId) } @@ -2431,7 +2432,7 @@ object SymDenotations { with ((TermSymbol, ClassSymbol) => LazyType) { self => /** Sets all missing fields of given denotation */ - def complete(denot: SymDenotation)(implicit ctx: Context): Unit + def complete(denot: SymDenotation)(using Context): Unit def apply(sym: Symbol): LazyType = this def apply(module: TermSymbol, modcls: ClassSymbol): LazyType = this @@ -2442,13 +2443,13 @@ object SymDenotations { private var myModuleClassFn: Context => Symbol = NoSymbolFn /** The type parameters computed by the completer before completion has finished */ - def completerTypeParams(sym: Symbol)(implicit ctx: Context): List[TypeParamInfo] = + def completerTypeParams(sym: Symbol)(using Context): List[TypeParamInfo] = if (sym.is(Touched)) Nil // return `Nil` instead of throwing a cyclic reference else sym.info.typeParams def decls: Scope = myDecls - def sourceModule(implicit ctx: Context): Symbol = mySourceModuleFn(ctx) - def moduleClass(implicit ctx: Context): Symbol = myModuleClassFn(ctx) + def sourceModule(using Context): Symbol = mySourceModuleFn(ctx) + def moduleClass(using Context): Symbol = myModuleClassFn(ctx) def withDecls(decls: Scope): this.type = { myDecls = decls; this } def withSourceModule(sourceModuleFn: Context => Symbol): this.type = { mySourceModuleFn = sourceModuleFn; this } @@ -2461,13 +2462,13 @@ object SymDenotations { * should be completed independently of the info. */ trait TypeParamsCompleter extends LazyType { - override def completerTypeParams(sym: Symbol)(implicit ctx: Context): List[TypeSymbol] = + override def completerTypeParams(sym: Symbol)(using Context): List[TypeSymbol] = unsupported("completerTypeParams") // should be abstract, but Scala-2 will then compute the wrong type for it } /** A missing completer */ trait NoCompleter extends LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = unsupported("complete") + def complete(denot: SymDenotation)(using Context): Unit = unsupported("complete") } @sharable object NoCompleter extends NoCompleter @@ -2478,8 +2479,8 @@ object SymDenotations { * module class, followed by copying the relevant fields to the module. */ class ModuleCompleter(_moduleClass: ClassSymbol) extends LazyType { - override def moduleClass(implicit ctx: Context): ClassSymbol = _moduleClass - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + override def moduleClass(using Context): ClassSymbol = _moduleClass + def complete(denot: SymDenotation)(using Context): Unit = { val from = moduleClass.denot.asClass denot.setFlag(from.flags.toTermFlags & RetainedModuleValFlags) denot.annotations = from.annotations filter (_.appliesToModule) @@ -2495,7 +2496,7 @@ object SymDenotations { /** A completer for missing references */ class StubInfo() extends LazyType { - def initializeToDefaults(denot: SymDenotation, errMsg: Message)(implicit ctx: Context): Unit = { + def initializeToDefaults(denot: SymDenotation, errMsg: Message)(using Context): Unit = { denot.info = denot match { case denot: ClassDenotation => ClassInfo(denot.owner.thisType, denot.classSymbol, Nil, EmptyScope) @@ -2505,7 +2506,7 @@ object SymDenotations { denot.setPrivateWithin(NoSymbol) } - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + def complete(denot: SymDenotation)(using Context): Unit = { val sym = denot.symbol val errMsg = BadSymbolicReference(denot) ctx.error(errMsg, sym.sourcePos) @@ -2520,10 +2521,10 @@ object SymDenotations { trait InheritedCache { /** Is the cache valid in current period? */ - def isValid(implicit ctx: Context): Boolean + def isValid(using Context): Boolean /** is the cache valid in current run at given phase? */ - def isValidAt(phase: Phase)(implicit ctx: Context): Boolean + def isValidAt(phase: Phase)(using Context): Boolean /** Render invalid this cache and all caches that depend on it */ def invalidate(): Unit @@ -2539,7 +2540,7 @@ object SymDenotations { implicit val None: MemberNames = new InvalidCache with MemberNames { def apply(keepOnly: NameFilter, clsd: ClassDenotation)(implicit onBehalf: MemberNames, ctx: Context) = ??? } - def newCache()(implicit ctx: Context): MemberNames = new MemberNamesImpl(ctx.period) + def newCache()(using Context): MemberNames = new MemberNamesImpl(ctx.period) } /** A cache for baseclasses, as a sequence in linearization order and as a set that @@ -2556,7 +2557,7 @@ object SymDenotations { def apply(clsd: ClassDenotation)(implicit onBehalf: BaseData, ctx: Context) = ??? def signalProvisional() = () } - def newCache()(implicit ctx: Context): BaseData = new BaseDataImpl(ctx.period) + def newCache()(using Context): BaseData = new BaseDataImpl(ctx.period) } private abstract class InheritedCacheImpl(val createdAt: Period) extends InheritedCache { @@ -2578,7 +2579,7 @@ object SymDenotations { dependent.put(dep, ()) } - def isValidAt(phase: Phase)(implicit ctx: Context) = + def isValidAt(phase: Phase)(using Context) = checkedPeriod == ctx.period || createdAt.runId == ctx.runId && createdAt.phaseId < ctx.phases.length && @@ -2587,15 +2588,15 @@ object SymDenotations { } private class InvalidCache extends InheritedCache { - def isValid(implicit ctx: Context) = false - def isValidAt(phase: Phase)(implicit ctx: Context) = false + def isValid(using Context) = false + def isValidAt(phase: Phase)(using Context) = false def invalidate(): Unit = () } private class MemberNamesImpl(createdAt: Period) extends InheritedCacheImpl(createdAt) with MemberNames { private var cache: SimpleIdentityMap[NameFilter, Set[Name]] = SimpleIdentityMap.Empty - final def isValid(implicit ctx: Context): Boolean = + final def isValid(using Context): Boolean = cache != null && isValidAt(ctx.phase) private var locked = false @@ -2638,7 +2639,7 @@ object SymDenotations { private var locked = false private var provisional = false - final def isValid(implicit ctx: Context): Boolean = valid && isValidAt(ctx.phase) + 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/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index 8bccb15ad212..0a794ee5c4fa 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -63,7 +63,7 @@ class ClassfileParser( protected val in: AbstractFileReader = new AbstractFileReader(classfile) - protected val staticModule: Symbol = moduleRoot.sourceModule(ictx) + protected val staticModule: Symbol = moduleRoot.sourceModule(using ictx) protected val instanceScope: MutableScope = newScope // the scope of all instance definitions protected val staticScope: MutableScope = newScope // the scope of all static definitions diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 0cb68ca1757e..d81074264aca 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -49,7 +49,7 @@ class Erasure extends Phase with DenotTransformer { case ref: SymDenotation => def isCompacted(sym: Symbol) = sym.isAnonymousFunction && { - sym.info(ctx.withPhase(ctx.phase.next)) match { + sym.info(using ctx.withPhase(ctx.phase.next)) match { case MethodType(nme.ALLARGS :: Nil) => true case _ => false } diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index 3b8cdad45230..71b3251eb4f7 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -135,7 +135,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete (imeth.flags | Final) &~ (Override | Protected | AbsOverride), fullyParameterizedType(imeth.info, imeth.owner.asClass), privateWithin = imeth.privateWithin, coord = imeth.coord) - extensionMeth.addAnnotations(imeth.annotations)(ctx.withPhase(thisPhase)) + extensionMeth.addAnnotations(imeth.annotations)(using ctx.withPhase(thisPhase)) // need to change phase to add tailrec annotation which gets removed from original method in the same phase. extensionMeth } From 86ae3ca102cfa97ec781a020585932cea4cae4c9 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 12:47:45 +0200 Subject: [PATCH 04/41] Remove implicit definitions of `ctx` that are not parameters --- .../tools/backend/jvm/BCodeAsmCommon.scala | 2 +- .../tools/backend/jvm/BCodeBodyBuilder.scala | 2 +- .../tools/backend/jvm/BCodeHelpers.scala | 6 +- .../tools/backend/jvm/BCodeIdiomatic.scala | 2 +- .../tools/backend/jvm/BCodeSkelBuilder.scala | 2 +- .../tools/backend/jvm/BCodeSyncAndTry.scala | 2 +- .../src/dotty/tools/backend/jvm/BTypes.scala | 2 +- .../tools/backend/jvm/BTypesFromSymbols.scala | 2 +- .../tools/backend/jvm/BytecodeWriters.scala | 2 +- .../dotty/tools/backend/jvm/CoreBTypes.scala | 2 +- .../backend/jvm/DottyBackendInterface.scala | 6 +- .../dotty/tools/backend/jvm/GenBCode.scala | 4 +- compiler/src/dotty/tools/dotc/Driver.scala | 12 +- .../dotc/ast/PluggableTransformers.scala | 105 ------------------ compiler/src/dotty/tools/dotc/ast/tpd.scala | 2 +- .../dotty/tools/dotc/core/Denotations.scala | 4 +- .../src/dotty/tools/dotc/core/Types.scala | 3 +- .../dotc/core/classfile/ClassfileParser.scala | 2 +- .../dotc/decompiler/IDEDecompilerDriver.scala | 18 +-- .../tools/dotc/transform/CapturedVars.scala | 4 +- .../dotc/transform/ElimErasedValueType.scala | 2 +- .../tools/dotc/transform/ExplicitOuter.scala | 2 +- .../tools/dotc/transform/FirstTransform.scala | 2 +- .../dotc/transform/GenericSignatures.scala | 2 +- .../tools/dotc/transform/LambdaLift.scala | 8 +- .../tools/dotc/transform/MegaPhase.scala | 2 +- .../transform/PrivateToStatic.scala.disabled | 2 +- .../tools/dotc/transform/SuperAccessors.scala | 2 +- .../tools/dotc/transform/TreeChecker.scala | 5 +- .../dotty/tools/dotc/typer/Applications.scala | 5 +- .../src/dotty/tools/repl/ParseResult.scala | 26 ++--- .../src/dotty/tools/repl/ReplCompiler.scala | 47 ++++---- .../src/dotty/tools/repl/ReplDriver.scala | 50 +++++---- docs/docs/internals/overall-structure.md | 2 +- .../languageserver/DottyLanguageServer.scala | 4 +- tests/{ => pending}/pos/inlinetuple.scala | 2 + 36 files changed, 121 insertions(+), 226 deletions(-) delete mode 100644 compiler/src/dotty/tools/dotc/ast/PluggableTransformers.scala rename tests/{ => pending}/pos/inlinetuple.scala (58%) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala b/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala index 816fec8adaa4..98627bfbec96 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeAsmCommon.scala @@ -10,7 +10,7 @@ import dotty.tools.dotc.core.Symbols._ * the compiler cake (Global). */ final class BCodeAsmCommon[I <: DottyBackendInterface](val interface: I) { - import interface._ + import interface.{_, given _} import DottyBackendInterface.symExtensions /** diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala index ff97bb307d3b..986d13372789 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala @@ -30,7 +30,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { // import global._ // import definitions._ import tpd._ - import int._ + import int.{_, given _} import DottyBackendInterface.symExtensions import bTypes._ import coreBTypes._ diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index cdfd3fa61352..f98b78494278 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala @@ -45,7 +45,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { import bTypes._ import tpd._ import coreBTypes._ - import int._ + import int.{_, given _} import DottyBackendInterface._ def ScalaATTRName: String = "Scala" @@ -360,7 +360,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { val narg = normalizeArgument(arg) // Transformation phases are not run on annotation trees, so we need to run // `constToLiteral` at this point. - val t = constToLiteral(narg)(ctx.withPhase(ctx.erasurePhase)) + val t = constToLiteral(narg)(using ctx.withPhase(ctx.erasurePhase)) t match { case Literal(const @ Constant(_)) => const.tag match { @@ -464,7 +464,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { } // end of trait BCAnnotGen trait BCJGenSigGen { - import int._ + import int.{_, given _} def getCurrentCUnit(): CompilationUnit diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala b/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala index a68f9f4bc14a..f763975663f5 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala @@ -19,7 +19,7 @@ trait BCodeIdiomatic { val int: DottyBackendInterface final lazy val bTypes = new BTypesFromSymbols[int.type](int) - import int._ + import int.{_, given _} import bTypes._ import coreBTypes._ diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala index bfa716d13426..98fa9a22967e 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala @@ -26,7 +26,7 @@ import dotty.tools.dotc.util.Spans._ * */ trait BCodeSkelBuilder extends BCodeHelpers { - import int._ + import int.{_, given _} import DottyBackendInterface.{symExtensions, _} import tpd._ import bTypes._ diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala b/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala index 60ceda5fa8b2..ac5748a42d5d 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala @@ -18,7 +18,7 @@ import dotty.tools.dotc.ast.tpd.TreeOps * */ trait BCodeSyncAndTry extends BCodeBodyBuilder { - import int._ + import int.{_, given _} import tpd._ import bTypes._ import coreBTypes._ diff --git a/compiler/src/dotty/tools/backend/jvm/BTypes.scala b/compiler/src/dotty/tools/backend/jvm/BTypes.scala index 7df2e674f3a5..5a65c0ff21f4 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypes.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypes.scala @@ -15,7 +15,7 @@ import scala.tools.asm abstract class BTypes { val int: DottyBackendInterface - import int._ + import int.{_, given _} /** * A map from internal names to ClassBTypes. Every ClassBType is added to this map on its * construction. diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index 02bb27f7234d..bffb1d106801 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala @@ -27,7 +27,7 @@ import dotty.tools.dotc.util.WeakHashSet * not have access to the compiler instance. */ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { - import int._ + import int.{_, given _} import DottyBackendInterface.{symExtensions, _} lazy val TransientAttr = requiredClass[scala.transient] diff --git a/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala b/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala index 513e2d7f127e..1de8d54e3eff 100644 --- a/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala +++ b/compiler/src/dotty/tools/backend/jvm/BytecodeWriters.scala @@ -16,7 +16,7 @@ class FileConflictException(msg: String, val file: AbstractFile) extends IOExcep */ trait BytecodeWriters { val int: DottyBackendInterface - import int._ + import int.{_, given _} /** * @param clsName cls.getName diff --git a/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala b/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala index 2d4aec72d0b1..f9db89a9eea9 100644 --- a/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala +++ b/compiler/src/dotty/tools/backend/jvm/CoreBTypes.scala @@ -33,7 +33,7 @@ import dotty.tools.dotc.transform.Erasure */ class CoreBTypes[BTFS <: BTypesFromSymbols[_ <: DottyBackendInterface]](val bTypes: BTFS) { import bTypes._ - import int._ + import int.{_, given _} import DottyBackendInterface._ //import global._ diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index b39e68646250..e84266f34eb2 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -34,7 +34,7 @@ import Names.TermName import Annotations.Annotation import Names.Name -class DottyBackendInterface(val outputDirectory: AbstractFile, val superCallsMap: Map[Symbol, Set[ClassSymbol]])(implicit val ctx: Context) { +class DottyBackendInterface(val outputDirectory: AbstractFile, val superCallsMap: Map[Symbol, Set[ClassSymbol]])(using val ctx: Context) { private val desugared = new java.util.IdentityHashMap[Type, tpd.Select] @@ -107,10 +107,10 @@ object DottyBackendInterface { else clazz.getName } - def requiredClass[T](implicit evidence: ClassTag[T], ctx: Context): Symbol = + def requiredClass[T](using evidence: ClassTag[T], ctx: Context): Symbol = ctx.requiredClass(erasureString(evidence.runtimeClass)) - def requiredModule[T](implicit evidence: ClassTag[T], ctx: Context): Symbol = { + 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) diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index 49fd86aef855..694ce9bd8b56 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -48,7 +48,7 @@ class GenBCode extends Phase { def run(implicit ctx: Context): Unit = { new GenBCodePipeline(new DottyBackendInterface( - outputDir, superCallsMap.toMap)(ctx))(ctx).run(ctx.compilationUnit.tpdTree) + outputDir, superCallsMap.toMap)(using ctx))(using ctx).run(ctx.compilationUnit.tpdTree) } override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { @@ -69,7 +69,7 @@ object GenBCode { val name: String = "genBCode" } -class GenBCodePipeline(val int: DottyBackendInterface)(implicit ctx: Context) extends BCodeSyncAndTry { +class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) extends BCodeSyncAndTry { import DottyBackendInterface.symExtensions private var tree: Tree = _ diff --git a/compiler/src/dotty/tools/dotc/Driver.scala b/compiler/src/dotty/tools/dotc/Driver.scala index 90f49595c784..187203ee68de 100644 --- a/compiler/src/dotty/tools/dotc/Driver.scala +++ b/compiler/src/dotty/tools/dotc/Driver.scala @@ -155,12 +155,12 @@ class Driver { */ final def process(args: Array[String], reporter: Reporter = null, callback: interfaces.CompilerCallback = null): Reporter = { - val ctx = initCtx.fresh + val compileCtx = initCtx.fresh if (reporter != null) - ctx.setReporter(reporter) + compileCtx.setReporter(reporter) if (callback != null) - ctx.setCompilerCallback(callback) - process(args, ctx) + compileCtx.setCompilerCallback(callback) + process(args, compileCtx) } /** Entry point to the compiler with no optional arguments. @@ -190,8 +190,8 @@ class Driver { * if compilation succeeded. */ def process(args: Array[String], rootCtx: Context): Reporter = { - val (fileNames, ctx) = setup(args, rootCtx) - doCompile(newCompiler(ctx), fileNames)(ctx) + val (fileNames, compileCtx) = setup(args, rootCtx) + doCompile(newCompiler(compileCtx), fileNames)(compileCtx) } def main(args: Array[String]): Unit = { diff --git a/compiler/src/dotty/tools/dotc/ast/PluggableTransformers.scala b/compiler/src/dotty/tools/dotc/ast/PluggableTransformers.scala deleted file mode 100644 index f03ec23049d2..000000000000 --- a/compiler/src/dotty/tools/dotc/ast/PluggableTransformers.scala +++ /dev/null @@ -1,105 +0,0 @@ -package dotty.tools.dotc -package ast - - -object PluggableTransformers { -/* - import Trees._, Contexts._ - - abstract class PluggableTransformer[T] extends TreeTransformer[T, Context] { - type PluginOp[-N <: Tree[T]] = N => Tree[T] - - private var _ctx: Context = _ - private var _oldTree: Tree[T] = _ - - protected implicit def ctx: Context = _ctx - protected def oldTree: Tree[T] = _oldTree - protected def thisTransformer: PluggableTransformer[T] = this - - class PluginOps[-N <: Tree[T]](op: PluginOp[N], val next: Plugins) { - def apply(tree: N, old: Tree[T], c: Context): Tree[T] = { - val savedCtx = _ctx - val savedOld = _oldTree - try { - op(tree) - } finally { - _oldTree = savedOld - _ctx = savedCtx - } - } - } - - val NoOp: PluginOp[Tree[T]] = identity - val NoOps = new PluginOps(NoOp, null) - - class Plugins { - def next: Plugins = null - - def processIdent: PluginOp[Ident[T]] = NoOp - def processSelect: PluginOp[Select[T]] = NoOp - - val IdentOps: PluginOps[Ident[T]] = NoOps - val SelectOps: PluginOps[Select[T]] = NoOps - } - - val EmptyPlugin = new Plugins - - private var _plugins: Plugins = EmptyPlugin - - override def plugins: Plugins = _plugins - - class Plugin extends Plugins { - override val next = _plugins - _plugins = this - - private def push[N <: Tree[T]](op: PluginOp[N], ops: => PluginOps[N]): PluginOps[N] = - if (op == NoOp) ops else new PluginOps(op, next) - - override val IdentOps: PluginOps[Ident[T]] = push(processIdent, next.IdentOps) - override val SelectOps: PluginOps[Select[T]] = push(processSelect, next.SelectOps) - } - - def postIdent(tree: Ident[T], old: Tree[T], c: Context, ops: PluginOps[Ident[T]]) = - if (ops eq NoOps) tree - else finishIdent(ops(tree, old, c), old, c, ops.next) - - override def finishIdent(tree: Tree[T], old: Tree[T], c: Context, plugins: Plugins): Tree[T] = tree match { - case tree: Ident[?] => postIdent(tree, old, c, plugins.IdentOps) - case _ => postProcess(tree, old, c, plugins) - } - - def postSelect(tree: Select[T], old: Tree[T], c: Context, ops: PluginOps[Select[T]]) = - if (ops eq NoOps) tree - else finishSelect(ops(tree, old, c), old, c, ops.next) - - override def finishSelect(tree: Tree[T], old: Tree[T], c: Context, plugins: Plugins): Tree[T] = tree match { - case tree: Select[?] => postSelect(tree, old, c, plugins.SelectOps) - case _ => postProcess(tree, old, c, plugins) - } - - protected def postProcess(tree: Tree[T], old: Tree[T], c: Context, plugins: Plugins): Tree[T] = tree match { - case tree: Ident[?] => finishIdent(tree, old, c, plugins) - case tree: Select[?] => finishSelect(tree, old, c, plugins) - } - } -} - -import PluggableTransformers._, Types._, Trees._, Contexts._ - -class ExampleTransformer extends PluggableTransformer[Type] { - - object ExamplePlugin extends Plugin { - override def processIdent = { - case tree @ Ident(x) if x.isTypeName => tree.derivedSelect(tree, x) - case tree => tpd.Ident(???) - } - override def processSelect = { tree => - if (tree.isType) tree.derivedIdent(tree.name) - else tpd.EmptyTree - } - } - - override def transform(tree: tpd.Tree, ctx: Context) = - super.transform(tree, ctx) -*/ -} diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 129c31ff1874..844b29d4e33b 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -847,7 +847,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { traverser.traverse(tree) tree } - else changeOwnerAfter(from, to, trans)(ctx.withPhase(trans.next)) + else changeOwnerAfter(from, to, trans)(using ctx.withPhase(trans.next)) /** A select node with the given selector name and a computed type */ def select(name: Name)(implicit ctx: Context): Select = diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index 465101fe3f5f..9ecd73f8561d 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -3,7 +3,7 @@ package dotc package core import SymDenotations.{ SymDenotation, ClassDenotation, NoDenotation, LazyType } -import Contexts.{Context, Ctx, ctx, ContextBase} +import Contexts.{Context, ctx, ContextBase} import Names._ import NameKinds._ import StdNames._ @@ -797,7 +797,7 @@ object Denotations { val transformer = ctx.base.denotTransformers(nextTransformerId) //println(s"transforming $this with $transformer") try - next = transformer.transform(cur)(ctx.withPhase(transformer)) + next = transformer.transform(cur)(using ctx.withPhase(transformer)) catch { case ex: CyclicReference => println(s"error while transforming $this") // DEBUG diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index d4d961baab27..270a6c47cac8 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -4919,7 +4919,8 @@ object Types { def mapOver(tp: Type): Type = { record(s"mapOver ${getClass}") record("mapOver total") - implicit val ctx = this.mapCtx + val ctx = this.mapCtx // optimization for performance + given Context = ctx tp match { case tp: NamedType => if stopBecauseStaticOrLocal(tp) then tp diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index 0a794ee5c4fa..ddc1c3421184 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -939,7 +939,7 @@ class ClassfileParser( val outerName = entry.outerName.stripModuleClassSuffix val innerName = entry.originalName val owner = classNameToSymbol(outerName) - val result = getMember(owner, innerName.toTypeName)(ctx.withPhase(ctx.typerPhase)) + val result = getMember(owner, innerName.toTypeName)(using ctx.withPhase(ctx.typerPhase)) assert(result ne NoSymbol, i"""failure to resolve inner class: |externalName = ${entry.externalName}, diff --git a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala index 25c487599901..54853314f277 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala @@ -29,16 +29,16 @@ class IDEDecompilerDriver(val settings: List[String]) extends dotc.Driver { val run = decompiler.newRun(myInitCtx.fresh.setReporter(reporter)) - implicit val ctx = run.runContext + inContext(run.runContext) { + run.compile(List(className)) + run.printSummary() + val unit = ctx.run.units.head - run.compile(List(className)) - run.printSummary() - val unit = ctx.run.units.head + val decompiled = ReflectionImpl.showTree(unit.tpdTree) + val tree = new TastyHTMLPrinter(unit.pickled.head._2).printContents() - val decompiled = ReflectionImpl.showTree(unit.tpdTree) - val tree = new TastyHTMLPrinter(unit.pickled.head._2).printContents() - - reporter.removeBufferedMessages.foreach(message => System.err.println(message)) - (tree, decompiled) + reporter.removeBufferedMessages.foreach(message => System.err.println(message)) + (tree, decompiled) + } } } diff --git a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala index e32c2e981a13..201f6c6b04df 100644 --- a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala +++ b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala @@ -76,7 +76,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = { val captured = (new CollectCaptured) - .runOver(ctx.compilationUnit.tpdTree)(ctx.withPhase(thisPhase)) + .runOver(ctx.compilationUnit.tpdTree)(using ctx.withPhase(thisPhase)) ctx.fresh.updateStore(Captured, captured) } @@ -91,7 +91,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = } override def prepareForValDef(vdef: ValDef)(implicit ctx: Context): Context = { - val sym = vdef.symbol(ctx.withPhase(thisPhase)) + val sym = vdef.symbol(using ctx.withPhase(thisPhase)) if (captured contains sym) { val newd = sym.denot(using ctx.withPhase(thisPhase)).copySymDenotation( info = refClass(sym.info.classSymbol, sym.hasAnnotation(defn.VolatileAnnot)).typeRef, diff --git a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala index 788e6240a05e..200812946f06 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala @@ -78,7 +78,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => * this phase, yet do not have matching types before erasure. */ private def checkNoClashes(root: Symbol)(implicit ctx: Context) = { - val opc = new OverridingPairs.Cursor(root)(ctx.withPhase(thisPhase)) { + 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) = diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index c88cd872a6a8..33c9004459a2 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -347,7 +347,7 @@ object ExplicitOuter { */ class OuterOps(val ictx: Context) extends AnyVal { /** The context of all operations of this class */ - private implicit def ctx: Context = ictx + given Context = ictx /** If `cls` has an outer parameter add one to the method type `tp`. */ def addParam(cls: ClassSymbol, tp: Type): Type = diff --git a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala index 5bf720e831fc..523a06fc2a9c 100644 --- a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala @@ -129,7 +129,7 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => } override def transformStats(trees: List[Tree])(implicit ctx: Context): List[Tree] = - ast.Trees.flatten(reorderAndComplete(trees)(ctx.withPhase(thisPhase.next))) + ast.Trees.flatten(reorderAndComplete(trees)(using ctx.withPhase(thisPhase.next))) private object collectBinders extends TreeAccumulator[List[Ident]] { def apply(annots: List[Ident], t: Tree)(implicit ctx: Context): List[Ident] = t match { diff --git a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala index 556347b1acee..b2ac64e4f230 100644 --- a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala +++ b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala @@ -34,7 +34,7 @@ object GenericSignatures { def javaSig(sym0: Symbol, info: Type)(implicit ctx: Context): Option[String] = // Avoid generating a signature for local symbols. if (sym0.isLocal) None - else javaSig0(sym0, info)(ctx.withPhase(ctx.erasurePhase)) + else javaSig0(sym0, info)(using ctx.withPhase(ctx.erasurePhase)) @noinline private final def javaSig0(sym0: Symbol, info: Type)(implicit ctx: Context): Option[String] = { diff --git a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala index b0e236db6d1a..1e92b5a4dfdc 100644 --- a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala +++ b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala @@ -162,7 +162,7 @@ object LambdaLift { if (intermediate.exists) narrowLiftedOwner(enclosure, intermediate) if !intermediate.isRealClass || nestedInConstructor(enclosure) then // Constructors and methods nested inside traits get the free variables - // of the enclosing trait or class. + // of the enclosing trait or class. // Conversely, local traits do not get free variables. // Methods inside constructors also don't have intermediates, // need to get all their free variables passed directly. @@ -374,8 +374,8 @@ object LambdaLift { (new CollectDependencies).traverse(ctx.compilationUnit.tpdTree) computeFreeVars() computeLiftedOwners() - generateProxies()(ctx.withPhase(thisPhase.next)) - liftLocals()(ctx.withPhase(thisPhase.next)) + generateProxies()(using ctx.withPhase(thisPhase.next)) + liftLocals()(using ctx.withPhase(thisPhase.next)) } def currentEnclosure(implicit ctx: Context): Symbol = @@ -421,7 +421,7 @@ object LambdaLift { } def proxyRef(sym: Symbol)(implicit ctx: Context): Tree = { - val psym = proxy(sym)(ctx.withPhase(thisPhase)) + val psym = proxy(sym)(using ctx.withPhase(thisPhase)) thisPhase.transformFollowingDeep(if (psym.owner.isTerm) ref(psym) else memberRef(psym)) } diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index 5f6ef3daf9ae..392138d1b864 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -424,7 +424,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { override def run(implicit ctx: Context): Unit = ctx.compilationUnit.tpdTree = - transformUnit(ctx.compilationUnit.tpdTree)(ctx.withPhase(miniPhases.last.next)) + transformUnit(ctx.compilationUnit.tpdTree)(using ctx.withPhase(miniPhases.last.next)) // Initialization code diff --git a/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled b/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled index 51dc44d8b90a..2c618bdd365a 100644 --- a/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled @@ -31,7 +31,7 @@ class PrivateToStatic extends MiniPhase with SymTransformer { thisTransform => private val Immovable = Deferred | Accessor | JavaStatic def shouldBeStatic(sd: SymDenotation)(implicit ctx: Context) = - sd.current(ctx.withPhase(thisTransform)).asSymDenotation + sd.current(using ctx.withPhase(thisTransform)).asSymDenotation .is(PrivateMethod, butNot = Immovable) && sd.owner.is(Trait) diff --git a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala index 3604c5d9f4f7..619821f5d5ac 100644 --- a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala @@ -147,7 +147,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { } if (name.isTermName && mix.name.isEmpty && (clazz.is(Trait) || clazz != ctx.owner.enclosingClass || !validCurrentClass)) - superAccessorCall(sel)(ctx.withPhase(thisPhase.next)) + superAccessorCall(sel)(using ctx.withPhase(thisPhase.next)) else sel } diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index f7737c29094a..df0655d8df2c 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -148,8 +148,9 @@ class TreeChecker extends Phase with SymTransformer { try checker.typedExpr(ctx.compilationUnit.tpdTree)(using checkingCtx) catch { case NonFatal(ex) => //TODO CHECK. Check that we are bootstrapped - implicit val ctx = checkingCtx - println(i"*** error while checking ${ctx.compilationUnit} after phase ${checkingCtx.phase.prev} ***") + inContext(checkingCtx) { + println(i"*** error while checking ${ctx.compilationUnit} after phase ${ctx.phase.prev} ***") + } throw ex } } diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index b8efedf721ab..f03374313693 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -1454,10 +1454,7 @@ trait Applications extends Compatibility { isApplicableMethodRef(alt2, formals1, WildcardType) || tp1.paramInfos.isEmpty && tp2.isInstanceOf[LambdaType] case tp1: PolyType => // (2) - val nestedCtx = ctx.fresh.setExploreTyperState() - locally { - implicit val ctx = nestedCtx - + inContext(ctx.fresh.setExploreTyperState()) { // Fully define the PolyType parameters so that the infos of the // tparams created below never contain TypeRefs whose underling types // contain uninstantiated TypeVars, this could lead to cycles in diff --git a/compiler/src/dotty/tools/repl/ParseResult.scala b/compiler/src/dotty/tools/repl/ParseResult.scala index c4ebb7cbfdf2..a88a90f152cd 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 +import dotc.core.Contexts.{Context, inContext} import dotc.core.StdNames.str import dotc.parsing.Parsers.Parser import dotc.parsing.Tokens @@ -142,18 +142,18 @@ object ParseResult { } } case _ => - implicit val ctx: Context = state.context - - val reporter = newStoreReporter - val stats = parseStats(state.context.fresh.setReporter(reporter).withSource(source)) - - if (reporter.hasErrors) - SyntaxErrors( - sourceCode, - reporter.removeBufferedMessages, - stats) - else - Parsed(source, stats) + inContext(state.context) { + val reporter = newStoreReporter + val stats = parseStats(state.context.fresh.setReporter(reporter).withSource(source)) + + if (reporter.hasErrors) + SyntaxErrors( + sourceCode, + reporter.removeBufferedMessages, + stats) + else + Parsed(source, stats) + } } } diff --git a/compiler/src/dotty/tools/repl/ReplCompiler.scala b/compiler/src/dotty/tools/repl/ReplCompiler.scala index 7947022444aa..05f8b8afbc4b 100644 --- a/compiler/src/dotty/tools/repl/ReplCompiler.scala +++ b/compiler/src/dotty/tools/repl/ReplCompiler.scala @@ -71,11 +71,9 @@ class ReplCompiler extends Compiler { private case class Definitions(stats: List[untpd.Tree], state: State) - private def definitions(trees: List[untpd.Tree], state: State): Definitions = { + private def definitions(trees: List[untpd.Tree], state: State): Definitions = inContext(state.context) { import untpd._ - implicit val ctx: Context = state.context - // If trees is of the form `{ def1; def2; def3 }` then `List(def1, def2, def3)` val flattened = trees match { case List(Block(stats, expr)) => @@ -127,17 +125,16 @@ class ReplCompiler extends Compiler { * } * ``` */ - private def wrapped(defs: Definitions, objectTermName: TermName, span: Span): untpd.PackageDef = { - import untpd._ + private def wrapped(defs: Definitions, objectTermName: TermName, span: Span): untpd.PackageDef = + inContext(defs.state.context) { + import untpd._ - implicit val ctx: Context = defs.state.context + val tmpl = Template(emptyConstructor, Nil, Nil, EmptyValDef, defs.stats) + val module = ModuleDef(objectTermName, tmpl) + .withSpan(span) - val tmpl = Template(emptyConstructor, Nil, Nil, EmptyValDef, defs.stats) - val module = ModuleDef(objectTermName, tmpl) - .withSpan(span) - - PackageDef(Ident(nme.EMPTY_PACKAGE), List(module)) - } + PackageDef(Ident(nme.EMPTY_PACKAGE), List(module)) + } private def createUnit(defs: Definitions, span: Span)(implicit ctx: Context): CompilationUnit = { val objectName = ctx.source.file.toString @@ -179,8 +176,7 @@ class ReplCompiler extends Compiler { } } - def docOf(expr: String)(implicit state: State): Result[String] = { - implicit val ctx: Context = state.context + def docOf(expr: String)(implicit state: State): Result[String] = inContext(state.context) { /** Extract the "selected" symbol from `tree`. * @@ -274,19 +270,20 @@ class ReplCompiler extends Compiler { val src = SourceFile.virtual("", expr) - implicit val ctx: Context = state.context.fresh + inContext(state.context.fresh .setReporter(newStoreReporter) .setSetting(state.context.settings.YstopAfter, List("typer")) - - wrapped(expr, src, state).flatMap { pkg => - val unit = CompilationUnit(src) - unit.untpdTree = pkg - ctx.run.compileUnits(unit :: Nil, ctx) - - if (errorsAllowed || !ctx.reporter.hasErrors) - unwrapped(unit.tpdTree, src) - else - ctx.reporter.removeBufferedMessages.errors[tpd.ValDef] // Workaround #4988 + ) { + wrapped(expr, src, state).flatMap { pkg => + val unit = CompilationUnit(src) + unit.untpdTree = pkg + ctx.run.compileUnits(unit :: Nil, ctx) + + if (errorsAllowed || !ctx.reporter.hasErrors) + unwrapped(unit.tpdTree, src) + else + ctx.reporter.removeBufferedMessages.errors[tpd.ValDef] // Workaround #4988 + } } } } diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 6d8c9c82043d..7b5ede2bf3f2 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -4,7 +4,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.Context +import dotty.tools.dotc.core.Contexts.{Context, ctx, inContext} import dotty.tools.dotc.core.Denotations.Denotation import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Mode @@ -207,10 +207,11 @@ class ReplDriver(settings: Array[String], case _ => // new line, empty tree state } - implicit val ctx: Context = newState.context - if (!ctx.settings.XreplDisableDisplay.value) - out.println() - newState + inContext(newState.context) { + if (!ctx.settings.XreplDisableDisplay.value) + out.println() + newState + } } /** Compile `parsed` trees and evolve `state` in accordance */ @@ -244,25 +245,26 @@ class ReplDriver(settings: Array[String], .removeBufferedMessages(newState.context) .map(rendering.formatError) - implicit val ctx: Context = newState.context - val (updatedState, definitions) = - if (!ctx.settings.XreplDisableDisplay.value) - renderDefinitions(unit.tpdTree, newestWrapper)(newStateWithImports) - else - (newStateWithImports, Seq.empty) - - // output is printed in the order it was put in. warnings should be - // shown before infos (eg. typedefs) for the same line. column - // ordering is mostly to make tests deterministic - implicit val diagnosticOrdering: Ordering[Diagnostic] = - Ordering[(Int, Int, Int)].on(d => (d.pos.line, -d.level, d.pos.column)) - - (definitions ++ warnings) - .sorted - .map(_.msg) - .foreach(out.println) - - updatedState + inContext(newState.context) { + val (updatedState, definitions) = + if (!ctx.settings.XreplDisableDisplay.value) + renderDefinitions(unit.tpdTree, newestWrapper)(newStateWithImports) + else + (newStateWithImports, Seq.empty) + + // output is printed in the order it was put in. warnings should be + // shown before infos (eg. typedefs) for the same line. column + // ordering is mostly to make tests deterministic + implicit val diagnosticOrdering: Ordering[Diagnostic] = + Ordering[(Int, Int, Int)].on(d => (d.pos.line, -d.level, d.pos.column)) + + (definitions ++ warnings) + .sorted + .map(_.msg) + .foreach(out.println) + + updatedState + } } ) } diff --git a/docs/docs/internals/overall-structure.md b/docs/docs/internals/overall-structure.md index 0783b1b96a66..f49942df3aee 100644 --- a/docs/docs/internals/overall-structure.md +++ b/docs/docs/internals/overall-structure.md @@ -55,7 +55,7 @@ call-graph. To run, e.g. some compiler function `f` at a given phase `phase`, we invoke `f` with an explicit context parameter, like this ```scala -f(/*normal args*/)(ctx.withPhase(phase)) +f(/*normal args*/)(using ctx.withPhase(phase)) ``` This assumes that `f` is defined in the way most compiler functions are: diff --git a/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala b/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala index 1cd39fac92ab..19fcef82dc37 100644 --- a/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala +++ b/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala @@ -360,7 +360,7 @@ class DottyLanguageServer extends LanguageServer perProjectInfo.flatMap { (remoteDriver, ctx, definitions) => definitions.flatMap { definition => - val name = definition.name(ctx).sourceModuleName.toString + val name = definition.name(using ctx).sourceModuleName.toString val trees = remoteDriver.sourceTreesContaining(name)(ctx) val matches = Interactive.findTreesMatching(trees, includes, definition)(ctx) matches.map(tree => location(tree.namePos(ctx))) @@ -418,7 +418,7 @@ class DottyLanguageServer extends LanguageServer perProjectInfo.flatMap { (remoteDriver, ctx, definitions) => definitions.flatMap { definition => - val name = definition.name(ctx).sourceModuleName.toString + val name = definition.name(using ctx).sourceModuleName.toString val trees = remoteDriver.sourceTreesContaining(name)(ctx) Interactive.findTreesMatching(trees, include, diff --git a/tests/pos/inlinetuple.scala b/tests/pending/pos/inlinetuple.scala similarity index 58% rename from tests/pos/inlinetuple.scala rename to tests/pending/pos/inlinetuple.scala index 62680108e161..ac457ebfa0d9 100644 --- a/tests/pos/inlinetuple.scala +++ b/tests/pending/pos/inlinetuple.scala @@ -1,3 +1,5 @@ +// TODO: Ensure that this inlines properly. So far only +// x._1 inlines, but not x._2. object Test: def g(x: Int, y: Int) = x + y From 1d8cb7cc57acda8f172e82365900ab2ac75c3631 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 13:42:55 +0200 Subject: [PATCH 05/41] Change Printers to givens --- compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala | 6 ++++-- compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala index 4615e221635d..d2fff4879719 100644 --- a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala +++ b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala @@ -3,7 +3,8 @@ package printing import core._ import Texts._, Types._, Flags._, Names._, Symbols._, NameOps._, Constants._, Denotations._ -import Contexts.Context, Scopes.Scope, Denotations.Denotation, Annotations.Annotation +import Contexts.{Context} +import Scopes.Scope, Denotations.Denotation, Annotations.Annotation import StdNames.nme import ast.Trees._ import typer.Implicits._ @@ -18,7 +19,8 @@ class PlainPrinter(_ctx: Context) extends Printer { /** The context of all public methods in Printer and subclasses. * Overridden in RefinedPrinter. */ - protected implicit def ctx: Context = _ctx.addMode(Mode.Printing) + protected def curCtx: Context = _ctx.addMode(Mode.Printing) + protected given ctx[Dummy] as Context = curCtx protected def printDebug = ctx.settings.YprintDebug.value diff --git a/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala b/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala index fa1218a80fec..7da1088188c0 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 +import Contexts.{Context} import Annotations.Annotation import Denotations._ import SymDenotations._ @@ -32,11 +32,11 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { /** A stack of enclosing DefDef, TypeDef, or ClassDef, or ModuleDefs nodes */ private var enclosingDef: untpd.Tree = untpd.EmptyTree - private var myCtx: Context = super.ctx + private var myCtx: Context = super.curCtx private var printPos = ctx.settings.YprintPos.value private val printLines = ctx.settings.printLines.value - override protected implicit def ctx: Context = myCtx + override protected def curCtx: Context = myCtx def withEnclosingDef(enclDef: Tree[? >: Untyped])(op: => Text): Text = { val savedCtx = myCtx From 9d52399a035422c64a515236480686eb53755c9c Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 13:44:21 +0200 Subject: [PATCH 06/41] Change Printers to givens --- compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala | 4 ++-- compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala index d2fff4879719..f31daa33d13c 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} +import Contexts.{Context, ctx} import Scopes.Scope, Denotations.Denotation, Annotations.Annotation import StdNames.nme import ast.Trees._ @@ -20,7 +20,7 @@ class PlainPrinter(_ctx: Context) extends Printer { * Overridden in RefinedPrinter. */ protected def curCtx: Context = _ctx.addMode(Mode.Printing) - protected given ctx[Dummy] as Context = curCtx + protected given [DummyToEnforceDef] as Context = curCtx protected def printDebug = ctx.settings.YprintDebug.value diff --git a/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala b/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala index 7da1088188c0..e9ed8d54887d 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} +import Contexts.{Context, ctx} import Annotations.Annotation import Denotations._ import SymDenotations._ From d1f2a11fd7710883088b4b2269df687270901296 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 13:50:44 +0200 Subject: [PATCH 07/41] Remove implicit definitions of `ctx` that are not parameters (2) --- .../tools/dotc/interactive/Interactive.scala | 4 +- .../dotc/interactive/InteractiveDriver.scala | 2 +- .../dotc/printing/SyntaxHighlighting.scala | 2 +- .../tools/dotc/transform/MegaPhase.scala | 64 +- .../PatternMatcherOld.scala.disabled | 1871 ----------------- .../transform/PrivateToStatic.scala.disabled | 94 - .../src/dotty/tools/repl/ReplCompiler.scala | 2 +- .../src/dotty/tools/repl/ReplDriver.scala | 6 +- 8 files changed, 40 insertions(+), 2005 deletions(-) delete mode 100644 compiler/src/dotty/tools/dotc/transform/PatternMatcherOld.scala.disabled delete mode 100644 compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled diff --git a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala index b03d69ad4a0d..d05d8772c6cd 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala @@ -333,7 +333,7 @@ object Interactive { * @return The definitions for the symbol at the end of `path`. */ def findDefinitions(path: List[Tree], pos: SourcePosition, driver: InteractiveDriver): List[SourceTree] = { - implicit val ctx = driver.currentCtx + given Context = driver.currentCtx val enclTree = enclosingTree(path) val includeOverridden = enclTree.isInstanceOf[MemberDef] val symbols = enclosingSourceSymbols(path, pos) @@ -355,7 +355,7 @@ object Interactive { driver: InteractiveDriver, includeOverridden: Boolean, includeExternal: Boolean): List[SourceTree] = { - implicit val ctx = driver.currentCtx + given Context = driver.currentCtx val include = Include.definitions | Include.overriding | (if (includeOverridden) Include.overridden else Include.empty) symbols.flatMap { sym => diff --git a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala index 14a7075fef65..1b2edc2e8288 100644 --- a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala +++ b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala @@ -149,7 +149,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { val run = compiler.newRun(myInitCtx.fresh.setReporter(reporter)) myCtx = run.runContext - implicit val ctx = myCtx + given Context = myCtx myOpenedFiles(uri) = source diff --git a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala index 56c6f5716b6d..f8815e62e841 100644 --- a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala +++ b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala @@ -35,7 +35,7 @@ object SyntaxHighlighting { else { val source = SourceFile.virtual("", in) - implicit val ctx = freshCtx.setCompilationUnit(CompilationUnit(source, mustExist = false)(freshCtx)) + given Context = freshCtx.setCompilationUnit(CompilationUnit(source, mustExist = false)(freshCtx)) val colorAt = Array.fill(in.length)(NoColor) diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index 392138d1b864..0c5ebffa99bd 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -221,14 +221,14 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def transformNamed(tree: Tree, start: Int, outerCtx: Context): Tree = tree match { case tree: Ident => - implicit val ctx = prepIdent(tree, start)(outerCtx) + given Context = prepIdent(tree, start)(outerCtx) goIdent(tree, start) case tree: Select => - implicit val ctx = prepSelect(tree, start)(outerCtx) + given Context = prepSelect(tree, start)(outerCtx) val qual = transformTree(tree.qualifier, start) goSelect(cpy.Select(tree)(qual, tree.name), start) case tree: ValDef => - implicit val ctx = prepValDef(tree, start)(outerCtx) + given Context = prepValDef(tree, start)(outerCtx) def mapValDef(implicit ctx: Context) = { val tpt = transformTree(tree.tpt, start) val rhs = transformTree(tree.rhs, start) @@ -237,7 +237,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { if (tree.isEmpty) tree else goValDef(mapValDef(if (tree.symbol.exists) localContext else ctx), start) case tree: DefDef => - implicit val ctx = prepDefDef(tree, start)(outerCtx) + given Context = prepDefDef(tree, start)(outerCtx) def mapDefDef(implicit ctx: Context) = { val tparams = transformSpecificTrees(tree.tparams, start) val vparamss = tree.vparamss.mapConserve(transformSpecificTrees(_, start)) @@ -247,110 +247,110 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } goDefDef(mapDefDef(localContext), start) case tree: TypeDef => - implicit val ctx = prepTypeDef(tree, start)(outerCtx) + given Context = prepTypeDef(tree, start)(outerCtx) val rhs = transformTree(tree.rhs, start)(localContext) goTypeDef(cpy.TypeDef(tree)(tree.name, rhs), start) case tree: Labeled => - implicit val ctx = prepLabeled(tree, start)(outerCtx) + given Context = prepLabeled(tree, start)(outerCtx) val bind = transformTree(tree.bind, start).asInstanceOf[Bind] val expr = transformTree(tree.expr, start) goLabeled(cpy.Labeled(tree)(bind, expr), start) case tree: Bind => - implicit val ctx = prepBind(tree, start)(outerCtx) + given Context = prepBind(tree, start)(outerCtx) val body = transformTree(tree.body, start) goBind(cpy.Bind(tree)(tree.name, body), start) case _ => - implicit val ctx = prepOther(tree, start)(outerCtx) + given Context = prepOther(tree, start)(outerCtx) goOther(tree, start) } def transformUnnamed(tree: Tree, start: Int, outerCtx: Context): Tree = tree match { case tree: Apply => - implicit val ctx = prepApply(tree, start)(outerCtx) + given Context = prepApply(tree, start)(outerCtx) val fun = transformTree(tree.fun, start) val args = transformTrees(tree.args, start) goApply(cpy.Apply(tree)(fun, args), start) case tree: TypeTree => - implicit val ctx = prepTypeTree(tree, start)(outerCtx) + given Context = prepTypeTree(tree, start)(outerCtx) goTypeTree(tree, start) case tree: Thicket => cpy.Thicket(tree)(transformTrees(tree.trees, start)) case tree: This => - implicit val ctx = prepThis(tree, start)(outerCtx) + given Context = prepThis(tree, start)(outerCtx) goThis(tree, start) case tree: Literal => - implicit val ctx = prepLiteral(tree, start)(outerCtx) + given Context = prepLiteral(tree, start)(outerCtx) goLiteral(tree, start) case tree: Block => - implicit val ctx = prepBlock(tree, start)(outerCtx) + given Context = prepBlock(tree, start)(outerCtx) val stats = transformStats(tree.stats, ctx.owner, start) val expr = transformTree(tree.expr, start) goBlock(cpy.Block(tree)(stats, expr), start) case tree: TypeApply => - implicit val ctx = prepTypeApply(tree, start)(outerCtx) + given Context = prepTypeApply(tree, start)(outerCtx) val fun = transformTree(tree.fun, start) val args = transformTrees(tree.args, start) goTypeApply(cpy.TypeApply(tree)(fun, args), start) case tree: If => - implicit val ctx = prepIf(tree, start)(outerCtx) + given Context = prepIf(tree, start)(outerCtx) val cond = transformTree(tree.cond, start) val thenp = transformTree(tree.thenp, start) val elsep = transformTree(tree.elsep, start) goIf(cpy.If(tree)(cond, thenp, elsep), start) case tree: New => - implicit val ctx = prepNew(tree, start)(outerCtx) + given Context = prepNew(tree, start)(outerCtx) val tpt = transformTree(tree.tpt, start) goNew(cpy.New(tree)(tpt), start) case tree: Typed => - implicit val ctx = prepTyped(tree, start)(outerCtx) + given Context = prepTyped(tree, start)(outerCtx) val expr = transformTree(tree.expr, start) val tpt = transformTree(tree.tpt, start) goTyped(cpy.Typed(tree)(expr, tpt), start) case tree: CaseDef => - implicit val ctx = prepCaseDef(tree, start)(outerCtx) + given Context = prepCaseDef(tree, start)(outerCtx) val pat = transformTree(tree.pat, start)(ctx.addMode(Mode.Pattern)) val guard = transformTree(tree.guard, start) val body = transformTree(tree.body, start) goCaseDef(cpy.CaseDef(tree)(pat, guard, body), start) case tree: Closure => - implicit val ctx = prepClosure(tree, start)(outerCtx) + given Context = prepClosure(tree, start)(outerCtx) val env = transformTrees(tree.env, start) val meth = transformTree(tree.meth, start) val tpt = transformTree(tree.tpt, start) goClosure(cpy.Closure(tree)(env, meth, tpt), start) case tree: Assign => - implicit val ctx = prepAssign(tree, start)(outerCtx) + given Context = prepAssign(tree, start)(outerCtx) val lhs = transformTree(tree.lhs, start) val rhs = transformTree(tree.rhs, start) goAssign(cpy.Assign(tree)(lhs, rhs), start) case tree: SeqLiteral => - implicit val ctx = prepSeqLiteral(tree, start)(outerCtx) + given Context = prepSeqLiteral(tree, start)(outerCtx) val elems = transformTrees(tree.elems, start) val elemtpt = transformTree(tree.elemtpt, start) goSeqLiteral(cpy.SeqLiteral(tree)(elems, elemtpt), start) case tree: Super => - implicit val ctx = prepSuper(tree, start)(outerCtx) + given Context = prepSuper(tree, start)(outerCtx) goSuper(tree, start) case tree: Template => - implicit val ctx = prepTemplate(tree, start)(outerCtx) + given Context = prepTemplate(tree, start)(outerCtx) val constr = transformSpecificTree(tree.constr, start) val parents = transformTrees(tree.parents, start)(ctx.superCallContext) val self = transformSpecificTree(tree.self, start) val body = transformStats(tree.body, tree.symbol, start) goTemplate(cpy.Template(tree)(constr, parents, Nil, self, body), start) case tree: Match => - implicit val ctx = prepMatch(tree, start)(outerCtx) + given Context = prepMatch(tree, start)(outerCtx) val selector = transformTree(tree.selector, start) val cases = transformSpecificTrees(tree.cases, start) goMatch(cpy.Match(tree)(selector, cases), start) case tree: UnApply => - implicit val ctx = prepUnApply(tree, start)(outerCtx) + given Context = prepUnApply(tree, start)(outerCtx) val fun = transformTree(tree.fun, start) val implicits = transformTrees(tree.implicits, start) val patterns = transformTrees(tree.patterns, start) goUnApply(cpy.UnApply(tree)(fun, implicits, patterns), start) case tree: PackageDef => - implicit val ctx = prepPackageDef(tree, start)(outerCtx) + given Context = prepPackageDef(tree, start)(outerCtx) def mapPackage(implicit ctx: Context) = { val pid = transformSpecificTree(tree.pid, start) val stats = transformStats(tree.stats, tree.symbol, start) @@ -358,33 +358,33 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } goPackageDef(mapPackage(localContext), start) case tree: Try => - implicit val ctx = prepTry(tree, start)(outerCtx) + given Context = prepTry(tree, start)(outerCtx) val expr = transformTree(tree.expr, start) val cases = transformSpecificTrees(tree.cases, start) val finalizer = transformTree(tree.finalizer, start) goTry(cpy.Try(tree)(expr, cases, finalizer), start) case tree: Inlined => - implicit val ctx = prepInlined(tree, start)(outerCtx) + given Context = prepInlined(tree, start)(outerCtx) val bindings = transformSpecificTrees(tree.bindings, start) val expansion = transformTree(tree.expansion, start)(inlineContext(tree.call)) goInlined(cpy.Inlined(tree)(tree.call, bindings, expansion), start) case tree: Return => - implicit val ctx = prepReturn(tree, start)(outerCtx) + given Context = prepReturn(tree, start)(outerCtx) val expr = transformTree(tree.expr, start) goReturn(cpy.Return(tree)(expr, tree.from), start) // don't transform `tree.from`, as this is not a normal ident, but // a pointer to the enclosing method. case tree: WhileDo => - implicit val ctx = prepWhileDo(tree, start)(outerCtx) + given Context = prepWhileDo(tree, start)(outerCtx) val cond = transformTree(tree.cond, start) val body = transformTree(tree.body, start) goWhileDo(cpy.WhileDo(tree)(cond, body), start) case tree: Alternative => - implicit val ctx = prepAlternative(tree, start)(outerCtx) + given Context = prepAlternative(tree, start)(outerCtx) val trees = transformTrees(tree.trees, start) goAlternative(cpy.Alternative(tree)(trees), start) case tree => - implicit val ctx = prepOther(tree, start)(outerCtx) + given Context = prepOther(tree, start)(outerCtx) goOther(tree, start) } diff --git a/compiler/src/dotty/tools/dotc/transform/PatternMatcherOld.scala.disabled b/compiler/src/dotty/tools/dotc/transform/PatternMatcherOld.scala.disabled deleted file mode 100644 index a1493f463bee..000000000000 --- a/compiler/src/dotty/tools/dotc/transform/PatternMatcherOld.scala.disabled +++ /dev/null @@ -1,1871 +0,0 @@ -package dotty.tools.dotc -package transform - -import scala.language.postfixOps - -import MegaPhase._ -import core.Denotations._ -import core.SymDenotations._ -import core.Contexts._ -import core.Symbols._ -import core.Types._ -import core.Constants._ -import core.StdNames._ -import core.NameKinds._ -import dotty.tools.dotc.ast.{untpd, TreeTypeMap, tpd} -import dotty.tools.dotc.core -import dotty.tools.dotc.core.DenotTransformers.DenotTransformer -import dotty.tools.dotc.core.Phases.Phase -import dotty.tools.dotc.core.{TypeApplications, Flags} -import dotty.tools.dotc.typer.Applications -import dotty.tools.dotc.util.Positions -import typer.ErrorReporting._ -import ast.Trees._ -import Applications._ -import TypeApplications._ -import SymUtils._, core.NameOps._ -import core.Mode -import patmat._ - -import dotty.tools.dotc.util.Positions.Position -import dotty.tools.dotc.core.Decorators._ -import dotty.tools.dotc.core.Flags - -/** This phase rewrites pattern matches. - * FIXME: A more detailed explanation would be good. - */ -class PatternMatcherOld extends MiniPhase with DenotTransformer { - import dotty.tools.dotc.ast.tpd._ - - override def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = ref - - override def runsAfter = Set(ElimRepeated.name) - - override def runsAfterGroupsOf = Set(TailRec.name) // tailrec is not capable of reversing the patmat tranformation made for tree - - override def phaseName = "patternMatcher" - - private[this] var _id = 0 // left for debuging - - override def transformMatch(tree: Match)(implicit ctx: Context): Tree = { - val translated = new Translator()(ctx).translator.translateMatch(tree) - - // check exhaustivity and unreachability - val engine = new SpaceEngine - if (engine.checkable(tree)) { - engine.checkExhaustivity(tree) - engine.checkRedundancy(tree) - } - - translated.ensureConforms(tree.tpe) - } - - class Translator(implicit ctx: Context) { - - def translator = { - new OptimizingMatchTranslator/*(localTyper)*/ - } - - class OptimizingMatchTranslator extends MatchOptimizer/*(val typer: analyzer.Typer)*/ with MatchTranslator - - trait CodegenCore { - - // assert(owner ne null); assert(owner ne NoSymbol) - def freshSym(pos: Position, tp: Type = NoType, unique: UniqueNameKind = PatMatStdBinderName, owner: Symbol = ctx.owner) = { - ctx.newSymbol(owner, unique.fresh(), Flags.Synthetic | Flags.Case, tp, coord = pos) - } - - def newSynthCaseLabel(unique: UniqueNameKind, tpe: Type, owner: Symbol = ctx.owner) = - ctx.newSymbol(owner, unique.fresh(), Flags.Label | Flags.Synthetic | Flags.Method, tpe).asTerm - //NoSymbol.newLabel(freshName(name), NoPosition) setFlag treeInfo.SYNTH_CASE_FLAGS - - // codegen relevant to the structure of the translation (how extractors are combined) - trait AbsCodegen { - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Symbol => Tree]): Tree - - // local / context-free - - /* cast b to tp */ - def _asInstanceOf(b: Symbol, tp: Type): Tree - /* a check `checker` == binder */ - def _equals(checker: Tree, binder: Symbol): Tree - /* b.isIsInstanceOf[tp] */ - def _isInstanceOf(b: Symbol, tp: Type): Tree - /* tgt is expected to be a Seq, call tgt.drop(n) */ - def drop(tgt: Tree)(n: Int): Tree - /* tgt is expected to have method apply(int), call tgt.apply(i) */ - def index(tgt: Tree)(i: Int): Tree - /* make tree that accesses the i'th component of the tuple referenced by binder */ - def tupleSel(binder: Symbol)(i: Int): Tree - } - - // structure - trait Casegen extends AbsCodegen { - def one(res: Tree): Tree - - def flatMap(prev: Tree, b: Symbol, next: Tree): Tree - def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree - def flatMapGuard(cond: Tree, next: Tree): Tree - def ifThenElseZero(c: Tree, thenp: Tree): Tree = - If(c, thenp, zero) - protected def zero: Tree - } - - def codegen: AbsCodegen - - abstract class CommonCodegen extends AbsCodegen { - def tupleSel(binder: Symbol)(i: Int): Tree = ref(binder).select(nme.productAccessorName(i)) - def index(tgt: Tree)(i: Int): Tree = { - if (i > 0) tgt.select(defn.Seq_apply).appliedTo(Literal(Constant(i))) - else tgt.select(defn.Seq_head).ensureApplied - } - - // Right now this blindly calls drop on the result of the unapplySeq - // unless it verifiably has no drop method (this is the case in particular - // with Array.) You should not actually have to write a method called drop - // for name-based matching, but this was an expedient route for the basics. - def drop(tgt: Tree)(n: Int): Tree = { - def callDirect = tgt.select(nme.drop).appliedTo(Literal(Constant(n))) - def callRuntime = ref(defn.ScalaRuntime_drop).appliedTo(tgt, Literal(Constant(n))) - - def needsRuntime = !(tgt.tpe derivesFrom defn.SeqClass) /*typeOfMemberNamedDrop(tgt.tpe) == NoType*/ - - if (needsRuntime) callRuntime else callDirect - } - - // NOTE: checker must be the target of the ==, that's the patmat semantics for ya - def _equals(checker: Tree, binder: Symbol): Tree = - tpd.applyOverloaded(checker, nme.EQ, List(ref(binder)), List.empty, defn.BooleanType) - - // the force is needed mainly to deal with the GADT typing hack (we can't detect it otherwise as tp nor pt need contain an abstract type, we're just casting wildly) - def _asInstanceOf(b: Symbol, tp: Type): Tree = ref(b).ensureConforms(tp) // andType here breaks t1048 - def _isInstanceOf(b: Symbol, tp: Type): Tree = ref(b).select(defn.Any_isInstanceOf).appliedToType(tp) - } - } - - object Rebindings { - def apply(from: Symbol, to: Symbol) = new Rebindings(List(from), List(ref(to))) - // requires sameLength(from, to) - def apply(from: List[Symbol], to: List[Tree]) = - if (from nonEmpty) new Rebindings(from, to) else NoRebindings - } - - class Rebindings(val lhs: List[Symbol], val rhs: List[Tree]) { - def >>(other: Rebindings) = { - if (other eq NoRebindings) this - else if (this eq NoRebindings) other - else { - assert((lhs.toSet ++ other.lhs.toSet).size == lhs.length + other.lhs.length, "no double assignments") - new Rebindings(this.lhs ++ other.lhs, this.rhs ++ other.rhs) - } - } - - def emitValDefs: List[ValDef] = { - lhs.lazyZip(rhs).map((symbol, tree) => ValDef(symbol.asTerm, tree.ensureConforms(symbol.info))) - } - } - object NoRebindings extends Rebindings(Nil, Nil) - - trait OptimizedCodegen extends CodegenCore { - override def codegen: AbsCodegen = optimizedCodegen - - // when we know we're targeting Option, do some inlining the optimizer won't do - // for example, `o.flatMap(f)` becomes `if (o == None) None else f(o.get)`, similarly for orElse and guard - // this is a special instance of the advanced inlining optimization that takes a method call on - // an object of a type that only has two concrete subclasses, and inlines both bodies, guarded by an if to distinguish the two cases - object optimizedCodegen extends CommonCodegen { - - /** Inline runOrElse and get rid of Option allocations - * - * runOrElse(scrut: scrutTp)(matcher): resTp = matcher(scrut) getOrElse ${catchAll(`scrut`)} - * the matcher's optional result is encoded as a flag, keepGoing, where keepGoing == true encodes result.isEmpty, - * if keepGoing is false, the result Some(x) of the naive translation is encoded as matchRes == x - */ - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Symbol => Tree]): Tree = { - //val matchRes = ctx.newSymbol(NoSymbol, ctx.freshName("matchRes").toTermName, Flags.Synthetic | Flags.Param | Flags.Label | Flags.Method, restpe /*withoutAnnotations*/) - //NoSymbol.newValueParameter(newTermName("x"), NoPosition, newFlags = SYNTHETIC) setInfo restpe.withoutAnnotations - - - val caseSyms: List[TermSymbol] = cases.scanLeft(ctx.owner.asTerm)((curOwner, nextTree) => - newSynthCaseLabel(PatMatCaseName, MethodType(Nil, restpe), curOwner)).tail - - // must compute catchAll after caseLabels (side-effects nextCase) - // catchAll.isEmpty iff no synthetic default case needed (the (last) user-defined case is a default) - // if the last user-defined case is a default, it will never jump to the next case; it will go immediately to matchEnd - val catchAllDef = matchFailGen.map { _(scrutSym) } - .getOrElse(Throw(New(defn.MatchErrorType, List(ref(scrutSym))))) - - val matchFail = newSynthCaseLabel(PatMatMatchFailName, MethodType(Nil, restpe)) - val catchAllDefBody = DefDef(matchFail, catchAllDef) - - val nextCases = (caseSyms.tail ::: List(matchFail)).map(ref(_).ensureApplied) - val caseDefs = (cases zip caseSyms zip nextCases).foldRight[Tree](catchAllDefBody) { - // dotty deviation - //case (((mkCase, sym), nextCase), acc) => - (x: (((Casegen => Tree), TermSymbol), Tree), acc: Tree) => x match { - case ((mkCase, sym), nextCase) => - val body = mkCase(new OptimizedCasegen(nextCase)).ensureConforms(restpe) - - DefDef(sym, _ => Block(List(acc), body)) - } - } - - // scrutSym == NoSymbol when generating an alternatives matcher - // val scrutDef = scrutSym.fold(List[Tree]())(ValDef(_, scrut) :: Nil) // for alternatives - - Block(List(caseDefs), ref(caseSyms.head).ensureApplied) - } - - class OptimizedCasegen(nextCase: Tree) extends CommonCodegen with Casegen { - def matcher(scrut: Tree, scrutSym: Symbol, restpe: Type)(cases: List[Casegen => Tree], matchFailGen: Option[Symbol => Tree]): Tree = - optimizedCodegen.matcher(scrut, scrutSym, restpe)(cases, matchFailGen) - - // only used to wrap the RHS of a body - // res: T - // returns MatchMonad[T] - def one(res: Tree): Tree = /*ref(matchEnd) appliedTo*/ res // a jump to a case label is special-cased in typedApply - protected def zero: Tree = nextCase - - // prev: MatchMonad[T] - // b: T - // next: MatchMonad[U] - // returns MatchMonad[U] - def flatMap(prev: Tree, b: Symbol, next: Tree): Tree = { - val resultArity = productArity(b.info) - if (isProductMatch(prev.tpe, resultArity)) { - val nullCheck: Tree = prev.select(defn.Object_ne).appliedTo(Literal(Constant(null))) - ifThenElseZero( - nullCheck, - Block( - List(ValDef(b.asTerm, prev)), - next //Substitution(b, ref(prevSym))(next) - ) - ) - } - else { - val getDenot = extractorMember(prev.tpe, nme.get) - val isEmptyDenot = extractorMember(prev.tpe, nme.isEmpty) - assert(getDenot.exists && isEmptyDenot.exists, i"${prev.tpe}") - - val tmpSym = freshSym(prev.pos, prev.tpe, PatMatOName) - val prevValue = ref(tmpSym).select(getDenot.symbol).ensureApplied - - Block( - List(ValDef(tmpSym, prev)), - // must be isEmpty and get as we don't control the target of the call (prev is an extractor call) - ifThenElseZero( - ref(tmpSym).select(isEmptyDenot.symbol).select(defn.Boolean_!), - Block(List(ValDef(b.asTerm, prevValue)), next) - ) - ) - } - } - - // cond: Boolean - // res: T - // nextBinder: T - // next == MatchMonad[U] - // returns MatchMonad[U] - def flatMapCond(cond: Tree, res: Tree, nextBinder: Symbol, next: Tree): Tree = { - val rest = Block(List(ValDef(nextBinder.asTerm, res)), next) - ifThenElseZero(cond, rest) - } - - // guardTree: Boolean - // next: MatchMonad[T] - // returns MatchMonad[T] - def flatMapGuard(guardTree: Tree, next: Tree): Tree = - ifThenElseZero(guardTree, next) - - def flatMapCondStored(cond: Tree, condSym: Symbol, res: Tree, nextBinder: Symbol, next: Tree): Tree = - ifThenElseZero(cond, Block( - List(Assign(ref(condSym), Literal(Constant(true))), - Assign(ref(nextBinder), res)), - next - )) - } - } - } - /*final*/ case class Suppression(exhaustive: Boolean, unreachable: Boolean) - object Suppression { - val NoSuppression = Suppression(false, false) - } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // the making of the trees - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - trait TreeMakers extends CodegenCore { - def optimizeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): (List[List[TreeMaker]], List[Tree]) - def analyzeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type, suppression: Suppression): Unit = {} - - def emitSwitch(scrut: Tree, scrutSym: Symbol, cases: List[List[TreeMaker]], pt: Type, matchFailGenOverride: Option[Symbol => Tree], unchecked: Boolean): Option[Tree] = { - // TODO Deal with guards? - - def isSwitchableType(tpe: Type): Boolean = - (tpe isRef defn.IntClass) || - (tpe isRef defn.ByteClass) || - (tpe isRef defn.ShortClass) || - (tpe isRef defn.CharClass) - - object IntEqualityTestTreeMaker { - def unapply(treeMaker: EqualityTestTreeMaker): Option[Int] = treeMaker match { - case EqualityTestTreeMaker(`scrutSym`, _, Literal(const), _) => - if (const.isIntRange) Some(const.intValue) - else None - case _ => - None - } - } - - def isSwitchCase(treeMakers: List[TreeMaker]): Boolean = treeMakers match { - // case 5 => - case List(IntEqualityTestTreeMaker(_), _: BodyTreeMaker) => - true - - // case 5 | 6 => - case List(AlternativesTreeMaker(`scrutSym`, alts, _), _: BodyTreeMaker) => - alts.forall { - case List(IntEqualityTestTreeMaker(_)) => true - case _ => false - } - - // case _ => - case List(_: BodyTreeMaker) => - true - - /* case x @ pat => - * This includes: - * case x => - * case x @ 5 => - * case x @ (5 | 6) => - */ - case (_: SubstOnlyTreeMaker) :: rest => - isSwitchCase(rest) - - case _ => - false - } - - /* (Nil, body) means that `body` is the default case - * It's a bit hacky but it simplifies manipulations. - */ - def extractSwitchCase(treeMakers: List[TreeMaker]): (List[Int], BodyTreeMaker) = (treeMakers: @unchecked) match { - // case 5 => - case List(IntEqualityTestTreeMaker(intValue), body: BodyTreeMaker) => - (List(intValue), body) - - // case 5 | 6 => - case List(AlternativesTreeMaker(_, alts, _), body: BodyTreeMaker) => - val intValues = alts.map { alt => - (alt: @unchecked) match { - case List(IntEqualityTestTreeMaker(intValue)) => intValue - } - } - (intValues, body) - - // case _ => - case List(body: BodyTreeMaker) => - (Nil, body) - - // case x @ pat => - case (_: SubstOnlyTreeMaker) :: rest => - /* Rebindings have been propagated, so the eventual body in `rest` - * contains all the necessary information. The substitution can be - * dropped at this point. - */ - extractSwitchCase(rest) - } - - def doOverlap(a: List[Int], b: List[Int]): Boolean = - a.exists(b.contains _) - - def makeSwitch(valuesToCases: List[(List[Int], BodyTreeMaker)]): Tree = { - def genBody(body: BodyTreeMaker): Tree = { - val valDefs = body.rebindings.emitValDefs - if (valDefs.isEmpty) body.body - else Block(valDefs, body.body) - } - - val intScrut = - if (pt isRef defn.IntClass) ref(scrutSym) - else Select(ref(scrutSym), nme.toInt) - - val (normalCases, defaultCaseAndRest) = valuesToCases.span(_._1.nonEmpty) - - val newCases = for { - (values, body) <- normalCases - } yield { - val literals = values.map(v => Literal(Constant(v))) - val pat = - if (literals.size == 1) literals.head - else Alternative(literals) - CaseDef(pat, EmptyTree, genBody(body)) - } - - val catchAllDef = { - if (defaultCaseAndRest.isEmpty) { - matchFailGenOverride.fold[Tree]( - Throw(New(defn.MatchErrorType, List(ref(scrutSym)))))( - _(scrutSym)) - } else { - /* After the default case, assuming the IR even allows anything, - * things are unreachable anyway and can be removed. - */ - genBody(defaultCaseAndRest.head._2) - } - } - val defaultCase = CaseDef(Underscore(defn.IntType), EmptyTree, catchAllDef) - - Match(intScrut, newCases :+ defaultCase) - } - - val dealiased = scrut.tpe.widenDealias - if (isSwitchableType(dealiased) && cases.forall(isSwitchCase)) { - val valuesToCases = cases.map(extractSwitchCase) - val values = valuesToCases.map(_._1) - if (values.tails.exists { tail => tail.nonEmpty && tail.tail.exists(doOverlap(_, tail.head)) }) { - // TODO Deal with overlapping cases (mostly useless without guards) - None - } else { - Some(makeSwitch(valuesToCases)) - } - } else { - if (dealiased hasAnnotation defn.SwitchAnnot) - ctx.warning("failed to emit switch for `@switch` annotated match", scrut.pos) - None - } - } - - // for catch (no need to customize match failure) - def emitTypeSwitch(bindersAndCases: List[(Symbol, List[TreeMaker])], pt: Type): Option[List[CaseDef]] = - None // todo - - abstract class TreeMaker { - def pos: Position - - private[this] var currSub: Rebindings = null - - /** captures the scope and the value of the bindings in patterns - * important *when* the substitution happens (can't accumulate and do at once after the full matcher has been constructed) - */ - def rebindings: Rebindings = - if (currSub eq null) introducedRebindings - else currSub - - protected def introducedRebindings: Rebindings - - private[TreeMakers] def incorporateOuterRebinding(outerSubst: Rebindings): Unit = { - if (currSub ne null) { - ctx.debuglog("BUG: incorporateOuterRebinding called more than once for " + ((this, currSub, outerSubst))) - if (ctx.debug) Thread.dumpStack() - } - else currSub = outerSubst >> rebindings - } - - /** The substitution that specifies the trees that compute the values of the subpattern binders. - * - * Should not be used to perform actual substitution! - * Only used to reason symbolically about the values the subpattern binders are bound to. - * See TreeMakerToCond#updateSubstitution. - * - * Overridden in PreserveSubPatBinders to pretend it replaces the subpattern binders by subpattern refs - * (Even though we don't do so anymore -- see SI-5158, SI-5739 and SI-6070.) - * - * TODO: clean this up, would be nicer to have some higher-level way to compute - * the binders bound by this tree maker and the symbolic values that correspond to them - */ - def subPatternsAsRebindings: Rebindings = rebindings - - // build Tree that chains `next` after the current extractor - def chainBefore(next: Tree)(casegen: Casegen): Tree - } - - sealed trait NoNewBinders extends TreeMaker { - protected val introducedRebindings: Rebindings = NoRebindings - } - - case class TrivialTreeMaker(tree: Tree) extends TreeMaker with NoNewBinders { - def pos = tree.pos - - def chainBefore(next: Tree)(casegen: Casegen): Tree = tree - } - - case class BodyTreeMaker(body: Tree, matchPt: Type) extends TreeMaker with NoNewBinders { - def pos = body.pos - - def chainBefore(next: Tree)(casegen: Casegen): Tree = // assert(next eq EmptyTree) - /*atPos(body.pos)*/(casegen.one(body)) // since SubstOnly treemakers are dropped, need to do it here - override def toString = "B" + ((body, matchPt)) - } - - /** - * In scalac for such block - * x match { - * case d => - * } - * - * d inside was to be substituted by x. - * - * In dotty, SubstOnlyTreeMakers instead generate normal ValDef, - * and does not create a new substitution. - * - * This was done for several reasons: - * 1) it is a lot easyer to Y-check, - * as d type could be used in . - * 2) it would simplify debugging of the generated code as - * this works also for nested patterns, and previously they used unreadable names - * 3) It showed better(~30%), performance, - * Rebuilding tree and propagating types was taking substantial time. - */ - case class SubstOnlyTreeMaker(prevBinder: Symbol, nextBinder: Symbol) extends TreeMaker { - val pos = Positions.NoPosition - - val introducedRebindings = Rebindings(prevBinder, nextBinder) - def chainBefore(next: Tree)(casegen: Casegen): Tree = next - //override def toString = "S" + localSubstitution - } - - sealed abstract class FunTreeMaker extends TreeMaker { - val nextBinder: Symbol - def pos = nextBinder.pos - } - - sealed abstract class CondTreeMaker extends FunTreeMaker { - val prevBinder: Symbol - val nextBinderTp: Type - val cond: Tree - val res: Tree - - val nextBinder: Symbol - lazy val introducedRebindings = /* - if (nextBinder ne prevBinder) Rebindings(prevBinder, nextBinder) - else */ NoRebindings - - def chainBefore(next: Tree)(casegen: Casegen): Tree = - if (prevBinder ne nextBinder) // happens when typeTest is known to succeed - /*atPos(pos)(*/casegen.flatMapCond(cond, res, nextBinder, next)//) - else casegen.flatMapGuard(cond, next) - } - - // unless we're optimizing, emit local variable bindings for all subpatterns of extractor/case class patterns - protected val debugInfoEmitVars = true //!settings.optimise.value - - /** - * Tree maker that captures sub pattern values during pattern match. - */ - sealed trait PreserveSubPatBinders extends TreeMaker { - val subPatBinders: List[Symbol] // captured values - val subPatRefs: List[Tree] // trees that will replace references to subPatBinders - val ignoredSubPatBinders: Set[Symbol] // ignored as they aren't used in body of pattern - - // unless `debugInfoEmitVars`, this set should contain the bare minimum for correctness - // mutable case class fields need to be stored regardless (SI-5158, SI-6070) -- see override in ProductExtractorTreeMaker - // sub patterns bound to wildcard (_) are never stored as they can't be referenced - // dirty debuggers will have to get dirty to see the wildcards - lazy val storedBinders: Set[Symbol] = - (if (debugInfoEmitVars) subPatBinders.toSet else Set.empty) ++ extraStoredBinders -- ignoredSubPatBinders - - // e.g., mutable fields of a case class in ProductExtractorTreeMaker - def extraStoredBinders: Set[Symbol] - - def emitVars = storedBinders.nonEmpty - - lazy val storedSubsted = subPatBinders.lazyZip(subPatRefs).partition{ case (sym, _) => storedBinders(sym) } - - def stored = storedSubsted._1 - - def substed = storedSubsted._2 - - // dd: this didn't yet trigger error. But I believe it would. if this causes double denition of symbol error this can be replaced with NoRebindings - protected lazy val introducedRebindings: Rebindings = if (!emitVars) Rebindings(subPatBinders, subPatRefs) - else { - val (subPatBindersSubstituted, subPatRefsSubstituted) = substed.unzip - Rebindings(subPatBindersSubstituted.toList, subPatRefsSubstituted.toList) - } - - /** The substitution that specifies the trees that compute the values of the subpattern binders. - * - * We pretend to replace the subpattern binders by subpattern refs - * (Even though we don't do so anymore -- see SI-5158, SI-5739 and SI-6070.) - */ - override def subPatternsAsRebindings = - Rebindings(subPatBinders, subPatRefs) >> super.subPatternsAsRebindings - - def bindSubPats(in: Tree): Tree = - if (!emitVars) in - else { - // binders in `subPatBindersStored` that are referenced by tree `in` - val usedBinders = new collection.mutable.HashSet[Symbol]() - // all potentially stored subpat binders - val potentiallyStoredBinders = stored.unzip._1.toSet - // compute intersection of all symbols in the tree `in` and all potentially stored subpat binders - new DeepFolder[Unit]((x: Unit, t: Tree) => - if (potentiallyStoredBinders(t.symbol)) usedBinders += t.symbol).apply((), in) - - if (usedBinders.isEmpty) in - else { - // only store binders actually used - val (subPatBindersStored, subPatRefsStored) = stored.filter{case (b, _) => usedBinders(b)}.unzip - - Block(subPatBindersStored.toList.lazyZip(subPatRefsStored.toList).map((bind, ref) => { - // required in case original pattern had a more precise type - // eg case s@"foo" => would be otherwise translated to s with type String instead of String("foo") - def refTpeWiden = ref.tpe.widen - def bindInfoWiden = bind.info.widen - def loc = bind.showFullName - if (!(ref.tpe <:< bind.info.widen)) { - ctx.debuglog(s"here ${bind.showFullName} expected: ${bindInfoWiden.show} got: ${refTpeWiden.show}") - } - val refCasted = ref.ensureConforms(bind.info) - ValDef(bind.asTerm, refCasted) - }), in) - } - } - } - - /** - * Make a TreeMaker that will result in an extractor call specified by `extractor` - * the next TreeMaker (here, we don't know which it'll be) is chained after this one by flatMap'ing - * a function with binder `nextBinder` over our extractor's result - * the function's body is determined by the next TreeMaker - * (furthermore, the interpretation of `flatMap` depends on the codegen instance we're using). - * - * The values for the subpatterns, as computed by the extractor call in `extractor`, - * are stored in local variables that re-use the symbols in `subPatBinders`. - * This makes extractor patterns more debuggable (SI-5739). - */ - case class ExtractorTreeMaker(extractor: Tree, extraCond: Option[Tree], nextBinder: Symbol)( - val subPatBinders: List[Symbol], - val subPatRefs: List[Tree], - extractorReturnsBoolean: Boolean, - val checkedLength: Option[Int], - val prevBinder: Symbol, - val ignoredSubPatBinders: Set[Symbol] - ) extends FunTreeMaker with PreserveSubPatBinders { - - def extraStoredBinders: Set[Symbol] = Set() - - ctx.debuglog(s""" - |ExtractorTreeMaker($extractor, $extraCond, $nextBinder) { - | $subPatBinders - | $subPatRefs - | $extractorReturnsBoolean - | $checkedLength - | $prevBinder - | $ignoredSubPatBinders - |}""".stripMargin) - - def chainBefore(next: Tree)(casegen: Casegen): Tree = { - val condAndNext = extraCond match { - case Some(cond: Tree) => - casegen.ifThenElseZero(cond, bindSubPats(next)) - case _ => - bindSubPats(next) - } - - if (extractorReturnsBoolean) casegen.flatMapCond(extractor, unitLiteral, nextBinder, condAndNext) - else casegen.flatMap(extractor, nextBinder, condAndNext) // getType? - } - - override def toString = "X" + ((extractor, nextBinder.name)) - } - - object IrrefutableExtractorTreeMaker { - // will an extractor with unapply method of methodtype `tp` always succeed? - // note: this assumes the other side-conditions implied by the extractor are met - // (argument of the right type, length check succeeds for unapplySeq,...) - def irrefutableExtractorType(tp: Type): Boolean = tp.resultType.dealias match { - // case TypeRef(_, SomeClass, _) => true todo - // probably not useful since this type won't be inferred nor can it be written down (yet) - // case ConstantTrue => true todo - case _ => false - } - - def unapply(xtm: ExtractorTreeMaker): Option[(Tree, Symbol)] = xtm match { - case ExtractorTreeMaker(extractor, None, nextBinder) if irrefutableExtractorType(extractor.tpe) => - Some((extractor, nextBinder)) - case _ => - None - } - } - - object TypeTestTreeMaker { - // factored out so that we can consistently generate other representations of the tree that implements the test - // (e.g. propositions for exhaustivity and friends, boolean for isPureTypeTest) - trait TypeTestCondStrategy { - type Result - - def outerTest(testedBinder: Symbol, expectedTp: Type): Result - // TODO: can probably always widen - def typeTest(testedBinder: Symbol, expectedTp: Type): Result - def nonNullTest(testedBinder: Symbol): Result - def equalsTest(pat: Tree, testedBinder: Symbol): Result - def eqTest(pat: Tree, testedBinder: Symbol): Result - def and(a: Result, b: Result): Result - def tru: Result - } - - object treeCondStrategy extends TypeTestCondStrategy { - type Result = Tree - - def and(a: Result, b: Result): Result = a.select(defn.Boolean_&&).appliedTo(b) - def tru = Literal(Constant(true)) - def typeTest(testedBinder: Symbol, expectedTp: Type) = codegen._isInstanceOf(testedBinder, expectedTp) - def nonNullTest(testedBinder: Symbol) = ref(testedBinder).select(defn.Object_ne).appliedTo(Literal(Constant(null))) - def equalsTest(pat: Tree, testedBinder: Symbol) = codegen._equals(pat, testedBinder) - def eqTest(pat: Tree, testedBinder: Symbol) = ref(testedBinder).select(defn.Object_eq).appliedTo(pat) - - def outerTest(testedBinder: Symbol, expectedTp: Type): Tree = { - val expectedOuter = expectedTp.normalizedPrefix match { - //case NoType => Literal(Constant(true)) // fallback for SI-6183 todo? - case pre: SingletonType => singleton(pre) - } - - // ExplicitOuter replaces `Select(q, outerSym) OBJ_EQ expectedPrefix` by `Select(q, outerAccessor(outerSym.owner)) OBJ_EQ expectedPrefix` - // if there's an outer accessor, otherwise the condition becomes `true` -- TODO: can we improve needsOuterTest so there's always an outerAccessor? - // val outer = expectedTp.typeSymbol.newMethod(vpmName.outer, newFlags = SYNTHETIC | ARTIFACT) setInfo expectedTp.prefix - - val expectedClass = expectedTp.dealias.classSymbol.asClass - val test = codegen._asInstanceOf(testedBinder, expectedTp) - // TODO: Use nme.OUTER_SELECT, like the Inliner does? - val outerAccessorTested = ctx.atPhase(ctx.explicitOuterPhase.next) { implicit ctx => - ExplicitOuter.ensureOuterAccessors(expectedClass) - test.select(ExplicitOuter.outerAccessor(expectedClass)).select(defn.Object_eq).appliedTo(expectedOuter) - } - outerAccessorTested - } - } - - /*object pureTypeTestChecker extends TypeTestCondStrategy { - type Result = Boolean - - def typeTest(testedBinder: Symbol, expectedTp: Type): Result = true - - def outerTest(testedBinder: Symbol, expectedTp: Type): Result = false - def nonNullTest(testedBinder: Symbol): Result = false - def equalsTest(pat: Tree, testedBinder: Symbol): Result = false - def eqTest(pat: Tree, testedBinder: Symbol): Result = false - def and(a: Result, b: Result): Result = false // we don't and type tests, so the conjunction must include at least one false - def tru = true - }*/ - - def nonNullImpliedByTestChecker(binder: Symbol) = new TypeTestCondStrategy { - type Result = Boolean - - def typeTest(testedBinder: Symbol, expectedTp: Type): Result = testedBinder eq binder - def outerTest(testedBinder: Symbol, expectedTp: Type): Result = false - def nonNullTest(testedBinder: Symbol): Result = testedBinder eq binder - def equalsTest(pat: Tree, testedBinder: Symbol): Result = false // could in principle analyse pat and see if it's statically known to be non-null - def eqTest(pat: Tree, testedBinder: Symbol): Result = false // could in principle analyse pat and see if it's statically known to be non-null - def and(a: Result, b: Result): Result = a || b - def tru = false - } - } - - /** implements the run-time aspects of (§8.2) (typedPattern has already done the necessary type transformations) - * - * Type patterns consist of types, type variables, and wildcards. A type pattern T is of one of the following forms: - - A reference to a class C, p.C, or T#C. - This type pattern matches any non-null instance of the given class. - Note that the prefix of the class, if it is given, is relevant for determining class instances. - For instance, the pattern p.C matches only instances of classes C which were created with the path p as prefix. - The bottom types scala.Nothing and scala.Null cannot be used as type patterns, because they would match nothing in any case. - - - A singleton type p.type. - This type pattern matches only the value denoted by the path p - (that is, a pattern match involved a comparison of the matched value with p using method eq in class AnyRef). // TODO: the actual pattern matcher uses ==, so that's what I'm using for now - // https://issues.scala-lang.org/browse/SI-4577 "pattern matcher, still disappointing us at equality time" - - - A compound type pattern T1 with ... with Tn where each Ti is a type pat- tern. - This type pattern matches all values that are matched by each of the type patterns Ti. - - - A parameterized type pattern T[a1,...,an], where the ai are type variable patterns or wildcards _. - This type pattern matches all values which match T for some arbitrary instantiation of the type variables and wildcards. - The bounds or alias type of these type variable are determined as described in (§8.3). - - - A parameterized type pattern scala.Array[T1], where T1 is a type pattern. // TODO - This type pattern matches any non-null instance of type scala.Array[U1], where U1 is a type matched by T1. - **/ - case class TypeTestTreeMaker(afterTest: Symbol, testedBinder: Symbol, expectedTp: Type, nextBinderTp: Type)(override val pos: Position, extractorArgTypeTest: Boolean = false) extends CondTreeMaker { - import TypeTestTreeMaker._ - - ctx.debuglog("TTTM" + ((prevBinder, extractorArgTypeTest, testedBinder, expectedTp, nextBinderTp))) - - val prevBinder = testedBinder - - val nextBinder = afterTest.asTerm - - def outerTestNeeded(implicit ctx: Context): Boolean = { - // See the test for SI-7214 for motivation for dealias. Later `treeCondStrategy#outerTest` - // generates an outer test based on `patType.prefix` with automatically dealises. - expectedTp.dealias match { - case tref @ TypeRef(pre: SingletonType, _) => - val s = tref - s.symbol.isClass && - ExplicitOuter.needsOuterIfReferenced(s.symbol.asClass) - case _ => - false - } - } - - override lazy val introducedRebindings = NoRebindings - - // the logic to generate the run-time test that follows from the fact that - // a `prevBinder` is expected to have type `expectedTp` - // the actual tree-generation logic is factored out, since the analyses generate Cond(ition)s rather than Trees - // TODO: `null match { x : T }` will yield a check that (indirectly) tests whether `null ne null` - // don't bother (so that we don't end up with the warning "comparing values of types Null and Null using `ne' will always yield false") - def renderCondition(cs: TypeTestCondStrategy): cs.Result = { - import cs._ - - // propagate expected type - def expTp(t: Tree): t.type = t // setType expectedTp todo: - - def testedWide = testedBinder.info.widen - def expectedWide = expectedTp.widen - def isAnyRef = testedWide <:< defn.AnyRefType - def isAsExpected = testedWide <:< expectedTp - def isExpectedPrimitiveType = isAsExpected && expectedTp.classSymbol.isPrimitiveValueClass - def isExpectedReferenceType = isAsExpected && (expectedTp <:< defn.AnyRefType) - def mkNullTest = nonNullTest(testedBinder) - def mkOuterTest = outerTest(testedBinder, expectedTp) - def mkTypeTest = typeTest(testedBinder, expectedWide) - - def mkEqualsTest(lhs: Tree): cs.Result = equalsTest(lhs, testedBinder) - def mkEqTest(lhs: Tree): cs.Result = eqTest(lhs, testedBinder) - def addOuterTest(res: cs.Result): cs.Result = if (outerTestNeeded) and(res, mkOuterTest) else res - - // If we conform to expected primitive type: - // it cannot be null and cannot have an outer pointer. No further checking. - // If we conform to expected reference type: - // have to test outer and non-null - // If we do not conform to expected type: - // have to test type and outer (non-null is implied by successful type test) - def mkDefault = ( - if (isExpectedPrimitiveType) tru - else addOuterTest( - if (isExpectedReferenceType) mkNullTest - else mkTypeTest - ) - ) - - // true when called to type-test the argument to an extractor - // don't do any fancy equality checking, just test the type - // TODO: verify that we don't need to special-case Array - // I think it's okay: - // - the isInstanceOf test includes a test for the element type - // - Scala's arrays are invariant (so we don't drop type tests unsoundly) - if (extractorArgTypeTest) mkDefault - else expectedTp match { - case ThisType(tref) if tref.symbol.flags is Flags.Module => - and(mkEqualsTest(ref(tref.symbol.companionModule)), mkTypeTest) // must use == to support e.g. List() == Nil - case ConstantType(Constant(null)) if isAnyRef => mkEqTest(expTp(Literal(Constant(null)))) - case ConstantType(const) => mkEqualsTest(expTp(Literal(const))) - case t: SingletonType => mkEqTest(singleton(expectedTp)) // SI-4577, SI-4897 - //case ThisType(sym) => mkEqTest(expTp(This(sym))) - case _ => mkDefault - } - } - - val cond = renderCondition(treeCondStrategy) - val res = codegen._asInstanceOf(testedBinder, nextBinderTp) - - // is this purely a type test, e.g. no outer check, no equality tests (used in switch emission) - //def isPureTypeTest = renderCondition(pureTypeTestChecker) - - def impliesBinderNonNull(binder: Symbol): Boolean = - // @odersky: scalac is able to infer in this method that nonNullImpliedByTestChecker.Result, - // dotty instead infers type projection TreeMakers.this.TypeTestTreeMaker.TypeTestCondStrategy#Result - // which in turn doesn't typecheck in this method. Can you please explain why? - // dotty deviation - renderCondition(nonNullImpliedByTestChecker(binder)).asInstanceOf[Boolean] - - override def toString = "TT" + ((expectedTp, testedBinder.name, nextBinderTp)) - } - - // need to substitute to deal with existential types -- TODO: deal with existentials better, don't substitute (see RichClass during quick.comp) - case class EqualityTestTreeMaker(prevBinder: Symbol, subpatBinder: Symbol, patTree: Tree, override val pos: Position) extends CondTreeMaker { - val nextBinderTp = patTree.tpe & prevBinder.info - val nextBinder = if (prevBinder eq subpatBinder) freshSym(pos, nextBinderTp) else subpatBinder - - // NOTE: generate `patTree == patBinder`, since the extractor must be in control of the equals method (also, patBinder may be null) - // equals need not be well-behaved, so don't intersect with pattern's (stabilized) type (unlike MaybeBoundTyped's accumType, where it's required) - val cond = codegen._equals(patTree, prevBinder) - val res = ref(prevBinder).ensureConforms(nextBinderTp) - override def toString = "ET" + ((prevBinder.name, patTree)) - } - - case class AlternativesTreeMaker(prevBinder: Symbol, var altss: List[List[TreeMaker]], pos: Position) extends TreeMaker with NoNewBinders { - // don't substitute prevBinder to nextBinder, a set of alternatives does not need to introduce a new binder, simply reuse the previous one - - override private[TreeMakers] def incorporateOuterRebinding(outerSubst: Rebindings): Unit = { - super.incorporateOuterRebinding(outerSubst) - altss = altss map (alts => propagateRebindings(alts, rebindings)) - } - - def chainBefore(next: Tree)(codegenAlt: Casegen): Tree = { - /*atPos(pos)*/{ - // one alternative may still generate multiple trees (e.g., an extractor call + equality test) - // (for now,) alternatives may not bind variables (except wildcards), so we don't care about the final substitution built internally by makeTreeMakers - val combinedAlts = altss map (altTreeMakers => - ((casegen: Casegen) => combineExtractors(altTreeMakers :+ TrivialTreeMaker(casegen.one(Literal(Constant(true)))))(casegen)) - ) - - val findAltMatcher = codegenAlt.matcher(EmptyTree, NoSymbol, defn.BooleanType)(combinedAlts, Some((x: Symbol) => Literal(Constant(false)))) - codegenAlt.ifThenElseZero(findAltMatcher, next) - } - } - } - - case class GuardTreeMaker(guardTree: Tree) extends TreeMaker with NoNewBinders { - val pos = guardTree.pos - - def chainBefore(next: Tree)(casegen: Casegen): Tree = casegen.flatMapGuard(guardTree, next) - override def toString = "G(" + guardTree + ")" - } - - // combineExtractors changes the current substitution's of the tree makers in `treeMakers` - // requires propagateSubstitution(treeMakers) has been called - def combineExtractors(treeMakers: List[TreeMaker])(casegen: Casegen): Tree = { - val (testsMakers, guardAndBodyMakers) = treeMakers.span(t => !(t.isInstanceOf[NoNewBinders])) - val body = guardAndBodyMakers.foldRight(EmptyTree: Tree)((a, b) => a.chainBefore(b)(casegen)) - val rebindings = guardAndBodyMakers.last.rebindings.emitValDefs - testsMakers.foldRight(Block(rebindings, body): Tree)((a, b) => a.chainBefore(b)(casegen)) - } - // a foldLeft to accumulate the localSubstitution left-to-right - // unlike in scalace it does not drop SubstOnly tree makers, - // as there could be types having them as prefix - def propagateRebindings(treeMakers: List[TreeMaker], initial: Rebindings): List[TreeMaker] = { - var accumSubst: Rebindings = initial - treeMakers foreach { maker => - maker incorporateOuterRebinding accumSubst - accumSubst = maker.rebindings - } - treeMakers - } - - // calls propagateSubstitution on the treemakers - def combineCases(scrut: Tree, scrutSym: Symbol, casesRaw: List[List[TreeMaker]], pt: Type, owner: Symbol, matchFailGenOverride: Option[Symbol => Tree]): Tree = { - // unlike in scalac SubstOnlyTreeMakers are maintained. - val casesRebindingPropagated = casesRaw map (propagateRebindings(_, NoRebindings)) - - def matchFailGen = matchFailGenOverride orElse Some((arg: Symbol) => Throw(New(defn.MatchErrorType, List(ref(arg))))) - - ctx.debuglog("combining cases: " + (casesRebindingPropagated.map(_.mkString(" >> ")).mkString("{", "\n", "}"))) - - val (suppression, requireSwitch): (Suppression, Boolean) = - /*if (settings.XnoPatmatAnalysis)*/ (Suppression.NoSuppression, false) - /*else scrut match { - case Typed(tree, tpt) => - val suppressExhaustive = tpt.tpe hasAnnotation UncheckedClass - val supressUnreachable = tree match { - case Ident(name) if name startsWith nme.CHECK_IF_REFUTABLE_STRING => true // SI-7183 don't warn for withFilter's that turn out to be irrefutable. - case _ => false - } - val suppression = Suppression(suppressExhaustive, supressUnreachable) - // matches with two or fewer cases need not apply for switchiness (if-then-else will do) - val requireSwitch = treeInfo.isSwitchAnnotation(tpt.tpe) && casesNoSubstOnly.lengthCompare(2) > 0 - (suppression, requireSwitch) - case _ => - (Suppression.NoSuppression, false) - }*/ - - emitSwitch(scrut, scrutSym, casesRebindingPropagated, pt, matchFailGenOverride, suppression.exhaustive).getOrElse{ - if (requireSwitch) ctx.warning("could not emit switch for @switch annotated match", scrut.pos) - - if (casesRebindingPropagated nonEmpty) { - // before optimizing, check casesNoSubstOnly for presence of a default case, - // since DCE will eliminate trivial cases like `case _ =>`, even if they're the last one - // exhaustivity and reachability must be checked before optimization as well - // TODO: improve notion of trivial/irrefutable -- a trivial type test before the body still makes for a default case - // ("trivial" depends on whether we're emitting a straight match or an exception, or more generally, any supertype of scrutSym.tpe is a no-op) - // irrefutability checking should use the approximation framework also used for CSE, unreachability and exhaustivity checking - val synthCatchAll: Option[Symbol => Tree] = - if (casesRebindingPropagated.nonEmpty && { - val nonTrivLast = casesRebindingPropagated.last - nonTrivLast.nonEmpty && nonTrivLast.head.isInstanceOf[BodyTreeMaker] - }) None - else matchFailGen - - analyzeCases(scrutSym, casesRebindingPropagated, pt, suppression) - - val (cases, toHoist) = optimizeCases(scrutSym, casesRebindingPropagated, pt) - - val matchRes = codegen.matcher(scrut, scrutSym, pt)(cases.map(x => combineExtractors(x) _), synthCatchAll) - - if (toHoist isEmpty) matchRes else Block(toHoist, matchRes) - } else { - codegen.matcher(scrut, scrutSym, pt)(Nil, matchFailGen) - } - } - } - } - - trait MatchOptimizer extends OptimizedCodegen with TreeMakers - /*with SwitchEmission // todo: toBe ported - with CommonSubconditionElimination*/ { - override def optimizeCases(prevBinder: Symbol, cases: List[List[TreeMaker]], pt: Type): (List[List[TreeMaker]], List[Tree]) = { - // TODO: do CSE on result of doDCE(prevBinder, cases, pt) - val optCases = cases// todo: doCSE(prevBinder, cases, pt) - val toHoist = Nil/*( - for (treeMakers <- optCases) - yield treeMakers.collect{case tm: ReusedCondTreeMaker => tm.treesToHoist} - ).flatten.flatten.toList*/ - (optCases, toHoist) - } - } - - trait MatchTranslator extends TreeMakers with ScalacPatternExpanders { - - def isVarPattern(pat: Tree): Boolean = pat match { - case x: BackquotedIdent => false - case x: Ident => x.name.isVariableName - case _ => false - } - - /** A conservative approximation of which patterns do not discern anything. - * They are discarded during the translation. - */ - object WildcardPattern { - def unapply(pat: Tree): Boolean = pat match { - case Typed(_, arg) if arg.tpe.isRepeatedParam => true - case Bind(nme.WILDCARD, WildcardPattern()) => true // don't skip when binding an interesting symbol! - case t if (tpd.isWildcardArg(t)) => true - case x: Ident => isVarPattern(x) - case Alternative(ps) => ps forall unapply - case EmptyTree => true - case _ => false - } - } - - object PatternBoundToUnderscore { - def unapply(pat: Tree): Boolean = pat match { - case Bind(nme.WILDCARD, _) => true // don't skip when binding an interesting symbol! - case Ident(nme.WILDCARD) => true - case Alternative(ps) => ps forall unapply - case Typed(PatternBoundToUnderscore(), _) => false // true // Dmitry: change in dotty. Type test will be performed and the field must be stored - case _ => false - } - } - - object SymbolBound { - def unapply(tree: Tree): Option[(Symbol, Tree)] = tree match { - case Bind(_, expr) if tree.symbol.exists => Some(tree.symbol -> expr) - case _ => None - } - } - - def newBoundTree(tree: Tree, pt: Type): BoundTree = tree match { - case SymbolBound(sym, Typed(subpat, tpe)) => BoundTree(freshSym(tree.pos, pt, PatMatPiName), tree) - case SymbolBound(sym, expr) => BoundTree(sym, expr) - case _ => BoundTree(freshSym(tree.pos, pt, PatMatPName), tree) - } - - /*final*/ case class BoundTree(binder: Symbol, tree: Tree) { - private lazy val extractor = ExtractorCall(tree, binder) - - def pos = tree.pos - def tpe = binder.info.widenDealias - def pt = unbound match { - // case Star(tpt) => this glbWith seqType(tpt.tpe) dd todo: - case TypeBound(tpe) => tpe - case tree => tree.tpe - } - - def glbWith(other: Type) = ctx.typeComparer.glb(tpe :: other :: Nil)// .normalize - - object SymbolAndTypeBound { - def unapply(tree: Tree): Option[(Symbol, Type)] = tree match { - case SymbolBound(sym, Typed(_: UnApply, _)) => None // see comment in #189 - case SymbolBound(sym, TypeBound(tpe)) => Some(sym -> tpe) - case TypeBound(tpe) => Some(binder -> tpe) - case _ => None - } - } - - object SymbolAndValueBound { - def unapply(tree: Tree): Option[(Symbol, Tree)] = tree match { - case SymbolBound(sym, ConstantPattern(const)) => Some(sym -> const) - case _ => None - } - } - - object TypeBound { - def unapply(tree: Tree): Option[Type] = tree match { - case Typed(_, arg) if !arg.tpe.isRepeatedParam => Some(tree.typeOpt) - case _ => None - } - } - - object ConstantPattern { - def unapply(tree: Tree): Option[Tree] = tree match { - case Literal(Constant(_)) | Ident(_) | Select(_, _) | This(_) => Some(tree) - case _ => None - } - } - - private def rebindTo(pattern: Tree) = BoundTree(binder, pattern) - private def step(treeMakers: TreeMaker*)(subpatterns: BoundTree*): TranslationStep = TranslationStep(treeMakers.toList, subpatterns.toList) - - private def bindingStep(sub: Symbol, subpattern: Tree) = step(SubstOnlyTreeMaker(sub, binder))(rebindTo(subpattern)) - private def equalityTestStep(testedSymbol: Symbol, constantSymbol: Symbol, constant: Tree) - = step(EqualityTestTreeMaker(testedSymbol, constantSymbol, constant, pos))() - private def typeTestStep(sub: Symbol, subPt: Type) = step(TypeTestTreeMaker(sub, binder, subPt, sub.termRef)(pos))() - private def alternativesStep(alts: List[Tree]) = step(AlternativesTreeMaker(binder, translatedAlts(alts), alts.head.pos))() - private def translatedAlts(alts: List[Tree]) = alts map (alt => rebindTo(alt).translate()) - private def noStep() = step()() - - private def unsupportedPatternMsg = - i"unsupported pattern: ${tree.show} / $this (this is a scalac bug.)" - - // example check: List[Int] <:< ::[Int] - private def extractorStep(): TranslationStep = { - def paramType = extractor.aligner.wholeType - import extractor.treeMaker - // chain a type-testing extractor before the actual extractor call - // it tests the type, checks the outer pointer and casts to the expected type - // TODO: the outer check is mandated by the spec for case classes, but we do it for user-defined unapplies as well [SPEC] - // (the prefix of the argument passed to the unapply must equal the prefix of the type of the binder) - lazy val typeTest = TypeTestTreeMaker(freshSym(pos, paramType), binder, paramType, paramType)(pos, extractorArgTypeTest = true) - // check whether typetest implies binder is not null, - // even though the eventual null check will be on typeTest.nextBinder - // it'll be equal to binder casted to paramType anyway (and the type test is on binder) - def extraction: TreeMaker = treeMaker(typeTest.nextBinder, typeTest.impliesBinderNonNull(binder), pos, paramType) - - // paramType = the type expected by the unapply - // TODO: paramType may contain unbound type params (run/t2800, run/t3530) - val makers = ( - // Statically conforms to paramType - if (tpe <:< paramType) treeMaker(binder, false, pos, tpe) :: Nil - else typeTest :: extraction :: Nil - ) - step(makers: _*)(extractor.subBoundTrees: _*) - } - - // Summary of translation cases. I moved the excerpts from the specification further below so all - // the logic can be seen at once. - // - // [1] skip wildcard trees -- no point in checking them - // [2] extractor and constructor patterns - // [3] replace subpatBinder by patBinder, as if the Bind was not there. - // It must be patBinder, as subpatBinder has the wrong info: even if the bind assumes a better type, - // this is not guaranteed until we cast - // [4] typed patterns - a typed pattern never has any subtrees - // must treat Typed and Bind together -- we need to know the patBinder of the Bind pattern to get at the actual type - // [5] literal and stable id patterns - // [6] pattern alternatives - // [7] symbol-less bind patterns - this happens in certain ill-formed programs, there'll be an error later - // don't fail here though (or should we?) - def nextStep(): TranslationStep = tree match { - case _: UnApply | _: Apply | Typed(_: UnApply | _: Apply, _) => extractorStep() - case SymbolAndTypeBound(sym, tpe) => typeTestStep(sym, tpe) - case TypeBound(tpe) => typeTestStep(binder, tpe) - case SymbolBound(sym, expr) => bindingStep(sym, expr) - case WildcardPattern() => noStep() - case ConstantPattern(const) => equalityTestStep(binder, binder, const) - case Alternative(alts) => alternativesStep(alts) - case _ => ctx.error(unsupportedPatternMsg, pos) ; noStep() - } - def translate(): List[TreeMaker] = nextStep() merge (_.translate()) - - private def concreteType = tpe.bounds.hi - private def unbound = unbind(tree) - private def tpe_s = if (pt <:< concreteType) "" + pt else s"$pt (binder: $tpe)" - private def at_s = unbound match { - case WildcardPattern() => "" - case pat => s" @ $pat" - } - override def toString = s"${binder.name}: $tpe_s$at_s" - } - - // a list of TreeMakers that encode `patTree`, and a list of arguments for recursive invocations of `translatePattern` to encode its subpatterns - /*final*/ case class TranslationStep(makers: List[TreeMaker], subpatterns: List[BoundTree]) { - def merge(f: BoundTree => List[TreeMaker]): List[TreeMaker] = makers ::: (subpatterns flatMap f) - override def toString = if (subpatterns.isEmpty) "" else subpatterns.mkString("(", ", ", ")") - } - - def isSyntheticDefaultCase(cdef: CaseDef) = cdef match { - case CaseDef(Bind(nme.DEFAULT_CASE, _), EmptyTree, _) => true - case _ => false - } - - /** Implement a pattern match by turning its cases (including the implicit failure case) - * into the corresponding (monadic) extractors, and combining them with the `orElse` combinator. - * - * For `scrutinee match { case1 ... caseN }`, the resulting tree has the shape - * `runOrElse(scrutinee)(x => translateCase1(x).orElse(translateCase2(x)).....orElse(zero))` - * - * NOTE: the resulting tree is not type checked, nor are nested pattern matches transformed - * thus, you must typecheck the result (and that will in turn translate nested matches) - * this could probably be optimized... (but note that the matchStrategy must be solved for each nested patternmatch) - */ - def translateMatch(match_ : Match): Tree = { - val Match(sel, cases) = match_ - - val selectorTp = sel.tpe.widen/*withoutAnnotations*/ - - val selectorSym = freshSym(sel.pos, selectorTp, PatMatSelectorName) - - val (nonSyntheticCases, defaultOverride) = cases match { - case init :+ last if isSyntheticDefaultCase(last) => (init, Some(((scrut: Symbol) => last.body))) - case _ => (cases, None) - } - - - // checkMatchVariablePatterns(nonSyntheticCases) // only used for warnings - - // we don't transform after uncurry - // (that would require more sophistication when generating trees, - // and the only place that emits Matches after typers is for exception handling anyway) - /*if (phase.id >= currentRun.uncurryPhase.id) - devWarning(s"running translateMatch past uncurry (at $phase) on $selector match $cases")*/ - - ctx.debuglog("translating " + cases.mkString("{", "\n", "}")) - - //val start = if (Statistics.canEnable) Statistics.startTimer(patmatNanos) else null - - // when one of the internal cps-type-state annotations is present, strip all CPS annotations - ///val origPt = removeCPSFromPt(match_.tpe) - // relevant test cases: pos/existentials-harmful.scala, pos/gadt-gilles.scala, pos/t2683.scala, pos/virtpatmat_exist4.scala - // pt is the skolemized version - val pt = match_.tpe.widen //repeatedToSeq(origPt) - - // val packedPt = repeatedToSeq(typer.packedType(match_, context.owner)) - selectorSym.setFlag(Flags.SyntheticCase) - - // pt = Any* occurs when compiling test/files/pos/annotDepMethType.scala with -Xexperimental - val combined = combineCases(sel, selectorSym, nonSyntheticCases map translateCase(selectorSym, pt), pt, ctx.owner, defaultOverride) - - // if (Statistics.canEnable) Statistics.stopTimer(patmatNanos, start) - Block(List(ValDef(selectorSym, sel)), combined) - } - - /** The translation of `pat if guard => body` has two aspects: - * 1) the substitution due to the variables bound by patterns - * 2) the combination of the extractor calls using `flatMap`. - * - * 2) is easy -- it looks like: `translatePattern_1.flatMap(translatePattern_2....flatMap(translatePattern_N.flatMap(translateGuard.flatMap((x_i) => success(Xbody(x_i)))))...)` - * this must be right-leaning tree, as can be seen intuitively by considering the scope of bound variables: - * variables bound by pat_1 must be visible from the function inside the left-most flatMap right up to Xbody all the way on the right - * 1) is tricky because translatePattern_i determines the shape of translatePattern_i + 1: - * zoom in on `translatePattern_1.flatMap(translatePattern_2)` for example -- it actually looks more like: - * `translatePattern_1(x_scrut).flatMap((x_1) => {y_i -> x_1._i}translatePattern_2)` - * - * `x_1` references the result (inside the monad) of the extractor corresponding to `pat_1`, - * this result holds the values for the constructor arguments, which translatePattern_1 has extracted - * from the object pointed to by `x_scrut`. The `y_i` are the symbols bound by `pat_1` (in order) - * in the scope of the remainder of the pattern, and they must thus be replaced by: - * - (for 1-ary unapply) x_1 - * - (for n-ary unapply, n > 1) selection of the i'th tuple component of `x_1` - * - (for unapplySeq) x_1.apply(i) - * - * in the treemakers, - * - * Thus, the result type of `translatePattern_i`'s extractor must conform to `M[(T_1,..., T_n)]`. - * - * Operationally, phase 1) is a foldLeft, since we must consider the depth-first-flattening of - * the transformed patterns from left to right. For every pattern ast node, it produces a transformed ast and - * a function that will take care of binding and substitution of the next ast (to the right). - * - */ - def translateCase(scrutSym: Symbol, pt: Type)(caseDef: CaseDef): List[TreeMaker] = { - val CaseDef(pattern, guard, body) = caseDef - translatePattern(BoundTree(scrutSym, pattern)) ++ translateGuard(guard) :+ translateBody(body, pt) - } - - def translatePattern(bound: BoundTree): List[TreeMaker] = bound.translate() - - def translateGuard(guard: Tree): List[TreeMaker] = - if (guard == EmptyTree) Nil - else List(GuardTreeMaker(guard)) - - // TODO: 1) if we want to support a generalisation of Kotlin's patmat continue, must not hard-wire lifting into the monad (which is now done by codegen.one), - // so that user can generate failure when needed -- use implicit conversion to lift into monad on-demand? - // to enable this, probably need to move away from Option to a monad specific to pattern-match, - // so that we can return Option's from a match without ambiguity whether this indicates failure in the monad, or just some result in the monad - // 2) body.tpe is the type of the body after applying the substitution that represents the solution of GADT type inference - // need the explicit cast in case our substitutions in the body change the type to something that doesn't take GADT typing into account - def translateBody(body: Tree, matchPt: Type): TreeMaker = - BodyTreeMaker(body, matchPt) - - // Some notes from the specification - - /*A constructor pattern is of the form c(p1, ..., pn) where n ≥ 0. - It consists of a stable identifier c, followed by element patterns p1, ..., pn. - The constructor c is a simple or qualified name which denotes a case class (§5.3.2). - - If the case class is monomorphic, then it must conform to the expected type of the pattern, - and the formal parameter types of x’s primary constructor (§5.3) are taken as the expected - types of the element patterns p1, ..., pn. - - If the case class is polymorphic, then its type parameters are instantiated so that the - instantiation of c conforms to the expected type of the pattern. - The instantiated formal parameter types of c’s primary constructor are then taken as the - expected types of the component patterns p1, ..., pn. - - The pattern matches all objects created from constructor invocations c(v1, ..., vn) - where each element pattern pi matches the corresponding value vi . - A special case arises when c’s formal parameter types end in a repeated parameter. - This is further discussed in (§8.1.9). - **/ - - /* A typed pattern x : T consists of a pattern variable x and a type pattern T. - The type of x is the type pattern T, where each type variable and wildcard is replaced by a fresh, unknown type. - This pattern matches any value matched by the type pattern T (§8.2); it binds the variable name to that value. - */ - - /* A pattern binder x@p consists of a pattern variable x and a pattern p. - The type of the variable x is the static type T of the pattern p. - This pattern matches any value v matched by the pattern p, - provided the run-time type of v is also an instance of T, <-- TODO! https://issues.scala-lang.org/browse/SI-1503 - and it binds the variable name to that value. - */ - - /* 8.1.4 Literal Patterns - A literal pattern L matches any value that is equal (in terms of ==) to the literal L. - The type of L must conform to the expected type of the pattern. - - 8.1.5 Stable Identifier Patterns (a stable identifier r (see §3.1)) - The pattern matches any value v such that r == v (§12.1). - The type of r must conform to the expected type of the pattern. - */ - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // helper methods: they analyze types and trees in isolation, but they are not (directly) concerned with the structure of the overall translation - /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - object ExtractorCall { - // TODO: check unargs == args - def apply(tree: Tree, binder: Symbol): ExtractorCall = { - tree match { - case Typed(unapply, _) => apply(unapply, binder) - case UnApply(unfun, implicits, args) => - val mt @ MethodType(_) = unfun.tpe.widen - val castedBinder = ref(binder).ensureConforms(mt.paramInfos.head) - var synth = unfun.appliedTo(castedBinder) - if (implicits.nonEmpty) synth = synth.appliedToArgs(implicits) - new ExtractorCallRegular(alignPatterns(tree, synth.tpe), synth, args, synth.tpe) - } - } - } - - abstract class ExtractorCall(val aligner: PatternAligned) { - - import aligner._ - - def args: List[Tree] - - // don't go looking for selectors if we only expect one pattern - def rawSubPatTypes = aligner.extractedTypes - - def typeArgOfBaseTypeOr(tp: Type, baseClass: Symbol)(or: => Type): Type = (tp.baseType(baseClass)).argInfos match { - case x :: Nil => x - case _ => or - } - - def resultInMonad = - if (aligner.isBool) defn.UnitType - else if (isProductMatch(resultType, aligner.prodArity)) resultType - else if (isGetMatch(resultType)) extractorMemberType(resultType, nme.get) - else resultType - - def resultType: Type - - /** Create the TreeMaker that embodies this extractor call - * - * `binder` has been casted to `paramType` if necessary - * `binderKnownNonNull` indicates whether the cast implies `binder` cannot be null - * when `binderKnownNonNull` is `true`, `ProductExtractorTreeMaker` does not do a (redundant) null check on binder - */ - def treeMaker(binder: Symbol, binderKnownNonNull: Boolean, pos: Position, binderTypeTested: Type): TreeMaker - - // `subPatBinders` are the variables bound by this pattern in the following patterns - // subPatBinders are replaced by references to the relevant part of the extractor's result (tuple component, seq element, the result as-is) - // must set infos to `subPatTypes`, which are provided by extractor's result, - // as b.info may be based on a Typed type ascription, which has not been taken into account yet by the translation - // (it will later result in a type test when `tp` is not a subtype of `b.info`) - // TODO: can we simplify this, together with the Bound case? - def subPatBinders = subBoundTrees map (_.binder) - lazy val subBoundTrees = args.lazyZip(subPatTypes) map newBoundTree - - // never store these in local variables (for PreserveSubPatBinders) - lazy val ignoredSubPatBinders: Set[Symbol] = subPatBinders zip args collect { case (b, PatternBoundToUnderscore()) => b } toSet - - // do repeated-parameter expansion to match up with the expected number of arguments (in casu, subpatterns) - private def nonStarSubPatTypes = aligner.typedNonStarPatterns map (_.tpe) - - def subPatTypes: List[Type] = typedPatterns map (_.tpe) - - // there are `prodArity` non-seq elements in the tuple. - protected def firstIndexingBinder = prodArity - protected def expectedLength = elementArity - protected def lastIndexingBinder = totalArity - starArity - 1 - - private def productElemsToN(binder: Symbol, n: Int): List[Tree] = 1 to n map tupleSel(binder) toList - private def genTake(binder: Symbol, n: Int): List[Tree] = (0 until n).toList map (codegen index seqTree(binder)) - private def genDrop(binder: Symbol, n: Int): List[Tree] = codegen.drop(seqTree(binder))(expectedLength) :: Nil - - // codegen.drop(seqTree(binder))(nbIndexingIndices)))).toList - protected def seqTree(binder: Symbol) = tupleSel(binder)(firstIndexingBinder + 1) - protected def tupleSel(binder: Symbol)(i: Int): Tree = { - val accessors = - if (defn.isProductSubType(binder.info)) - productSelectors(binder.info) - else binder.caseAccessors - val res = - if (accessors.isDefinedAt(i - 1)) ref(binder).select(accessors(i - 1).name) - else codegen.tupleSel(binder)(i) // this won't type check for case classes, as they do not inherit ProductN - val rsym = res.symbol // just for debugging - res - } - - // the trees that select the subpatterns on the extractor's result, - // referenced by `binder` - protected def subPatRefsSeq(binder: Symbol): List[Tree] = { - def lastTrees: List[Tree] = ( - if (!aligner.isStar) Nil - else if (expectedLength == 0) seqTree(binder) :: Nil - else genDrop(binder, expectedLength) - ) - // this error-condition has already been checked by checkStarPatOK: - // if (isSeq) assert(firstIndexingBinder + nbIndexingIndices + (if (lastIsStar) 1 else 0) == totalArity, "(resultInMonad, ts, subPatTypes, subPats)= " +(resultInMonad, ts, subPatTypes, subPats)) - - // [1] there are `firstIndexingBinder` non-seq tuple elements preceding the Seq - // [2] then we have to index the binder that represents the sequence for the remaining subpatterns, except for... - // [3] the last one -- if the last subpattern is a sequence wildcard: - // drop the prefix (indexed by the refs on the preceding line), return the remainder - ( productElemsToN(binder, firstIndexingBinder) - ++ genTake(binder, expectedLength) - ++ lastTrees - ).toList - } - - // the trees that select the subpatterns on the extractor's result, referenced by `binder` - // require (nbSubPats > 0 && (!lastIsStar || isSeq)) - protected def subPatRefs(binder: Symbol): List[Tree] = { - val refs = if (totalArity > 0 && isSeq) subPatRefsSeq(binder) - else if (binder.info.member(nme._1).exists && !isSeq) productElemsToN(binder, totalArity) - else ref(binder) :: Nil - refs - } - - val mathSignymSymbol = defn.ScalaMathPackageVal.requiredMethod("signum".toTermName, List(defn.IntType)) - val mathSignum = ref(defn.ScalaMathPackageVal).select(mathSignymSymbol) - - - private def compareInts(t1: Tree, t2: Tree) = - mathSignum.appliedTo(t1.select(defn.Int_-).appliedTo(t2)) - //gen.mkMethodCall(termMember(ScalaPackage, "math"), TermName("signum"), Nil, (t1 INT_- t2) :: Nil) - - protected def lengthGuard(binder: Symbol): Option[Tree] = - // no need to check unless it's an unapplySeq and the minimal length is non-trivially satisfied - checkedLength map { expectedLength => - // `binder.lengthCompare(expectedLength)` - // ...if binder has a lengthCompare method, otherwise - // `scala.math.signum(binder.length - expectedLength)` - def checkExpectedLength: Tree = sequenceType.member(nme.lengthCompare) match { - case NoDenotation => compareInts(Select(seqTree(binder), nme.length), Literal(Constant(expectedLength))) - case x:SingleDenotation => (seqTree(binder).select(x.symbol)).appliedTo(Literal(Constant(expectedLength))) - case _ => - ctx.error("TODO: multiple lengthCompare") - EmptyTree - } - - // the comparison to perform - // when the last subpattern is a wildcard-star the expectedLength is but a lower bound - // (otherwise equality is required) - def compareOp: (Tree, Tree) => Tree = - if (aligner.isStar) _.select(defn.Int_>=).appliedTo(_) - else _.select(defn.Int_==).appliedTo(_) - - // `if (binder != null && $checkExpectedLength [== | >=] 0) then else zero` - (seqTree(binder).select(defn.Any_!=).appliedTo(Literal(Constant(null)))).select(defn.Boolean_&&).appliedTo(compareOp(checkExpectedLength, Literal(Constant(0)))) - } - - def checkedLength: Option[Int] = - // no need to check unless it's an unapplySeq and the minimal length is non-trivially satisfied - if (!isSeq || expectedLength < starArity) None - else Some(expectedLength) - } - - class ExtractorCallRegular(aligner: PatternAligned, extractorCallIncludingDummy: Tree, val args: List[Tree], val resultType: Type) extends ExtractorCall(aligner) { - - /** Create the TreeMaker that embodies this extractor call - * - * `binder` has been casted to `paramType` if necessary - * `binderKnownNonNull` is not used in this subclass - * - * TODO: implement review feedback by @retronym: - * Passing the pair of values around suggests: - * case class Binder(sym: Symbol, knownNotNull: Boolean). - * Perhaps it hasn't reached critical mass, but it would already clean things up a touch. - */ - def treeMaker(patBinderOrCasted: Symbol, binderKnownNonNull: Boolean, pos: Position, binderTypeTested: Type): TreeMaker = { - // the extractor call (applied to the binder bound by the flatMap corresponding - // to the previous (i.e., enclosing/outer) pattern) - val extractorApply = extractorCallIncludingDummy// spliceApply(patBinderOrCasted) - // can't simplify this when subPatBinders.isEmpty, since UnitTpe is definitely - // wrong when isSeq, and resultInMonad should always be correct since it comes - // directly from the extractor's result type - val binder = freshSym(pos, resultInMonad) - val spb = subPatBinders - ExtractorTreeMaker(extractorApply, lengthGuard(binder), binder)( - spb, - subPatRefs(binder, spb, resultType), - aligner.isBool, - checkedLength, - patBinderOrCasted, - ignoredSubPatBinders - ) - } - - override protected def seqTree(binder: Symbol): Tree = - if (firstIndexingBinder == 0) ref(binder) - else super.seqTree(binder) - - // the trees that select the subpatterns on the extractor's result, referenced by `binder` - // require (totalArity > 0 && (!lastIsStar || isSeq)) - protected def subPatRefs(binder: Symbol, subpatBinders: List[Symbol], binderTypeTested: Type): List[Tree] = { - if (aligner.isSingle && aligner.extractor.prodArity == 1 && defn.isTupleType(binder.info)) { - // special case for extractor - // comparing with scalac additional assertions added - val subpw = subpatBinders.head.info.widen - val binderw = binder.info.widen - val go = subpatBinders.head.info <:< binder.info - val go1 = binder.info <:< subpatBinders.head.info - //val spr = subPatRefs(binder) - assert(go && go1) - ref(binder) :: Nil - } - else if ((aligner.isSingle && aligner.extractor.prodArity == 1) && - !isProductMatch(binderTypeTested, aligner.prodArity) && isGetMatch(binderTypeTested)) - List(ref(binder)) - else - subPatRefs(binder) - } - - /*protected def spliceApply(binder: Symbol): Tree = { - object splice extends TreeMap { - def binderRef(pos: Position): Tree = - ref(binder) //setPos pos - - override def transform(t: tpd.Tree)(implicit ctx: Context): tpd.Tree = t match { - // duplicated with the extractor Unapplied - case Apply(x, List(i @ Ident(nme.SELECTOR_DUMMY))) => - cpy.Apply(t, x, binderRef(i.pos) :: Nil) - // SI-7868 Account for numeric widening, e.g. .toInt - case Apply(x, List(i @ (sel @ Select(Ident(nme.SELECTOR_DUMMY), name)))) => - cpy.Apply(t, x, cpy.Select(sel, binderRef(i.pos), name) :: Nil) - case _ => - super.transform(t) - } - } - splice transform extractorCallIncludingDummy - }*/ - - override def rawSubPatTypes = aligner.extractor.varargsTypes - } - } - - /** An extractor returns: F1, F2, ..., Fi, opt[Seq[E] or E*] - * A case matches: P1, P2, ..., Pj, opt[Seq[E]] - * Put together: P1/F1, P2/F2, ... Pi/Fi, Pi+1/E, Pi+2/E, ... Pj/E, opt[Seq[E]] - * - * Here Pm/Fi is the last pattern to match the fixed arity section. - * - * prodArity: the value of i, i.e. the number of non-sequence types in the extractor - * nonStarArity: the value of j, i.e. the number of non-star patterns in the case definition - * elementArity: j - i, i.e. the number of non-star patterns which must match sequence elements - * starArity: 1 or 0 based on whether there is a star (sequence-absorbing) pattern - * totalArity: nonStarArity + starArity, i.e. the number of patterns in the case definition - * - * Note that prodArity is a function only of the extractor, and - * nonStar/star/totalArity are all functions of the patterns. The key - * value for aligning and typing the patterns is elementArity, as it - * is derived from both sets of information. - */ - trait PatternExpander[Pattern, Type] { - /** You'll note we're not inside the cake. "Pattern" and "Type" are - * arbitrary types here, and NoPattern and NoType arbitrary values. - */ - def NoPattern: Pattern - def NoType: Type - - /** It's not optimal that we're carrying both sequence and repeated - * type here, but the implementation requires more unraveling before - * it can be avoided. - * - * sequenceType is Seq[T], elementType is T, repeatedType is T*. - */ - sealed case class Repeated(sequenceType: Type, elementType: Type, repeatedType: Type) { - def exists = elementType != NoType - - def elementList = if (exists) elementType :: Nil else Nil - def sequenceList = if (exists) sequenceType :: Nil else Nil - def repeatedList = if (exists) repeatedType :: Nil else Nil - - override def toString = s"${elementType}*" - } - object NoRepeated extends Repeated(NoType, NoType, NoType) { - override def toString = "" - } - - /*final*/ case class Patterns(fixed: List[Pattern], star: Pattern) { - def hasStar = star != NoPattern - def starArity = if (hasStar) 1 else 0 - def nonStarArity = fixed.length - def totalArity = nonStarArity + starArity - def starPatterns = if (hasStar) star :: Nil else Nil - def all = fixed ::: starPatterns - - override def toString = all mkString ", " - } - - /** An 'extractor' can be a case class or an unapply or unapplySeq method. - * Decoding what it is that they extract takes place before we arrive here, - * so that this class can concentrate only on the relationship between - * patterns and types. - * - * In a case class, the class is the unextracted type and the fixed and - * repeated types are derived from its constructor parameters. - * - * In an unapply, this is reversed: the parameter to the unapply is the - * unextracted type, and the other types are derived based on the return - * type of the unapply method. - * - * In other words, this case class and unapply are encoded the same: - * - * case class Foo(x: Int, y: Int, zs: Char*) - * def unapplySeq(x: Foo): Option[(Int, Int, Seq[Char])] - * - * Both are Extractor(Foo, Int :: Int :: Nil, Repeated(Seq[Char], Char, Char*)) - * - * @param whole The type in its unextracted form - * @param fixed The non-sequence types which are extracted - * @param repeated The sequence type which is extracted - */ - /*final*/ case class Extractor(whole: Type, fixed: List[Type], repeated: Repeated) { - require(whole != NoType, s"expandTypes($whole, $fixed, $repeated)") - - def prodArity = fixed.length - def hasSeq = repeated.exists - def elementType = repeated.elementType - def sequenceType = repeated.sequenceType - def allTypes = fixed ::: repeated.sequenceList - def varargsTypes = fixed ::: repeated.repeatedList - def isErroneous = allTypes contains NoType - - private def typeStrings = fixed.map("" + _) ::: ( if (hasSeq) List("" + repeated) else Nil ) - - def offeringString = if (isErroneous) "" else typeStrings match { - case Nil => "Boolean" - case tp :: Nil => tp - case tps => tps.mkString("(", ", ", ")") - } - override def toString = "%s => %s".format(whole, offeringString) - } - - /*final*/ case class TypedPat(pat: Pattern, tpe: Type) { - override def toString = s"$pat: $tpe" - } - - /** If elementArity is... - * 0: A perfect match between extractor and the fixed patterns. - * If there is a star pattern it will match any sequence. - * > 0: There are more patterns than products. There will have to be a - * sequence which can populate at least patterns. - * < 0: There are more products than patterns: compile time error. - */ - /*final*/ case class Aligned(patterns: Patterns, extractor: Extractor) { - def elementArity = patterns.nonStarArity - prodArity - def prodArity = extractor.prodArity - def starArity = patterns.starArity - def totalArity = patterns.totalArity - - def wholeType = extractor.whole - def sequenceType = extractor.sequenceType - def productTypes = extractor.fixed - def extractedTypes = extractor.allTypes - def typedNonStarPatterns = products ::: elements - def typedPatterns = typedNonStarPatterns ::: stars - - def isBool = !isSeq && prodArity == 0 - def isSingle = !isSeq && totalArity == 1 - def isStar = patterns.hasStar - def isSeq = extractor.hasSeq - - private def typedAsElement(pat: Pattern) = TypedPat(pat, extractor.elementType) - private def typedAsSequence(pat: Pattern) = TypedPat(pat, extractor.sequenceType) - private def productPats = patterns.fixed take prodArity - private def elementPats = patterns.fixed drop prodArity - private def products = productPats.lazyZip(productTypes) map TypedPat - private def elements = elementPats map typedAsElement - private def stars = patterns.starPatterns map typedAsSequence - - override def toString = s""" - |Aligned { - | patterns $patterns - | extractor $extractor - | arities $prodArity/$elementArity/$starArity // product/element/star - | typed ${typedPatterns mkString ", "} - |}""".stripMargin.trim - } - } - - /** This is scalac-specific logic layered on top of the scalac-agnostic - * "matching products to patterns" logic defined in PatternExpander. - */ - trait ScalacPatternExpanders { - - type PatternAligned = ScalacPatternExpander#Aligned - - implicit class AlignedOps(val aligned: PatternAligned) { - import aligned._ - def expectedTypes = typedPatterns map (_.tpe) - def unexpandedFormals = extractor.varargsTypes - } - - trait ScalacPatternExpander extends PatternExpander[Tree, Type] { - def NoPattern = EmptyTree - def NoType = core.Types.NoType - - def newPatterns(patterns: List[Tree]): Patterns = patterns match { - case init :+ last if tpd.isWildcardStarArg(last) => Patterns(init, last) - case _ => Patterns(patterns, NoPattern) - } - def typeOfMemberNamedHead(tpe: Type): Type = tpe.select(nme.head) - def typeOfMemberNamedApply(tpe: Type): Type = tpe.select(nme.apply) - - def elementTypeOf(tpe: Type) = { - val seq = tpe //repeatedToSeq(tpe) - - ( typeOfMemberNamedHead(seq) - orElse typeOfMemberNamedApply(seq) - orElse seq.elemType - ) - } - def newExtractor(whole: Type, fixed: List[Type], repeated: Repeated): Extractor = { - ctx.log(s"newExtractor($whole, $fixed, $repeated") - Extractor(whole, fixed, repeated) - } - - // Turn Seq[A] into Repeated(Seq[A], A, A*) - def repeatedFromSeq(seqType: Type): Repeated = { - val elem = elementTypeOf(seqType) - val repeated = /*scalaRepeatedType(*/elem//) - - Repeated(seqType, elem, repeated) - } - // Turn A* into Repeated(Seq[A], A, A*) - def repeatedFromVarargs(repeated: Type): Repeated = - //Repeated(repeatedToSeq(repeated), repeatedToSingle(repeated), repeated) - Repeated(repeated, repeated.elemType, repeated) - - /** In this case we are basing the pattern expansion on a case class constructor. - * The argument is the MethodType carried by the primary constructor. - */ - def applyMethodTypes(method: Type): Extractor = { - val whole = method.finalResultType - - method.paramInfoss.head match { - case init :+ last if last.isRepeatedParam => newExtractor(whole, init, repeatedFromVarargs(last)) - case tps => newExtractor(whole, tps, NoRepeated) - } - } - - def hasSelectors(tpe: Type) = tpe.member(nme._1).exists && tpe.member(nme._2).exists // dd todo: ??? - - - /** In this case, expansion is based on an unapply or unapplySeq method. - * Unfortunately the MethodType does not carry the information of whether - * it was unapplySeq, so we have to funnel that information in separately. - */ - def unapplyMethodTypes(tree: Tree, fun: Tree, args: List[Tree], resultType: Type, isSeq: Boolean): Extractor = { - _id = _id + 1 - - val whole = tree.tpe // see scaladoc for Trees.Unapply - // fun.tpe.widen.paramTypess.headOption.flatMap(_.headOption).getOrElse(NoType)//firstParamType(method) - val resultOfGet = extractorMemberType(resultType, nme.get) - - val expanded: List[Type] = /*( - if (result =:= defn.BooleanType) Nil - else if (defn.isProductSubType(result)) productSelectorTypes(result) - else if (result.classSymbol is Flags.CaseClass) result.decls.filter(x => x.is(Flags.CaseAccessor) && x.is(Flags.Method)).map(_.info).toList - else result.select(nme.get) :: Nil - )*/ - if (isProductMatch(resultType, args.length)) productSelectorTypes(resultType) - else if (isGetMatch(resultType)) getUnapplySelectors(resultOfGet, args) - else if (resultType isRef defn.BooleanClass) Nil - else { - ctx.error(i"invalid return type in Unapply node: $resultType") - Nil - } - - expanded match { - case init :+ last if isSeq => newExtractor(whole, init, repeatedFromSeq(last)) - case tps => newExtractor(whole, tps, NoRepeated) - } - } - } - - object alignPatterns extends ScalacPatternExpander { - private def validateAligned(tree: Tree, aligned: Aligned): Aligned = { - import aligned._ - - def owner = tree.symbol.owner - def offering = extractor.offeringString - def symString = tree.symbol.showLocated - def offerString = if (extractor.isErroneous) "" else s" offering $offering" - def arityExpected = (if (extractor.hasSeq) "at least " else "") + prodArity - - def err(msg: String) = ctx.error(msg, tree.pos) - def warn(msg: String) = ctx.warning(msg, tree.pos) - def arityError(what: String) = err(s"${_id} $what patterns for $owner$offerString: expected $arityExpected, found $totalArity") - - if (isStar && !isSeq) - err("Star pattern must correspond with varargs or unapplySeq") - else if (elementArity < 0) - arityError("not enough") - else if (elementArity > 0 && !extractor.hasSeq) - arityError("too many") - - aligned - } - - object Applied { - // Duplicated with `spliceApply` - def unapply(tree: Tree): Option[Tree] = tree match { - // SI-7868 Admit Select() to account for numeric widening, e.g. .toInt - /*case Apply(fun, (Ident(nme.SELECTOR_DUMMY)| Select(Ident(nme.SELECTOR_DUMMY), _)) :: Nil) - => Some(fun)*/ - case Apply(fun, _) => unapply(fun) - case _ => None - } - } - - def apply(tree: Tree, sel: Tree, args: List[Tree], resultType: Type): Aligned = { - val fn = sel match { - case Applied(fn) => fn - case _ => sel - } - val patterns = newPatterns(args) - val isSeq = sel.symbol.name == nme.unapplySeq - val extractor = sel.symbol.name match { - case nme.unapply => unapplyMethodTypes(tree, /*fn*/sel, args, resultType, isSeq = false) - case nme.unapplySeq => unapplyMethodTypes(tree, /*fn*/sel, args, resultType, isSeq = true) - case _ => applyMethodTypes(/*fn*/sel.tpe) - } - - validateAligned(fn, Aligned(patterns, extractor)) - } - - def apply(tree: Tree, resultType: Type): Aligned = tree match { - case Typed(tree, _) => apply(tree, resultType) - case Apply(fn, args) => apply(tree, fn, args, resultType) - case UnApply(fn, implicits, args) => apply(tree, fn, args, resultType) - } - } - } - } -} diff --git a/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled b/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled deleted file mode 100644 index 2c618bdd365a..000000000000 --- a/compiler/src/dotty/tools/dotc/transform/PrivateToStatic.scala.disabled +++ /dev/null @@ -1,94 +0,0 @@ -package dotty.tools.dotc -package transform - -import core._ -import DenotTransformers.SymTransformer -import Contexts.Context -import Symbols._ -import Scopes._ -import Flags._ -import StdNames._ -import SymDenotations._ -import Types._ -import collection.mutable -import MegaPhase._ -import Decorators._ -import ast.Trees._ -import MegaPhase.TransformerInfo - -/** Makes private methods static, provided they not deferred, accessors, or static, - * by rewriting a method `m` in class `C` as follows: - * - * private def m(ps) = e - * - * --> private static def($this: C, ps) = [this -> $this] e - */ -class PrivateToStatic extends MiniPhase with SymTransformer { thisTransform => - import ast.tpd._ - override def phaseName = "privateToStatic" - override def relaxedTyping = true - - private val Immovable = Deferred | Accessor | JavaStatic - - def shouldBeStatic(sd: SymDenotation)(implicit ctx: Context) = - sd.current(using ctx.withPhase(thisTransform)).asSymDenotation - .is(PrivateMethod, butNot = Immovable) && - sd.owner.is(Trait) - - override def transformSym(sd: SymDenotation)(implicit ctx: Context): SymDenotation = - if (shouldBeStatic(sd)) { - val mt @ MethodType(pnames, ptypes) = sd.info - sd.copySymDenotation( - initFlags = sd.flags | JavaStatic, - info = MethodType(nme.SELF :: pnames, sd.owner.thisType :: ptypes, mt.resultType)) - } - else sd - - val treeTransform = new Transform(NoSymbol) - - class Transform(thisParam: Symbol) extends TreeTransform { - def phase = thisTransform - - override def prepareForDefDef(tree: DefDef)(implicit ctx: Context) = - if (shouldBeStatic(tree.symbol)) { - val selfParam = ctx.newSymbol(tree.symbol, nme.SELF, Param, tree.symbol.owner.thisType, coord = tree.pos) - new Transform(selfParam) - } - else this - - override def transformDefDef(tree: DefDef)(implicit ctx: Context) = - if (shouldBeStatic(tree.symbol)) { - val thisParamDef = ValDef(thisParam.asTerm) - val vparams :: Nil = tree.vparamss - cpy.DefDef(tree)(vparamss = (thisParamDef :: vparams) :: Nil) - } - else tree - - override def transformThis(tree: This)(implicit ctx: Context) = - if (shouldBeStatic(ctx.owner.enclosingMethod)) ref(thisParam).withPos(tree.pos) - else tree - - /** Rwrites a call to a method `m` which is made static as folows: - * - * qual.m(args) --> m(qual, args) - */ - override def transformApply(tree: Apply)(implicit ctx: Context) = - tree.fun match { - case fun @ Select(qual, name) if shouldBeStatic(fun.symbol) => - ctx.debuglog(i"mapping $tree to ${cpy.Ident(fun)(name)} (${qual :: tree.args}%, %)") - cpy.Apply(tree)(ref(fun.symbol).withPos(fun.pos), qual :: tree.args) - case _ => - tree - } - - override def transformClosure(tree: Closure)(implicit ctx: Context) = - tree.meth match { - case meth @ Select(qual, name) if shouldBeStatic(meth.symbol) => - cpy.Closure(tree)( - env = qual :: tree.env, - meth = ref(meth.symbol).withPos(meth.pos)) - case _ => - tree - } - } -} diff --git a/compiler/src/dotty/tools/repl/ReplCompiler.scala b/compiler/src/dotty/tools/repl/ReplCompiler.scala index 05f8b8afbc4b..80f60f670de0 100644 --- a/compiler/src/dotty/tools/repl/ReplCompiler.scala +++ b/compiler/src/dotty/tools/repl/ReplCompiler.scala @@ -165,7 +165,7 @@ class ReplCompiler extends Compiler { final def typeOf(expr: String)(implicit state: State): Result[String] = typeCheck(expr).map { tree => - implicit val ctx = state.context + given Context = state.context tree.rhs match { case Block(xs, _) => xs.last.tpe.widen.show case _ => diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 7b5ede2bf3f2..1c9e7a2ac9a4 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -111,7 +111,7 @@ class ReplDriver(settings: Array[String], val comps = completions(line.cursor, line.line, state) candidates.addAll(comps.asJava) } - implicit val ctx = state.context + given Context = state.context try { val line = terminal.readLine(completer) ParseResult(line)(state) @@ -181,7 +181,7 @@ class ReplDriver(settings: Array[String], val file = SourceFile.virtual("", expr, maybeIncomplete = true) val unit = CompilationUnit(file)(state.context) unit.tpdTree = tree - implicit val ctx = state.context.fresh.setCompilationUnit(unit) + given Context = state.context.fresh.setCompilationUnit(unit) val srcPos = SourcePosition(file, Span(cursor)) val (_, completions) = Completion.completions(srcPos) completions.map(makeCandidate) @@ -270,7 +270,7 @@ class ReplDriver(settings: Array[String], } private def renderDefinitions(tree: tpd.Tree, newestWrapper: Name)(implicit state: State): (State, Seq[Diagnostic]) = { - implicit val ctx = state.context + given Context = state.context def resAndUnit(denot: Denotation) = { import scala.util.{Success, Try} From 017a5789ee8cd389828b27ac93ab8200ecff20b6 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 14:19:29 +0200 Subject: [PATCH 08/41] Convert to givens in TypeComparer --- compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala | 4 +++- compiler/src/dotty/tools/dotc/core/Contexts.scala | 2 +- compiler/src/dotty/tools/dotc/core/GadtConstraint.scala | 2 +- .../src/dotty/tools/dotc/core/PatternTypeConstrainer.scala | 1 + compiler/src/dotty/tools/dotc/core/TypeComparer.scala | 4 ++-- 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala index fc8149a57a31..ca6a1b8d553d 100644 --- a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala +++ b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala @@ -26,7 +26,9 @@ trait ConstraintHandling[AbstractContext] { def constr: config.Printers.Printer = config.Printers.constr - implicit def ctx(implicit ac: AbstractContext): Context + def comparerCtx(using AbstractContext): Context + + given (using AbstractContext) as Context = comparerCtx protected def isSubType(tp1: Type, tp2: Type)(implicit actx: AbstractContext): Boolean protected def isSameType(tp1: Type, tp2: Type)(implicit actx: AbstractContext): Boolean diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index f97e8bd6eece..4382ec5242e2 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -160,7 +160,7 @@ object Contexts { private var _typeComparer: TypeComparer = _ protected def typeComparer_=(typeComparer: TypeComparer): Unit = _typeComparer = typeComparer def typeComparer: TypeComparer = { - if (_typeComparer.ctx ne this) + if (_typeComparer.comparerCtx ne this) _typeComparer = _typeComparer.copyIn(this) _typeComparer } diff --git a/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala b/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala index 862e148e6b60..ff707e8b3567 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 ----------------------------------------------- - implicit override def ctx(implicit ctx: Context): Context = ctx + override def comparerCtx(using ctx: 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/PatternTypeConstrainer.scala b/compiler/src/dotty/tools/dotc/core/PatternTypeConstrainer.scala index 848393925259..5935fbd91705 100644 --- a/compiler/src/dotty/tools/dotc/core/PatternTypeConstrainer.scala +++ b/compiler/src/dotty/tools/dotc/core/PatternTypeConstrainer.scala @@ -6,6 +6,7 @@ import Decorators._ import Symbols._ import Types._ import Flags._ +import Contexts.ctx import dotty.tools.dotc.reporting.trace import config.Feature.migrateTo3 import config.Printers._ diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index a210224448e9..f0eec95d4c71 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -32,7 +32,7 @@ object AbsentContext { */ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] with PatternTypeConstrainer { import TypeComparer._ - implicit def ctx(implicit nc: AbsentContext): Context = initctx + def comparerCtx(using AbsentContext): Context = initctx val state = ctx.typerState def constraint: Constraint = state.constraint @@ -237,7 +237,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w def firstTry: Boolean = tp2 match { case tp2: NamedType => def compareNamed(tp1: Type, tp2: NamedType): Boolean = - val ctx = this.ctx + val ctx = comparerCtx given Context = ctx // optimization for performance val info2 = tp2.info info2 match From f16fec06ffe5d7ed98eab23a836df2e27ca60865 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 14:27:46 +0200 Subject: [PATCH 09/41] Convert core classes (1) --- compiler/src/dotty/tools/dotc/Run.scala | 4 +- .../dotty/tools/dotc/core/Annotations.scala | 70 +++++++++---------- .../tools/dotc/core/CheckRealizable.scala | 18 ++--- .../src/dotty/tools/dotc/core/Comments.scala | 26 +++---- .../src/dotty/tools/dotc/core/Constants.scala | 4 +- .../dotty/tools/dotc/core/Constraint.scala | 24 +++---- .../tools/dotc/core/ConstraintHandling.scala | 2 +- .../tools/dotc/core/ConstraintRunInfo.scala | 2 +- .../src/dotty/tools/dotc/core/Contexts.scala | 12 ++-- .../dotc/decompiler/IDEDecompilerDriver.scala | 2 +- .../dotc/interactive/InteractiveDriver.scala | 2 +- .../src/dotty/tools/repl/ReplDriver.scala | 2 +- 12 files changed, 84 insertions(+), 84 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index b15640ebd9a4..785ed7326418 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -60,7 +60,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint * imports For each element of RootImports, an import context */ protected def rootContext(implicit ctx: Context): Context = { - ctx.initialize()(ctx) + ctx.initialize() ctx.base.setPhasePlan(comp.phases) val rootScope = new MutableScope val bootstrap = ctx.fresh @@ -72,7 +72,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint .setTyper(new Typer) .addMode(Mode.ImplicitsEnabled) .setTyperState(new TyperState(ctx.typerState)) - ctx.initialize()(start) // re-initialize the base context with start + ctx.initialize()(using start) // re-initialize the base context with start def addImport(ctx: Context, rootRef: ImportInfo.RootRef) = ctx.fresh.setImportInfo(ImportInfo.rootImport(rootRef)) defn.RootImportFns.foldLeft(start.setRun(this))(addImport) diff --git a/compiler/src/dotty/tools/dotc/core/Annotations.scala b/compiler/src/dotty/tools/dotc/core/Annotations.scala index 170fcd9aa2e5..0220a496a03a 100644 --- a/compiler/src/dotty/tools/dotc/core/Annotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Annotations.scala @@ -15,24 +15,24 @@ object Annotations { else tree.tpe.typeSymbol abstract class Annotation { - def tree(implicit ctx: Context): Tree + def tree(using Context): Tree - def symbol(implicit ctx: Context): Symbol = annotClass(tree) + def symbol(using Context): Symbol = annotClass(tree) - def matches(cls: Symbol)(implicit ctx: Context): Boolean = symbol.derivesFrom(cls) + def matches(cls: Symbol)(using Context): Boolean = symbol.derivesFrom(cls) def appliesToModule: Boolean = true // for now; see remark in SymDenotations - def derivedAnnotation(tree: Tree)(implicit ctx: Context): Annotation = + def derivedAnnotation(tree: Tree)(using Context): Annotation = if (tree eq this.tree) this else Annotation(tree) - def arguments(implicit ctx: Context): List[Tree] = ast.tpd.arguments(tree) + def arguments(using Context): List[Tree] = ast.tpd.arguments(tree) - def argument(i: Int)(implicit ctx: Context): Option[Tree] = { + def argument(i: Int)(using Context): Option[Tree] = { val args = arguments if (i < args.length) Some(args(i)) else None } - def argumentConstant(i: Int)(implicit ctx: Context): Option[Constant] = + def argumentConstant(i: Int)(using Context): Option[Constant] = for (ConstantType(c) <- argument(i) map (_.tpe)) yield c /** The tree evaluaton is in progress. */ @@ -41,14 +41,14 @@ object Annotations { /** The tree evaluation has finished. */ def isEvaluated: Boolean = true - def ensureCompleted(implicit ctx: Context): Unit = tree + def ensureCompleted(using Context): Unit = tree - def sameAnnotation(that: Annotation)(implicit ctx: Context): Boolean = + def sameAnnotation(that: Annotation)(using Context): Boolean = symbol == that.symbol && tree.sameTree(that.tree) } case class ConcreteAnnotation(t: Tree) extends Annotation { - def tree(implicit ctx: Context): Tree = t + def tree(using Context): Tree = t } /** The context to use to evaluate an annotation */ @@ -94,15 +94,15 @@ object Annotations { * pickling/unpickling and TypeTreeMaps */ abstract class BodyAnnotation extends Annotation { - override def symbol(implicit ctx: Context): ClassSymbol = defn.BodyAnnot - override def derivedAnnotation(tree: Tree)(implicit ctx: Context): Annotation = + override def symbol(using Context): ClassSymbol = defn.BodyAnnot + override def derivedAnnotation(tree: Tree)(using Context): Annotation = if (tree eq this.tree) this else ConcreteBodyAnnotation(tree) - override def arguments(implicit ctx: Context): List[Tree] = Nil - override def ensureCompleted(implicit ctx: Context): Unit = () + override def arguments(using Context): List[Tree] = Nil + override def ensureCompleted(using Context): Unit = () } class ConcreteBodyAnnotation(body: Tree) extends BodyAnnotation { - def tree(implicit ctx: Context): Tree = body + def tree(using Context): Tree = body } abstract class LazyBodyAnnotation extends BodyAnnotation { @@ -132,52 +132,52 @@ object Annotations { def apply(tree: Tree): ConcreteAnnotation = ConcreteAnnotation(tree) - def apply(cls: ClassSymbol)(implicit ctx: Context): Annotation = + def apply(cls: ClassSymbol)(using Context): Annotation = apply(cls, Nil) - def apply(cls: ClassSymbol, arg: Tree)(implicit ctx: Context): Annotation = + def apply(cls: ClassSymbol, arg: Tree)(using Context): Annotation = apply(cls, arg :: Nil) - def apply(cls: ClassSymbol, arg1: Tree, arg2: Tree)(implicit ctx: Context): Annotation = + def apply(cls: ClassSymbol, arg1: Tree, arg2: Tree)(using Context): Annotation = apply(cls, arg1 :: arg2 :: Nil) - def apply(cls: ClassSymbol, args: List[Tree])(implicit ctx: Context): Annotation = + def apply(cls: ClassSymbol, args: List[Tree])(using Context): Annotation = apply(cls.typeRef, args) - def apply(atp: Type, arg: Tree)(implicit ctx: Context): Annotation = + def apply(atp: Type, arg: Tree)(using Context): Annotation = apply(atp, arg :: Nil) - def apply(atp: Type, arg1: Tree, arg2: Tree)(implicit ctx: Context): Annotation = + def apply(atp: Type, arg1: Tree, arg2: Tree)(using Context): Annotation = apply(atp, arg1 :: arg2 :: Nil) - def apply(atp: Type, args: List[Tree])(implicit ctx: Context): Annotation = + def apply(atp: Type, args: List[Tree])(using Context): Annotation = apply(New(atp, args)) /** Create an annotation where the tree is computed lazily. */ - def deferred(sym: Symbol)(treeFn: Context ?=> Tree)(implicit ctx: Context): Annotation = + 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 } /** Create an annotation where the symbol and the tree are computed lazily. */ - def deferredSymAndTree(symFn: Context ?=> Symbol)(treeFn: Context ?=> Tree)(implicit ctx: Context): Annotation = + 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) } - def deferred(atp: Type, args: List[Tree])(implicit ctx: Context): Annotation = + def deferred(atp: Type, args: List[Tree])(using Context): Annotation = deferred(atp.classSymbol)(New(atp, args)) - def deferredResolve(atp: Type, args: List[ast.untpd.Tree])(implicit ctx: Context): Annotation = + def deferredResolve(atp: Type, args: List[ast.untpd.Tree])(using Context): Annotation = deferred(atp.classSymbol)(ast.untpd.resolveConstructor(atp, args)) /** Extractor for child annotations */ object Child { /** A deferred annotation to the result of a given child computation */ - def later(delayedSym: Context ?=> Symbol, span: Span)(implicit ctx: Context): Annotation = { + def later(delayedSym: Context ?=> Symbol, span: Span)(using Context): Annotation = { def makeChildLater(using Context) = { val sym = delayedSym New(defn.ChildAnnot.typeRef.appliedTo(sym.owner.thisType.select(sym.name, sym)), Nil) @@ -187,9 +187,9 @@ object Annotations { } /** A regular, non-deferred Child annotation */ - def apply(sym: Symbol, span: Span)(implicit ctx: Context): Annotation = later(sym, span) + def apply(sym: Symbol, span: Span)(using Context): Annotation = later(sym, span) - def unapply(ann: Annotation)(implicit ctx: Context): Option[Symbol] = + def unapply(ann: Annotation)(using Context): Option[Symbol] = if (ann.symbol == defn.ChildAnnot) { val AppliedType(_, (arg: NamedType) :: Nil) = ann.tree.tpe Some(arg.symbol) @@ -197,11 +197,11 @@ object Annotations { else None } - def makeSourceFile(path: String)(implicit ctx: Context): Annotation = + def makeSourceFile(path: String)(using Context): Annotation = apply(defn.SourceFileAnnot, Literal(Constant(path))) } - def ThrowsAnnotation(cls: ClassSymbol)(implicit ctx: Context): Annotation = { + def ThrowsAnnotation(cls: ClassSymbol)(using Context): Annotation = { val tref = cls.typeRef Annotation(defn.ThrowsAnnot.typeRef.appliedTo(tref), Ident(tref)) } @@ -211,24 +211,24 @@ object Annotations { */ implicit class AnnotInfo(val sym: Symbol) extends AnyVal { - def isDeprecated(implicit ctx: Context): Boolean = + def isDeprecated(using Context): Boolean = sym.hasAnnotation(defn.DeprecatedAnnot) - def deprecationMessage(implicit ctx: Context): Option[String] = + def deprecationMessage(using Context): Option[String] = for { annot <- sym.getAnnotation(defn.DeprecatedAnnot) arg <- annot.argumentConstant(0) } yield arg.stringValue - def migrationVersion(implicit ctx: Context): Option[Try[ScalaVersion]] = + def migrationVersion(using Context): Option[Try[ScalaVersion]] = for { annot <- sym.getAnnotation(defn.MigrationAnnot) arg <- annot.argumentConstant(1) } yield ScalaVersion.parse(arg.stringValue) - def migrationMessage(implicit ctx: Context): Option[Try[ScalaVersion]] = + def migrationMessage(using Context): Option[Try[ScalaVersion]] = for { annot <- sym.getAnnotation(defn.MigrationAnnot) arg <- annot.argumentConstant(0) diff --git a/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala b/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala index b298ada649ce..f53bfd762363 100644 --- a/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala +++ b/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala @@ -23,30 +23,30 @@ object CheckRealizable { object NotConcrete extends Realizability(" is not a concrete type") - class NotFinal(sym: Symbol)(implicit ctx: Context) + class NotFinal(sym: Symbol)(using Context) extends Realizability(i" refers to nonfinal $sym") - class HasProblemBounds(name: Name, info: Type)(implicit ctx: Context) + class HasProblemBounds(name: Name, info: Type)(using Context) extends Realizability(i" has a member $name with possibly conflicting bounds ${info.bounds.lo} <: ... <: ${info.bounds.hi}") - class HasProblemBaseArg(typ: Type, argBounds: TypeBounds)(implicit ctx: Context) + class HasProblemBaseArg(typ: Type, argBounds: TypeBounds)(using Context) extends Realizability(i" has a base type $typ with possibly conflicting parameter bounds ${argBounds.lo} <: ... <: ${argBounds.hi}") - class HasProblemBase(base1: Type, base2: Type)(implicit ctx: Context) + class HasProblemBase(base1: Type, base2: Type)(using Context) extends Realizability(i" has conflicting base types $base1 and $base2") - class HasProblemField(fld: SingleDenotation, problem: Realizability)(implicit ctx: Context) + class HasProblemField(fld: SingleDenotation, problem: Realizability)(using Context) extends Realizability(i" has a member $fld which is not a legal path\nsince ${fld.symbol.name}: ${fld.info}${problem.msg}") - class ProblemInUnderlying(tp: Type, problem: Realizability)(implicit ctx: Context) + class ProblemInUnderlying(tp: Type, problem: Realizability)(using Context) extends Realizability(i"s underlying type ${tp}${problem.msg}") { assert(problem != Realizable) } - def realizability(tp: Type)(implicit ctx: Context): Realizability = + def realizability(tp: Type)(using Context): Realizability = new CheckRealizable().realizability(tp) - def boundsRealizability(tp: Type)(implicit ctx: Context): Realizability = + def boundsRealizability(tp: Type)(using Context): Realizability = new CheckRealizable().boundsRealizability(tp) private val LateInitializedFlags = Lazy | Erased @@ -61,7 +61,7 @@ object CheckRealizable { * In general, a realizable type can have multiple inhabitants, hence it need not be stable (in the sense of * Type.isStable). */ -class CheckRealizable(implicit ctx: Context) { +class CheckRealizable(using Context) { import CheckRealizable._ /** A set of all fields that have already been checked. Used diff --git a/compiler/src/dotty/tools/dotc/core/Comments.scala b/compiler/src/dotty/tools/dotc/core/Comments.scala index b42c14867eca..7e5b770eff9a 100644 --- a/compiler/src/dotty/tools/dotc/core/Comments.scala +++ b/compiler/src/dotty/tools/dotc/core/Comments.scala @@ -62,7 +62,7 @@ object Comments { * @param f The expansion function. * @return The expanded comment, with the `usecases` populated. */ - def expand(f: String => String)(implicit ctx: Context): Comment = { + def expand(f: String => String)(using Context): Comment = { val expandedComment = f(raw) val useCases = Comment.parseUsecases(expandedComment, span) Comment(span, raw, Some(expandedComment), useCases) @@ -76,7 +76,7 @@ object Comments { def apply(span: Span, raw: String): Comment = Comment(span, raw, None, Nil) - private def parseUsecases(expandedComment: String, span: Span)(implicit ctx: Context): List[UseCase] = + private def parseUsecases(expandedComment: String, span: Span)(using Context): List[UseCase] = if (!isDocComment(expandedComment)) Nil else @@ -92,7 +92,7 @@ object Comments { * def foo: A = ??? * }}} */ - private def decomposeUseCase(body: String, span: Span, start: Int, end: Int)(implicit ctx: Context): UseCase = { + private def decomposeUseCase(body: String, span: Span, start: Int, end: Int)(using Context): UseCase = { def subPos(start: Int, end: Int) = if (span == NoSpan) NoSpan else { @@ -115,7 +115,7 @@ object Comments { } object UseCase { - def apply(code: String, codePos: Span)(implicit ctx: Context): UseCase = { + def apply(code: String, codePos: Span)(using Context): UseCase = { val tree = { val tree = new Parser(SourceFile.virtual("", code)).localDef(codePos.start) tree match { @@ -140,7 +140,7 @@ object Comments { import dotc.config.Printers.dottydoc import scala.collection.mutable - def expand(sym: Symbol, site: Symbol)(implicit ctx: Context): String = { + def expand(sym: Symbol, site: Symbol)(using Context): String = { val parent = if (site != NoSymbol) site else sym defineVariables(parent) expandedDocComment(sym, parent) @@ -154,7 +154,7 @@ object Comments { * of the same string are done, which is * interpreted as a recursive variable definition. */ - def expandedDocComment(sym: Symbol, site: Symbol, docStr: String = "")(implicit ctx: Context): String = { + def expandedDocComment(sym: Symbol, site: Symbol, docStr: String = "")(using Context): String = { // when parsing a top level class or module, use the (module-)class itself to look up variable definitions val parent = if ((sym.is(Flags.Module) || sym.isClass) && site.is(Flags.Package)) sym else site @@ -177,7 +177,7 @@ object Comments { docStr.replaceAll("""\{@inheritDoc\p{Zs}*\}""", "@inheritdoc") /** The cooked doc comment of an overridden symbol */ - protected def superComment(sym: Symbol)(implicit ctx: Context): Option[String] = + protected def superComment(sym: Symbol)(using Context): Option[String] = allInheritedOverriddenSymbols(sym).iterator map (x => cookedDocComment(x)) find (_ != "") private val cookedDocComments = newMutableSymbolMap[String] @@ -187,7 +187,7 @@ object Comments { * If a symbol does not have a doc comment but some overridden version of it does, * the doc comment of the overridden version is copied instead. */ - def cookedDocComment(sym: Symbol, docStr: String = "")(implicit ctx: Context): String = cookedDocComments.getOrElseUpdate(sym, { + def cookedDocComment(sym: Symbol, docStr: String = "")(using Context): String = cookedDocComments.getOrElseUpdate(sym, { var ownComment = if (docStr.length == 0) ctx.docCtx.flatMap(_.docstring(sym).map(c => template(c.raw))).getOrElse("") else template(docStr) @@ -342,7 +342,7 @@ object Comments { out.toString } - protected def expandVariables(initialStr: String, sym: Symbol, site: Symbol)(implicit ctx: Context): String = { + protected def expandVariables(initialStr: String, sym: Symbol, site: Symbol)(using Context): String = { val expandLimit = 10 def expandInternal(str: String, depth: Int): String = { @@ -394,7 +394,7 @@ object Comments { expandInternal(initialStr, 0).replace("""\$""", "$") } - def defineVariables(sym: Symbol)(implicit ctx: Context): Unit = { + def defineVariables(sym: Symbol)(using Context): Unit = { val Trim = "(?s)^[\\s&&[^\n\r]]*(.*?)\\s*$".r val raw = ctx.docCtx.flatMap(_.docstring(sym).map(_.raw)).getOrElse("") @@ -420,7 +420,7 @@ object Comments { * @param vble The variable for which a definition is searched * @param site The class for which doc comments are generated */ - def lookupVariable(vble: String, site: Symbol)(implicit ctx: Context): Option[String] = site match { + def lookupVariable(vble: String, site: Symbol)(using Context): Option[String] = site match { case NoSymbol => None case _ => val searchList = @@ -437,14 +437,14 @@ object Comments { * If a symbol does not have a doc comment but some overridden version of it does, * the position of the doc comment of the overridden version is returned instead. */ - def docCommentPos(sym: Symbol)(implicit ctx: Context): Span = + def docCommentPos(sym: Symbol)(using Context): Span = ctx.docCtx.flatMap(_.docstring(sym).map(_.span)).getOrElse(NoSpan) /** A version which doesn't consider self types, as a temporary measure: * an infinite loop has broken out between superComment and cookedDocComment * since r23926. */ - private def allInheritedOverriddenSymbols(sym: Symbol)(implicit ctx: Context): List[Symbol] = + private def allInheritedOverriddenSymbols(sym: Symbol)(using Context): List[Symbol] = if (!sym.owner.isClass) Nil else sym.allOverriddenSymbols.toList.filter(_ != NoSymbol) //TODO: could also be `sym.owner.allOverrid..` //else sym.owner.ancestors map (sym overriddenSymbol _) filter (_ != NoSymbol) diff --git a/compiler/src/dotty/tools/dotc/core/Constants.scala b/compiler/src/dotty/tools/dotc/core/Constants.scala index 81b876cb5d00..040c6d7b45fc 100644 --- a/compiler/src/dotty/tools/dotc/core/Constants.scala +++ b/compiler/src/dotty/tools/dotc/core/Constants.scala @@ -37,7 +37,7 @@ object Constants { def isNonUnitAnyVal: Boolean = BooleanTag <= tag && tag <= DoubleTag def isAnyVal: Boolean = UnitTag <= tag && tag <= DoubleTag - def tpe(implicit ctx: Context): Type = tag match { + def tpe(using Context): Type = tag match { case UnitTag => defn.UnitType case BooleanTag => defn.BooleanType case ByteTag => defn.ByteType @@ -150,7 +150,7 @@ object Constants { /** Convert constant value to conform to given type. */ - def convertTo(pt: Type)(implicit ctx: Context): Constant = { + def convertTo(pt: Type)(using Context): Constant = { def classBound(pt: Type): Type = pt.dealias.stripTypeVar match { case tref: TypeRef if !tref.symbol.isClass && tref.info.exists => classBound(tref.info.bounds.lo) diff --git a/compiler/src/dotty/tools/dotc/core/Constraint.scala b/compiler/src/dotty/tools/dotc/core/Constraint.scala index e3c8d5eeba26..1b0e36a24731 100644 --- a/compiler/src/dotty/tools/dotc/core/Constraint.scala +++ b/compiler/src/dotty/tools/dotc/core/Constraint.scala @@ -68,7 +68,7 @@ abstract class Constraint extends Showable { * are not contained in the return bounds. * @pre `param` is not part of the constraint domain. */ - def nonParamBounds(param: TypeParamRef)(implicit ctx: Context): TypeBounds + def nonParamBounds(param: TypeParamRef)(using Context): TypeBounds /** A new constraint which is derived from this constraint by adding * entries for all type parameters of `poly`. @@ -77,7 +77,7 @@ abstract class Constraint extends Showable { * satisfiability but will solved to give instances of * type variables. */ - def add(poly: TypeLambda, tvars: List[TypeVar])(implicit ctx: Context): This + def add(poly: TypeLambda, tvars: List[TypeVar])(using Context): This /** A new constraint which is derived from this constraint by updating * the entry for parameter `param` to `tp`. @@ -88,18 +88,18 @@ abstract class Constraint extends Showable { * * @pre `this contains param`. */ - def updateEntry(param: TypeParamRef, tp: Type)(implicit ctx: Context): This + def updateEntry(param: TypeParamRef, tp: Type)(using Context): This /** A constraint that includes the relationship `p1 <: p2`. * `<:` relationships between parameters ("edges") are propagated, but * non-parameter bounds are left alone. */ - def addLess(p1: TypeParamRef, p2: TypeParamRef)(implicit ctx: Context): This + def addLess(p1: TypeParamRef, p2: TypeParamRef)(using Context): This /** A constraint resulting from adding p2 = p1 to this constraint, and at the same * time transferring all bounds of p2 to p1 */ - def unify(p1: TypeParamRef, p2: TypeParamRef)(implicit ctx: Context): This + def unify(p1: TypeParamRef, p2: TypeParamRef)(using Context): This /** A new constraint which is derived from this constraint by removing * the type parameter `param` from the domain and replacing all top-level occurrences @@ -107,7 +107,7 @@ abstract class Constraint extends Showable { * approximation of it if that is needed to avoid cycles. * Occurrences nested inside a refinement or prefix are not affected. */ - def replace(param: TypeParamRef, tp: Type)(implicit ctx: Context): This + def replace(param: TypeParamRef, tp: Type)(using Context): This /** Is entry associated with `tl` removable? This is the case if * all type parameters of the entry are associated with type variables @@ -116,15 +116,15 @@ abstract class Constraint extends Showable { def isRemovable(tl: TypeLambda): Boolean /** A new constraint with all entries coming from `tl` removed. */ - def remove(tl: TypeLambda)(implicit ctx: Context): This + def remove(tl: TypeLambda)(using Context): This /** A new constraint with entry `tl` renamed to a fresh type lambda */ - def rename(tl: TypeLambda)(implicit ctx: Context): This + def rename(tl: TypeLambda)(using Context): This /** The given `tl` in case it is not contained in this constraint, * a fresh copy of `tl` otherwise. */ - def ensureFresh(tl: TypeLambda)(implicit ctx: Context): TypeLambda + def ensureFresh(tl: TypeLambda)(using Context): TypeLambda /** The type lambdas constrained by this constraint */ def domainLambdas: List[TypeLambda] @@ -148,10 +148,10 @@ abstract class Constraint extends Showable { * returning an approximate constraint, instead of * failing with an exception */ - def & (other: Constraint, otherHasErrors: Boolean)(implicit ctx: Context): Constraint + def & (other: Constraint, otherHasErrors: Boolean)(using Context): Constraint /** Check that no constrained parameter contains itself as a bound */ - def checkNonCyclic()(implicit ctx: Context): this.type + def checkNonCyclic()(using Context): this.type /** Does `param` occur at the toplevel in `tp` ? * Toplevel means: the type itself or a factor in some @@ -160,7 +160,7 @@ abstract class Constraint extends Showable { def occursAtToplevel(param: TypeParamRef, tp: Type)(using Context): Boolean /** Check that constraint only refers to TypeParamRefs bound by itself */ - def checkClosed()(implicit ctx: Context): Unit + def checkClosed()(using Context): Unit /** Constraint has not yet been retracted from a typer state */ def isRetracted: Boolean diff --git a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala index ca6a1b8d553d..c1d65385008d 100644 --- a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala +++ b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala @@ -190,7 +190,7 @@ trait ConstraintHandling[AbstractContext] { res } - def location(implicit ctx: Context) = "" // i"in ${ctx.typerState.stateChainStr}" // use for debugging + def location(using Context) = "" // i"in ${ctx.typerState.stateChainStr}" // use for debugging /** Make p2 = p1, transfer all bounds of p2 to p1 * @pre less(p1)(p2) diff --git a/compiler/src/dotty/tools/dotc/core/ConstraintRunInfo.scala b/compiler/src/dotty/tools/dotc/core/ConstraintRunInfo.scala index 9b3135228c04..225560585b4b 100644 --- a/compiler/src/dotty/tools/dotc/core/ConstraintRunInfo.scala +++ b/compiler/src/dotty/tools/dotc/core/ConstraintRunInfo.scala @@ -12,7 +12,7 @@ trait ConstraintRunInfo { self: Run => maxSize = size maxConstraint = c } - def printMaxConstraint()(implicit ctx: Context): Unit = { + def printMaxConstraint()(using Context): Unit = { val printer = if (ctx.settings.YdetailedStats.value) default else typr if (maxSize > 0) printer.println(s"max constraint = ${maxConstraint.show}") } diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 4382ec5242e2..4e9e92393eeb 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -494,9 +494,9 @@ object Contexts { } override def toString: String = { - def iinfo(implicit ctx: Context) = if (ctx.importInfo == null) "" else i"${ctx.importInfo.selectors}%, %" + def iinfo(using Context) = if (ctx.importInfo == null) "" else i"${ctx.importInfo.selectors}%, %" "Context(\n" + - (outersIterator map ( ctx => s" owner = ${ctx.owner}, scope = ${ctx.scope}, import = ${iinfo(ctx)}") mkString "\n") + (outersIterator.map(ctx => s" owner = ${ctx.owner}, scope = ${ctx.scope}, import = ${iinfo(using ctx)}").mkString("\n")) } def typerPhase: Phase = base.typerPhase @@ -525,7 +525,7 @@ object Contexts { def uniques: util.HashSet[Type] = base.uniques def nextSymId: Int = base.nextSymId - def initialize()(implicit ctx: Context): Unit = base.initialize()(ctx) + def initialize()(using Context): Unit = base.initialize() } /** A condensed context provides only a small memory footprint over @@ -681,12 +681,12 @@ object Contexts { _platform } - protected def newPlatform(implicit ctx: Context): Platform = + protected def newPlatform(using Context): Platform = if (settings.scalajs.value) new SJSPlatform else new JavaPlatform /** The loader that loads the members of _root_ */ - def rootLoader(root: TermSymbol)(implicit ctx: Context): SymbolLoader = platform.rootLoader(root) + def rootLoader(root: TermSymbol)(using Context): SymbolLoader = platform.rootLoader(root) // Set up some phases to get started */ usePhases(List(SomePhase)) @@ -697,7 +697,7 @@ object Contexts { /** Initializes the `ContextBase` with a starting context. * This initializes the `platform` and the `definitions`. */ - def initialize()(implicit ctx: Context): Unit = { + def initialize()(using Context): Unit = { _platform = newPlatform definitions.init() } diff --git a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala index 54853314f277..e97e0c4ddfb2 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala @@ -18,7 +18,7 @@ class IDEDecompilerDriver(val settings: List[String]) extends dotc.Driver { rootCtx.setSetting(rootCtx.settings.YretainTrees, true) rootCtx.setSetting(rootCtx.settings.fromTasty, true) val ctx = setup(settings.toArray :+ "dummy.scala", rootCtx)._2 - ctx.initialize()(ctx) + ctx.initialize()(using ctx) ctx } diff --git a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala index 1b2edc2e8288..c0cb06acf73a 100644 --- a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala +++ b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala @@ -31,7 +31,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { rootCtx.setSetting(rootCtx.settings.YretainTrees, true) rootCtx.setSetting(rootCtx.settings.YcookComments, true) val ctx = setup(settings.toArray, rootCtx)._2 - ctx.initialize()(ctx) + ctx.initialize()(using ctx) ctx } diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 1c9e7a2ac9a4..54df925758fd 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -66,7 +66,7 @@ class ReplDriver(settings: Array[String], val rootCtx = initCtx.fresh.addMode(Mode.ReadPositions | Mode.Interactive | Mode.ReadComments) rootCtx.setSetting(rootCtx.settings.YcookComments, true) val ictx = setup(settings, rootCtx)._2 - ictx.base.initialize()(ictx) + ictx.base.initialize()(using ictx) ictx } From 0c0d896659c6933ca7fcefc096b73e5f8481cc80 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 14:40:20 +0200 Subject: [PATCH 10/41] Convert core classes (2) --- .../dotty/tools/backend/sjs/JSCodeGen.scala | 2 +- compiler/src/dotty/tools/dotc/Run.scala | 2 +- .../tools/dotc/config/PathResolver.scala | 4 +- .../dotty/tools/dotc/core/Decorators.scala | 12 +- .../dotty/tools/dotc/core/Definitions.scala | 110 +++++++++--------- .../tools/dotc/core/DenotTransformers.scala | 18 +-- .../dotc/core/classfile/ClassfileParser.scala | 2 +- .../tools/dotc/core/tasty/TreeUnpickler.scala | 10 +- .../core/unpickleScala2/Scala2Unpickler.scala | 8 +- .../dotty/tools/dotc/transform/LazyVals.scala | 2 +- compiler/test/dotty/tools/DottyTest.scala | 2 +- 11 files changed, 86 insertions(+), 86 deletions(-) diff --git a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala index 4db55c6d5229..7e6f9741d8d3 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala @@ -62,7 +62,7 @@ class JSCodeGen()(implicit ctx: Context) { private val jsdefn = JSDefinitions.jsdefn private val primitives = new JSPrimitives(ctx) - private val positionConversions = new JSPositions()(ctx) + private val positionConversions = new JSPositions()(using ctx) import positionConversions._ // Some state -------------------------------------------------------------- diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 785ed7326418..3e5653471a5d 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -149,7 +149,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint def compileUnits(us: List[CompilationUnit], ctx: Context): Unit = { units = us - compileUnits()(ctx) + compileUnits()(using ctx) } private def compileUnits()(implicit ctx: Context) = Stats.maybeMonitored { diff --git a/compiler/src/dotty/tools/dotc/config/PathResolver.scala b/compiler/src/dotty/tools/dotc/config/PathResolver.scala index 55f63cc9a339..5a510d43b726 100644 --- a/compiler/src/dotty/tools/dotc/config/PathResolver.scala +++ b/compiler/src/dotty/tools/dotc/config/PathResolver.scala @@ -130,7 +130,7 @@ object PathResolver { def fromPathString(path: String)(implicit ctx: Context): ClassPath = { val settings = ctx.settings.classpath.update(path) - new PathResolver()(ctx.fresh.setSettings(settings)).result + new PathResolver()(using ctx.fresh.setSettings(settings)).result } /** Show values in Environment and Defaults when no argument is provided. @@ -146,7 +146,7 @@ object PathResolver { val ArgsSummary(sstate, rest, errors, warnings) = ctx.settings.processArguments(args.toList, true) errors.foreach(println) - val pr = new PathResolver()(ctx.fresh.setSettings(sstate)) + val pr = new PathResolver()(using ctx.fresh.setSettings(sstate)) println(" COMMAND: 'scala %s'".format(args.mkString(" "))) println("RESIDUAL: 'scala %s'\n".format(rest.mkString(" "))) diff --git a/compiler/src/dotty/tools/dotc/core/Decorators.scala b/compiler/src/dotty/tools/dotc/core/Decorators.scala index 224e886f3601..670d99ea10c1 100644 --- a/compiler/src/dotty/tools/dotc/core/Decorators.scala +++ b/compiler/src/dotty/tools/dotc/core/Decorators.scala @@ -170,7 +170,7 @@ object Decorators { xss.zipWithConserve(yss)((xs, ys) => xs.zipWithConserve(ys)(f)) implicit class TextToString(val text: Text) extends AnyVal { - def show(implicit ctx: Context): String = text.mkString(ctx.settings.pageWidth.value, ctx.settings.printLines.value) + def show(using Context): String = text.mkString(ctx.settings.pageWidth.value, ctx.settings.printLines.value) } /** Test whether a list of strings representing phases contains @@ -205,11 +205,11 @@ object Decorators { } implicit class genericDeco[T](val x: T) extends AnyVal { - def assertingErrorsReported(implicit ctx: Context): T = { + def assertingErrorsReported(using Context): T = { assert(ctx.reporter.errorsReported) x } - def assertingErrorsReported(msg: => String)(implicit ctx: Context): T = { + def assertingErrorsReported(msg: => String)(using Context): T = { assert(ctx.reporter.errorsReported, msg) x } @@ -217,19 +217,19 @@ object Decorators { implicit class StringInterpolators(val sc: StringContext) extends AnyVal { /** General purpose string formatting */ - def i(args: Any*)(implicit ctx: Context): String = + def i(args: Any*)(using Context): String = new StringFormatter(sc).assemble(args) /** Formatting for error messages: Like `i` but suppress follow-on * error messages after the first one if some of their arguments are "non-sensical". */ - def em(args: Any*)(implicit ctx: Context): String = + def em(args: Any*)(using Context): String = new ErrorMessageFormatter(sc).assemble(args) /** Formatting with added explanations: Like `em`, but add explanations to * give more info about type variables and to disambiguate where needed. */ - def ex(args: Any*)(implicit ctx: Context): String = + def ex(args: Any*)(using Context): String = explained(em(args: _*)) } diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index 9c90c9d686e0..b6df0be591d9 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -63,7 +63,7 @@ class Definitions { // See . private def enterSpecialPolyClass(name: TypeName, paramFlags: FlagSet, parentConstrs: => Seq[Type]): ClassSymbol = { val completer = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + def complete(denot: SymDenotation)(using Context): Unit = { val cls = denot.asClass.classSymbol val paramDecls = newScope val typeParam = enterSyntheticTypeParam(cls, paramFlags, paramDecls) @@ -112,7 +112,7 @@ class Definitions { */ def newFunctionNTrait(name: TypeName): ClassSymbol = { val completer = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + def complete(denot: SymDenotation)(using Context): Unit = { val cls = denot.asClass.classSymbol val decls = newScope val arity = name.functionArity @@ -164,7 +164,7 @@ class Definitions { val info = if (useCompleter) new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = + def complete(denot: SymDenotation)(using Context): Unit = denot.info = ptype } else ptype @@ -388,10 +388,10 @@ class Definitions { @tu lazy val Predef_identity : Symbol = ScalaPredefModule.requiredMethod(nme.identity) @tu lazy val Predef_undefined: Symbol = ScalaPredefModule.requiredMethod(nme.???) - def SubTypeClass(implicit ctx: Context): ClassSymbol = ctx.requiredClass("scala.<:<") + def SubTypeClass(using Context): ClassSymbol = ctx.requiredClass("scala.<:<") @tu lazy val SubType_refl: Symbol = SubTypeClass.companionModule.requiredMethod(nme.refl) - def DummyImplicitClass(implicit ctx: Context): ClassSymbol = ctx.requiredClass("scala.DummyImplicit") + def DummyImplicitClass(using Context): ClassSymbol = ctx.requiredClass("scala.DummyImplicit") @tu lazy val ScalaRuntimeModule: Symbol = ctx.requiredModule("scala.runtime.ScalaRunTime") def runtimeMethodRef(name: PreName): TermRef = ScalaRuntimeModule.requiredMethodRef(name) @@ -416,8 +416,8 @@ class Definitions { private var myDottyPredefModule: Symbol = _ @tu lazy val DottyArraysModule: Symbol = ctx.requiredModule("dotty.runtime.Arrays") - def newGenericArrayMethod(implicit ctx: Context): TermSymbol = DottyArraysModule.requiredMethod("newGenericArray") - def newArrayMethod(implicit ctx: Context): TermSymbol = DottyArraysModule.requiredMethod("newArray") + def newGenericArrayMethod(using Context): TermSymbol = DottyArraysModule.requiredMethod("newGenericArray") + def newArrayMethod(using Context): TermSymbol = DottyArraysModule.requiredMethod("newArray") def getWrapVarargsArrayModule: Symbol = ScalaRuntimeModule @@ -584,7 +584,7 @@ class Definitions { cls.infoOrCompleter match { case completer: ClassfileLoader => cls.info = new ClassfileLoader(completer.classfile) { - override def complete(root: SymDenotation)(implicit ctx: Context): Unit = { + override def complete(root: SymDenotation)(using Context): Unit = { super.complete(root) val constr = cls.primaryConstructor val newInfo = constr.info match { @@ -649,7 +649,7 @@ class Definitions { @tu lazy val Product_productPrefix : Symbol = ProductClass.requiredMethod(nme.productPrefix) @tu lazy val IteratorClass: ClassSymbol = ctx.requiredClass("scala.collection.Iterator") - def IteratorModule(implicit ctx: Context): Symbol = IteratorClass.companionModule + def IteratorModule(using Context): Symbol = IteratorClass.companionModule @tu lazy val ModuleSerializationProxyClass: ClassSymbol = ctx.requiredClass("scala.runtime.ModuleSerializationProxy") @tu lazy val ModuleSerializationProxyConstructor: TermSymbol = @@ -720,7 +720,7 @@ class Definitions { @tu lazy val Unpickler_unpickleType: Symbol = ctx.requiredMethod("scala.internal.quoted.Unpickler.unpickleType") @tu lazy val EqlClass: ClassSymbol = ctx.requiredClass("scala.Eql") - def Eql_eqlAny(implicit ctx: Context): TermSymbol = EqlClass.companionModule.requiredMethod(nme.eqlAny) + def Eql_eqlAny(using Context): TermSymbol = EqlClass.companionModule.requiredMethod(nme.eqlAny) @tu lazy val TypeBoxClass: ClassSymbol = ctx.requiredClass("scala.internal.TypeBox") @tu lazy val TypeBox_CAP: TypeSymbol = TypeBoxClass.requiredType(tpnme.CAP) @@ -747,18 +747,18 @@ class Definitions { @tu lazy val CLP_showError: Symbol = CommandLineParserModule.requiredMethod("showError") @tu lazy val TupleTypeRef: TypeRef = ctx.requiredClassRef("scala.Tuple") - def TupleClass(implicit ctx: Context): ClassSymbol = TupleTypeRef.symbol.asClass + 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") - def NonEmptyTupleClass(implicit ctx: Context): ClassSymbol = NonEmptyTupleTypeRef.symbol.asClass + 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 TupleXXLClass: ClassSymbol = ctx.requiredClass("scala.runtime.TupleXXL") - def TupleXXLModule(implicit ctx: Context): Symbol = TupleXXLClass.companionModule + def TupleXXLModule(using Context): Symbol = TupleXXLClass.companionModule - def TupleXXL_fromIterator(implicit ctx: Context): Symbol = TupleXXLModule.requiredMethod("fromIterator") + def TupleXXL_fromIterator(using Context): Symbol = TupleXXLModule.requiredMethod("fromIterator") @tu lazy val RuntimeTupleModule: Symbol = ctx.requiredModule("scala.runtime.Tuple") @tu lazy val RuntimeTupleModuleClass: Symbol = RuntimeTupleModule.moduleClass @@ -776,11 +776,11 @@ class Definitions { lazy val RuntimeTuple_isInstanceOfNonEmptyTuple: Symbol = RuntimeTupleModule.requiredMethod("isInstanceOfNonEmptyTuple") @tu lazy val TupledFunctionTypeRef: TypeRef = ctx.requiredClassRef("scala.TupledFunction") - def TupledFunctionClass(implicit ctx: Context): ClassSymbol = TupledFunctionTypeRef.symbol.asClass + def TupledFunctionClass(using Context): ClassSymbol = TupledFunctionTypeRef.symbol.asClass @tu lazy val InternalTupledFunctionTypeRef: TypeRef = ctx.requiredClassRef("scala.internal.TupledFunction") - def InternalTupleFunctionClass(implicit ctx: Context): ClassSymbol = InternalTupledFunctionTypeRef.symbol.asClass - def InternalTupleFunctionModule(implicit ctx: Context): Symbol = ctx.requiredModule("scala.internal.TupledFunction") + def InternalTupleFunctionClass(using Context): ClassSymbol = InternalTupledFunctionTypeRef.symbol.asClass + def InternalTupleFunctionModule(using Context): Symbol = ctx.requiredModule("scala.internal.TupledFunction") // Annotation base classes @tu lazy val AnnotationClass: ClassSymbol = ctx.requiredClass("scala.annotation.Annotation") @@ -864,13 +864,13 @@ class Definitions { def RepeatedParamType: TypeRef = RepeatedParamClass.typeRef - def ClassType(arg: Type)(implicit ctx: Context): Type = { + def ClassType(arg: Type)(using Context): Type = { val ctype = ClassClass.typeRef if (ctx.phase.erasedTypes) ctype else ctype.appliedTo(arg) } /** The enumeration type, goven a value of the enumeration */ - def EnumType(sym: Symbol)(implicit ctx: Context): TypeRef = + def EnumType(sym: Symbol)(using Context): TypeRef = // given (in java): "class A { enum E { VAL1 } }" // - sym: the symbol of the actual enumeration value (VAL1) // - .owner: the ModuleClassSymbol of the enumeration (object E) @@ -878,9 +878,9 @@ class Definitions { sym.owner.linkedClass.typeRef object FunctionOf { - def apply(args: List[Type], resultType: Type, isContextual: Boolean = false, isErased: Boolean = false)(implicit ctx: Context): Type = + def apply(args: List[Type], resultType: Type, isContextual: Boolean = false, isErased: Boolean = false)(using Context): Type = FunctionType(args.length, isContextual, isErased).appliedTo(args ::: resultType :: Nil) - def unapply(ft: Type)(implicit ctx: Context): Option[(List[Type], Type, Boolean, Boolean)] = { + def unapply(ft: Type)(using Context): Option[(List[Type], Type, Boolean, Boolean)] = { val tsym = ft.typeSymbol if (isFunctionClass(tsym)) { val targs = ft.dealias.argInfos @@ -892,9 +892,9 @@ class Definitions { } object PartialFunctionOf { - def apply(arg: Type, result: Type)(implicit ctx: Context): Type = + def apply(arg: Type, result: Type)(using Context): Type = PartialFunctionClass.typeRef.appliedTo(arg :: result :: Nil) - def unapply(pft: Type)(implicit ctx: Context): Option[(Type, List[Type])] = + def unapply(pft: Type)(using Context): Option[(Type, List[Type])] = if (pft.isRef(PartialFunctionClass)) { val targs = pft.dealias.argInfos if (targs.length == 2) Some((targs.head, targs.tail)) else None @@ -903,25 +903,25 @@ class Definitions { } object ArrayOf { - def apply(elem: Type)(implicit ctx: Context): Type = + def apply(elem: Type)(using Context): Type = if (ctx.erasedTypes) JavaArrayType(elem) else ArrayType.appliedTo(elem :: Nil) - def unapply(tp: Type)(implicit ctx: Context): Option[Type] = tp.dealias match { + def unapply(tp: Type)(using Context): Option[Type] = tp.dealias match { case AppliedType(at, arg :: Nil) if at.isRef(ArrayType.symbol) => Some(arg) case _ => None } } object MatchCase { - def apply(pat: Type, body: Type)(implicit ctx: Context): Type = + def apply(pat: Type, body: Type)(using Context): Type = MatchCaseClass.typeRef.appliedTo(pat, body) - def unapply(tp: Type)(implicit ctx: Context): Option[(Type, Type)] = tp match { + def unapply(tp: Type)(using Context): Option[(Type, Type)] = tp match { case AppliedType(tycon, pat :: body :: Nil) if tycon.isRef(MatchCaseClass) => Some((pat, body)) case _ => None } - def isInstance(tp: Type)(implicit ctx: Context): Boolean = tp match { + def isInstance(tp: Type)(using Context): Boolean = tp match { case AppliedType(tycon: TypeRef, _) => tycon.name == tpnme.MatchCase && // necessary pre-filter to avoid forcing symbols tycon.isRef(MatchCaseClass) @@ -940,9 +940,9 @@ class Definitions { * MultiArrayOf(, 2) */ object MultiArrayOf { - def apply(elem: Type, ndims: Int)(implicit ctx: Context): Type = + def apply(elem: Type, ndims: Int)(using Context): Type = if (ndims == 0) elem else ArrayOf(apply(elem, ndims - 1)) - def unapply(tp: Type)(implicit ctx: Context): Option[(Type, Int)] = tp match { + def unapply(tp: Type)(using Context): Option[(Type, Int)] = tp match { case ArrayOf(elemtp) => def recur(elemtp: Type): Option[(Type, Int)] = elemtp.dealias match { case TypeBounds(lo, hi) => recur(hi) @@ -955,7 +955,7 @@ class Definitions { } } - final def isCompiletime_S(sym: Symbol)(implicit ctx: Context): Boolean = + final def isCompiletime_S(sym: Symbol)(using Context): Boolean = sym.name == tpnme.S && sym.owner == CompiletimePackageObject.moduleClass private val compiletimePackageAnyTypes: Set[Name] = Set(tpnme.Equals, tpnme.NotEquals) @@ -968,7 +968,7 @@ class Definitions { private val compiletimePackageBooleanTypes: Set[Name] = Set(tpnme.Not, tpnme.Xor, tpnme.And, tpnme.Or) private val compiletimePackageStringTypes: Set[Name] = Set(tpnme.Plus) - final def isCompiletimeAppliedType(sym: Symbol)(implicit ctx: Context): Boolean = { + final def isCompiletimeAppliedType(sym: Symbol)(using Context): Boolean = { def isOpsPackageObjectAppliedType: Boolean = sym.owner == CompiletimeOpsPackageObjectAny.moduleClass && compiletimePackageAnyTypes.contains(sym.name) || sym.owner == CompiletimeOpsPackageObjectInt.moduleClass && compiletimePackageIntTypes.contains(sym.name) || @@ -983,7 +983,7 @@ class Definitions { @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)) - def AbstractFunctionClass(n: Int)(implicit ctx: Context): Symbol = AbstractFunctionClassPerRun()(ctx)(n) + 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)) @@ -1004,7 +1004,7 @@ class Definitions { @tu lazy val TupleType: Array[TypeRef] = mkArityArray("scala.Tuple", MaxTupleArity, 1) - def FunctionClass(n: Int, isContextual: Boolean = false, isErased: Boolean = false)(implicit ctx: Context): Symbol = + def FunctionClass(n: Int, isContextual: Boolean = false, isErased: Boolean = false)(using Context): Symbol = if (isContextual && isErased) ctx.requiredClass("scala.ErasedContextFunction" + n.toString) else if (isContextual) @@ -1012,13 +1012,13 @@ class Definitions { else if (isErased) ctx.requiredClass("scala.ErasedFunction" + n.toString) else if (n <= MaxImplementedFunctionArity) - FunctionClassPerRun()(ctx)(n) + FunctionClassPerRun()(using ctx)(n) else ctx.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)(implicit ctx: Context): TypeRef = + def FunctionType(n: Int, isContextual: Boolean = false, isErased: Boolean = false)(using Context): TypeRef = if (n <= MaxImplementedFunctionArity && (!isContextual || ctx.erasedTypes) && !isErased) ImplementedFunctionType(n) else FunctionClass(n, isContextual, isErased).typeRef @@ -1026,11 +1026,11 @@ class Definitions { def PolyFunctionType = PolyFunctionClass.typeRef /** If `cls` is a class in the scala package, its name, otherwise EmptyTypeName */ - def scalaClassName(cls: Symbol)(implicit ctx: Context): TypeName = + def scalaClassName(cls: Symbol)(using Context): TypeName = if (cls.isClass && cls.owner == ScalaPackageClass) cls.asClass.name else EmptyTypeName /** If type `ref` refers to a class in the scala package, its name, otherwise EmptyTypeName */ - def scalaClassName(ref: Type)(implicit ctx: Context): TypeName = scalaClassName(ref.classSymbol) + def scalaClassName(ref: Type)(using Context): TypeName = scalaClassName(ref.classSymbol) private def isVarArityClass(cls: Symbol, prefix: String) = cls.isClass && cls.owner.eq(ScalaPackageClass) && @@ -1178,7 +1178,7 @@ class Definitions { def isPolymorphicAfterErasure(sym: Symbol): Boolean = (sym eq Any_isInstanceOf) || (sym eq Any_asInstanceOf) || (sym eq Object_synchronized) - def isTupleType(tp: Type)(implicit ctx: Context): Boolean = { + def isTupleType(tp: Type)(using Context): Boolean = { val arity = tp.dealias.argInfos.length arity <= MaxTupleArity && TupleType(arity) != null && tp.isRef(TupleType(arity).symbol) } @@ -1189,7 +1189,7 @@ class Definitions { else TypeOps.nestedPairs(elems) } - def tupleTypes(tp: Type, bound: Int = Int.MaxValue)(implicit ctx: Context): Option[List[Type]] = { + def tupleTypes(tp: Type, bound: Int = Int.MaxValue)(using Context): Option[List[Type]] = { @tailrec def rec(tp: Type, acc: List[Type], bound: Int): Option[List[Type]] = tp.normalized.dealias match { case _ if bound < 0 => Some(acc.reverse) case tp: AppliedType if defn.PairClass == tp.classSymbol => rec(tp.args(1), tp.args.head :: acc, bound - 1) @@ -1200,12 +1200,12 @@ class Definitions { rec(tp.stripTypeVar, Nil, bound) } - def isProductSubType(tp: Type)(implicit ctx: Context): Boolean = tp.derivesFrom(ProductClass) + def isProductSubType(tp: Type)(using Context): Boolean = tp.derivesFrom(ProductClass) /** Is `tp` (an alias) of either a scala.FunctionN or a scala.ContextFunctionN * instance? */ - def isNonRefinedFunction(tp: Type)(implicit ctx: Context): Boolean = { + def isNonRefinedFunction(tp: Type)(using Context): Boolean = { val arity = functionArity(tp) val sym = tp.dealias.typeSymbol @@ -1216,7 +1216,7 @@ class Definitions { } /** Is `tp` a representation of a (possibly depenent) function type or an alias of such? */ - def isFunctionType(tp: Type)(implicit ctx: Context): Boolean = + def isFunctionType(tp: Type)(using Context): Boolean = isNonRefinedFunction(tp.dropDependentRefinement) // Specialized type parameters defined for scala.Function{0,1,2}. @@ -1242,7 +1242,7 @@ class Definitions { @tu lazy val Function2SpecializedReturnClasses: PerRun[collection.Set[Symbol]] = new PerRun(implicit ctx => Function2SpecializedReturnTypes.map(_.symbol)) - def isSpecializableFunction(cls: ClassSymbol, paramTypes: List[Type], retType: Type)(implicit ctx: Context): Boolean = + def isSpecializableFunction(cls: ClassSymbol, paramTypes: List[Type], retType: Type)(using Context): Boolean = paramTypes.length <= 2 && cls.derivesFrom(FunctionClass(paramTypes.length)) && (paramTypes match { case Nil => Function0SpecializedReturnClasses().contains(retType.typeSymbol) @@ -1257,7 +1257,7 @@ class Definitions { false }) - def functionArity(tp: Type)(implicit ctx: Context): Int = tp.dropDependentRefinement.dealias.argInfos.length - 1 + def functionArity(tp: Type)(using Context): Int = tp.dropDependentRefinement.dealias.argInfos.length - 1 /** Return underlying context function type (i.e. instance of an ContextFunctionN class) * or NoType if none exists. The following types are considered as underlying types: @@ -1265,7 +1265,7 @@ class Definitions { * - the instance or origin of a TypeVar (i.e. the result of a stripTypeVar) * - the upper bound of a TypeParamRef in the current constraint */ - def asContextFunctionType(tp: Type)(implicit ctx: Context): Type = + def asContextFunctionType(tp: Type)(using Context): Type = tp.stripTypeVar.dealias match { case tp1: TypeParamRef if ctx.typerState.constraint.contains(tp1) => asContextFunctionType(ctx.typeComparer.bounds(tp1).hiBound) @@ -1275,7 +1275,7 @@ class Definitions { } /** Is `tp` an context function type? */ - def isContextFunctionType(tp: Type)(implicit ctx: Context): Boolean = + def isContextFunctionType(tp: Type)(using Context): Boolean = asContextFunctionType(tp).exists /** An extractor for context function types `As ?=> B`, possibly with @@ -1293,7 +1293,7 @@ class Definitions { Some((args.init, args.last, tp1.typeSymbol.name.isErasedFunction)) else None - def isErasedFunctionType(tp: Type)(implicit ctx: Context): Boolean = + def isErasedFunctionType(tp: Type)(using Context): Boolean = isFunctionType(tp) && tp.dealias.typeSymbol.name.isErasedFunction /** A whitelist of Scala-2 classes that are known to be pure */ @@ -1331,7 +1331,7 @@ class Definitions { HasProblematicGetClass.contains(className) /** Is synthesized symbol with alphanumeric name allowed to be used as an infix operator? */ - def isInfix(sym: Symbol)(implicit ctx: Context): Boolean = + def isInfix(sym: Symbol)(using Context): Boolean = (sym eq Object_eq) || (sym eq Object_ne) @tu lazy val assumedSuperTraits = @@ -1355,7 +1355,7 @@ class Definitions { class PerRun[T](generate: Context => T) { private var current: RunId = NoRunId private var cached: T = _ - def apply()(implicit ctx: Context): T = { + def apply()(using Context): T = { if (current != ctx.runId) { cached = generate(ctx) current = ctx.runId @@ -1395,7 +1395,7 @@ class Definitions { } /** The type of the boxed class corresponding to primitive value type `tp`. */ - def boxedType(tp: Type)(implicit ctx: Context): TypeRef = { + def boxedType(tp: Type)(using Context): TypeRef = { val cls = tp.classSymbol if (cls eq ByteClass) BoxedByteClass else if (cls eq ShortClass) BoxedShortClass @@ -1410,10 +1410,10 @@ class Definitions { }.typeRef /** The JVM tag for `tp` if it's a primitive, `java.lang.Object` otherwise. */ - def typeTag(tp: Type)(implicit ctx: Context): Name = typeTags(scalaClassName(tp)) + def typeTag(tp: Type)(using Context): Name = typeTags(scalaClassName(tp)) // /** The `Class[?]` of a primitive value type name */ -// def valueTypeNameToJavaType(name: TypeName)(implicit ctx: Context): Option[Class[?]] = +// def valueTypeNameToJavaType(name: TypeName)(using Context): Option[Class[?]] = // valueTypeNamesToJavaType.get(if (name.firstPart eq nme.scala) name.lastPart.toTypeName else name) type PrimitiveClassEnc = Int @@ -1428,7 +1428,7 @@ class Definitions { val BooleanEnc: Int = 17 val UnitEnc: Int = 19 - def isValueSubType(tref1: TypeRef, tref2: TypeRef)(implicit ctx: Context): Boolean = + def isValueSubType(tref1: TypeRef, tref2: TypeRef)(using Context): Boolean = valueTypeEnc(tref2.name) % valueTypeEnc(tref1.name) == 0 def isValueSubClass(sym1: Symbol, sym2: Symbol): Boolean = valueTypeEnc(sym2.asClass.name) % valueTypeEnc(sym1.asClass.name) == 0 @@ -1473,7 +1473,7 @@ class Definitions { private var isInitialized = false - def init()(implicit ctx: Context): Unit = { + def init()(using Context): Unit = { this.initCtx = ctx if (!isInitialized) { // Enter all symbols from the scalaShadowing package in the scala package diff --git a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala index 8b3bca405488..4b08c9442102 100644 --- a/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala +++ b/compiler/src/dotty/tools/dotc/core/DenotTransformers.scala @@ -20,22 +20,22 @@ object DenotTransformers { trait DenotTransformer extends Phase { /** The last phase during which the transformed denotations are valid */ - def lastPhaseId(implicit ctx: Context): Int = ctx.base.nextDenotTransformerId(id + 1) + def lastPhaseId(using Context): Int = ctx.base.nextDenotTransformerId(id + 1) /** The validity period of the transformed denotations in the given context */ - def validFor(implicit ctx: Context): Period = + def validFor(using Context): Period = Period(ctx.runId, id + 1, lastPhaseId) /** The transformation method */ - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation + def transform(ref: SingleDenotation)(using Context): SingleDenotation } /** A transformer that only transforms the info field of denotations */ trait InfoTransformer extends DenotTransformer { - def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type + def transformInfo(tp: Type, sym: Symbol)(using Context): Type - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = { + def transform(ref: SingleDenotation)(using Context): SingleDenotation = { val sym = ref.symbol if (sym.exists && !mayChange(sym)) ref else { @@ -54,7 +54,7 @@ object DenotTransformers { * unaffected by this transform, so `transformInfo` need not be run. This * can save time, and more importantly, can help avoid forcing symbol completers. */ - protected def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = true + protected def mayChange(sym: Symbol)(using Context): Boolean = true } /** A transformer that only transforms SymDenotations. @@ -64,9 +64,9 @@ object DenotTransformers { */ trait SymTransformer extends DenotTransformer { - def transformSym(sym: SymDenotation)(implicit ctx: Context): SymDenotation + def transformSym(sym: SymDenotation)(using Context): SymDenotation - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = ref match { + def transform(ref: SingleDenotation)(using Context): SingleDenotation = ref match { case ref: SymDenotation => transformSym(ref) case _ => ref } @@ -77,6 +77,6 @@ object DenotTransformers { * installed using `installAfter` and `enteredAfter` at the end of the phase. */ trait IdentityDenotTransformer extends DenotTransformer { - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = ref + def transform(ref: SingleDenotation)(using Context): SingleDenotation = ref } } diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index ddc1c3421184..09c009cc3e0b 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -751,7 +751,7 @@ class ClassfileParser( } val unpickler = new unpickleScala2.Scala2Unpickler(bytes, classRoot, moduleRoot)(ctx) - unpickler.run()(ctx.addMode(Scala2UnpicklingMode)) + unpickler.run()(using ctx.addMode(Scala2UnpicklingMode)) Some(unpickler) } diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index e88e9d52204d..2579cdf95ff2 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -241,7 +241,7 @@ class TreeUnpickler(reader: TastyReader, case Some(sym) => sym case None => - val sym = forkAt(addr).createSymbol()(ctx.withOwner(ownerTree.findOwner(addr))) + val sym = forkAt(addr).createSymbol()(using ctx.withOwner(ownerTree.findOwner(addr))) ctx.log(i"forward reference to $sym") sym } @@ -968,7 +968,7 @@ class TreeUnpickler(reader: TastyReader, setSpan(start, PackageDef(pid, readIndexedStats(exprOwner, end)(ctx))) } case _ => - readTerm()(ctx.withOwner(exprOwner)) + readTerm()(using ctx.withOwner(exprOwner)) } def readImport()(implicit ctx: Context): Tree = { @@ -1054,7 +1054,7 @@ class TreeUnpickler(reader: TastyReader, ConstFold(untpd.Select(qual, name).withType(tpe)) def completeSelect(name: Name, sig: Signature): Select = - val qual = readTerm()(ctx) + val qual = readTerm()(using ctx) val denot = accessibleDenot(qual.tpe.widenIfUnstable, name, sig) makeSelect(qual, name, denot) @@ -1292,9 +1292,9 @@ class TreeUnpickler(reader: TastyReader, collectWhile((nextUnsharedTag == CASEDEF) && currentAddr != end) { if (nextByte == SHAREDterm) { readByte() - forkAt(readAddr()).readCase()(ctx.fresh.setNewScope) + forkAt(readAddr()).readCase()(using ctx.fresh.setNewScope) } - else readCase()(ctx.fresh.setNewScope) + else readCase()(using ctx.fresh.setNewScope) } def readCase()(implicit ctx: Context): CaseDef = { diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index dbaf5ee66185..c71f1b942591 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -436,7 +436,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas // symbols that were pickled with Pickler.writeSymInfo val nameref = readNat() - var name = at(nameref, () => readName()(ctx)) + var name = at(nameref, () => readName()(using ctx)) val owner = readSymbolRef() if (name eq nme.getClass_) && defn.hasProblematicGetClass(owner.name) then @@ -572,7 +572,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas if (isSymbolRef(inforef)) inforef = readNat() // println("reading type for " + denot) // !!! DEBUG - val tp = at(inforef, () => readType()(ctx)) + val tp = at(inforef, () => readType()(using ctx)) if denot.is(Method) then var params = paramssOfType(tp) if denot.isConstructor && denot.owner.typeParams.nonEmpty then @@ -623,12 +623,12 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas val end = readNat() + readIndex if (tag == POLYtpe) { val unusedRestpeRef = readNat() - until(end, () => readSymbolRef()(ctx)).asInstanceOf[List[TypeSymbol]] + until(end, () => readSymbolRef()(using ctx)).asInstanceOf[List[TypeSymbol]] } else Nil } private def loadTypeParams(implicit ctx: Context) = - atReadPos(index(infoRef), () => readTypeParams()(ctx)) + atReadPos(index(infoRef), () => readTypeParams()(using ctx)) /** Force reading type params early, we need them in setClassInfo of subclasses. */ def init()(implicit ctx: Context): List[TypeSymbol] = loadTypeParams diff --git a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala index 186bc9521041..c15f5aac22a6 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -153,7 +153,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { // val x$lzy = new scala.runtime.LazyInt() val holderName = LazyLocalName.fresh(xname) - val holderImpl = defn.LazyHolder()(ctx)(tpe.typeSymbol) + val holderImpl = defn.LazyHolder()(using ctx)(tpe.typeSymbol) val holderSymbol = ctx.newSymbol(x.symbol.owner, holderName, containerFlags, holderImpl.typeRef, coord = x.span) val holderTree = ValDef(holderSymbol, New(holderImpl.typeRef, Nil)) diff --git a/compiler/test/dotty/tools/DottyTest.scala b/compiler/test/dotty/tools/DottyTest.scala index 5d5bcd15b260..ecb1eae5449c 100644 --- a/compiler/test/dotty/tools/DottyTest.scala +++ b/compiler/test/dotty/tools/DottyTest.scala @@ -30,7 +30,7 @@ trait DottyTest extends ContextEscapeDetection { initializeCtx(ctx) // when classpath is changed in ctx, we need to re-initialize to get the // correct classpath from PathResolver - base.initialize()(ctx) + base.initialize()(using ctx) ctx } From 114e0d282e552901f6284b9d013e1b15495a769b Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 14:41:34 +0200 Subject: [PATCH 11/41] Convert core classes (3) --- .../tools/dotc/core/GadtConstraint.scala | 72 +++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala b/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala index ff707e8b3567..c598cea81a13 100644 --- a/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala +++ b/compiler/src/dotty/tools/dotc/core/GadtConstraint.scala @@ -15,46 +15,46 @@ import scala.annotation.internal.sharable /** Represents GADT constraints currently in scope */ sealed abstract class GadtConstraint extends Showable { /** Immediate bounds of `sym`. Does not contain lower/upper symbols (see [[fullBounds]]). */ - def bounds(sym: Symbol)(implicit ctx: Context): TypeBounds + def bounds(sym: Symbol)(using Context): TypeBounds /** Full bounds of `sym`, including TypeRefs to other lower/upper symbols. * * @note this performs subtype checks between ordered symbols. * Using this in isSubType can lead to infinite recursion. Consider `bounds` instead. */ - def fullBounds(sym: Symbol)(implicit ctx: Context): TypeBounds + def fullBounds(sym: Symbol)(using Context): TypeBounds /** Is `sym1` ordered to be less than `sym2`? */ - def isLess(sym1: Symbol, sym2: Symbol)(implicit ctx: Context): Boolean + def isLess(sym1: Symbol, sym2: Symbol)(using Context): Boolean /** Add symbols to constraint, correctly handling inter-dependencies. * * @see [[ConstraintHandling.addToConstraint]] */ - def addToConstraint(syms: List[Symbol])(implicit ctx: Context): Boolean - def addToConstraint(sym: Symbol)(implicit ctx: Context): Boolean = addToConstraint(sym :: Nil) + def addToConstraint(syms: List[Symbol])(using Context): Boolean + def addToConstraint(sym: Symbol)(using Context): Boolean = addToConstraint(sym :: Nil) /** Further constrain a symbol already present in the constraint. */ - def addBound(sym: Symbol, bound: Type, isUpper: Boolean)(implicit ctx: Context): Boolean + def addBound(sym: Symbol, bound: Type, isUpper: Boolean)(using Context): Boolean /** Is the symbol registered in the constraint? * * @note this is true even if the symbol is constrained to be equal to another type, unlike [[Constraint.contains]]. */ - def contains(sym: Symbol)(implicit ctx: Context): Boolean + def contains(sym: Symbol)(using Context): Boolean def isEmpty: Boolean final def nonEmpty: Boolean = !isEmpty /** See [[ConstraintHandling.approximation]] */ - def approximation(sym: Symbol, fromBelow: Boolean)(implicit ctx: Context): Type + def approximation(sym: Symbol, fromBelow: Boolean)(using Context): Type def fresh: GadtConstraint /** Restore the state from other [[GadtConstraint]], probably copied using [[fresh]] */ def restore(other: GadtConstraint): Unit - def debugBoundsDescription(implicit ctx: Context): String + def debugBoundsDescription(using Context): String } final class ProperGadtConstraint private( @@ -71,7 +71,7 @@ final class ProperGadtConstraint private( ) /** Exposes ConstraintHandling.subsumes */ - def subsumes(left: GadtConstraint, right: GadtConstraint, pre: GadtConstraint)(implicit ctx: Context): Boolean = { + def subsumes(left: GadtConstraint, right: GadtConstraint, pre: GadtConstraint)(using Context): Boolean = { def extractConstraint(g: GadtConstraint) = g match { case s: ProperGadtConstraint => s.constraint case EmptyGadtConstraint => OrderingConstraint.empty @@ -79,7 +79,7 @@ final class ProperGadtConstraint private( subsumes(extractConstraint(left), extractConstraint(right), extractConstraint(pre)) } - override def addToConstraint(params: List[Symbol])(implicit ctx: Context): Boolean = { + override def addToConstraint(params: List[Symbol])(using Context): Boolean = { import NameKinds.DepParamName val poly1 = PolyType(params.map { sym => DepParamName.fresh(sym.name.toTypeName) })( @@ -87,7 +87,7 @@ final class ProperGadtConstraint private( // In bound type `tp`, replace the symbols in dependent positions with their internal TypeParamRefs. // The replaced symbols will be later picked up in `ConstraintHandling#addToConstraint` // and used as orderings. - def substDependentSyms(tp: Type, isUpper: Boolean)(implicit ctx: Context): Type = { + def substDependentSyms(tp: Type, isUpper: Boolean)(using Context): Type = { def loop(tp: Type) = substDependentSyms(tp, isUpper) tp match { case tp @ AndType(tp1, tp2) if !isUpper => @@ -128,7 +128,7 @@ final class ProperGadtConstraint private( .reporting(i"added to constraint: [$poly1] $params%, %\n$debugBoundsDescription", gadts) } - override def addBound(sym: Symbol, bound: Type, isUpper: Boolean)(implicit ctx: Context): Boolean = { + override def addBound(sym: Symbol, bound: Type, isUpper: Boolean)(using Context): Boolean = { @annotation.tailrec def stripInternalTypeVar(tp: Type): Type = tp match { case tv: TypeVar => val inst = instType(tv) @@ -165,10 +165,10 @@ final class ProperGadtConstraint private( }, gadts) } - override def isLess(sym1: Symbol, sym2: Symbol)(implicit ctx: Context): Boolean = + override def isLess(sym1: Symbol, sym2: Symbol)(using Context): Boolean = constraint.isLess(tvarOrError(sym1).origin, tvarOrError(sym2).origin) - override def fullBounds(sym: Symbol)(implicit ctx: Context): TypeBounds = + override def fullBounds(sym: Symbol)(using Context): TypeBounds = mapping(sym) match { case null => null case tv => @@ -176,7 +176,7 @@ final class ProperGadtConstraint private( .ensuring(containsNoInternalTypes(_)) } - override def bounds(sym: Symbol)(implicit ctx: Context): TypeBounds = + override def bounds(sym: Symbol)(using Context): TypeBounds = mapping(sym) match { case null => null case tv => @@ -191,9 +191,9 @@ final class ProperGadtConstraint private( //.ensuring(containsNoInternalTypes(_)) } - override def contains(sym: Symbol)(implicit ctx: Context): Boolean = mapping(sym) ne null + override def contains(sym: Symbol)(using Context): Boolean = mapping(sym) ne null - override def approximation(sym: Symbol, fromBelow: Boolean)(implicit ctx: Context): Type = { + override def approximation(sym: Symbol, fromBelow: Boolean)(using Context): Type = { val res = approximation(tvarOrError(sym).origin, fromBelow = fromBelow) gadts.println(i"approximating $sym ~> $res") res @@ -222,21 +222,21 @@ final class ProperGadtConstraint private( override protected def constraint = myConstraint override protected def constraint_=(c: Constraint) = myConstraint = c - override def isSubType(tp1: Type, tp2: Type)(implicit ctx: Context): Boolean = ctx.typeComparer.isSubType(tp1, tp2) - override def isSameType(tp1: Type, tp2: Type)(implicit ctx: Context): Boolean = ctx.typeComparer.isSameType(tp1, tp2) + override def isSubType(tp1: Type, tp2: Type)(using Context): Boolean = ctx.typeComparer.isSubType(tp1, tp2) + override def isSameType(tp1: Type, tp2: Type)(using Context): Boolean = ctx.typeComparer.isSameType(tp1, tp2) - override def nonParamBounds(param: TypeParamRef)(implicit ctx: Context): TypeBounds = + override def nonParamBounds(param: TypeParamRef)(using Context): TypeBounds = constraint.nonParamBounds(param) match { case TypeAlias(tpr: TypeParamRef) => TypeAlias(externalize(tpr)) case tb => tb } - override def fullLowerBound(param: TypeParamRef)(implicit ctx: Context): Type = + override def fullLowerBound(param: TypeParamRef)(using Context): Type = constraint.minLower(param).foldLeft(nonParamBounds(param).lo) { (t, u) => t | externalize(u) } - override def fullUpperBound(param: TypeParamRef)(implicit ctx: Context): Type = + override def fullUpperBound(param: TypeParamRef)(using Context): Type = constraint.minUpper(param).foldLeft(nonParamBounds(param).hi) { (t, u) => val eu = externalize(u) // Any as the upper bound means "no bound", but if F is higher-kinded, @@ -246,26 +246,26 @@ final class ProperGadtConstraint private( // ---- Private ---------------------------------------------------------- - private def externalize(param: TypeParamRef)(implicit ctx: Context): Type = + private def externalize(param: TypeParamRef)(using Context): Type = reverseMapping(param) match { case sym: Symbol => sym.typeRef case null => param } - private def tvarOrError(sym: Symbol)(implicit ctx: Context): TypeVar = + private def tvarOrError(sym: Symbol)(using Context): TypeVar = mapping(sym).ensuring(_ ne null, i"not a constrainable symbol: $sym") private def containsNoInternalTypes( tp: Type, acc: TypeAccumulator[Boolean] = null - )(implicit ctx: Context): Boolean = tp match { + )(using Context): Boolean = tp match { case tpr: TypeParamRef => !reverseMapping.contains(tpr) case tv: TypeVar => !reverseMapping.contains(tv.origin) case tp => (if (acc ne null) acc else new ContainsNoInternalTypesAccumulator()).foldOver(true, tp) } - private class ContainsNoInternalTypesAccumulator(implicit ctx: Context) extends TypeAccumulator[Boolean] { + private class ContainsNoInternalTypesAccumulator(using Context) extends TypeAccumulator[Boolean] { override def apply(x: Boolean, tp: Type): Boolean = x && containsNoInternalTypes(tp) } @@ -275,7 +275,7 @@ final class ProperGadtConstraint private( override def toText(printer: Printer): Texts.Text = constraint.toText(printer) - override def debugBoundsDescription(implicit ctx: Context): String = { + override def debugBoundsDescription(using Context): String = { val sb = new mutable.StringBuilder sb ++= constraint.show sb += '\n' @@ -287,25 +287,25 @@ final class ProperGadtConstraint private( } @sharable object EmptyGadtConstraint extends GadtConstraint { - override def bounds(sym: Symbol)(implicit ctx: Context): TypeBounds = null - override def fullBounds(sym: Symbol)(implicit ctx: Context): TypeBounds = null + override def bounds(sym: Symbol)(using Context): TypeBounds = null + override def fullBounds(sym: Symbol)(using Context): TypeBounds = null - override def isLess(sym1: Symbol, sym2: Symbol)(implicit ctx: Context): Boolean = unsupported("EmptyGadtConstraint.isLess") + override def isLess(sym1: Symbol, sym2: Symbol)(using Context): Boolean = unsupported("EmptyGadtConstraint.isLess") override def isEmpty: Boolean = true - override def contains(sym: Symbol)(implicit ctx: Context) = false + override def contains(sym: Symbol)(using Context) = false - override def addToConstraint(params: List[Symbol])(implicit ctx: Context): Boolean = unsupported("EmptyGadtConstraint.addToConstraint") - override def addBound(sym: Symbol, bound: Type, isUpper: Boolean)(implicit ctx: Context): Boolean = unsupported("EmptyGadtConstraint.addBound") + override def addToConstraint(params: List[Symbol])(using Context): Boolean = unsupported("EmptyGadtConstraint.addToConstraint") + override def addBound(sym: Symbol, bound: Type, isUpper: Boolean)(using Context): Boolean = unsupported("EmptyGadtConstraint.addBound") - override def approximation(sym: Symbol, fromBelow: Boolean)(implicit ctx: Context): Type = unsupported("EmptyGadtConstraint.approximation") + override def approximation(sym: Symbol, fromBelow: Boolean)(using Context): Type = unsupported("EmptyGadtConstraint.approximation") override def fresh = new ProperGadtConstraint override def restore(other: GadtConstraint): Unit = if (!other.isEmpty) sys.error("cannot restore a non-empty GADTMap") - override def debugBoundsDescription(implicit ctx: Context): String = "EmptyGadtConstraint" + override def debugBoundsDescription(using Context): String = "EmptyGadtConstraint" override def toText(printer: Printer): Texts.Text = "EmptyGadtConstraint" } From 23b19e8b3e92cf8d51045880a4762dce92550eec Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 14:44:12 +0200 Subject: [PATCH 12/41] Convert core classes (4) --- compiler/src/dotty/tools/dotc/Run.scala | 2 +- .../tools/dotc/core/JavaNullInterop.scala | 16 ++-- .../tools/dotc/core/MacroClassLoader.scala | 6 +- .../src/dotty/tools/dotc/core/NameKinds.scala | 6 +- .../src/dotty/tools/dotc/core/NameOps.scala | 8 +- .../tools/dotc/core/NullOpsDecorator.scala | 14 +-- .../tools/dotc/core/OrderingConstraint.scala | 52 +++++------ .../src/dotty/tools/dotc/core/ParamInfo.scala | 16 ++-- .../src/dotty/tools/dotc/core/Phases.scala | 26 +++--- .../src/dotty/tools/dotc/core/Scopes.scala | 86 +++++++++---------- .../src/dotty/tools/dotc/core/Signature.scala | 14 +-- .../tools/dotc/core/StagingContext.scala | 14 +-- .../src/dotty/tools/dotc/core/StdNames.scala | 2 +- .../dotty/tools/dotc/core/SymbolLoaders.scala | 64 +++++++------- .../src/dotty/tools/dotc/core/Symbols.scala | 14 +-- .../dotc/transform/PCPCheckAndHeal.scala | 2 +- .../dotc/transform/init/SetDefTree.scala | 2 +- 17 files changed, 172 insertions(+), 172 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 3e5653471a5d..95af51ad12f3 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -66,7 +66,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint val bootstrap = ctx.fresh .setPeriod(Period(comp.nextRunId, FirstPhaseId)) .setScope(rootScope) - rootScope.enter(ctx.definitions.RootPackage)(bootstrap) + rootScope.enter(ctx.definitions.RootPackage)(using bootstrap) val start = bootstrap.fresh .setOwner(defn.RootClass) .setTyper(new Typer) diff --git a/compiler/src/dotty/tools/dotc/core/JavaNullInterop.scala b/compiler/src/dotty/tools/dotc/core/JavaNullInterop.scala index 86bcd161a102..1a64389bab82 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.core.Flags.JavaDefined import dotty.tools.dotc.core.StdNames.{jnme, nme} import dotty.tools.dotc.core.Symbols._ @@ -52,7 +52,7 @@ object JavaNullInterop { * * But the selection can throw an NPE if the returned value is `null`. */ - def nullifyMember(sym: Symbol, tp: Type, isEnumValueDef: Boolean)(implicit ctx: Context): Type = { + def nullifyMember(sym: Symbol, tp: Type, isEnumValueDef: Boolean)(using Context): Type = { assert(ctx.explicitNulls) assert(sym.is(JavaDefined), "can only nullify java-defined members") @@ -70,7 +70,7 @@ object JavaNullInterop { nullifyType(tp) } - private def hasNotNullAnnot(sym: Symbol)(implicit ctx: Context): Boolean = + private def hasNotNullAnnot(sym: Symbol)(using Context): Boolean = ctx.definitions.NotNullAnnots.exists(nna => sym.unforcedAnnotation(nna).isDefined) /** If tp is a MethodType, the parameters and the inside of return type are nullified, @@ -78,12 +78,12 @@ object JavaNullInterop { * If tp is a type of a field, the inside of the type is nullified, * but the result type is not nullable. */ - private def nullifyExceptReturnType(tp: Type)(implicit ctx: Context): Type = - new JavaNullMap(true)(ctx)(tp) + private def nullifyExceptReturnType(tp: Type)(using Context): Type = + new JavaNullMap(true)(tp) /** Nullifies a Java type by adding `| UncheckedNull` in the relevant places. */ - private def nullifyType(tp: Type)(implicit ctx: Context): Type = - new JavaNullMap(false)(ctx)(tp) + private def nullifyType(tp: Type)(using Context): Type = + new JavaNullMap(false)(tp) /** A type map that implements the nullification function on types. Given a Java-sourced type, this adds `| UncheckedNull` * in the right places to make the nulls explicit in Scala. @@ -96,7 +96,7 @@ object JavaNullInterop { * This is useful for e.g. constructors, and also so that `A & B` is nullified * to `(A & B) | UncheckedNull`, instead of `(A|UncheckedNull & B|UncheckedNull) | UncheckedNull`. */ - private class JavaNullMap(var outermostLevelAlreadyNullable: Boolean)(implicit ctx: Context) extends TypeMap { + private class JavaNullMap(var outermostLevelAlreadyNullable: Boolean)(using Context) extends TypeMap { /** Should we nullify `tp` at the outermost level? */ def needsNull(tp: Type): Boolean = !outermostLevelAlreadyNullable && (tp match { diff --git a/compiler/src/dotty/tools/dotc/core/MacroClassLoader.scala b/compiler/src/dotty/tools/dotc/core/MacroClassLoader.scala index 86f4f7a7c7a6..261b1f26a64d 100644 --- a/compiler/src/dotty/tools/dotc/core/MacroClassLoader.scala +++ b/compiler/src/dotty/tools/dotc/core/MacroClassLoader.scala @@ -12,14 +12,14 @@ object MacroClassLoader { private val MacroClassLoaderKey = new Property.Key[ClassLoader] /** Get the macro class loader */ - def fromContext(implicit ctx: Context): ClassLoader = + def fromContext(using Context): ClassLoader = ctx.property(MacroClassLoaderKey).getOrElse(makeMacroClassLoader) /** Context with a cached macro class loader that can be accessed with `macroClassLoader` */ def init(ctx: FreshContext): ctx.type = - ctx.setProperty(MacroClassLoaderKey, makeMacroClassLoader(ctx)) + ctx.setProperty(MacroClassLoaderKey, makeMacroClassLoader(using ctx)) - private def makeMacroClassLoader(implicit ctx: Context): ClassLoader = trace("new macro class loader") { + private def makeMacroClassLoader(using Context): ClassLoader = trace("new macro class loader") { val urls = ctx.settings.classpath.value.split(java.io.File.pathSeparatorChar).map(cp => java.nio.file.Paths.get(cp).toUri.toURL) val out = ctx.settings.outputDir.value.jpath.toUri.toURL // to find classes in case of suspended compilation new java.net.URLClassLoader(urls :+ out, getClass.getClassLoader) diff --git a/compiler/src/dotty/tools/dotc/core/NameKinds.scala b/compiler/src/dotty/tools/dotc/core/NameKinds.scala index f1e0cf68f5dd..8b5f6e6d326c 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 +import Contexts.{Context, ctx} import collection.mutable import scala.annotation.internal.sharable @@ -214,11 +214,11 @@ object NameKinds { } /** Generate fresh unique term name of this kind with given prefix name */ - def fresh(prefix: TermName = EmptyTermName)(implicit ctx: Context): TermName = + def fresh(prefix: TermName = EmptyTermName)(using Context): TermName = ctx.compilationUnit.freshNames.newName(prefix, this) /** Generate fresh unique type name of this kind with given prefix name */ - def fresh(prefix: TypeName)(implicit ctx: Context): TypeName = + def fresh(prefix: TypeName)(using Context): TypeName = fresh(prefix.toTermName).toTypeName uniqueNameKinds(separator) = this diff --git a/compiler/src/dotty/tools/dotc/core/NameOps.scala b/compiler/src/dotty/tools/dotc/core/NameOps.scala index c1423b61b204..07e1d6963b22 100644 --- a/compiler/src/dotty/tools/dotc/core/NameOps.scala +++ b/compiler/src/dotty/tools/dotc/core/NameOps.scala @@ -150,7 +150,7 @@ object NameOps { * This is the fully qualified name of `base` with `ExpandPrefixName` as separator, * followed by `kind` and the name. */ - def expandedName(base: Symbol, kind: QualifiedNameKind = ExpandedName)(implicit ctx: Context): N = + def expandedName(base: Symbol, kind: QualifiedNameKind = ExpandedName)(using Context): N = likeSpacedN { base.fullNameSeparated(ExpandPrefixName, kind, name) } /** Revert the expanded name. */ @@ -160,7 +160,7 @@ object NameOps { def errorName: N = likeSpacedN(name ++ nme.ERROR) - def freshened(implicit ctx: Context): N = likeSpacedN { + def freshened(using Context): N = likeSpacedN { name.toTermName match { case ModuleClassName(original) => ModuleClassName(original.freshened) case name => UniqueName.fresh(name) @@ -230,7 +230,7 @@ object NameOps { case nme.clone_ => nme.clone_ } - def specializedFor(classTargs: List[Type], classTargsNames: List[Name], methodTargs: List[Type], methodTarsNames: List[Name])(implicit ctx: Context): N = { + def specializedFor(classTargs: List[Type], classTargsNames: List[Name], methodTargs: List[Type], methodTarsNames: List[Name])(using Context): N = { val methodTags: Seq[Name] = (methodTargs zip methodTarsNames).sortBy(_._2).map(x => defn.typeTag(x._1)) val classTags: Seq[Name] = (classTargs zip classTargsNames).sortBy(_._2).map(x => defn.typeTag(x._1)) @@ -241,7 +241,7 @@ object NameOps { } /** If name length exceeds allowable limit, replace part of it by hash */ - def compactified(implicit ctx: Context): TermName = termName(compactify(name.toString)) + def compactified(using Context): TermName = termName(compactify(name.toString)) def unmangleClassName: N = name.toTermName match { case name: SimpleName diff --git a/compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala b/compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala index c7849936b035..e14c331ee3f6 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.core.Symbols.defn import dotty.tools.dotc.core.Types._ @@ -9,7 +9,7 @@ object NullOpsDecorator { implicit class NullOps(val self: Type) { /** Is this type exactly `UncheckedNull` (no vars, aliases, refinements etc allowed)? */ - def isUncheckedNullType(implicit ctx: Context): Boolean = { + def isUncheckedNullType(using Context): Boolean = { assert(ctx.explicitNulls) // We can't do `self == defn.UncheckedNull` because when trees are unpickled new references // to `UncheckedNull` could be created that are different from `defn.UncheckedNull`. @@ -24,7 +24,7 @@ object NullOpsDecorator { * * @param onlyUncheckedNull whether we only remove `UncheckedNull`, the default value is false */ - def stripNull(onlyUncheckedNull: Boolean = false)(implicit ctx: Context): Type = { + def stripNull(onlyUncheckedNull: Boolean = false)(using Context): Type = { assert(ctx.explicitNulls) def isNull(tp: Type) = @@ -56,14 +56,14 @@ object NullOpsDecorator { } /** Like `stripNull`, but removes only the `UncheckedNull`s. */ - def stripUncheckedNull(implicit ctx: Context): Type = self.stripNull(true) + def stripUncheckedNull(using Context): Type = self.stripNull(true) /** Collapses all `UncheckedNull` unions within this type, and not just the outermost ones (as `stripUncheckedNull` does). * e.g. (Array[String|UncheckedNull]|UncheckedNull).stripUncheckedNull => Array[String|UncheckedNull] * (Array[String|UncheckedNull]|UncheckedNull).stripAllUncheckedNull => Array[String] * If no `UncheckedNull` unions are found within the type, then returns the input type unchanged. */ - def stripAllUncheckedNull(implicit ctx: Context): Type = { + def stripAllUncheckedNull(using Context): Type = { object RemoveNulls extends TypeMap { override def apply(tp: Type): Type = mapOver(tp.stripNull(true)) } @@ -72,13 +72,13 @@ object NullOpsDecorator { } /** Is self (after widening and dealiasing) a type of the form `T | Null`? */ - def isNullableUnion(implicit ctx: Context): Boolean = { + def isNullableUnion(using Context): Boolean = { val stripped = self.stripNull() stripped ne self } /** Is self (after widening and dealiasing) a type of the form `T | UncheckedNull`? */ - def isUncheckedNullableUnion(implicit ctx: Context): Boolean = { + def isUncheckedNullableUnion(using Context): Boolean = { val stripped = self.stripNull(true) stripped ne self } diff --git a/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala b/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala index 7ebdb04da641..b25bfda84bf7 100644 --- a/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala +++ b/compiler/src/dotty/tools/dotc/core/OrderingConstraint.scala @@ -24,7 +24,7 @@ object OrderingConstraint { type ParamOrdering = ArrayValuedMap[List[TypeParamRef]] /** A new constraint with given maps */ - private def newConstraint(boundsMap: ParamBounds, lowerMap: ParamOrdering, upperMap: ParamOrdering)(implicit ctx: Context) : OrderingConstraint = { + private def newConstraint(boundsMap: ParamBounds, lowerMap: ParamOrdering, upperMap: ParamOrdering)(using Context) : OrderingConstraint = { val result = new OrderingConstraint(boundsMap, lowerMap, upperMap) ctx.run.recordConstraintSize(result, result.boundsMap.size) result @@ -33,7 +33,7 @@ object OrderingConstraint { /** A lens for updating a single entry array in one of the three constraint maps */ abstract class ConstraintLens[T <: AnyRef: ClassTag] { def entries(c: OrderingConstraint, poly: TypeLambda): Array[T] - def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[T])(implicit ctx: Context): OrderingConstraint + def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[T])(using Context): OrderingConstraint def initial: T def apply(c: OrderingConstraint, poly: TypeLambda, idx: Int): T = { @@ -47,7 +47,7 @@ object OrderingConstraint { * parts of `current` which are not shared by `prev`. */ def update(prev: OrderingConstraint, current: OrderingConstraint, - poly: TypeLambda, idx: Int, entry: T)(implicit ctx: Context): OrderingConstraint = { + poly: TypeLambda, idx: Int, entry: T)(using Context): OrderingConstraint = { var es = entries(current, poly) if (es != null && (es(idx) eq entry)) current else { @@ -68,22 +68,22 @@ object OrderingConstraint { } def update(prev: OrderingConstraint, current: OrderingConstraint, - param: TypeParamRef, entry: T)(implicit ctx: Context): OrderingConstraint = + param: TypeParamRef, entry: T)(using Context): OrderingConstraint = update(prev, current, param.binder, param.paramNum, entry) def map(prev: OrderingConstraint, current: OrderingConstraint, - poly: TypeLambda, idx: Int, f: T => T)(implicit ctx: Context): OrderingConstraint = + poly: TypeLambda, idx: Int, f: T => T)(using Context): OrderingConstraint = update(prev, current, poly, idx, f(apply(current, poly, idx))) def map(prev: OrderingConstraint, current: OrderingConstraint, - param: TypeParamRef, f: T => T)(implicit ctx: Context): OrderingConstraint = + param: TypeParamRef, f: T => T)(using Context): OrderingConstraint = map(prev, current, param.binder, param.paramNum, f) } val boundsLens: ConstraintLens[Type] = new ConstraintLens[Type] { def entries(c: OrderingConstraint, poly: TypeLambda): Array[Type] = c.boundsMap(poly) - def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[Type])(implicit ctx: Context): OrderingConstraint = + def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[Type])(using Context): OrderingConstraint = newConstraint(c.boundsMap.updated(poly, entries), c.lowerMap, c.upperMap) def initial = NoType } @@ -91,7 +91,7 @@ object OrderingConstraint { val lowerLens: ConstraintLens[List[TypeParamRef]] = new ConstraintLens[List[TypeParamRef]] { def entries(c: OrderingConstraint, poly: TypeLambda): Array[List[TypeParamRef]] = c.lowerMap(poly) - def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[List[TypeParamRef]])(implicit ctx: Context): OrderingConstraint = + def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[List[TypeParamRef]])(using Context): OrderingConstraint = newConstraint(c.boundsMap, c.lowerMap.updated(poly, entries), c.upperMap) def initial = Nil } @@ -99,7 +99,7 @@ object OrderingConstraint { val upperLens: ConstraintLens[List[TypeParamRef]] = new ConstraintLens[List[TypeParamRef]] { def entries(c: OrderingConstraint, poly: TypeLambda): Array[List[TypeParamRef]] = c.upperMap(poly) - def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[List[TypeParamRef]])(implicit ctx: Context): OrderingConstraint = + def updateEntries(c: OrderingConstraint, poly: TypeLambda, entries: Array[List[TypeParamRef]])(using Context): OrderingConstraint = newConstraint(c.boundsMap, c.lowerMap, c.upperMap.updated(poly, entries)) def initial = Nil } @@ -192,7 +192,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, def isLess(param1: TypeParamRef, param2: TypeParamRef): Boolean = upper(param1).contains(param2) - def nonParamBounds(param: TypeParamRef)(implicit ctx: Context): TypeBounds = + def nonParamBounds(param: TypeParamRef)(using Context): TypeBounds = entry(param).bounds def typeVarOfParam(param: TypeParamRef): Type = { @@ -232,7 +232,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, * @param isUpper If true, `bound` is an upper bound, else a lower bound. */ private def stripParams(tp: Type, paramBuf: mutable.ListBuffer[TypeParamRef], - isUpper: Boolean)(implicit ctx: Context): Type = tp match { + isUpper: Boolean)(using Context): Type = tp match { case param: TypeParamRef if contains(param) => if (!paramBuf.contains(param)) paramBuf += param NoType @@ -261,11 +261,11 @@ class OrderingConstraint(private val boundsMap: ParamBounds, * @param isUpper If true, `bound` is an upper bound, else a lower bound. */ private def normalizedType(tp: Type, paramBuf: mutable.ListBuffer[TypeParamRef], - isUpper: Boolean)(implicit ctx: Context): Type = + isUpper: Boolean)(using Context): Type = stripParams(tp, paramBuf, isUpper) .orElse(if (isUpper) defn.AnyKindType else defn.NothingType) - def add(poly: TypeLambda, tvars: List[TypeVar])(implicit ctx: Context): This = { + def add(poly: TypeLambda, tvars: List[TypeVar])(using Context): This = { assert(!contains(poly)) val nparams = poly.paramNames.length val entries1 = new Array[Type](nparams * 2) @@ -278,7 +278,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, * Update all bounds to be normalized and update ordering to account for * dependent parameters. */ - private def init(poly: TypeLambda)(implicit ctx: Context): This = { + private def init(poly: TypeLambda)(using Context): This = { var current = this val loBuf, hiBuf = new mutable.ListBuffer[TypeParamRef] var i = 0 @@ -348,7 +348,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, /** Add the fact `param1 <: param2` to the constraint `current` and propagate * `<:<` relationships between parameters ("edges") but not bounds. */ - private def order(current: This, param1: TypeParamRef, param2: TypeParamRef)(implicit ctx: Context): This = + private def order(current: This, param1: TypeParamRef, param2: TypeParamRef)(using Context): This = if (param1 == param2 || current.isLess(param1, param2)) this else { assert(contains(param1), i"$param1") @@ -375,7 +375,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, case _ => Nil - private def updateEntry(current: This, param: TypeParamRef, tp: Type)(implicit ctx: Context): This = { + private def updateEntry(current: This, param: TypeParamRef, tp: Type)(using Context): This = { var current1 = boundsLens.update(this, current, param, tp) tp match { case TypeBounds(lo, hi) => @@ -389,13 +389,13 @@ class OrderingConstraint(private val boundsMap: ParamBounds, } /** The public version of `updateEntry`. Guarantees that there are no cycles */ - def updateEntry(param: TypeParamRef, tp: Type)(implicit ctx: Context): This = + def updateEntry(param: TypeParamRef, tp: Type)(using Context): This = updateEntry(this, param, ensureNonCyclic(param, tp)).checkNonCyclic() - def addLess(param1: TypeParamRef, param2: TypeParamRef)(implicit ctx: Context): This = + def addLess(param1: TypeParamRef, param2: TypeParamRef)(using Context): This = order(this, param1, param2).checkNonCyclic() - def unify(p1: TypeParamRef, p2: TypeParamRef)(implicit ctx: Context): This = + def unify(p1: TypeParamRef, p2: TypeParamRef)(using Context): This = val p1Bounds = (nonParamBounds(p1) & nonParamBounds(p2)).substParam(p2, p1) updateEntry(p1, p1Bounds).replace(p2, p1) @@ -405,7 +405,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, * the type parameter `param` from the domain and replacing all top-level occurrences * of the parameter elsewhere in the constraint by type `tp`. */ - def replace(param: TypeParamRef, tp: Type)(implicit ctx: Context): OrderingConstraint = + def replace(param: TypeParamRef, tp: Type)(using Context): OrderingConstraint = val replacement = tp.dealiasKeepAnnots.stripTypeVar if param == replacement then this.checkNonCyclic() else @@ -427,7 +427,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, current.checkNonCyclic() end replace - def remove(pt: TypeLambda)(implicit ctx: Context): This = { + def remove(pt: TypeLambda)(using Context): This = { def removeFromOrdering(po: ParamOrdering) = { def removeFromBoundss(key: TypeLambda, bndss: Array[List[TypeParamRef]]): Array[List[TypeParamRef]] = { val bndss1 = bndss.map(_.filterConserve(_.binder ne pt)) @@ -452,7 +452,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, // ----------- Joins ----------------------------------------------------- - def & (other: Constraint, otherHasErrors: Boolean)(implicit ctx: Context): OrderingConstraint = { + def & (other: Constraint, otherHasErrors: Boolean)(using Context): OrderingConstraint = { def merge[T](m1: ArrayValuedMap[T], m2: ArrayValuedMap[T], join: (T, T) => T): ArrayValuedMap[T] = { var merged = m1 @@ -511,7 +511,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, merge(this.upperMap, that.upperMap, mergeParams)) }.reporting(i"constraint merge $this with $other = $result", constr) - def rename(tl: TypeLambda)(implicit ctx: Context): OrderingConstraint = { + def rename(tl: TypeLambda)(using Context): OrderingConstraint = { assert(contains(tl)) val tl1 = ensureFresh(tl) def swapKey[T](m: ArrayValuedMap[T]) = m.remove(tl).updated(tl1, m(tl)) @@ -530,7 +530,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, current.checkNonCyclic() } - def ensureFresh(tl: TypeLambda)(implicit ctx: Context): TypeLambda = + def ensureFresh(tl: TypeLambda)(using Context): TypeLambda = if (contains(tl)) { var paramInfos = tl.paramInfos if (tl.isInstanceOf[HKLambda]) { @@ -593,7 +593,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, // ---------- Checking ----------------------------------------------- - def checkNonCyclic()(implicit ctx: Context): this.type = + def checkNonCyclic()(using Context): this.type = if Config.checkConstraintsNonCyclic then domainParams.foreach { param => val inst = entry(param) @@ -604,7 +604,7 @@ class OrderingConstraint(private val boundsMap: ParamBounds, } this - def occursAtToplevel(param: TypeParamRef, inst: Type)(implicit ctx: Context): Boolean = + def occursAtToplevel(param: TypeParamRef, inst: Type)(using Context): Boolean = def occurs(tp: Type)(using Context): Boolean = tp match case tp: AndOrType => diff --git a/compiler/src/dotty/tools/dotc/core/ParamInfo.scala b/compiler/src/dotty/tools/dotc/core/ParamInfo.scala index ed235a2866aa..9593ba0b5d13 100644 --- a/compiler/src/dotty/tools/dotc/core/ParamInfo.scala +++ b/compiler/src/dotty/tools/dotc/core/ParamInfo.scala @@ -15,37 +15,37 @@ trait ParamInfo { /** Is this the info of a type parameter? Will return `false` for symbols * that are not type parameters. */ - def isTypeParam(implicit ctx: Context): Boolean + def isTypeParam(using Context): Boolean /** The name of the type parameter */ - def paramName(implicit ctx: Context): ThisName + def paramName(using Context): ThisName /** The info of the type parameter */ - def paramInfo(implicit ctx: Context): Type + def paramInfo(using Context): Type /** The info of the type parameter as seen from a prefix type. * For type parameter symbols, this is the `memberInfo` as seen from `prefix`. * For type lambda parameters, it's the same as `paramInfos` as * `asSeenFrom` has already been applied to the whole type lambda. */ - def paramInfoAsSeenFrom(prefix: Type)(implicit ctx: Context): Type + def paramInfoAsSeenFrom(prefix: Type)(using Context): Type /** The parameter bounds, or the completer if the type parameter * is an as-yet uncompleted symbol. */ - def paramInfoOrCompleter(implicit ctx: Context): Type + def paramInfoOrCompleter(using Context): Type /** The variance of the type parameter */ - def paramVariance(implicit ctx: Context): Variance + def paramVariance(using Context): Variance /** The variance of the type parameter, as a number -1, 0, +1. * Bivariant is mapped to 1, i.e. it is treated like Covariant. */ - final def paramVarianceSign(implicit ctx: Context): Int = + final def paramVarianceSign(using Context): Int = varianceToInt(paramVariance) /** A type that refers to the parameter */ - def paramRef(implicit ctx: Context): Type + def paramRef(using Context): Type } object ParamInfo { diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index a679a851e39a..53a8e9524575 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -53,22 +53,22 @@ object Phases { object NoPhase extends Phase { override def exists: Boolean = false def phaseName: String = "" - def run(implicit ctx: Context): Unit = unsupported("run") - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = unsupported("transform") + def run(using Context): Unit = unsupported("run") + def transform(ref: SingleDenotation)(using Context): SingleDenotation = unsupported("transform") } object SomePhase extends Phase { def phaseName: String = "" - def run(implicit ctx: Context): Unit = unsupported("run") + def run(using Context): Unit = unsupported("run") } /** A sentinel transformer object */ class TerminalPhase extends DenotTransformer { def phaseName: String = "terminal" - def run(implicit ctx: Context): Unit = unsupported("run") - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = + def run(using Context): Unit = unsupported("run") + def transform(ref: SingleDenotation)(using Context): SingleDenotation = unsupported("transform") - override def lastPhaseId(implicit ctx: Context): Int = id + override def lastPhaseId(using Context): Int = id } final def phasePlan: List[List[Phase]] = this.phasesPlan @@ -82,7 +82,7 @@ object Phases { phasesToSkip: List[String], stopBeforePhases: List[String], stopAfterPhases: List[String], - YCheckAfter: List[String])(implicit ctx: Context): List[Phase] = { + YCheckAfter: List[String])(using Context): List[Phase] = { val squashedPhases = ListBuffer[Phase]() var prevPhases: Set[String] = Set.empty val YCheckAll = YCheckAfter.contains("all") @@ -290,7 +290,7 @@ object Phases { */ def phaseName: String - def isRunnable(implicit ctx: Context): Boolean = + def isRunnable(using Context): Boolean = !ctx.reporter.hasErrors // TODO: This might test an unintended condition. // To find out whether any errors have been reported during this @@ -309,13 +309,13 @@ object Phases { def runsAfter: Set[String] = Set.empty /** @pre `isRunnable` returns true */ - def run(implicit ctx: Context): Unit + def run(using Context): Unit /** @pre `isRunnable` returns true */ - def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = + def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = units.map { unit => val unitCtx = ctx.fresh.setPhase(this.start).setCompilationUnit(unit) - run(unitCtx) + run(using unitCtx) unitCtx.compilationUnit } @@ -326,7 +326,7 @@ object Phases { /** Check what the phase achieves, to be called at any point after it is finished. */ - def checkPostCondition(tree: tpd.Tree)(implicit ctx: Context): Unit = () + def checkPostCondition(tree: tpd.Tree)(using Context): Unit = () /** Is this phase the standard typerphase? True for FrontEnd, but * not for other first phases (such as FromTasty). The predicate @@ -344,7 +344,7 @@ object Phases { /** Can this transform change the base types of a type? */ def changesBaseTypes: Boolean = changesParents - def isEnabled(implicit ctx: Context): Boolean = true + def isEnabled(using Context): Boolean = true def exists: Boolean = true diff --git a/compiler/src/dotty/tools/dotc/core/Scopes.scala b/compiler/src/dotty/tools/dotc/core/Scopes.scala index 7e29871f9ec2..b2e0db8b9ac7 100644 --- a/compiler/src/dotty/tools/dotc/core/Scopes.scala +++ b/compiler/src/dotty/tools/dotc/core/Scopes.scala @@ -80,20 +80,20 @@ object Scopes { /** The symbols in this scope in the order they were entered; * inherited from outer ones first. */ - def toList(implicit ctx: Context): List[Symbol] + def toList(using Context): List[Symbol] /** Return all symbols as an iterator in the order they were entered in this scope. */ - def iterator(implicit ctx: Context): Iterator[Symbol] = toList.iterator + def iterator(using Context): Iterator[Symbol] = toList.iterator /** Is the scope empty? */ def isEmpty: Boolean = lastEntry eq null /** Applies a function f to all Symbols of this Scope. */ - def foreach[U](f: Symbol => U)(implicit ctx: Context): Unit = toList.foreach(f) + def foreach[U](f: Symbol => U)(using Context): Unit = toList.foreach(f) /** Selects all Symbols of this Scope which satisfy a predicate. */ - def filter(p: Symbol => Boolean)(implicit ctx: Context): List[Symbol] = { + def filter(p: Symbol => Boolean)(using Context): List[Symbol] = { ensureComplete() var syms: List[Symbol] = Nil var e = lastEntry @@ -106,32 +106,32 @@ object Scopes { } /** Tests whether a predicate holds for at least one Symbol of this Scope. */ - def exists(p: Symbol => Boolean)(implicit ctx: Context): Boolean = filter(p).nonEmpty + def exists(p: Symbol => Boolean)(using Context): Boolean = filter(p).nonEmpty /** Finds the first Symbol of this Scope satisfying a predicate, if any. */ - def find(p: Symbol => Boolean)(implicit ctx: Context): Symbol = filter(p) match { + def find(p: Symbol => Boolean)(using Context): Symbol = filter(p) match { case sym :: _ => sym case _ => NoSymbol } /** Returns a new mutable scope with the same content as this one. */ - def cloneScope(implicit ctx: Context): MutableScope + def cloneScope(using Context): MutableScope /** Lookup a symbol entry matching given name. */ - def lookupEntry(name: Name)(implicit ctx: Context): ScopeEntry + def lookupEntry(name: Name)(using Context): ScopeEntry /** Lookup next entry with same name as this one */ - def lookupNextEntry(entry: ScopeEntry)(implicit ctx: Context): ScopeEntry + def lookupNextEntry(entry: ScopeEntry)(using Context): ScopeEntry /** Lookup a symbol */ - final def lookup(name: Name)(implicit ctx: Context): Symbol = { + final def lookup(name: Name)(using Context): Symbol = { val e = lookupEntry(name) if (e eq null) NoSymbol else e.sym } /** Returns an iterator yielding every symbol with given name in this scope. */ - final def lookupAll(name: Name)(implicit ctx: Context): Iterator[Symbol] = new Iterator[Symbol] { + final def lookupAll(name: Name)(using Context): Iterator[Symbol] = new Iterator[Symbol] { var e = lookupEntry(name) def hasNext: Boolean = e ne null def next(): Symbol = { val r = e.sym; e = lookupNextEntry(e); r } @@ -141,7 +141,7 @@ object Scopes { * Symbols occur in the result in reverse order relative to their occurrence * in `this.toList`. */ - final def denotsNamed(name: Name, select: SymDenotation => Boolean = selectAll)(implicit ctx: Context): PreDenotation = { + final def denotsNamed(name: Name, select: SymDenotation => Boolean = selectAll)(using Context): PreDenotation = { var syms: PreDenotation = NoDenotation var e = lookupEntry(name) while (e != null) { @@ -156,7 +156,7 @@ object Scopes { * given predicates. If all symbols match, returns the scope itself, otherwise * a copy with the matching symbols. */ - final def filteredScope(p: Symbol => Boolean)(implicit ctx: Context): Scope = { + final def filteredScope(p: Symbol => Boolean)(using Context): Scope = { var result: MutableScope = null for (sym <- iterator) if (!p(sym)) { @@ -166,19 +166,19 @@ object Scopes { if (result == null) this else result } - def implicitDecls(implicit ctx: Context): List[TermRef] = Nil + def implicitDecls(using Context): List[TermRef] = Nil def openForMutations: MutableScope = unsupported("openForMutations") final def toText(printer: Printer): Text = printer.toText(this) - def checkConsistent()(implicit ctx: Context): Unit = () + def checkConsistent()(using Context): Unit = () /** Ensure that all elements of this scope have been entered. * Overridden by SymbolLoaders.PackageLoader#PackageScope, where it * makes sure that all names with `$`'s have been added. */ - protected def ensureComplete()(implicit ctx: Context): Unit = () + protected def ensureComplete()(using Context): Unit = () } /** A subclass of Scope that defines methods for entering and @@ -191,9 +191,9 @@ object Scopes { extends Scope { /** Scope shares elements with `base` */ - protected[Scopes] def this(base: Scope)(implicit ctx: Context) = { + protected[Scopes] def this(base: Scope)(using Context) = { this(base.lastEntry, base.size, base.nestingLevel + 1) - ensureCapacity(MinHashedScopeSize)(ctx) // WTH? it seems the implicit is not in scope for a secondary constructor call. + ensureCapacity(MinHashedScopeSize) } def this() = this(null, 0, 0) @@ -224,7 +224,7 @@ object Scopes { /** Clone scope, taking care not to force the denotations of any symbols in the scope. */ - def cloneScope(implicit ctx: Context): MutableScope = { + def cloneScope(using Context): MutableScope = { val entries = new mutable.ArrayBuffer[ScopeEntry] var e = lastEntry while ((e ne null) && e.owner == this) { @@ -241,7 +241,7 @@ object Scopes { } /** create and enter a scope entry with given name and symbol */ - protected def newScopeEntry(name: Name, sym: Symbol)(implicit ctx: Context): ScopeEntry = { + protected def newScopeEntry(name: Name, sym: Symbol)(using Context): ScopeEntry = { ensureCapacity(if (hashTable ne null) hashTable.length else MinHashedScopeSize) val e = new ScopeEntry(name, sym, this) e.prev = lastEntry @@ -253,10 +253,10 @@ object Scopes { } /** create and enter a scope entry */ - protected def newScopeEntry(sym: Symbol)(implicit ctx: Context): ScopeEntry = + protected def newScopeEntry(sym: Symbol)(using Context): ScopeEntry = newScopeEntry(sym.name, sym) - private def enterInHash(e: ScopeEntry)(implicit ctx: Context): Unit = { + private def enterInHash(e: ScopeEntry)(using Context): Unit = { val idx = e.name.hashCode & (hashTable.length - 1) e.tail = hashTable(idx) assert(e.tail != e) @@ -264,7 +264,7 @@ object Scopes { } /** enter a symbol in this scope. */ - final def enter[T <: Symbol](sym: T)(implicit ctx: Context): T = { + final def enter[T <: Symbol](sym: T)(using Context): T = { if (sym.isType && ctx.phaseId <= ctx.typerPhase.id) assert(lookup(sym.name) == NoSymbol, s"duplicate ${sym.debugString}; previous was ${lookup(sym.name).debugString}") // !!! DEBUG @@ -273,15 +273,15 @@ object Scopes { } /** enter a symbol, asserting that no symbol with same name exists in scope */ - final def enterUnique(sym: Symbol)(implicit ctx: Context): Unit = { + final def enterUnique(sym: Symbol)(using Context): Unit = { assert(lookup(sym.name) == NoSymbol, (sym.showLocated, lookup(sym.name).showLocated)) enter(sym) } - private def ensureCapacity(tableSize: Int)(implicit ctx: Context): Unit = + private def ensureCapacity(tableSize: Int)(using Context): Unit = if (size >= tableSize * FillFactor) createHash(tableSize * 2) - private def createHash(tableSize: Int)(implicit ctx: Context): Unit = + private def createHash(tableSize: Int)(using Context): Unit = if (size > tableSize * FillFactor) createHash(tableSize * 2) else { hashTable = new Array[ScopeEntry](tableSize) @@ -289,7 +289,7 @@ object Scopes { // checkConsistent() // DEBUG } - private def enterAllInHash(e: ScopeEntry, n: Int = 0)(implicit ctx: Context): Unit = + private def enterAllInHash(e: ScopeEntry, n: Int = 0)(using Context): Unit = if (e ne null) if (n < MaxRecursions) { enterAllInHash(e.prev, n + 1) @@ -306,7 +306,7 @@ object Scopes { } /** Remove entry from this scope (which is required to be present) */ - final def unlink(e: ScopeEntry)(implicit ctx: Context): Unit = { + final def unlink(e: ScopeEntry)(using Context): Unit = { if (lastEntry == e) lastEntry = e.prev else { @@ -329,11 +329,11 @@ object Scopes { } /** remove symbol from this scope if it is present */ - final def unlink(sym: Symbol)(implicit ctx: Context): Unit = + final def unlink(sym: Symbol)(using Context): Unit = unlink(sym, sym.name) /** remove symbol from this scope if it is present under the given name */ - final def unlink(sym: Symbol, name: Name)(implicit ctx: Context): Unit = { + final def unlink(sym: Symbol, name: Name)(using Context): Unit = { var e = lookupEntry(name) while (e ne null) { if (e.sym == sym) unlink(e) @@ -344,7 +344,7 @@ object Scopes { /** Replace symbol `prev` (if it exists in current scope) by symbol `replacement`. * @pre `prev` and `replacement` have the same name. */ - final def replace(prev: Symbol, replacement: Symbol)(implicit ctx: Context): Unit = { + final def replace(prev: Symbol, replacement: Symbol)(using Context): Unit = { require(prev.name == replacement.name) var e = lookupEntry(prev.name) while (e ne null) { @@ -356,7 +356,7 @@ object Scopes { /** Lookup a symbol entry matching given name. */ - override def lookupEntry(name: Name)(implicit ctx: Context): ScopeEntry = { + override def lookupEntry(name: Name)(using Context): ScopeEntry = { var e: ScopeEntry = null if (hashTable ne null) { e = hashTable(name.hashCode & (hashTable.length - 1)) @@ -376,7 +376,7 @@ object Scopes { } /** lookup next entry with same name as this one */ - override final def lookupNextEntry(entry: ScopeEntry)(implicit ctx: Context): ScopeEntry = { + override final def lookupNextEntry(entry: ScopeEntry)(using Context): ScopeEntry = { var e = entry if (hashTable ne null) while ({ e = e.tail ; (e ne null) && e.name != entry.name }) () @@ -388,7 +388,7 @@ object Scopes { /** Returns all symbols as a list in the order they were entered in this scope. * Does _not_ include the elements of inherited scopes. */ - override final def toList(implicit ctx: Context): List[Symbol] = { + override final def toList(using Context): List[Symbol] = { if (elemsCache eq null) { ensureComplete() elemsCache = Nil @@ -401,7 +401,7 @@ object Scopes { elemsCache } - override def implicitDecls(implicit ctx: Context): List[TermRef] = { + override def implicitDecls(using Context): List[TermRef] = { ensureComplete() var irefs = new mutable.ListBuffer[TermRef] var e = lastEntry @@ -417,12 +417,12 @@ object Scopes { /** Vanilla scope - symbols are stored in declaration order. */ - final def sorted(implicit ctx: Context): List[Symbol] = toList + final def sorted(using Context): List[Symbol] = toList override def openForMutations: MutableScope = this /** Check that all symbols in this scope are in their correct hashtable buckets. */ - override def checkConsistent()(implicit ctx: Context): Unit = { + override def checkConsistent()(using Context): Unit = { ensureComplete() var e = lastEntry while (e != null) { @@ -438,10 +438,10 @@ object Scopes { def newScope: MutableScope = new MutableScope() /** Create a new scope nested in another one with which it shares its elements */ - def newNestedScope(outer: Scope)(implicit ctx: Context): MutableScope = new MutableScope(outer) + def newNestedScope(outer: Scope)(using Context): MutableScope = new MutableScope(outer) /** Create a new scope with given initial elements */ - def newScopeWith(elems: Symbol*)(implicit ctx: Context): MutableScope = { + def newScopeWith(elems: Symbol*)(using Context): MutableScope = { val scope = newScope elems foreach scope.enter scope @@ -462,10 +462,10 @@ object Scopes { override private[dotc] def lastEntry: ScopeEntry = null override def size: Int = 0 override def nestingLevel: Int = 0 - override def toList(implicit ctx: Context): List[Symbol] = Nil - override def cloneScope(implicit ctx: Context): MutableScope = unsupported("cloneScope") - override def lookupEntry(name: Name)(implicit ctx: Context): ScopeEntry = null - override def lookupNextEntry(entry: ScopeEntry)(implicit ctx: Context): ScopeEntry = null + override def toList(using Context): List[Symbol] = Nil + override def cloneScope(using Context): MutableScope = unsupported("cloneScope") + override def lookupEntry(name: Name)(using Context): ScopeEntry = null + override def lookupNextEntry(entry: ScopeEntry)(using Context): ScopeEntry = null } /** A class for error scopes (mutable) diff --git a/compiler/src/dotty/tools/dotc/core/Signature.scala b/compiler/src/dotty/tools/dotc/core/Signature.scala index 56601f920ab3..4636c13dde66 100644 --- a/compiler/src/dotty/tools/dotc/core/Signature.scala +++ b/compiler/src/dotty/tools/dotc/core/Signature.scala @@ -56,7 +56,7 @@ case class Signature(paramsSig: List[ParamSig], resSig: TypeName) { * This is the case if all parameter signatures are _consistent_, i.e. they are either * equal or on of them is tpnme.Uninstantiated. */ - final def consistentParams(that: Signature)(implicit ctx: Context): Boolean = { + final def consistentParams(that: Signature)(using Context): Boolean = { @tailrec def loop(names1: List[ParamSig], names2: List[ParamSig]): Boolean = if (names1.isEmpty) names2.isEmpty else !names2.isEmpty && consistent(names1.head, names2.head) && loop(names1.tail, names2.tail) @@ -87,7 +87,7 @@ case class Signature(paramsSig: List[ParamSig], resSig: TypeName) { * or `ParamMatch`. * If the parameters are inconsistent, the result is always `NoMatch`. */ - final def matchDegree(that: Signature)(implicit ctx: Context): MatchDegree = + final def matchDegree(that: Signature)(using Context): MatchDegree = if consistentParams(that) then if resSig == that.resSig || isWildcard(resSig) || isWildcard(that.resSig) then FullMatch @@ -99,7 +99,7 @@ case class Signature(paramsSig: List[ParamSig], resSig: TypeName) { NoMatch /** Does this signature potentially clash with `that` ? */ - def clashes(that: Signature)(implicit ctx: Context): Boolean = + def clashes(that: Signature)(using Context): Boolean = matchDegree(that) == FullMatch private def isWildcard(name: TypeName) = name == tpnme.WILDCARD @@ -109,7 +109,7 @@ case class Signature(paramsSig: List[ParamSig], resSig: TypeName) { * * Like Signature#apply, the result is only cacheable if `isUnderDefined == false`. */ - def prependTermParams(params: List[Type], isJava: Boolean)(implicit ctx: Context): Signature = + def prependTermParams(params: List[Type], isJava: Boolean)(using Context): Signature = Signature(params.map(p => sigName(p, isJava)) ::: paramsSig, resSig) /** Construct a signature by prepending the length of a type parameter section @@ -117,14 +117,14 @@ case class Signature(paramsSig: List[ParamSig], resSig: TypeName) { * * Like Signature#apply, the result is only cacheable if `isUnderDefined == false`. */ - def prependTypeParams(typeParamSigsSectionLength: Int)(implicit ctx: Context): Signature = + def prependTypeParams(typeParamSigsSectionLength: Int)(using Context): Signature = Signature(typeParamSigsSectionLength :: paramsSig, resSig) /** A signature is under-defined if its paramsSig part contains at least one * `tpnme.Uninstantiated`. Under-defined signatures arise when taking a signature * of a type that still contains uninstantiated type variables. */ - def isUnderDefined(implicit ctx: Context): Boolean = + def isUnderDefined(using Context): Boolean = paramsSig.contains(tpnme.Uninstantiated) || resSig == tpnme.Uninstantiated } @@ -164,7 +164,7 @@ object Signature { * otherwise the signature will change once the contained type variables have * been instantiated. */ - def apply(resultType: Type, isJava: Boolean)(implicit ctx: Context): Signature = { + def apply(resultType: Type, isJava: Boolean)(using Context): Signature = { assert(!resultType.isInstanceOf[ExprType]) apply(Nil, sigName(resultType, isJava)) } diff --git a/compiler/src/dotty/tools/dotc/core/StagingContext.scala b/compiler/src/dotty/tools/dotc/core/StagingContext.scala index 0926ca85220d..25de93d44d5a 100644 --- a/compiler/src/dotty/tools/dotc/core/StagingContext.scala +++ b/compiler/src/dotty/tools/dotc/core/StagingContext.scala @@ -24,33 +24,33 @@ object StagingContext { private val TaggedTypes = new Property.Key[PCPCheckAndHeal.QuoteTypeTags] /** All enclosing calls that are currently inlined, from innermost to outermost. */ - def level(implicit ctx: Context): Int = + def level(using Context): Int = ctx.property(QuotationLevel).getOrElse(0) /** Context with an incremented quotation level. */ - def quoteContext(implicit ctx: Context): Context = + def quoteContext(using Context): Context = ctx.fresh.setProperty(QuotationLevel, level + 1) /** Context with an incremented quotation level and pushes a refecence to a QuoteContext on the quote context stack */ - def pushQuoteContext(qctxRef: tpd.Tree)(implicit ctx: Context): Context = + def pushQuoteContext(qctxRef: tpd.Tree)(using Context): Context = val old = ctx.property(QuoteContextStack).getOrElse(List.empty) ctx.fresh.setProperty(QuotationLevel, level + 1) .setProperty(QuoteContextStack, qctxRef :: old) /** Context with a decremented quotation level. */ - def spliceContext(implicit ctx: Context): Context = + def spliceContext(using Context): Context = ctx.fresh.setProperty(QuotationLevel, level - 1) - def contextWithQuoteTypeTags(taggedTypes: PCPCheckAndHeal.QuoteTypeTags)(implicit ctx: Context) = + def contextWithQuoteTypeTags(taggedTypes: PCPCheckAndHeal.QuoteTypeTags)(using Context) = ctx.fresh.setProperty(TaggedTypes, taggedTypes) - def getQuoteTypeTags(implicit ctx: Context): PCPCheckAndHeal.QuoteTypeTags = + def getQuoteTypeTags(using Context): PCPCheckAndHeal.QuoteTypeTags = ctx.property(TaggedTypes).get /** Context with a decremented quotation level and pops the Some of top of the quote context stack or None if the stack is empty. * The quotation stack could be empty if we are in a top level splice or an eroneous splice directly witin a top level splice. */ - def popQuoteContext()(implicit ctx: Context): (Option[tpd.Tree], Context) = + def popQuoteContext()(using Context): (Option[tpd.Tree], Context) = val ctx1 = ctx.fresh.setProperty(QuotationLevel, level - 1) val head = ctx.property(QuoteContextStack) match diff --git a/compiler/src/dotty/tools/dotc/core/StdNames.scala b/compiler/src/dotty/tools/dotc/core/StdNames.scala index 80f386664972..c732043ff3df 100644 --- a/compiler/src/dotty/tools/dotc/core/StdNames.scala +++ b/compiler/src/dotty/tools/dotc/core/StdNames.scala @@ -799,7 +799,7 @@ object StdNames { case _ => termName("_" + j) } - def localDummyName(clazz: Symbol)(implicit ctx: Context): TermName = + def localDummyName(clazz: Symbol)(using Context): TermName = termName(str.LOCALDUMMY_PREFIX + clazz.name + ">") def newBitmapName(bitmapPrefix: TermName, n: Int): TermName = bitmapPrefix ++ n.toString diff --git a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala index 5e31a7e506a2..8d0fcede5f6e 100644 --- a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala +++ b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala @@ -32,7 +32,7 @@ object SymbolLoaders { private def enterNew( owner: Symbol, member: Symbol, - completer: SymbolLoader, scope: Scope = EmptyScope)(implicit ctx: Context): Symbol = { + completer: SymbolLoader, scope: Scope = EmptyScope)(using Context): Symbol = { val comesFromScan = completer.isInstanceOf[SourcefileLoader] assert(comesFromScan || scope.lookup(member.name) == NoSymbol, @@ -45,7 +45,7 @@ object SymbolLoaders { */ def enterClass( owner: Symbol, name: PreName, completer: SymbolLoader, - flags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(implicit ctx: Context): Symbol = { + flags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(using Context): Symbol = { val cls = ctx.newClassSymbol(owner, name.toTypeName.unmangleClassName.decode, flags, completer, assocFile = completer.sourceFileOrNull) enterNew(owner, cls, completer, scope) } @@ -54,7 +54,7 @@ object SymbolLoaders { */ def enterModule( owner: Symbol, name: PreName, completer: SymbolLoader, - modFlags: FlagSet = EmptyFlags, clsFlags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(implicit ctx: Context): Symbol = { + modFlags: FlagSet = EmptyFlags, clsFlags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(using Context): Symbol = { val module = ctx.newModuleSymbol( owner, name.toTermName.decode, modFlags, clsFlags, (module, _) => completer.proxy withDecls newScope withSourceModule (_ => module), @@ -66,7 +66,7 @@ object SymbolLoaders { /** Enter package with given `name` into scope of `owner` * and give them `completer` as type. */ - def enterPackage(owner: Symbol, pname: TermName, completer: (TermSymbol, ClassSymbol) => PackageLoader)(implicit ctx: Context): Symbol = { + def enterPackage(owner: Symbol, pname: TermName, completer: (TermSymbol, ClassSymbol) => PackageLoader)(using Context): Symbol = { val preExisting = owner.info.decls lookup pname if (preExisting != NoSymbol) // Some jars (often, obfuscated ones) include a package and @@ -97,7 +97,7 @@ object SymbolLoaders { */ def enterClassAndModule( owner: Symbol, name: PreName, completer: SymbolLoader, - flags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(implicit ctx: Context): Unit = { + flags: FlagSet = EmptyFlags, scope: Scope = EmptyScope)(using Context): Unit = { val clazz = enterClass(owner, name, completer, flags, scope) val module = enterModule( owner, name, completer, @@ -114,7 +114,7 @@ object SymbolLoaders { */ def enterToplevelsFromSource( owner: Symbol, name: PreName, src: AbstractFile, - scope: Scope = EmptyScope)(implicit ctx: Context): Unit = + scope: Scope = EmptyScope)(using Context): Unit = if src.exists && !src.isDirectory val completer = new SourcefileLoader(src) val filePath = owner.ownersIterator.takeWhile(!_.isRoot).map(_.name.toTermName).toList @@ -125,7 +125,7 @@ object SymbolLoaders { case _ => path } - def enterScanned(unit: CompilationUnit)(implicit ctx: Context) = { + def enterScanned(unit: CompilationUnit)(using Context) = { def checkPathMatches(path: List[TermName], what: String, tree: NameTree): Boolean = { val ok = filePath == path @@ -168,7 +168,7 @@ object SymbolLoaders { } val unit = CompilationUnit(ctx.getSource(src.path)) - enterScanned(unit)(ctx.fresh.setCompilationUnit(unit)) + enterScanned(unit)(using ctx.fresh.setCompilationUnit(unit)) /** The package objects of scala and scala.reflect should always * be loaded in binary if classfiles are available, even if sourcefiles @@ -177,13 +177,13 @@ object SymbolLoaders { * Note: We do a name-base comparison here because the method is called before we even * have ReflectPackage defined. */ - def binaryOnly(owner: Symbol, name: String)(implicit ctx: Context): Boolean = + def binaryOnly(owner: Symbol, name: String)(using Context): Boolean = name == "package" && (owner.fullName.toString == "scala" || owner.fullName.toString == "scala.reflect") /** Initialize toplevel class and module symbols in `owner` from class path representation `classRep` */ - def initializeFromClassPath(owner: Symbol, classRep: ClassRepresentation)(implicit ctx: Context): Unit = + 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) @@ -203,8 +203,8 @@ object SymbolLoaders { class PackageLoader(_sourceModule: TermSymbol, classPath: ClassPath) extends SymbolLoader { override def sourceFileOrNull: AbstractFile = null - override def sourceModule(implicit ctx: Context): TermSymbol = _sourceModule - def description(implicit ctx: Context): String = "package loader " + sourceModule.fullName + override def sourceModule(using Context): TermSymbol = _sourceModule + def description(using Context): String = "package loader " + sourceModule.fullName private var enterFlatClasses: Option[Context => Unit] = None @@ -217,10 +217,10 @@ object SymbolLoaders { * 2. Some function types in the `scala` package are synthesized. */ final class PackageScope extends MutableScope { - override def newScopeEntry(name: Name, sym: Symbol)(implicit ctx: Context): ScopeEntry = + override def newScopeEntry(name: Name, sym: Symbol)(using Context): ScopeEntry = super.newScopeEntry(name.mangled, sym) - override def lookupEntry(name: Name)(implicit ctx: Context): ScopeEntry = { + override def lookupEntry(name: Name)(using Context): ScopeEntry = { val mangled = name.mangled val e = super.lookupEntry(mangled) if (e != null) e @@ -232,7 +232,7 @@ object SymbolLoaders { else e } - override def ensureComplete()(implicit ctx: Context): Unit = + override def ensureComplete()(using Context): Unit = for (enter <- enterFlatClasses) enter(ctx) override def newScopeLikeThis(): PackageScope = new PackageScope @@ -256,7 +256,7 @@ object SymbolLoaders { def maybeModuleClass(classRep: ClassRepresentation): Boolean = classRep.name.last == '$' - private def enterClasses(root: SymDenotation, packageName: String, flat: Boolean)(implicit ctx: Context) = { + private def enterClasses(root: SymDenotation, packageName: String, flat: Boolean)(using Context) = { def isAbsent(classRep: ClassRepresentation) = !root.unforcedDecls.lookup(classRep.name.toTypeName).exists @@ -274,7 +274,7 @@ object SymbolLoaders { } } - def doComplete(root: SymDenotation)(implicit ctx: Context): Unit = { + def doComplete(root: SymDenotation)(using Context): Unit = { assert(root is PackageClass, root) val pre = root.owner.thisType root.info = ClassInfo(pre, root.symbol.asClass, Nil, currentDecls, pre select sourceModule) @@ -285,7 +285,7 @@ object SymbolLoaders { enterFlatClasses = Some { ctx => enterFlatClasses = None - enterClasses(root, packageName, flat = true)(ctx) + enterClasses(root, packageName, flat = true)(using ctx) } enterClasses(root, packageName, flat = false) if (!root.isEmptyPackage) @@ -307,24 +307,24 @@ object SymbolLoaders { */ abstract class SymbolLoader extends LazyType { self => /** Load source or class file for `root`, return */ - def doComplete(root: SymDenotation)(implicit ctx: Context): Unit + def doComplete(root: SymDenotation)(using Context): Unit def sourceFileOrNull: AbstractFile /** Description of the resource (ClassPath, AbstractFile) * being processed by this loader */ - def description(implicit ctx: Context): String + def description(using Context): String /** A proxy to this loader that keeps the doComplete operation * but provides fresh slots for scope/sourceModule/moduleClass */ def proxy: SymbolLoader = new SymbolLoader { export self.{doComplete, sourceFileOrNull} - def description(implicit ctx: Context): String = "proxy to ${self.description}" + def description(using Context): String = "proxy to ${self.description}" } - override def complete(root: SymDenotation)(implicit ctx: Context): Unit = { + override def complete(root: SymDenotation)(using Context): Unit = { def signalError(ex: Exception): Unit = { if (ctx.debug) ex.printStackTrace() val msg = ex.getMessage() @@ -363,7 +363,7 @@ abstract class SymbolLoader extends LazyType { self => } } - protected def rootDenots(rootDenot: ClassDenotation)(implicit ctx: Context): (ClassDenotation, ClassDenotation) = { + protected def rootDenots(rootDenot: ClassDenotation)(using Context): (ClassDenotation, ClassDenotation) = { val linkedDenot = rootDenot.scalacLinkedClass.denot match { case d: ClassDenotation => d case d => @@ -391,12 +391,12 @@ class ClassfileLoader(val classfile: AbstractFile) extends SymbolLoader { override def sourceFileOrNull: AbstractFile = classfile - def description(implicit ctx: Context): String = "class file " + classfile.toString + def description(using Context): String = "class file " + classfile.toString - override def doComplete(root: SymDenotation)(implicit ctx: Context): Unit = + override def doComplete(root: SymDenotation)(using Context): Unit = load(root) - def load(root: SymDenotation)(implicit ctx: Context): Unit = { + def load(root: SymDenotation)(using Context): Unit = { val (classRoot, moduleRoot) = rootDenots(root.asClass) val classfileParser = new ClassfileParser(classfile, classRoot, moduleRoot)(ctx) val result = classfileParser.run() @@ -409,23 +409,23 @@ class ClassfileLoader(val classfile: AbstractFile) extends SymbolLoader { } } - private def mayLoadTreesFromTasty(implicit ctx: Context): Boolean = + private def mayLoadTreesFromTasty(using Context): Boolean = ctx.settings.YretainTrees.value || ctx.settings.fromTasty.value } class SourcefileLoader(val srcfile: AbstractFile) extends SymbolLoader { - def description(implicit ctx: Context): String = "source file " + srcfile.toString + def description(using Context): String = "source file " + srcfile.toString override def sourceFileOrNull: AbstractFile = srcfile - def doComplete(root: SymDenotation)(implicit ctx: Context): Unit = + def doComplete(root: SymDenotation)(using Context): Unit = ctx.run.lateCompile(srcfile, typeCheck = ctx.settings.YretainTrees.value) } /** A NoCompleter which is also a SymbolLoader. */ class NoLoader extends SymbolLoader with NoCompleter { - def description(implicit ctx: Context): String = "NoLoader" + def description(using Context): String = "NoLoader" override def sourceFileOrNull: AbstractFile = null - override def complete(root: SymDenotation)(implicit ctx: Context): Unit = + override def complete(root: SymDenotation)(using Context): Unit = super[NoCompleter].complete(root) - def doComplete(root: SymDenotation)(implicit ctx: Context): Unit = + def doComplete(root: SymDenotation)(using Context): Unit = unsupported("doComplete") } diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index 721cdf5543a5..a2d739445df8 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -701,13 +701,13 @@ object Symbols { } // ParamInfo types and methods - def isTypeParam(implicit ctx: Context): Boolean = denot.is(TypeParam) - def paramName(implicit ctx: Context): ThisName = name.asInstanceOf[ThisName] - def paramInfo(implicit ctx: Context): Type = denot.info - def paramInfoAsSeenFrom(pre: Type)(implicit ctx: Context): Type = pre.memberInfo(this) - def paramInfoOrCompleter(implicit ctx: Context): Type = denot.infoOrCompleter - def paramVariance(implicit ctx: Context): Variance = denot.variance - def paramRef(implicit ctx: Context): TypeRef = denot.typeRef + 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 -------------------------------------------------------- diff --git a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala index 657d3fb7250d..23cfd3edbc69 100644 --- a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala +++ b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala @@ -107,7 +107,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( ctx.error("Cannot have a quote in an annotation", quote.sourcePos) val contextWithQuote = - if level == 0 then contextWithQuoteTypeTags(taggedTypes)(quoteContext) + if level == 0 then contextWithQuoteTypeTags(taggedTypes)(using quoteContext) else quoteContext val body1 = transform(body)(contextWithQuote) val body2 = diff --git a/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala b/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala index 4c4b2f480273..f2300b03441e 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala @@ -18,7 +18,7 @@ class SetDefTree extends MiniPhase { override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { val ctx2 = ctx.fresh.setSetting(ctx.settings.YretainTrees, true) - super.runOn(units)(ctx2) + super.runOn(units)(using ctx2) } override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = tree.setDefTree From 50144f492ba7683b849dd9cb614449d3d3c1360b Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 14:56:36 +0200 Subject: [PATCH 13/41] Convert core classes (5) --- .../src/dotty/tools/dotc/core/Contexts.scala | 2 +- .../tools/dotc/core/TypeApplications.scala | 58 ++++++++--------- .../dotty/tools/dotc/core/TypeComparer.scala | 24 +++---- .../dotty/tools/dotc/core/TypeErasure.scala | 62 +++++++++---------- .../dotty/tools/dotc/core/TypeErrors.scala | 18 +++--- .../src/dotty/tools/dotc/core/TypeOps.scala | 10 +-- .../dotty/tools/dotc/core/TyperState.scala | 10 +-- .../src/dotty/tools/dotc/core/Types.scala | 2 +- 8 files changed, 93 insertions(+), 93 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 4e9e92393eeb..4d3b5e6b52d2 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -326,7 +326,7 @@ object Contexts { /** 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)(this) + 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 = diff --git a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala index 597a8e76ff03..d8d195781482 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeApplications.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeApplications.scala @@ -34,12 +34,12 @@ object TypeApplications { * @param tycon C */ object EtaExpansion { - def apply(tycon: Type)(implicit ctx: Context): Type = { + def apply(tycon: Type)(using Context): Type = { assert(tycon.typeParams.nonEmpty, tycon) tycon.EtaExpand(tycon.typeParamSymbols) } - def unapply(tp: Type)(implicit ctx: Context): Option[TypeRef] = tp match { + def unapply(tp: Type)(using Context): Option[TypeRef] = tp match { case tp @ HKTypeLambda(tparams, AppliedType(fn: TypeRef, args)) if (args == tparams.map(_.paramRef)) => Some(fn) case _ => None } @@ -47,7 +47,7 @@ object TypeApplications { /** Adapt all arguments to possible higher-kinded type parameters using etaExpandIfHK */ - def EtaExpandIfHK(tparams: List[TypeParamInfo], args: List[Type])(implicit ctx: Context): List[Type] = + def EtaExpandIfHK(tparams: List[TypeParamInfo], args: List[Type])(using Context): List[Type] = if (tparams.isEmpty) args else args.zipWithConserve(tparams)((arg, tparam) => arg.EtaExpandIfHK(tparam.paramInfoOrCompleter)) @@ -86,7 +86,7 @@ object TypeApplications { * result type. Using this mode, we can guarantee that `appliedTo` will never * produce a higher-kinded application with a type lambda as type constructor. */ - class Reducer(tycon: TypeLambda, args: List[Type])(implicit ctx: Context) extends TypeMap { + class Reducer(tycon: TypeLambda, args: List[Type])(using Context) extends TypeMap { private var available = (0 until args.length).toSet var allReplaced: Boolean = true def hasWildcardArg(p: TypeParamRef): Boolean = @@ -143,7 +143,7 @@ class TypeApplications(val self: Type) extends AnyVal { * For a refinement type, the type parameters of its parent, dropping * any type parameter that is-rebound by the refinement. */ - final def typeParams(implicit ctx: Context): List[TypeParamInfo] = { + final def typeParams(using Context): List[TypeParamInfo] = { record("typeParams") def isTrivial(prefix: Type, tycon: Symbol) = prefix match { case prefix: ThisType => @@ -184,11 +184,11 @@ class TypeApplications(val self: Type) extends AnyVal { } /** If `self` is a higher-kinded type, its type parameters, otherwise Nil */ - final def hkTypeParams(implicit ctx: Context): List[TypeParamInfo] = + final def hkTypeParams(using Context): List[TypeParamInfo] = if (isLambdaSub) typeParams else Nil /** If `self` is a generic class, its type parameter symbols, otherwise Nil */ - final def typeParamSymbols(implicit ctx: Context): List[TypeSymbol] = typeParams match { + final def typeParamSymbols(using Context): List[TypeSymbol] = typeParams match { case (_: Symbol) :: _ => assert(typeParams.forall(_.isInstanceOf[Symbol])) typeParams.asInstanceOf[List[TypeSymbol]] @@ -196,10 +196,10 @@ class TypeApplications(val self: Type) extends AnyVal { } /** Is self type bounded by a type lambda or AnyKind? */ - def isLambdaSub(implicit ctx: Context): Boolean = hkResult.exists + def isLambdaSub(using Context): Boolean = hkResult.exists /** Is self type of kind "*"? */ - def hasSimpleKind(implicit ctx: Context): Boolean = + def hasSimpleKind(using Context): Boolean = typeParams.isEmpty && !self.hasAnyKind || { val alias = self.dealias (alias ne self) && alias.hasSimpleKind @@ -208,7 +208,7 @@ class TypeApplications(val self: Type) extends AnyVal { /** If self type is higher-kinded, its result type, otherwise NoType. * Note: The hkResult of an any-kinded type is again AnyKind. */ - def hkResult(implicit ctx: Context): Type = self.dealias match { + def hkResult(using Context): Type = self.dealias match { case self: TypeRef => if (self.symbol == defn.AnyKindClass) self else self.info.hkResult case self: AppliedType => @@ -227,7 +227,7 @@ class TypeApplications(val self: Type) extends AnyVal { /** Do self and other have the same kinds (not counting bounds and variances)? * Note: An any-kinded type "has the same kind" as any other type. */ - def hasSameKindAs(other: Type)(implicit ctx: Context): Boolean = { + def hasSameKindAs(other: Type)(using Context): Boolean = { def isAnyKind(tp: Type) = tp match { case tp: TypeRef => tp.symbol == defn.AnyKindClass case _ => false @@ -245,7 +245,7 @@ class TypeApplications(val self: Type) extends AnyVal { } /** Dealias type if it can be done without forcing the TypeRef's info */ - def safeDealias(implicit ctx: Context): Type = self match { + def safeDealias(using Context): Type = self match { case self: TypeRef if self.denot.exists && self.symbol.isAliasType => self.superType.stripTypeVar.safeDealias case _ => @@ -255,16 +255,16 @@ class TypeApplications(val self: Type) extends AnyVal { /** Convert a type constructor `TC` which has type parameters `X1, ..., Xn` * to `[X1, ..., Xn] -> TC[X1, ..., Xn]`. */ - def EtaExpand(tparams: List[TypeParamInfo])(implicit ctx: Context): Type = + def EtaExpand(tparams: List[TypeParamInfo])(using Context): Type = HKTypeLambda.fromParams(tparams, self.appliedTo(tparams.map(_.paramRef))) //.ensuring(res => res.EtaReduce =:= self, s"res = $res, core = ${res.EtaReduce}, self = $self, hc = ${res.hashCode}") /** If self is not lambda-bound, eta expand it. */ - def ensureLambdaSub(implicit ctx: Context): Type = + def ensureLambdaSub(using Context): Type = if (isLambdaSub) self else EtaExpansion(self) /** Eta expand if `self` is a (non-lambda) class reference and `bound` is a higher-kinded type */ - def EtaExpandIfHK(bound: Type)(implicit ctx: Context): Type = { + def EtaExpandIfHK(bound: Type)(using Context): Type = { val hkParams = bound.hkTypeParams if (hkParams.isEmpty) self else self match { @@ -282,7 +282,7 @@ class TypeApplications(val self: Type) extends AnyVal { * @param self = `T` * @param args = `U1,...,Un` */ - final def appliedTo(args: List[Type])(implicit ctx: Context): Type = { + final def appliedTo(args: List[Type])(using Context): Type = { record("appliedTo") val typParams = self.typeParams val stripped = self.stripTypeVar @@ -347,10 +347,10 @@ class TypeApplications(val self: Type) extends AnyVal { } } - final def appliedTo(arg: Type)(implicit ctx: Context): Type = appliedTo(arg :: Nil) - final def appliedTo(arg1: Type, arg2: Type)(implicit ctx: Context): Type = appliedTo(arg1 :: arg2 :: Nil) + final def appliedTo(arg: Type)(using Context): Type = appliedTo(arg :: Nil) + final def appliedTo(arg1: Type, arg2: Type)(using Context): Type = appliedTo(arg1 :: arg2 :: Nil) - final def applyIfParameterized(args: List[Type])(implicit ctx: Context): Type = + final def applyIfParameterized(args: List[Type])(using Context): Type = if (typeParams.nonEmpty) appliedTo(args) else self /** A cycle-safe version of `appliedTo` where computing type parameters do not force @@ -358,7 +358,7 @@ class TypeApplications(val self: Type) extends AnyVal { * up hk type parameters matching the arguments. This is needed when unpickling * Scala2 files such as `scala.collection.generic.Mapfactory`. */ - final def safeAppliedTo(args: List[Type])(implicit ctx: Context): Type = self match { + final def safeAppliedTo(args: List[Type])(using Context): Type = self match { case self: TypeRef if !self.symbol.isClass && self.symbol.isCompleting => AppliedType(self, args) case _ => @@ -369,7 +369,7 @@ class TypeApplications(val self: Type) extends AnyVal { * A (possible lambda abstracted) match type is turned into a match alias. * Every other type is turned into a type alias */ - final def toBounds(implicit ctx: Context): TypeBounds = self match { + final def toBounds(using Context): TypeBounds = self match { case self: TypeBounds => self // this can happen for wildcard args case _ => if (self.isMatch) MatchAlias(self) else TypeAlias(self) } @@ -378,7 +378,7 @@ class TypeApplications(val self: Type) extends AnyVal { * `from` and `to` must be static classes, both with one type parameter, and the same variance. * Do the same for by name types => From[T] and => To[T] */ - def translateParameterized(from: ClassSymbol, to: ClassSymbol, wildcardArg: Boolean = false)(implicit ctx: Context): Type = self match { + def translateParameterized(from: ClassSymbol, to: ClassSymbol, wildcardArg: Boolean = false)(using Context): Type = self match { case self @ ExprType(tp) => self.derivedExprType(tp.translateParameterized(from, to)) case _ => @@ -439,37 +439,37 @@ class TypeApplications(val self: Type) extends AnyVal { * otherwise return Nil. * Existential types in arguments are returned as TypeBounds instances. */ - final def argInfos(implicit ctx: Context): List[Type] = self.stripTypeVar.stripAnnots match { + final def argInfos(using Context): List[Type] = self.stripTypeVar.stripAnnots match { case AppliedType(tycon, args) => args case _ => Nil } /** Argument types where existential types in arguments are disallowed */ - def argTypes(implicit ctx: Context): List[Type] = argInfos mapConserve noBounds + def argTypes(using Context): List[Type] = argInfos mapConserve noBounds /** Argument types where existential types in arguments are approximated by their lower bound */ - def argTypesLo(implicit ctx: Context): List[Type] = argInfos.mapConserve(_.loBound) + def argTypesLo(using Context): List[Type] = argInfos.mapConserve(_.loBound) /** Argument types where existential types in arguments are approximated by their upper bound */ - def argTypesHi(implicit ctx: Context): List[Type] = argInfos.mapConserve(_.hiBound) + def argTypesHi(using Context): List[Type] = argInfos.mapConserve(_.hiBound) /** If this is the image of a type argument; recover the type argument, * otherwise NoType. */ - final def argInfo(implicit ctx: Context): Type = self match { + final def argInfo(using Context): Type = self match { case self: TypeAlias => self.alias case self: TypeBounds => self case _ => NoType } /** If this is a type alias, its underlying type, otherwise the type itself */ - def dropAlias(implicit ctx: Context): Type = self match { + def dropAlias(using Context): Type = self match { case TypeAlias(alias) => alias case _ => self } /** The element type of a sequence or array */ - def elemType(implicit ctx: Context): Type = self.widenDealias match { + def elemType(using Context): Type = self.widenDealias match { case defn.ArrayOf(elemtp) => elemtp case JavaArrayType(elemtp) => elemtp case _ => self.baseType(defn.SeqClass).argInfos.headOption.getOrElse(NoType) diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index f0eec95d4c71..ed241bac56af 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -119,11 +119,11 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w true } - protected def gadtBounds(sym: Symbol)(implicit ctx: Context) = ctx.gadt.bounds(sym) + protected def gadtBounds(sym: Symbol)(using Context) = ctx.gadt.bounds(sym) protected def gadtAddLowerBound(sym: Symbol, b: Type): Boolean = ctx.gadt.addBound(sym, b, isUpper = false) protected def gadtAddUpperBound(sym: Symbol, b: Type): Boolean = ctx.gadt.addBound(sym, b, isUpper = true) - protected def typeVarInstance(tvar: TypeVar)(implicit ctx: Context): Type = tvar.underlying + protected def typeVarInstance(tvar: TypeVar)(using Context): Type = tvar.underlying // Subtype testing `<:<` @@ -1860,7 +1860,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w /** The greatest lower bound of a list types */ final def glb(tps: List[Type]): Type = tps.foldLeft(AnyType: Type)(glb) - def widenInUnions(implicit ctx: Context): Boolean = + def widenInUnions(using Context): Boolean = migrateTo3 || ctx.erasedTypes /** The least upper bound of two types @@ -2175,7 +2175,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } /** Show type, handling type types better than the default */ - private def showType(tp: Type)(implicit ctx: Context) = tp match { + private def showType(tp: Type)(using Context) = tp match { case ClassInfo(_, cls, _, _, _) => cls.showLocated case bounds: TypeBounds => "type bounds" + bounds.show case _ => tp.show @@ -2231,7 +2231,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } /** Show subtype goal that led to an assertion failure */ - def showGoal(tp1: Type, tp2: Type)(implicit ctx: Context): Unit = { + def showGoal(tp1: Type, tp2: Type)(using Context): Unit = { ctx.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}") @@ -2310,7 +2310,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w * property that in all possible contexts, the same match type expression * is either stuck or reduces to the same case. */ - def provablyDisjoint(tp1: Type, tp2: Type)(implicit ctx: Context): Boolean = { + def provablyDisjoint(tp1: Type, tp2: Type)(using Context): Boolean = { // println(s"provablyDisjoint(${tp1.show}, ${tp2.show})") /** Can we enumerate all instantiations of this type? */ def isClosedSum(tp: Symbol): Boolean = @@ -2432,7 +2432,7 @@ object TypeComparer { var tpe: Type = NoType } - private[core] def show(res: Any)(implicit ctx: Context): String = res match { + private[core] def show(res: Any)(using Context): String = res match { case res: printing.Showable if !ctx.settings.YexplainLowlevel.value => res.show case _ => String.valueOf(res) } @@ -2467,14 +2467,14 @@ object TypeComparer { val FreshApprox: ApproxState = new ApproxState(4) /** Show trace of comparison operations when performing `op` */ - def explaining[T](say: String => Unit)(op: Context ?=> T)(implicit ctx: Context): T = { + def explaining[T](say: String => Unit)(op: Context ?=> T)(using Context): T = { val nestedCtx = ctx.fresh.setTypeComparerFn(new ExplainingTypeComparer(_)) val res = try { op(using nestedCtx) } finally { say(nestedCtx.typeComparer.lastTrace()) } res } /** Like [[explaining]], but returns the trace instead */ - def explained[T](op: Context ?=> T)(implicit ctx: Context): String = { + def explained[T](op: Context ?=> T)(using Context): String = { var trace: String = null try { explaining(trace = _)(op) } catch { case ex: Throwable => ex.printStackTrace } trace @@ -2496,7 +2496,7 @@ class TrackingTypeComparer(initctx: Context) extends TypeComparer(initctx) { super.addOneBound(param, bound, isUpper) } - override def gadtBounds(sym: Symbol)(implicit ctx: Context): TypeBounds = { + override def gadtBounds(sym: Symbol)(using Context): TypeBounds = { if (sym.exists) footprint += sym.typeRef super.gadtBounds(sym) } @@ -2511,12 +2511,12 @@ class TrackingTypeComparer(initctx: Context) extends TypeComparer(initctx) { super.gadtAddUpperBound(sym, b) } - override def typeVarInstance(tvar: TypeVar)(implicit ctx: Context): Type = { + override def typeVarInstance(tvar: TypeVar)(using Context): Type = { footprint += tvar super.typeVarInstance(tvar) } - def matchCases(scrut: Type, cases: List[Type])(implicit ctx: Context): Type = { + def matchCases(scrut: Type, cases: List[Type])(using Context): Type = { def paramInstances = new TypeAccumulator[Array[Type]] { def apply(inst: Array[Type], t: Type) = t match { case t @ TypeParamRef(b, n) if b `eq` caseLambda => diff --git a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala index 41b0ff272759..c10111c6f6ad 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala @@ -35,10 +35,10 @@ import scala.annotation.tailrec */ object TypeErasure { - private def erasureDependsOnArgs(sym: Symbol)(implicit ctx: Context) = + private def erasureDependsOnArgs(sym: Symbol)(using Context) = sym == defn.ArrayClass || sym == defn.PairClass - def normalizeClass(cls: ClassSymbol)(implicit ctx: Context): ClassSymbol = { + def normalizeClass(cls: ClassSymbol)(using Context): ClassSymbol = { if (cls.owner == defn.ScalaPackageClass) { if (defn.specialErasure.contains(cls)) return defn.specialErasure(cls) @@ -53,7 +53,7 @@ object TypeErasure { * ErasedValueType is considered an erased type because it is valid after Erasure (it is * eliminated by ElimErasedValueType). */ - def isErasedType(tp: Type)(implicit ctx: Context): Boolean = tp match { + def isErasedType(tp: Type)(using Context): Boolean = tp match { case _: ErasedValueType => true case tp: TypeRef => @@ -101,7 +101,7 @@ object TypeErasure { extends ErasedValueType(tycon, erasedUnderlying) object ErasedValueType { - def apply(tycon: TypeRef, erasedUnderlying: Type)(implicit ctx: Context): ErasedValueType = { + def apply(tycon: TypeRef, erasedUnderlying: Type)(using Context): ErasedValueType = { assert(erasedUnderlying.exists) unique(new CachedErasedValueType(tycon, erasedUnderlying)) } @@ -131,40 +131,40 @@ object TypeErasure { erasures(erasureIdx(isJava, semiEraseVCs, isConstructor, wildcardOK)) /** The current context with a phase no later than erasure */ - def preErasureCtx(implicit ctx: Context) = + def preErasureCtx(using Context) = if (ctx.erasedTypes) ctx.withPhase(ctx.erasurePhase) else ctx /** The standard erasure of a Scala type. Value classes are erased as normal classes. * * @param tp The type to erase. */ - def erasure(tp: Type)(implicit ctx: Context): Type = - erasureFn(isJava = false, semiEraseVCs = false, isConstructor = false, wildcardOK = false)(tp)(preErasureCtx) + def erasure(tp: Type)(using Context): Type = + erasureFn(isJava = false, semiEraseVCs = false, isConstructor = false, wildcardOK = false)(tp)(using preErasureCtx) /** The value class erasure of a Scala type, where value classes are semi-erased to * ErasedValueType (they will be fully erased in [[ElimErasedValueType]]). * * @param tp The type to erase. */ - def valueErasure(tp: Type)(implicit ctx: Context): Type = - erasureFn(isJava = false, semiEraseVCs = true, isConstructor = false, wildcardOK = false)(tp)(preErasureCtx) + def valueErasure(tp: Type)(using Context): Type = + erasureFn(isJava = false, semiEraseVCs = true, isConstructor = false, wildcardOK = false)(tp)(using preErasureCtx) /** Like value class erasure, but value classes erase to their underlying type erasure */ - def fullErasure(tp: Type)(implicit ctx: Context): Type = + def fullErasure(tp: Type)(using Context): Type = valueErasure(tp) match case ErasedValueType(_, underlying) => erasure(underlying) case etp => etp - def sigName(tp: Type, isJava: Boolean)(implicit ctx: Context): TypeName = { + def sigName(tp: Type, isJava: Boolean)(using Context): TypeName = { val normTp = tp.translateFromRepeated(toArray = isJava) val erase = erasureFn(isJava, semiEraseVCs = false, isConstructor = false, wildcardOK = true) - erase.sigName(normTp)(preErasureCtx) + erase.sigName(normTp)(using preErasureCtx) } /** The erasure of a top-level reference. Differs from normal erasure in that * TermRefs are kept instead of being widened away. */ - def erasedRef(tp: Type)(implicit ctx: Context): Type = tp match { + def erasedRef(tp: Type)(using Context): Type = tp match { case tp: TermRef => assert(tp.symbol.exists, tp) val tp1 = makePackageObjPrefixExplicit(tp) @@ -186,7 +186,7 @@ object TypeErasure { * - For all other symbols : the semi-erasure of their types, with * isJava, isConstructor set according to symbol. */ - def transformInfo(sym: Symbol, tp: Type)(implicit ctx: Context): Type = { + def transformInfo(sym: Symbol, tp: Type)(using Context): Type = { val isJava = sym is JavaDefined val semiEraseVCs = !isJava val erase = erasureFn(isJava, semiEraseVCs, sym.isConstructor, wildcardOK = false) @@ -197,9 +197,9 @@ object TypeErasure { if (defn.isPolymorphicAfterErasure(sym)) eraseParamBounds(sym.info.asInstanceOf[PolyType]) else if (sym.isAbstractType) TypeAlias(WildcardType) - else if (sym.isConstructor) outer.addParam(sym.owner.asClass, erase(tp)(preErasureCtx)) - else if (sym.is(Label)) erase.eraseResult(sym.info)(preErasureCtx) - else erase.eraseInfo(tp, sym)(preErasureCtx) match { + else if (sym.isConstructor) outer.addParam(sym.owner.asClass, erase(tp)(using preErasureCtx)) + else if (sym.is(Label)) erase.eraseResult(sym.info)(using preErasureCtx) + else erase.eraseInfo(tp, sym)(using preErasureCtx) match { case einfo: MethodType => if (sym.isGetter && einfo.resultType.isRef(defn.UnitClass)) MethodType(Nil, defn.BoxedUnitClass.typeRef) @@ -231,7 +231,7 @@ object TypeErasure { /** Underlying type that does not contain aliases or abstract types * at top-level, treating opaque aliases as transparent. */ - def classify(tp: Type)(implicit ctx: Context): Type = + def classify(tp: Type)(using Context): Type = if (tp.typeSymbol.isClass) tp else tp match { case tp: TypeProxy => classify(tp.translucentSuperType) @@ -243,7 +243,7 @@ object TypeErasure { * or a universal trait as upper bound and that is not Java defined? Arrays of such types are * erased to `Object` instead of `Object[]`. */ - def isUnboundedGeneric(tp: Type)(implicit ctx: Context): Boolean = tp.dealias match { + def isUnboundedGeneric(tp: Type)(using Context): Boolean = tp.dealias match { case tp: TypeRef if !tp.symbol.isOpaqueAlias => !tp.symbol.isClass && !classify(tp).derivesFrom(defn.ObjectClass) && @@ -263,7 +263,7 @@ object TypeErasure { } /** Is `tp` an abstract type or polymorphic type parameter, or another unbounded generic type? */ - def isGeneric(tp: Type)(implicit ctx: Context): Boolean = tp.dealias match { + def isGeneric(tp: Type)(using Context): Boolean = tp.dealias match { case tp: TypeRef if !tp.symbol.isOpaqueAlias => !tp.symbol.isClass case tp: TypeParamRef => true case tp: TypeProxy => isGeneric(tp.translucentSuperType) @@ -286,7 +286,7 @@ object TypeErasure { * The reason to pick last is that we prefer classes over traits that way, * which leads to more predictable bytecode and (?) faster dynamic dispatch. */ - def erasedLub(tp1: Type, tp2: Type)(implicit ctx: Context): Type = { + def erasedLub(tp1: Type, tp2: Type)(using Context): Type = { // After erasure, C | {Null, Nothing} is just C, if C is a reference type. // We need to short-circuit this case here because the regular lub logic below // relies on the class hierarchy, which doesn't properly capture `Null`s subtyping @@ -350,7 +350,7 @@ object TypeErasure { * - subtypes over supertypes, unless isJava is set * - real classes over traits */ - def erasedGlb(tp1: Type, tp2: Type, isJava: Boolean)(implicit ctx: Context): Type = tp1 match { + def erasedGlb(tp1: Type, tp2: Type, isJava: Boolean)(using Context): Type = tp1 match { case JavaArrayType(elem1) => tp2 match { case JavaArrayType(elem2) => JavaArrayType(erasedGlb(elem1, elem2, isJava)) @@ -375,7 +375,7 @@ object TypeErasure { /** Does the (possibly generic) type `tp` have the same erasure in all its * possible instantiations? */ - def hasStableErasure(tp: Type)(implicit ctx: Context): Boolean = tp match { + def hasStableErasure(tp: Type)(using Context): Boolean = tp match { case tp: TypeRef if !tp.symbol.isOpaqueAlias => tp.info match { case TypeAlias(alias) => hasStableErasure(alias) @@ -436,7 +436,7 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean * - For NoType or NoPrefix, the type itself. * - For any other type, exception. */ - private def apply(tp: Type)(implicit ctx: Context): Type = tp match { + private def apply(tp: Type)(using Context): Type = tp match { case _: ErasedValueType => tp case tp: TypeRef => @@ -511,14 +511,14 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean tp } - private def eraseArray(tp: Type)(implicit ctx: Context) = { + private def eraseArray(tp: Type)(using Context) = { val defn.ArrayOf(elemtp) = tp if (classify(elemtp).derivesFrom(defn.NullClass)) JavaArrayType(defn.ObjectType) else if (isUnboundedGeneric(elemtp) && !isJava) defn.ObjectType else JavaArrayType(erasureFn(isJava, semiEraseVCs = false, isConstructor, wildcardOK)(elemtp)) } - private def erasePair(tp: Type)(implicit ctx: Context): Type = { + private def erasePair(tp: Type)(using Context): Type = { val arity = tp.tupleArity if (arity < 0) defn.ProductClass.typeRef else if (arity <= Definitions.MaxTupleArity) defn.TupleType(arity) @@ -529,7 +529,7 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean * `PolyType`s are treated. `eraseInfo` maps them them to method types, whereas `apply` maps them * to the underlying type. */ - def eraseInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = + def eraseInfo(tp: Type, sym: Symbol)(using Context): Type = val tp1 = tp match case tp: MethodicType => integrateContextResults(tp, contextResultCount(sym)) case _ => tp @@ -549,7 +549,7 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean case rt => MethodType(Nil, Nil, rt) case tp1 => this(tp1) - private def eraseDerivedValueClassRef(tref: TypeRef)(implicit ctx: Context): Type = { + private def eraseDerivedValueClassRef(tref: TypeRef)(using Context): Type = { val cls = tref.symbol.asClass val underlying = underlyingOfValueClass(cls) if underlying.exists && !isCyclic(cls) then @@ -561,13 +561,13 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean else NoType } - private def eraseNormalClassRef(tref: TypeRef)(implicit ctx: Context): Type = { + private def eraseNormalClassRef(tref: TypeRef)(using Context): Type = { val cls = tref.symbol.asClass (if (cls.owner.is(Package)) normalizeClass(cls) else cls).typeRef } /** The erasure of a function result type. */ - private def eraseResult(tp: Type)(implicit ctx: Context): Type = tp match { + private def eraseResult(tp: Type)(using Context): Type = tp match { case tp: TypeRef => val sym = tp.typeSymbol if (sym eq defn.UnitClass) sym.typeRef @@ -587,7 +587,7 @@ class TypeErasure(isJava: Boolean, semiEraseVCs: Boolean, isConstructor: Boolean /** The name of the type as it is used in `Signature`s. * Need to ensure correspondence with erasure! */ - private def sigName(tp: Type)(implicit ctx: Context): TypeName = try + private def sigName(tp: Type)(using Context): TypeName = try tp match { case tp: TypeRef => if (!tp.denot.exists) diff --git a/compiler/src/dotty/tools/dotc/core/TypeErrors.scala b/compiler/src/dotty/tools/dotc/core/TypeErrors.scala index 24db641b7fca..60548db38006 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeErrors.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeErrors.scala @@ -17,25 +17,25 @@ import config.Printers.cyclicErrors class TypeError(msg: String) extends Exception(msg) { def this() = this("") - final def toMessage(implicit ctx: Context): Message = + final def toMessage(using Context): Message = produceMessage(using ctx.addMode(Mode.Printing)) def produceMessage(using Context): Message = super.getMessage override def getMessage: String = super.getMessage } class MalformedType(pre: Type, denot: Denotation, absMembers: Set[Name]) extends TypeError { - override def produceMessage(implicit ctx: Context): Message = + override def produceMessage(using Context): Message = i"malformed type: $pre is not a legal prefix for $denot because it contains abstract type member${if (absMembers.size == 1) "" else "s"} ${absMembers.mkString(", ")}" } class MissingType(pre: Type, name: Name) extends TypeError { - private def otherReason(pre: Type)(implicit ctx: Context): String = pre match { + private def otherReason(pre: Type)(using Context): String = pre match { case pre: ThisType if pre.cls.givenSelfType.exists => i"\nor the self type of $pre might not contain all transitive dependencies" case _ => "" } - override def produceMessage(implicit ctx: Context): Message = { + override def produceMessage(using Context): Message = { if (ctx.debug) printStackTrace() i"""cannot resolve reference to type $pre.$name |the classfile defining the type might be missing from the classpath${otherReason(pre)}""" @@ -59,7 +59,7 @@ class RecursionOverflow(val op: String, details: => String, val previous: Throwa loop(this) } - def opsString(rs: List[RecursionOverflow])(implicit ctx: Context): String = { + def opsString(rs: List[RecursionOverflow])(using Context): String = { val maxShown = 20 if (rs.lengthCompare(maxShown) > 0) i"""${opsString(rs.take(maxShown / 2))} @@ -69,7 +69,7 @@ class RecursionOverflow(val op: String, details: => String, val previous: Throwa (rs.map(_.explanation): List[String]).mkString("\n ", "\n| ", "") } - override def produceMessage(implicit ctx: Context): Message = NoExplanation { + override def produceMessage(using Context): Message = NoExplanation { val mostCommon = recursions.groupBy(_.op).toList.maxBy(_._2.map(_.weight).sum)._2.reverse s"""Recursion limit exceeded. |Maybe there is an illegal cyclic reference? @@ -88,7 +88,7 @@ class RecursionOverflow(val op: String, details: => String, val previous: Throwa // Beware: Since this object is only used when handling a StackOverflow, this code // cannot consume significant amounts of stack. object handleRecursive { - def apply(op: String, details: => String, exc: Throwable, weight: Int = 1)(implicit ctx: Context): Nothing = + def apply(op: String, details: => String, exc: Throwable, weight: Int = 1)(using Context): Nothing = if (ctx.settings.YnoDecodeStacktraces.value) throw exc else @@ -111,7 +111,7 @@ object handleRecursive { class CyclicReference private (val denot: SymDenotation) extends TypeError { var inImplicitSearch: Boolean = false - override def produceMessage(implicit ctx: Context): Message = { + override def produceMessage(using Context): Message = { val cycleSym = denot.symbol // cycleSym.flags would try completing denot and would fail, but here we can use flagsUNSAFE to detect flags @@ -152,7 +152,7 @@ class CyclicReference private (val denot: SymDenotation) extends TypeError { } object CyclicReference { - def apply(denot: SymDenotation)(implicit ctx: Context): CyclicReference = { + def apply(denot: SymDenotation)(using Context): CyclicReference = { val ex = new CyclicReference(denot) if (!(ctx.mode is Mode.CheckCyclic) || ctx.settings.Ydebug.value) { cyclicErrors.println(s"Cyclic reference involving! $denot") diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index 8a497dde349e..a0bbbed19527 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -580,11 +580,11 @@ object TypeOps: val hiBound = instantiate(bounds.hi, skolemizedArgTypes) val loBound = instantiate(bounds.lo, skolemizedArgTypes) - def check(implicit ctx: Context) = { + def check(using Context) = { if (!(lo <:< hiBound)) violations += ((arg, "upper", hiBound)) if (!(loBound <:< hi)) violations += ((arg, "lower", loBound)) } - check(checkCtx) + check(using checkCtx) } arg.tpe match { case TypeBounds(lo, hi) => checkOverlapsBounds(lo, hi) @@ -643,7 +643,7 @@ object TypeOps: */ private def instantiateToSubType(tp1: NamedType, tp2: Type)(using Context): Type = { /** expose abstract type references to their bounds or tvars according to variance */ - class AbstractTypeMap(maximize: Boolean)(implicit ctx: Context) extends TypeMap { + class AbstractTypeMap(maximize: Boolean)(using Context) extends TypeMap { def expose(lo: Type, hi: Type): Type = if (variance == 0) newTypeVar(TypeBounds(lo, hi)) @@ -677,8 +677,8 @@ object TypeOps: } } - def minTypeMap(implicit ctx: Context) = new AbstractTypeMap(maximize = false) - def maxTypeMap(implicit ctx: Context) = new AbstractTypeMap(maximize = true) + def minTypeMap(using Context) = new AbstractTypeMap(maximize = false) + def maxTypeMap(using Context) = new AbstractTypeMap(maximize = true) // Prefix inference, replace `p.C.this.Child` with `X.Child` where `X <: p.C` // Note: we need to strip ThisType in `p` recursively. diff --git a/compiler/src/dotty/tools/dotc/core/TyperState.scala b/compiler/src/dotty/tools/dotc/core/TyperState.scala index 64c72c7bc539..aace096fb776 100644 --- a/compiler/src/dotty/tools/dotc/core/TyperState.scala +++ b/compiler/src/dotty/tools/dotc/core/TyperState.scala @@ -39,7 +39,7 @@ class TyperState(private val previous: TyperState /* | Null */) { else previous.constraint def constraint: Constraint = myConstraint - def constraint_=(c: Constraint)(implicit ctx: Context): Unit = { + def constraint_=(c: Constraint)(using Context): Unit = { if (Config.debugCheckConstraintsClosed && isGlobalCommittable) c.checkClosed() myConstraint = c } @@ -96,7 +96,7 @@ class TyperState(private val previous: TyperState /* | Null */) { * typerstate. If it is unshared, run `op` in current typerState, restoring typerState * to previous state afterwards. */ - def test[T](op: Context ?=> T)(implicit ctx: Context): T = + def test[T](op: Context ?=> T)(using Context): T = if (isShared) op(using ctx.fresh.setExploreTyperState()) else { @@ -141,7 +141,7 @@ class TyperState(private val previous: TyperState /* | Null */) { * isApplicableSafe but also for (e.g. erased-lubs.scala) as well as * many parts of dotty itself. */ - def commit()(implicit ctx: Context): Unit = { + def commit()(using Context): Unit = { Stats.record("typerState.commit") val targetState = ctx.typerState if (constraint ne targetState.constraint) @@ -158,14 +158,14 @@ class TyperState(private val previous: TyperState /* | Null */) { isCommitted = true } - def mergeConstraintWith(that: TyperState)(implicit ctx: Context): Unit = + def mergeConstraintWith(that: TyperState)(using Context): Unit = constraint = constraint & (that.constraint, otherHasErrors = that.reporter.errorsReported) /** Make type variable instances permanent by assigning to `inst` field if * type variable instantiation cannot be retracted anymore. Then, remove * no-longer needed constraint entries. */ - def gc()(implicit ctx: Context): Unit = { + def gc()(using Context): Unit = { val toCollect = new mutable.ListBuffer[TypeLambda] constraint foreachTypeVar { tvar => if (!tvar.inst.exists) { diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index 270a6c47cac8..2075974c1617 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -4314,7 +4314,7 @@ object Types { myReduced = trace(i"reduce match type $this $hashCode", typr, show = true) { try - typeComparer.matchCases(scrutinee.normalized, cases)(trackingCtx) + typeComparer.matchCases(scrutinee.normalized, cases)(using trackingCtx) catch { case ex: Throwable => handleRecursive("reduce type ", i"$scrutinee match ...", ex) From adc75a0fb104b3955f4f12fc5df2f72f8442ff94 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 15:00:34 +0200 Subject: [PATCH 14/41] Convert core classes (6) --- .../src/dotty/tools/dotc/core/Uniques.scala | 4 +- .../src/dotty/tools/dotc/core/Variances.scala | 22 +++---- .../dotc/core/classfile/ClassfileParser.scala | 58 +++++++++---------- .../dotc/core/quoted/PickledQuotes.scala | 26 ++++----- .../dotty/tools/dottydoc/DottyDocTest.scala | 2 +- .../dotty/tools/dottydoc/MarkdownTests.scala | 2 +- 6 files changed, 57 insertions(+), 57 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/Uniques.scala b/compiler/src/dotty/tools/dotc/core/Uniques.scala index 9f22ab35f153..d02a728bb81c 100644 --- a/compiler/src/dotty/tools/dotc/core/Uniques.scala +++ b/compiler/src/dotty/tools/dotc/core/Uniques.scala @@ -24,7 +24,7 @@ object Uniques { record(s"cached: $clazz") } - def unique[T <: Type](tp: T)(implicit ctx: Context): T = { + def unique[T <: Type](tp: T)(using Context): T = { if (monitored) recordCaching(tp) if (tp.hash == NotCached) tp else if (monitored) { @@ -56,7 +56,7 @@ object Uniques { e } - def enterIfNew(prefix: Type, designator: Designator, isTerm: Boolean)(implicit ctx: Context): NamedType = { + def enterIfNew(prefix: Type, designator: Designator, isTerm: Boolean)(using Context): NamedType = { val h = doHash(null, designator, prefix) if (monitored) recordCaching(h, classOf[NamedType]) def newType = diff --git a/compiler/src/dotty/tools/dotc/core/Variances.scala b/compiler/src/dotty/tools/dotc/core/Variances.scala index a849152ae71b..122c7a10e4b7 100644 --- a/compiler/src/dotty/tools/dotc/core/Variances.scala +++ b/compiler/src/dotty/tools/dotc/core/Variances.scala @@ -37,22 +37,22 @@ object Variances { else cut(v) /** Compute variance of type parameter `tparam` in types of all symbols `sym`. */ - def varianceInSyms(syms: List[Symbol])(tparam: Symbol)(implicit ctx: Context): Variance = + def varianceInSyms(syms: List[Symbol])(tparam: Symbol)(using Context): Variance = syms.foldLeft(Bivariant) ((v, sym) => v & varianceInSym(sym)(tparam)) /** Compute variance of type parameter `tparam` in type of symbol `sym`. */ - def varianceInSym(sym: Symbol)(tparam: Symbol)(implicit ctx: Context): Variance = + def varianceInSym(sym: Symbol)(tparam: Symbol)(using Context): Variance = if (sym.isAliasType) cut(varianceInType(sym.info)(tparam)) else varianceInType(sym.info)(tparam) /** Compute variance of type parameter `tparam` in all types `tps`. */ - def varianceInTypes(tps: List[Type])(tparam: Symbol)(implicit ctx: Context): Variance = + def varianceInTypes(tps: List[Type])(tparam: Symbol)(using Context): Variance = tps.foldLeft(Bivariant) ((v, tp) => v & varianceInType(tp)(tparam)) /** Compute variance of type parameter `tparam` in all type arguments * tps which correspond to formal type parameters `tparams1`. */ - def varianceInArgs(tps: List[Type], tparams1: List[Symbol])(tparam: Symbol)(implicit ctx: Context): Variance = { + def varianceInArgs(tps: List[Type], tparams1: List[Symbol])(tparam: Symbol)(using Context): Variance = { var v: Variance = Bivariant; for ((tp, tparam1) <- tps zip tparams1) { val v1 = varianceInType(tp)(tparam) @@ -64,15 +64,15 @@ object Variances { } /** Compute variance of type parameter `tparam` in all type annotations `annots`. */ - def varianceInAnnots(annots: List[Annotation])(tparam: Symbol)(implicit ctx: Context): Variance = + def varianceInAnnots(annots: List[Annotation])(tparam: Symbol)(using Context): Variance = annots.foldLeft(Bivariant) ((v, annot) => v & varianceInAnnot(annot)(tparam)) /** Compute variance of type parameter `tparam` in type annotation `annot`. */ - def varianceInAnnot(annot: Annotation)(tparam: Symbol)(implicit ctx: Context): Variance = + def varianceInAnnot(annot: Annotation)(tparam: Symbol)(using Context): Variance = varianceInType(annot.tree.tpe)(tparam) /** Compute variance of type parameter tparam in type tp. */ - def varianceInType(tp: Type)(tparam: Symbol)(implicit ctx: Context): Variance = tp match { + def varianceInType(tp: Type)(tparam: Symbol)(using Context): Variance = tp match { case TermRef(pre, _) => varianceInType(pre)(tparam) case tp @ TypeRef(pre, _) => @@ -109,7 +109,7 @@ object Variances { Bivariant } - def setStructuralVariances(lam: HKTypeLambda)(implicit ctx: Context): Unit = + def setStructuralVariances(lam: HKTypeLambda)(using Context): Unit = assert(!lam.isDeclaredVarianceLambda) for param <- lam.typeParams do param.storedVariance = Bivariant object narrowVariances extends TypeTraverser { @@ -132,14 +132,14 @@ object Variances { /** Does the variance of type parameter `tparam1` conform to the variance of type parameter `tparam2`? */ - def varianceConforms(tparam1: TypeParamInfo, tparam2: TypeParamInfo)(implicit ctx: Context): Boolean = + def varianceConforms(tparam1: TypeParamInfo, tparam2: TypeParamInfo)(using Context): Boolean = tparam1.paramVariance.isAllOf(tparam2.paramVariance) /** Do the variances of type parameters `tparams1` conform to the variances * of corresponding type parameters `tparams2`? * This is only the case if `tparams1` and `tparams2` have the same length. */ - def variancesConform(tparams1: List[TypeParamInfo], tparams2: List[TypeParamInfo])(implicit ctx: Context): Boolean = + def variancesConform(tparams1: List[TypeParamInfo], tparams2: List[TypeParamInfo])(using Context): Boolean = val needsDetailedCheck = tparams2 match case (_: Symbol) :: _ => true case LambdaParam(tl: HKTypeLambda, _) :: _ => tl.isDeclaredVarianceLambda @@ -147,7 +147,7 @@ object Variances { if needsDetailedCheck then tparams1.corresponds(tparams2)(varianceConforms) else tparams1.hasSameLengthAs(tparams2) - def varianceSign(sym: Symbol)(implicit ctx: Context): String = + def varianceSign(sym: Symbol)(using Context): String = varianceSign(sym.variance) def varianceSign(v: Variance): String = varianceSign(varianceToInt(v)) diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index 09c009cc3e0b..608d78708f3b 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -32,7 +32,7 @@ object ClassfileParser { object NoEmbedded extends Embedded /** Replace raw types with wildcard applications */ - def cook(implicit ctx: Context): TypeMap = new TypeMap { + def cook(using Context): TypeMap = new TypeMap { def apply(tp: Type): Type = tp match { case tp: TypeRef if tp.symbol.typeParams.nonEmpty => AppliedType(tp, tp.symbol.typeParams.map(Function.const(TypeBounds.empty))) @@ -77,12 +77,12 @@ class ClassfileParser( classRoot.info = NoLoader().withDecls(instanceScope) moduleRoot.info = NoLoader().withDecls(staticScope).withSourceModule(_ => staticModule) - private def currentIsTopLevel(implicit ctx: Context) = classRoot.owner.is(Flags.PackageClass) + private def currentIsTopLevel(using Context) = classRoot.owner.is(Flags.PackageClass) private def mismatchError(className: SimpleName) = throw new IOException(s"class file '${in.file.canonicalPath}' has location not matching its contents: contains class $className") - def run()(implicit ctx: Context): Option[Embedded] = try { + def run()(using Context): Option[Embedded] = try { ctx.debuglog("[class] >> " + classRoot.fullName) parseHeader() this.pool = new ConstantPool @@ -110,14 +110,14 @@ class ClassfileParser( } /** Return the class symbol of the given name. */ - def classNameToSymbol(name: Name)(implicit ctx: Context): Symbol = innerClasses.get(name) match { + def classNameToSymbol(name: Name)(using Context): Symbol = innerClasses.get(name) match { case Some(entry) => innerClasses.classSymbol(entry) case None => ctx.requiredClass(name) } var sawPrivateConstructor: Boolean = false - def parseClass()(implicit ctx: Context): Option[Embedded] = { + def parseClass()(using Context): Option[Embedded] = { val jflags = in.nextChar val isAnnotation = hasAnnotation(jflags) val sflags = classTranslation.flags(jflags) @@ -207,7 +207,7 @@ class ClassfileParser( } /** Add type parameters of enclosing classes */ - def addEnclosingTParams()(implicit ctx: Context): Unit = { + def addEnclosingTParams()(using Context): Unit = { var sym = classRoot.owner while (sym.isClass && !sym.is(Flags.ModuleClass)) { for (tparam <- sym.typeParams) @@ -216,7 +216,7 @@ class ClassfileParser( } } - def parseMember(method: Boolean)(implicit ctx: Context): Unit = { + def parseMember(method: Boolean)(using Context): Unit = { val start = indexCoord(in.bp) val jflags = in.nextChar val sflags = @@ -236,7 +236,7 @@ class ClassfileParser( val memberCompleter: LazyType = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + def complete(denot: SymDenotation)(using Context): Unit = { val oldbp = in.bp try { in.bp = denot.symbol.coord.toIndex @@ -307,7 +307,7 @@ class ClassfileParser( } /** Map direct references to Object to references to Any */ - final def objToAny(tp: Type)(implicit ctx: Context): Type = + final def objToAny(tp: Type)(using Context): Type = if (tp.isDirectRef(defn.ObjectClass) && !ctx.phase.erasedTypes) defn.AnyType else tp def constantTagToType(tag: Int)(using Context): Type = @@ -323,7 +323,7 @@ class ClassfileParser( case BOOL_TAG => defn.BooleanType } - private def sigToType(sig: SimpleName, owner: Symbol = null)(implicit ctx: Context): Type = { + private def sigToType(sig: SimpleName, owner: Symbol = null)(using Context): Type = { var index = 0 val end = sig.length def accept(ch: Char): Unit = { @@ -337,7 +337,7 @@ class ClassfileParser( } // Warning: sigToType contains nested completers which might be forced in a later run! // So local methods need their own ctx parameters. - def sig2type(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(implicit ctx: Context): Type = { + def sig2type(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(using Context): Type = { val tag = sig(index); index += 1 (tag: @switch) match { case 'L' => @@ -415,7 +415,7 @@ class ClassfileParser( } // sig2type(tparams, skiptvs) - def sig2typeBounds(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(implicit ctx: Context): Type = { + def sig2typeBounds(tparams: immutable.Map[Name, Symbol], skiptvs: Boolean)(using Context): Type = { val ts = new ListBuffer[Type] while (sig(index) == ':') { index += 1 @@ -429,7 +429,7 @@ class ClassfileParser( var tparams = classTParams def typeParamCompleter(start: Int) = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + def complete(denot: SymDenotation)(using Context): Unit = { val savedIndex = index try { index = start @@ -476,7 +476,7 @@ class ClassfileParser( } // sigToType - def parseAnnotArg(skip: Boolean = false)(implicit ctx: Context): Option[untpd.Tree] = { + def parseAnnotArg(skip: Boolean = false)(using Context): Option[untpd.Tree] = { // If we encounter an empty array literal, we need the type of the corresponding // parameter to properly type it, but that would require forcing the annotation @@ -534,7 +534,7 @@ class ClassfileParser( /** Parse and return a single annotation. If it is malformed, * return None. */ - def parseAnnotation(attrNameIndex: Char, skip: Boolean = false)(implicit ctx: Context): Option[Annotation] = try { + def parseAnnotation(attrNameIndex: Char, skip: Boolean = false)(using Context): Option[Annotation] = try { val attrType = pool.getType(attrNameIndex) attrType match case tp: TypeRef => @@ -573,7 +573,7 @@ class ClassfileParser( None // ignore malformed annotations } - def parseAttributes(sym: Symbol, symtype: Type)(implicit ctx: Context): Type = { + def parseAttributes(sym: Symbol, symtype: Type)(using Context): Type = { var newType = symtype def parseAttribute(): Unit = { @@ -662,7 +662,7 @@ class ClassfileParser( /** Annotations in Scala are assumed to get all their arguments as constructor * parameters. For Java annotations we need to fake it by making up the constructor. */ - def addAnnotationConstructor(classInfo: TempClassInfoType)(implicit ctx: Context): Unit = + def addAnnotationConstructor(classInfo: TempClassInfoType)(using Context): Unit = ctx.newSymbol( owner = classRoot.symbol, name = nme.CONSTRUCTOR, @@ -671,7 +671,7 @@ class ClassfileParser( ).entered class AnnotConstructorCompleter(classInfo: TempClassInfoType) extends LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = { + def complete(denot: SymDenotation)(using Context): Unit = { val attrs = classInfo.decls.toList.filter(sym => sym.isTerm && sym != denot.symbol) val paramNames = attrs.map(_.name.asTermName) val paramTypes = attrs.map(_.info.resultType) @@ -682,7 +682,7 @@ class ClassfileParser( /** Enter own inner classes in the right scope. It needs the scopes to be set up, * and implicitly current class' superclasses. */ - private def enterOwnInnerClasses()(implicit ctx: Context): Unit = { + private def enterOwnInnerClasses()(using Context): Unit = { def className(name: Name): Name = { val name1 = name.toSimpleName name1.drop(name1.lastIndexOf('.') + 1) @@ -715,7 +715,7 @@ class ClassfileParser( * Restores the old `bp`. * @return true iff classfile is from Scala, so no Java info needs to be read. */ - def unpickleOrParseInnerClasses()(implicit ctx: Context): Option[Embedded] = { + def unpickleOrParseInnerClasses()(using Context): Option[Embedded] = { val oldbp = in.bp try { skipSuperclasses() @@ -905,7 +905,7 @@ class ClassfileParser( /** Return the Symbol of the top level class enclosing `name`, * or 'name's symbol if no entry found for `name`. */ - def topLevelClass(name: Name)(implicit ctx: Context): Symbol = { + def topLevelClass(name: Name)(using Context): Symbol = { val tlName = if (isDefinedAt(name)) { var entry = this(name) while (isDefinedAt(entry.outerName)) @@ -920,8 +920,8 @@ class ClassfileParser( /** Return the class symbol for `entry`. It looks it up in its outer class. * This might force outer class symbols. */ - def classSymbol(entry: InnerClassEntry)(implicit ctx: Context): Symbol = { - def getMember(sym: Symbol, name: Name)(implicit ctx: Context): Symbol = + def classSymbol(entry: InnerClassEntry)(using Context): Symbol = { + def getMember(sym: Symbol, name: Name)(using Context): Symbol = if (isStatic(entry.jflags)) if (sym == classRoot.symbol) staticScope.lookup(name) @@ -977,7 +977,7 @@ class ClassfileParser( protected def getScope(flags: Int): MutableScope = if (isStatic(flags)) staticScope else instanceScope - private def getPrivateWithin(jflags: Int)(implicit ctx: Context): Symbol = + private def getPrivateWithin(jflags: Int)(using Context): Symbol = if ((jflags & (JAVA_ACC_PRIVATE | JAVA_ACC_PUBLIC)) == 0) classRoot.enclosingPackageClass else @@ -1048,7 +1048,7 @@ class ClassfileParser( internalized(index) } - def getClassSymbol(index: Int)(implicit ctx: Context): Symbol = { + def getClassSymbol(index: Int)(using Context): Symbol = { if (index <= 0 || len <= index) errorBadIndex(index) var c = values(index).asInstanceOf[Symbol] if (c eq null) { @@ -1077,7 +1077,7 @@ class ClassfileParser( * arrays are considered to be class types, they might * appear as entries in 'newarray' or 'cast' opcodes. */ - def getClassOrArrayType(index: Int)(implicit ctx: Context): Type = { + def getClassOrArrayType(index: Int)(using Context): Type = { if (index <= 0 || len <= index) errorBadIndex(index) val value = values(index) var c: Type = null @@ -1102,15 +1102,15 @@ class ClassfileParser( c } - def getType(index: Int)(implicit ctx: Context): Type = + def getType(index: Int)(using Context): Type = sigToType(getExternalName(index)) - def getSuperClass(index: Int)(implicit ctx: Context): Symbol = { + def getSuperClass(index: Int)(using Context): Symbol = { assert(index != 0, "attempt to parse java.lang.Object from classfile") getClassSymbol(index) } - def getConstant(index: Int, pt: Type = WildcardType)(implicit ctx: Context): Constant = { + def getConstant(index: Int, pt: Type = WildcardType)(using Context): Constant = { if (index <= 0 || len <= index) errorBadIndex(index) var value = values(index) if (value eq null) { diff --git a/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala b/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala index 98770350fb84..b798130f8a55 100644 --- a/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala +++ b/compiler/src/dotty/tools/dotc/core/quoted/PickledQuotes.scala @@ -28,7 +28,7 @@ object PickledQuotes { import tpd._ /** Pickle the tree of the quote into strings */ - def pickleQuote(tree: Tree)(implicit ctx: Context): PickledQuote = + def pickleQuote(tree: Tree)(using Context): PickledQuote = if (ctx.reporter.hasErrors) Nil else { assert(!tree.isInstanceOf[Hole]) // Should not be pickled as it represents `'{$x}` which should be optimized to `x` @@ -37,23 +37,23 @@ object PickledQuotes { } /** Transform the expression into its fully spliced Tree */ - def quotedExprToTree[T](expr: quoted.Expr[T])(implicit ctx: Context): Tree = { + def quotedExprToTree[T](expr: quoted.Expr[T])(using Context): Tree = { val expr1 = expr.asInstanceOf[scala.internal.quoted.Expr[Tree]] QuoteContext.checkScopeId(expr1.scopeId) healOwner(expr1.tree) } /** Transform the expression into its fully spliced TypeTree */ - def quotedTypeToTree(tpe: quoted.Type[?])(implicit ctx: Context): Tree = { + def quotedTypeToTree(tpe: quoted.Type[?])(using Context): Tree = { val tpe1 = tpe.asInstanceOf[scala.internal.quoted.Type[Tree]] QuoteContext.checkScopeId(tpe1.scopeId) healOwner(tpe1.typeTree) } /** Unpickle the tree contained in the TastyExpr */ - def unpickleExpr(tasty: PickledQuote, splices: PickledArgs)(implicit ctx: Context): Tree = { + def unpickleExpr(tasty: PickledQuote, splices: PickledArgs)(using Context): Tree = { val tastyBytes = TastyString.unpickle(tasty) - val unpickled = unpickle(tastyBytes, splices, isType = false)(ctx.addMode(Mode.ReadPositions)) + val unpickled = unpickle(tastyBytes, splices, isType = false)(using ctx.addMode(Mode.ReadPositions)) val Inlined(call, Nil, expnasion) = unpickled val inlineCtx = inlineContext(call) val expansion1 = spliceTypes(expnasion, splices)(using inlineCtx) @@ -62,16 +62,16 @@ object PickledQuotes { } /** Unpickle the tree contained in the TastyType */ - def unpickleType(tasty: PickledQuote, args: PickledArgs)(implicit ctx: Context): Tree = { + def unpickleType(tasty: PickledQuote, args: PickledArgs)(using Context): Tree = { val tastyBytes = TastyString.unpickle(tasty) - val unpickled = unpickle(tastyBytes, args, isType = true)(ctx.addMode(Mode.ReadPositions)) + val unpickled = unpickle(tastyBytes, args, isType = true)(using ctx.addMode(Mode.ReadPositions)) spliceTypes(unpickled, args) } /** Replace all term holes with the spliced terms */ private def spliceTerms(tree: Tree, splices: PickledArgs)(using Context): Tree = { val evaluateHoles = new TreeMap { - override def transform(tree: tpd.Tree)(implicit ctx: Context): tpd.Tree = tree match { + override def transform(tree: tpd.Tree)(using Context): tpd.Tree = tree match { case Hole(isTerm, idx, args) => val reifiedArgs = args.map { arg => if (arg.isTerm) (using qctx: scala.quoted.QuoteContext) => new scala.internal.quoted.Expr(arg, QuoteContext.scopeId) @@ -160,7 +160,7 @@ object PickledQuotes { // TASTY picklingtests/pos/quoteTest.scala /** Pickle tree into it's TASTY bytes s*/ - private def pickle(tree: Tree)(implicit ctx: Context): Array[Byte] = { + private def pickle(tree: Tree)(using Context): Array[Byte] = { quotePickling.println(i"**** pickling quote of\n$tree") val pickler = new TastyPickler(defn.RootClass) val treePkl = pickler.treePkl @@ -177,7 +177,7 @@ object PickledQuotes { } /** Unpickle TASTY bytes into it's tree */ - private def unpickle(bytes: Array[Byte], splices: Seq[Any], isType: Boolean)(implicit ctx: Context): Tree = { + private def unpickle(bytes: Array[Byte], splices: Seq[Any], isType: Boolean)(using Context): Tree = { quotePickling.println(s"**** unpickling quote from TASTY\n${new TastyPrinter(bytes).printContents()}") val mode = if (isType) UnpickleMode.TypeTree else UnpickleMode.Term @@ -188,7 +188,7 @@ object PickledQuotes { // Make sure trees and positions are fully loaded new TreeTraverser { - def traverse(tree: Tree)(implicit ctx: Context): Unit = traverseChildren(tree) + def traverse(tree: Tree)(using Context): Unit = traverseChildren(tree) }.traverse(tree) quotePickling.println(i"**** unpickled quote\n$tree") @@ -196,9 +196,9 @@ object PickledQuotes { } /** Make sure that the owner of this tree is `ctx.owner` */ - def healOwner(tree: Tree)(implicit ctx: Context): Tree = { + def healOwner(tree: Tree)(using Context): Tree = { val getCurrentOwner = new TreeAccumulator[Option[Symbol]] { - def apply(x: Option[Symbol], tree: tpd.Tree)(implicit ctx: Context): Option[Symbol] = + def apply(x: Option[Symbol], tree: tpd.Tree)(using Context): Option[Symbol] = if (x.isDefined) x else tree match { case tree: DefTree => Some(tree.symbol.owner) diff --git a/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala b/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala index d12abdbc7973..7c552debb82d 100644 --- a/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala +++ b/doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala @@ -39,7 +39,7 @@ trait DottyDocTest extends MessageRendering { (TestConfiguration.basicClasspath :: extraClasspath).mkString(java.io.File.pathSeparator) ) ctx.setReporter(new StoreReporter(ctx.reporter)) - base.initialize()(ctx) + base.initialize()(using ctx) ctx } implicit val ctx: FreshContext = freshCtx(Nil) diff --git a/doc-tool/test/dotty/tools/dottydoc/MarkdownTests.scala b/doc-tool/test/dotty/tools/dottydoc/MarkdownTests.scala index db8115e321c9..b8e5e09dc383 100644 --- a/doc-tool/test/dotty/tools/dottydoc/MarkdownTests.scala +++ b/doc-tool/test/dotty/tools/dottydoc/MarkdownTests.scala @@ -27,7 +27,7 @@ class MarkdownTests extends DottyDocTest with CheckFromSource { ctx.settings.classpath, TestConfiguration.basicClasspath ) - base.initialize()(ctx) + base.initialize()(using ctx) ctx } From a66f8f3d72cdd9239d5b1b4fa0ec1731ee9cdd92 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 15:15:04 +0200 Subject: [PATCH 15/41] Convert tasty and unpickler classes --- .../dotc/core/classfile/ClassfileParser.scala | 2 +- .../dotc/core/tasty/CommentPickler.scala | 6 +- .../dotc/core/tasty/DottyUnpickler.scala | 6 +- .../dotc/core/tasty/PositionPickler.scala | 2 +- .../dotc/core/tasty/TastyHTMLPrinter.scala | 2 +- .../tools/dotc/core/tasty/TastyPrinter.scala | 2 +- .../tools/dotc/core/tasty/TreePickler.scala | 46 +++--- .../tools/dotc/core/tasty/TreeUnpickler.scala | 156 +++++++++--------- .../core/unpickleScala2/Scala2Unpickler.scala | 128 +++++++------- 9 files changed, 175 insertions(+), 175 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index 608d78708f3b..828577216419 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -757,7 +757,7 @@ class ClassfileParser( def unpickleTASTY(bytes: Array[Byte]): Some[Embedded] = { val unpickler = new tasty.DottyUnpickler(bytes) - unpickler.enter(roots = Set(classRoot, moduleRoot, moduleRoot.sourceModule))(ctx.withSource(util.NoSource)) + unpickler.enter(roots = Set(classRoot, moduleRoot, moduleRoot.sourceModule))(using ctx.withSource(util.NoSource)) Some(unpickler) } diff --git a/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala index 1b57588f45a8..aaea6a8212d8 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/CommentPickler.scala @@ -2,14 +2,14 @@ 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.tasty.TastyBuffer import TastyBuffer.{Addr, NoAddr} import java.nio.charset.Charset -class CommentPickler(pickler: TastyPickler, addrOfTree: tpd.Tree => Addr)(implicit ctx: Context) { +class CommentPickler(pickler: TastyPickler, addrOfTree: tpd.Tree => Addr)(using Context) { private val buf = new TastyBuffer(5000) pickler.newSection("Comments", buf) @@ -31,7 +31,7 @@ class CommentPickler(pickler: TastyPickler, addrOfTree: tpd.Tree => Addr)(implic } private class Traverser(docCtx: ContextDocstrings) extends tpd.TreeTraverser { - override def traverse(tree: tpd.Tree)(implicit ctx: Context): Unit = + override def traverse(tree: tpd.Tree)(using Context): Unit = tree match { case md: tpd.MemberDef => val comment = docCtx.docstring(md.symbol) diff --git a/compiler/src/dotty/tools/dotc/core/tasty/DottyUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/DottyUnpickler.scala index 5c80e4437e3e..a62236edbddf 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/DottyUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/DottyUnpickler.scala @@ -50,17 +50,17 @@ class DottyUnpickler(bytes: Array[Byte], mode: UnpickleMode = UnpickleMode.TopLe /** Enter all toplevel classes and objects into their scopes * @param roots a set of SymDenotations that should be overwritten by unpickling */ - def enter(roots: Set[SymDenotation])(implicit ctx: Context): Unit = + def enter(roots: Set[SymDenotation])(using Context): Unit = treeUnpickler.enter(roots) protected def treeSectionUnpickler(posUnpicklerOpt: Option[PositionUnpickler], commentUnpicklerOpt: Option[CommentUnpickler]): TreeSectionUnpickler = new TreeSectionUnpickler(posUnpicklerOpt, commentUnpicklerOpt) - protected def computeRootTrees(implicit ctx: Context): List[Tree] = treeUnpickler.unpickle(mode) + protected def computeRootTrees(using Context): List[Tree] = treeUnpickler.unpickle(mode) private var ids: Array[String] = null - override def mightContain(id: String)(implicit ctx: Context): Boolean = { + override def mightContain(id: String)(using Context): Boolean = { if (ids == null) ids = unpickler.nameAtRef.contents.toArray.collect { diff --git a/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala index 92bedc790461..4133755e8c98 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/PositionPickler.scala @@ -28,7 +28,7 @@ class PositionPickler(pickler: TastyPickler, addrOfTree: untpd.Tree => Addr) { (addrDelta << 3) | (toInt(hasStartDelta) << 2) | (toInt(hasEndDelta) << 1) | toInt(hasPoint) } - def picklePositions(roots: List[Tree])(implicit ctx: Context): Unit = { + def picklePositions(roots: List[Tree])(using Context): Unit = { var lastIndex = 0 var lastSpan = Span(0, 0) def pickleDeltas(index: Int, span: Span) = { diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TastyHTMLPrinter.scala b/compiler/src/dotty/tools/dotc/core/tasty/TastyHTMLPrinter.scala index f8f6c11ce6c1..28766cc9ff06 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TastyHTMLPrinter.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TastyHTMLPrinter.scala @@ -10,7 +10,7 @@ import TastyUnpickler._ import util.Spans.offsetToInt import printing.Highlighting._ -class TastyHTMLPrinter(bytes: Array[Byte])(implicit ctx: Context) extends TastyPrinter(bytes) { +class TastyHTMLPrinter(bytes: Array[Byte])(using Context) extends TastyPrinter(bytes) { override protected def nameColor(str: String): String = s"$str" override protected def treeColor(str: String): String = s"$str" override protected def lengthColor(str: String): String = s"$str" diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TastyPrinter.scala b/compiler/src/dotty/tools/dotc/core/tasty/TastyPrinter.scala index 77442ead9298..f2ed4df5422c 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TastyPrinter.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TastyPrinter.scala @@ -11,7 +11,7 @@ import TastyUnpickler._ import util.Spans.offsetToInt import printing.Highlighting._ -class TastyPrinter(bytes: Array[Byte])(implicit ctx: Context) { +class TastyPrinter(bytes: Array[Byte])(using Context) { private val sb: StringBuilder = new StringBuilder diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala index 470ce6b13822..85c6830de5cc 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala @@ -53,7 +53,7 @@ class TreePickler(pickler: TastyPickler) { def addrOfSym(sym: Symbol): Option[Addr] = symRefs.get(sym) - def preRegister(tree: Tree)(implicit ctx: Context): Unit = tree match { + def preRegister(tree: Tree)(using Context): Unit = tree match { case tree: MemberDef => if (!symRefs.contains(tree.symbol)) symRefs(tree.symbol) = NoAddr case _ => @@ -76,7 +76,7 @@ class TreePickler(pickler: TastyPickler) { if (sig eq Signature.NotAMethod) name else SignedName(name.toTermName, sig)) - private def pickleSymRef(sym: Symbol)(implicit ctx: Context) = symRefs.get(sym) match { + private def pickleSymRef(sym: Symbol)(using Context) = symRefs.get(sym) match { case Some(label) => if (label != NoAddr) writeRef(label) else pickleForwardSymRef(sym) case None => @@ -88,16 +88,16 @@ class TreePickler(pickler: TastyPickler) { pickleForwardSymRef(sym) } - private def pickleForwardSymRef(sym: Symbol)(implicit ctx: Context) = { + private def pickleForwardSymRef(sym: Symbol)(using Context) = { val ref = reserveRef(relative = false) assert(!sym.is(Flags.Package), sym) forwardSymRefs(sym) = ref :: forwardSymRefs.getOrElse(sym, Nil) } - private def isLocallyDefined(sym: Symbol)(implicit ctx: Context) = + private def isLocallyDefined(sym: Symbol)(using Context) = sym.topLevelClass.isLinkedWith(pickler.rootCls) - def pickleConstant(c: Constant)(implicit ctx: Context): Unit = c.tag match { + def pickleConstant(c: Constant)(using Context): Unit = c.tag match { case UnitTag => writeByte(UNITconst) case BooleanTag => @@ -145,7 +145,7 @@ class TreePickler(pickler: TastyPickler) { else STABLE) case _ => - def pickleType(tpe0: Type, richTypes: Boolean = false)(implicit ctx: Context): Unit = { + def pickleType(tpe0: Type, richTypes: Boolean = false)(using Context): Unit = { val tpe = tpe0.stripTypeVar try { val prev = pickledTypes.get(tpe) @@ -165,7 +165,7 @@ class TreePickler(pickler: TastyPickler) { } } - private def pickleNewType(tpe: Type, richTypes: Boolean)(implicit ctx: Context): Unit = tpe match { + private def pickleNewType(tpe: Type, richTypes: Boolean)(using Context): Unit = tpe match { case AppliedType(tycon, args) => writeByte(APPLIEDtype) withLength { pickleType(tycon); args.foreach(pickleType(_)) } @@ -281,7 +281,7 @@ class TreePickler(pickler: TastyPickler) { pickleType(tpe.ref) } - def pickleMethodic(tag: Int, tpe: LambdaType, mods: FlagSet)(implicit ctx: Context): Unit = { + def pickleMethodic(tag: Int, tpe: LambdaType, mods: FlagSet)(using Context): Unit = { writeByte(tag) withLength { pickleType(tpe.resultType, richTypes = true) @@ -292,7 +292,7 @@ class TreePickler(pickler: TastyPickler) { } } - def pickleParamRef(tpe: ParamRef)(implicit ctx: Context): Boolean = { + def pickleParamRef(tpe: ParamRef)(using Context): Boolean = { val binder = pickledTypes.get(tpe.binder) val pickled = binder != null if (pickled) { @@ -302,14 +302,14 @@ class TreePickler(pickler: TastyPickler) { pickled } - def pickleTpt(tpt: Tree)(implicit ctx: Context): Unit = + def pickleTpt(tpt: Tree)(using Context): Unit = pickleTree(tpt) - def pickleTreeUnlessEmpty(tree: Tree)(implicit ctx: Context): Unit = { + def pickleTreeUnlessEmpty(tree: Tree)(using Context): Unit = { if (!tree.isEmpty) pickleTree(tree) } - def pickleDef(tag: Int, sym: Symbol, tpt: Tree, rhs: Tree = EmptyTree, pickleParams: => Unit = ())(implicit ctx: Context): Unit = { + def pickleDef(tag: Int, sym: Symbol, tpt: Tree, rhs: Tree = EmptyTree, pickleParams: => Unit = ())(using Context): Unit = { assert(symRefs(sym) == NoAddr, sym) registerDef(sym) writeByte(tag) @@ -325,7 +325,7 @@ class TreePickler(pickler: TastyPickler) { } } - def pickleParam(tree: Tree)(implicit ctx: Context): Unit = { + def pickleParam(tree: Tree)(using Context): Unit = { registerTreeAddr(tree) tree match { case tree: ValDef => pickleDef(PARAM, tree.symbol, tree.tpt) @@ -334,17 +334,17 @@ class TreePickler(pickler: TastyPickler) { } } - def pickleParams(trees: List[Tree])(implicit ctx: Context): Unit = { + def pickleParams(trees: List[Tree])(using Context): Unit = { trees.foreach(preRegister) trees.foreach(pickleParam) } - def pickleStats(stats: List[Tree])(implicit ctx: Context): Unit = { + def pickleStats(stats: List[Tree])(using Context): Unit = { stats.foreach(preRegister) stats.foreach(stat => if (!stat.isEmpty) pickleTree(stat)) } - def pickleTree(tree: Tree)(implicit ctx: Context): Unit = { + def pickleTree(tree: Tree)(using Context): Unit = { val addr = registerTreeAddr(tree) if (addr != currentAddr) { writeByte(SHAREDterm) @@ -629,7 +629,7 @@ class TreePickler(pickler: TastyPickler) { } } - def pickleSelectors(selectors: List[untpd.ImportSelector])(implicit ctx: Context): Unit = + def pickleSelectors(selectors: List[untpd.ImportSelector])(using Context): Unit = for sel <- selectors do pickleSelector(IMPORTED, sel.imported) sel.renamed match @@ -642,13 +642,13 @@ class TreePickler(pickler: TastyPickler) { pickleTree(tpt) case _ => - def pickleSelector(tag: Int, id: untpd.Ident)(implicit ctx: Context): Unit = { + def pickleSelector(tag: Int, id: untpd.Ident)(using Context): Unit = { registerTreeAddr(id) writeByte(tag) pickleName(id.name) } - def pickleModifiers(sym: Symbol)(implicit ctx: Context): Unit = { + def pickleModifiers(sym: Symbol)(using Context): Unit = { import Flags._ var flags = sym.flags val privateWithin = sym.privateWithin @@ -663,7 +663,7 @@ class TreePickler(pickler: TastyPickler) { sym.annotations.foreach(pickleAnnotation(sym, _)) } - def pickleFlags(flags: FlagSet, isTerm: Boolean)(implicit ctx: Context): Unit = { + def pickleFlags(flags: FlagSet, isTerm: Boolean)(using Context): Unit = { import Flags._ def writeModTag(tag: Int) = { assert(isModifierTag(tag)) @@ -713,7 +713,7 @@ class TreePickler(pickler: TastyPickler) { } } - private def isUnpicklable(owner: Symbol, ann: Annotation)(implicit ctx: Context) = ann match { + private def isUnpicklable(owner: Symbol, ann: Annotation)(using Context) = ann match { case Annotation.Child(sym) => sym.isInaccessibleChildOf(owner) // If child annotation refers to a local class or enum value under // a different toplevel class, it is impossible to pickle a reference to it. @@ -723,7 +723,7 @@ class TreePickler(pickler: TastyPickler) { ann.symbol == defn.BodyAnnot // inline bodies are reconstituted automatically when unpickling } - def pickleAnnotation(owner: Symbol, ann: Annotation)(implicit ctx: Context): Unit = { + def pickleAnnotation(owner: Symbol, ann: Annotation)(using Context): Unit = { if (!isUnpicklable(owner, ann)) { writeByte(ANNOTATION) withLength { pickleType(ann.symbol.typeRef); pickleTree(ann.tree) } @@ -732,7 +732,7 @@ class TreePickler(pickler: TastyPickler) { // ---- main entry points --------------------------------------- - def pickle(trees: List[Tree])(implicit ctx: Context): Unit = { + def pickle(trees: List[Tree])(using Context): Unit = { trees.foreach(tree => if (!tree.isEmpty) pickleTree(tree)) def missing = forwardSymRefs.keysIterator.map(sym => sym.showLocated + "(line " + sym.sourcePos.line + ")").toList assert(forwardSymRefs.isEmpty, i"unresolved symbols: $missing%, % when pickling ${ctx.source}") diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index 2579cdf95ff2..81ff5890cab7 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -89,7 +89,7 @@ class TreeUnpickler(reader: TastyReader, /** Enter all toplevel classes and objects into their scopes * @param roots a set of SymDenotations that should be overwritten by unpickling */ - def enter(roots: Set[SymDenotation])(implicit ctx: Context): Unit = { + def enter(roots: Set[SymDenotation])(using Context): Unit = { this.roots = roots val rdr = new TreeReader(reader).fork ownerTree = new OwnerTree(NoAddr, 0, rdr.fork, reader.endAddr) @@ -98,7 +98,7 @@ class TreeUnpickler(reader: TastyReader, } /** The unpickled trees */ - def unpickle(mode: UnpickleMode)(implicit ctx: Context): List[Tree] = { + def unpickle(mode: UnpickleMode)(using Context): List[Tree] = { assert(roots != null, "unpickle without previous enterTopLevel") val rdr = new TreeReader(reader) mode match { @@ -108,14 +108,14 @@ class TreeUnpickler(reader: TastyReader, } } - class Completer(reader: TastyReader)(implicit @constructorOnly ctx: Context) extends LazyType { + class Completer(reader: TastyReader)(using @constructorOnly _ctx: Context) extends LazyType { import reader._ val owner = ctx.owner val source = ctx.source - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = + def complete(denot: SymDenotation)(using Context): Unit = treeAtAddr(currentAddr) = new TreeReader(reader).readIndexedDef()( - ctx.withPhaseNoLater(ctx.picklerPhase).withOwner(owner).withSource(source)) + using ctx.withPhaseNoLater(ctx.picklerPhase).withOwner(owner).withSource(source)) } class TreeReader(val reader: TastyReader) { @@ -226,7 +226,7 @@ class TreeUnpickler(reader: TastyReader, (names, mods) /** Read `n` parameter types or bounds which are interleaved with names */ - def readParamTypes[T <: Type](n: Int)(implicit ctx: Context): List[T] = + def readParamTypes[T <: Type](n: Int)(using Context): List[T] = if n == 0 then Nil else val t = readType().asInstanceOf[T] @@ -234,10 +234,10 @@ class TreeUnpickler(reader: TastyReader, t :: readParamTypes(n - 1) /** Read reference to definition and return symbol created at that definition */ - def readSymRef()(implicit ctx: Context): Symbol = symbolAt(readAddr()) + def readSymRef()(using Context): Symbol = symbolAt(readAddr()) /** The symbol at given address; createa new one if none exists yet */ - def symbolAt(addr: Addr)(implicit ctx: Context): Symbol = symAtAddr.get(addr) match { + def symbolAt(addr: Addr)(using Context): Symbol = symAtAddr.get(addr) match { case Some(sym) => sym case None => @@ -247,7 +247,7 @@ class TreeUnpickler(reader: TastyReader, } /** The symbol defined by current definition */ - def symbolAtCurrent()(implicit ctx: Context): Symbol = symAtAddr.get(currentAddr) match { + def symbolAtCurrent()(using Context): Symbol = symAtAddr.get(currentAddr) match { case Some(sym) => assert(ctx.owner == sym.owner, i"owner discrepancy for $sym, expected: ${ctx.owner}, found: ${sym.owner}") sym @@ -255,7 +255,7 @@ class TreeUnpickler(reader: TastyReader, createSymbol() } - def readConstant(tag: Int)(implicit ctx: Context): Constant = (tag: @switch) match { + def readConstant(tag: Int)(using Context): Constant = (tag: @switch) match { case UNITconst => Constant(()) case TRUEconst => @@ -287,7 +287,7 @@ class TreeUnpickler(reader: TastyReader, } /** Read a type */ - def readType()(implicit ctx: Context): Type = { + def readType()(using Context): Type = { val start = currentAddr val tag = readByte() pickling.println(s"reading type ${astTagToString(tag)} at $start, ${ctx.source}") @@ -437,7 +437,7 @@ class TreeUnpickler(reader: TastyReader, if (tag < firstLengthTreeTag) readSimpleType() else readLengthType() } - private def readSymNameRef()(implicit ctx: Context): Type = { + private def readSymNameRef()(using Context): Type = { val sym = readSymRef() val prefix = readType() val res = NamedType(prefix, sym) @@ -450,7 +450,7 @@ class TreeUnpickler(reader: TastyReader, } } - private def readPackageRef()(implicit ctx: Context): TermSymbol = { + private def readPackageRef()(using Context): TermSymbol = { val name = readName() if (name == nme.ROOT || name == nme.ROOTPKG) defn.RootPackage else if (name == nme.EMPTY_PACKAGE) defn.EmptyPackageVal @@ -460,7 +460,7 @@ class TreeUnpickler(reader: TastyReader, def readTypeRef(): Type = typeAtAddr(readAddr()) - def readTermRef()(implicit ctx: Context): TermRef = + def readTermRef()(using Context): TermRef = readType().asInstanceOf[TermRef] // ------ Reading definitions ----------------------------------------------------- @@ -468,10 +468,10 @@ class TreeUnpickler(reader: TastyReader, private def nothingButMods(end: Addr): Boolean = currentAddr == end || isModifierTag(nextByte) - private def localContext(owner: Symbol)(implicit ctx: Context) = + private def localContext(owner: Symbol)(using Context) = ctx.fresh.setOwner(owner) - private def normalizeFlags(tag: Int, givenFlags: FlagSet, name: Name, isAbsType: Boolean, rhsIsEmpty: Boolean)(implicit ctx: Context): FlagSet = { + private def normalizeFlags(tag: Int, givenFlags: FlagSet, name: Name, isAbsType: Boolean, rhsIsEmpty: Boolean)(using Context): FlagSet = { val lacksDefinition = rhsIsEmpty && name.isTermName && !name.isConstructorName && !givenFlags.isOneOf(TermParamOrAccessor) || @@ -493,7 +493,7 @@ class TreeUnpickler(reader: TastyReader, flags } - def isAbstractType(ttag: Int)(implicit ctx: Context): Boolean = nextUnsharedTag match { + def isAbstractType(ttag: Int)(using Context): Boolean = nextUnsharedTag match { case LAMBDAtpt => val rdr = fork rdr.reader.readByte() // tag @@ -507,7 +507,7 @@ class TreeUnpickler(reader: TastyReader, /** Create symbol of definition node and enter in symAtAddr map * @return the created symbol */ - def createSymbol()(implicit ctx: Context): Symbol = nextByte match { + def createSymbol()(using Context): Symbol = nextByte match { case VALDEF | DEFDEF | TYPEDEF | TYPEPARAM | PARAM => createMemberSymbol() case BIND => @@ -520,7 +520,7 @@ class TreeUnpickler(reader: TastyReader, throw new Error(s"illegal createSymbol at $currentAddr, tag = $tag") } - private def createBindSymbol()(implicit ctx: Context): Symbol = { + private def createBindSymbol()(using Context): Symbol = { val start = currentAddr val tag = readByte() val end = readEnd() @@ -528,7 +528,7 @@ class TreeUnpickler(reader: TastyReader, if nextUnsharedTag == TYPEBOUNDS then name = name.toTypeName val typeReader = fork val completer = new LazyType { - def complete(denot: SymDenotation)(implicit ctx: Context) = + def complete(denot: SymDenotation)(using Context) = denot.info = typeReader.readType() } val sym = ctx.newSymbol(ctx.owner, name, Flags.Case, completer, coord = coordAt(start)) @@ -539,7 +539,7 @@ class TreeUnpickler(reader: TastyReader, /** Create symbol of member definition or parameter node and enter in symAtAddr map * @return the created symbol */ - def createMemberSymbol()(implicit ctx: Context): Symbol = { + def createMemberSymbol()(using Context): Symbol = { val start = currentAddr val tag = readByte() val end = readEnd() @@ -588,12 +588,12 @@ class TreeUnpickler(reader: TastyReader, registerSym(start, sym) if (isClass) { sym.completer.withDecls(newScope) - forkAt(templateStart).indexTemplateParams()(localContext(sym)) + forkAt(templateStart).indexTemplateParams()(using localContext(sym)) } else if (sym.isInlineMethod) sym.addAnnotation(LazyBodyAnnotation { (using ctx0: Context) => - val ctx1 = localContext(sym)(ctx0).addMode(Mode.ReadPositions) - given Context = sourceChangeContext(Addr(0))(ctx1) + val ctx1 = localContext(sym)(using ctx0).addMode(Mode.ReadPositions) + given Context = sourceChangeContext(Addr(0))(using ctx1) // avoids space leaks by not capturing the current context forkAt(rhsStart).readTerm() }) @@ -606,7 +606,7 @@ class TreeUnpickler(reader: TastyReader, */ def readModifiers[WithinType, AnnotType] (end: Addr, readAnnot: Context => Symbol => AnnotType, readWithin: Context => WithinType, defaultWithin: WithinType) - (implicit ctx: Context): (FlagSet, List[Symbol => AnnotType], WithinType) = { + (using Context): (FlagSet, List[Symbol => AnnotType], WithinType) = { var flags: FlagSet = EmptyFlags var annotFns: List[Symbol => AnnotType] = Nil var privateWithin = defaultWithin @@ -691,7 +691,7 @@ class TreeUnpickler(reader: TastyReader, * @return the largest subset of {NoInits, PureInterface} that a * trait owning the indexed statements can have as flags. */ - def indexStats(end: Addr)(implicit ctx: Context): FlagSet = { + def indexStats(end: Addr)(using Context): FlagSet = { var initsFlags = NoInitsInterface while (currentAddr.index < end.index) nextByte match { @@ -720,9 +720,9 @@ class TreeUnpickler(reader: TastyReader, * - an end address, * - a context which has the processed package as owner */ - def processPackage[T](op: (RefTree, Addr) => Context => T)(implicit ctx: Context): T = { + def processPackage[T](op: (RefTree, Addr) => Context => T)(using Context): T = { val sctx = sourceChangeContext() - if (sctx `ne` ctx) return processPackage(op)(sctx) + if (sctx `ne` ctx) return processPackage(op)(using sctx) readByte() val end = readEnd() val pid = ref(readTermRef()).asInstanceOf[RefTree] @@ -732,7 +732,7 @@ class TreeUnpickler(reader: TastyReader, /** Create symbols the longest consecutive sequence of parameters with given * `tag` starting at current address. */ - def indexParams(tag: Int)(implicit ctx: Context): Unit = + def indexParams(tag: Int)(using Context): Unit = while (nextByte == tag) { symbolAtCurrent() skipTree() @@ -741,7 +741,7 @@ class TreeUnpickler(reader: TastyReader, /** Create symbols for all type and value parameters of template starting * at current address. */ - def indexTemplateParams()(implicit ctx: Context): Unit = { + def indexTemplateParams()(using Context): Unit = { assert(readByte() == TEMPLATE) readEnd() indexParams(TYPEPARAM) @@ -751,7 +751,7 @@ class TreeUnpickler(reader: TastyReader, /** If definition was already read by a completer, return the previously read tree * or else read definition. */ - def readIndexedDef()(implicit ctx: Context): Tree = treeAtAddr.remove(currentAddr) match { + def readIndexedDef()(using Context): Tree = treeAtAddr.remove(currentAddr) match { case Some(tree) => assert(tree != PoisonTree, s"Cyclic reference while unpickling definition at address ${currentAddr.index} in unit ${ctx.compilationUnit}") skipTree() @@ -764,15 +764,15 @@ class TreeUnpickler(reader: TastyReader, tree } - private def readNewDef()(implicit ctx: Context): Tree = { + private def readNewDef()(using Context): Tree = { val sctx = sourceChangeContext() - if (sctx `ne` ctx) return readNewDef()(sctx) + if (sctx `ne` ctx) return readNewDef()(using sctx) val start = currentAddr val sym = symAtAddr(start) val tag = readByte() val end = readEnd() - def readParamss(implicit ctx: Context): List[List[ValDef]] = nextByte match + def readParamss(using Context): List[List[ValDef]] = nextByte match case PARAM | PARAMEND => readParams[ValDef](PARAM) :: (if nextByte == PARAMEND then { readByte(); readParamss } else Nil) @@ -781,24 +781,24 @@ class TreeUnpickler(reader: TastyReader, val localCtx = localContext(sym) - def readRhs(implicit ctx: Context): LazyTree = + def readRhs(using Context): LazyTree = if (nothingButMods(end)) EmptyTree else if sym.isInlineMethod && !sym.is(Deferred) then // The body of an inline method is stored in an annotation, so no need to unpickle it again new Trees.Lazy[Tree] { - def complete(implicit ctx: Context) = typer.Inliner.bodyToInline(sym) + def complete(using Context) = typer.Inliner.bodyToInline(sym) } else readLater(end, rdr => implicit ctx => rdr.readTerm()) def ValDef(tpt: Tree) = - ta.assignType(untpd.ValDef(sym.name.asTermName, tpt, readRhs(localCtx)), sym) + ta.assignType(untpd.ValDef(sym.name.asTermName, tpt, readRhs(using localCtx)), sym) def DefDef(tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree) = sym.setParamssFromDefs(tparams, vparamss) ta.assignType( - untpd.DefDef(sym.name.asTermName, tparams, vparamss, tpt, readRhs(localCtx)), + untpd.DefDef(sym.name.asTermName, tparams, vparamss, tpt, readRhs(using localCtx)), sym) def TypeDef(rhs: Tree) = @@ -810,9 +810,9 @@ class TreeUnpickler(reader: TastyReader, pickling.println(s"reading def of $name at $start") val tree: MemberDef = tag match { case DEFDEF => - val tparams = readParams[TypeDef](TYPEPARAM)(localCtx) - val vparamss = readParamss(localCtx) - val tpt = readTpt()(localCtx) + val tparams = readParams[TypeDef](TYPEPARAM)(using localCtx) + val vparamss = readParamss(using localCtx) + val tpt = readTpt()(using localCtx) val typeParams = tparams.map(_.symbol) val valueParamss = ctx.normalizeIfConstructor( vparamss.nestedMap(_.symbol), name == nme.CONSTRUCTOR) @@ -820,7 +820,7 @@ class TreeUnpickler(reader: TastyReader, sym.info = ctx.methodType(typeParams, valueParamss, resType) DefDef(tparams, vparamss, tpt) case VALDEF => - val tpt = readTpt()(localCtx) + val tpt = readTpt()(using localCtx) sym.info = tpt.tpe ValDef(tpt) case TYPEDEF | TYPEPARAM => @@ -835,14 +835,14 @@ class TreeUnpickler(reader: TastyReader, def isCodefined = roots.contains(companion.denot) == seenRoots.contains(companion) if (companion.exists && isCodefined) sym.registerCompanion(companion) - TypeDef(readTemplate(localCtx)) + TypeDef(readTemplate(using localCtx)) } else { sym.info = TypeBounds.empty // needed to avoid cyclic references when unpickling rhs, see i3816.scala sym.setFlag(Provisional) - val rhs = readTpt()(localCtx) + val rhs = readTpt()(using localCtx) sym.info = new NoCompleter { - override def completerTypeParams(sym: Symbol)(implicit ctx: Context) = + override def completerTypeParams(sym: Symbol)(using Context) = rhs.tpe.typeParams } sym.info = sym.opaqueToBounds( @@ -856,7 +856,7 @@ class TreeUnpickler(reader: TastyReader, TypeDef(rhs) } case PARAM => - val tpt = readTpt()(localCtx) + val tpt = readTpt()(using localCtx) if (nothingButMods(end)) { sym.info = tpt.tpe ValDef(tpt) @@ -884,7 +884,7 @@ class TreeUnpickler(reader: TastyReader, tree.setDefTree } - private def readTemplate(implicit ctx: Context): Template = { + private def readTemplate(using Context): Template = { val start = currentAddr assert(sourcePathAt(start).isEmpty) val cls = ctx.owner.asClass @@ -908,8 +908,8 @@ class TreeUnpickler(reader: TastyReader, } val parents = collectWhile(nextByte != SELFDEF && nextByte != DEFDEF) { nextUnsharedTag match { - case APPLY | TYPEAPPLY | BLOCK => readTerm()(parentCtx) - case _ => readTpt()(parentCtx) + case APPLY | TYPEAPPLY | BLOCK => readTerm()(using parentCtx) + case _ => readTpt()(using parentCtx) } } val parentTypes = parents.map(_.tpe.dealias) @@ -936,17 +936,17 @@ class TreeUnpickler(reader: TastyReader, .withType(localDummy.termRef)) } - def skipToplevel()(implicit ctx: Context): Unit= { + def skipToplevel()(using Context): Unit= { if (!isAtEnd && isTopLevel) { skipTree() skipToplevel() } } - def isTopLevel(implicit ctx: Context): Boolean = + def isTopLevel(using Context): Boolean = nextByte == IMPORT || nextByte == PACKAGE - def readTopLevel()(implicit ctx: Context): List[Tree] = { + def readTopLevel()(using Context): List[Tree] = { @tailrec def read(acc: ListBuffer[Tree]): List[Tree] = if (isTopLevel) { acc += readIndexedStat(NoSymbol) @@ -957,7 +957,7 @@ class TreeUnpickler(reader: TastyReader, read(new ListBuffer[tpd.Tree]) } - def readIndexedStat(exprOwner: Symbol)(implicit ctx: Context): Tree = nextByte match { + def readIndexedStat(exprOwner: Symbol)(using Context): Tree = nextByte match { case TYPEDEF | VALDEF | DEFDEF => readIndexedDef() case IMPORT => @@ -965,13 +965,13 @@ class TreeUnpickler(reader: TastyReader, case PACKAGE => val start = currentAddr processPackage { (pid, end) => implicit ctx => - setSpan(start, PackageDef(pid, readIndexedStats(exprOwner, end)(ctx))) + setSpan(start, PackageDef(pid, readIndexedStats(exprOwner, end)(using ctx))) } case _ => readTerm()(using ctx.withOwner(exprOwner)) } - def readImport()(implicit ctx: Context): Tree = { + def readImport()(using Context): Tree = { val start = currentAddr assert(sourcePathAt(start).isEmpty) readByte() @@ -981,7 +981,7 @@ class TreeUnpickler(reader: TastyReader, val expr = readTerm() setSpan(start, Import(expr, readSelectors(importGiven))) } - def readSelectors(givenPrefix: Boolean)(implicit ctx: Context): List[untpd.ImportSelector] = + def readSelectors(givenPrefix: Boolean)(using Context): List[untpd.ImportSelector] = if nextByte == IMPORTED then val start = currentAddr assert(sourcePathAt(start).isEmpty) @@ -1006,18 +1006,18 @@ class TreeUnpickler(reader: TastyReader, else Nil - def readIndexedStats(exprOwner: Symbol, end: Addr)(implicit ctx: Context): List[Tree] = + def readIndexedStats(exprOwner: Symbol, end: Addr)(using Context): List[Tree] = until(end)(readIndexedStat(exprOwner)) - def readStats(exprOwner: Symbol, end: Addr)(implicit ctx: Context): List[Tree] = { + def readStats(exprOwner: Symbol, end: Addr)(using Context): List[Tree] = { fork.indexStats(end) readIndexedStats(exprOwner, end) } - def readIndexedParams[T <: MemberDef](tag: Int)(implicit ctx: Context): List[T] = + def readIndexedParams[T <: MemberDef](tag: Int)(using Context): List[T] = collectWhile(nextByte == tag) { readIndexedDef().asInstanceOf[T] } - def readParams[T <: MemberDef](tag: Int)(implicit ctx: Context): List[T] = + def readParams[T <: MemberDef](tag: Int)(using Context): List[T] = if nextByte == tag then fork.indexParams(tag) readIndexedParams(tag) @@ -1025,9 +1025,9 @@ class TreeUnpickler(reader: TastyReader, // ------ Reading trees ----------------------------------------------------- - def readTerm()(implicit ctx: Context): Tree = { // TODO: rename to readTree + def readTerm()(using Context): Tree = { // TODO: rename to readTree val sctx = sourceChangeContext() - if (sctx `ne` ctx) return readTerm()(sctx) + if (sctx `ne` ctx) return readTerm()(using sctx) val start = currentAddr val tag = readByte() pickling.println(s"reading term ${astTagToString(tag)} at $start, ${ctx.source}") @@ -1207,7 +1207,7 @@ class TreeUnpickler(reader: TastyReader, registerSym(start, refineCls) typeAtAddr(start) = refineCls.typeRef val parent = readTpt() - val refinements = readStats(refineCls, end)(localContext(refineCls)) + val refinements = readStats(refineCls, end)(using localContext(refineCls)) RefinedTypeTree(parent, refinements, refineCls) case APPLIEDtpt => // If we do directly a tpd.AppliedType tree we might get a @@ -1254,9 +1254,9 @@ class TreeUnpickler(reader: TastyReader, setSpan(start, tree) } - def readTpt()(implicit ctx: Context): Tree = { + def readTpt()(using Context): Tree = { val sctx = sourceChangeContext() - if (sctx `ne` ctx) return readTpt()(sctx) + if (sctx `ne` ctx) return readTpt()(using sctx) val start = currentAddr val tree = nextByte match { case SHAREDterm => @@ -1288,7 +1288,7 @@ class TreeUnpickler(reader: TastyReader, setSpan(start, tree) } - def readCases(end: Addr)(implicit ctx: Context): List[CaseDef] = + def readCases(end: Addr)(using Context): List[CaseDef] = collectWhile((nextUnsharedTag == CASEDEF) && currentAddr != end) { if (nextByte == SHAREDterm) { readByte() @@ -1297,9 +1297,9 @@ class TreeUnpickler(reader: TastyReader, else readCase()(using ctx.fresh.setNewScope) } - def readCase()(implicit ctx: Context): CaseDef = { + def readCase()(using Context): CaseDef = { val sctx = sourceChangeContext() - if (sctx `ne` ctx) return readCase()(sctx) + if (sctx `ne` ctx) return readCase()(using sctx) val start = currentAddr assert(readByte() == CASEDEF) val end = readEnd() @@ -1309,10 +1309,10 @@ class TreeUnpickler(reader: TastyReader, setSpan(start, CaseDef(pat, guard, rhs)) } - def readLater[T <: AnyRef](end: Addr, op: TreeReader => Context => T)(implicit ctx: Context): Trees.Lazy[T] = - readLaterWithOwner(end, op)(ctx)(ctx.owner) + 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)(implicit ctx: 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) @@ -1321,7 +1321,7 @@ class TreeUnpickler(reader: TastyReader, // ------ Setting positions ------------------------------------------------ /** Pickled span for `addr`. */ - def spanAt(addr: Addr)(implicit ctx: Context): Span = + def spanAt(addr: Addr)(using Context): Span = if (ctx.mode.is(Mode.ReadPositions)) posUnpicklerOpt match { case Some(posUnpickler) => @@ -1332,7 +1332,7 @@ class TreeUnpickler(reader: TastyReader, else NoSpan /** Coordinate for the symbol at `addr`. */ - def coordAt(addr: Addr)(implicit ctx: Context): Coord = { + def coordAt(addr: Addr)(using Context): Coord = { val span = spanAt(addr) if (span.exists) spanCoord(span) @@ -1341,7 +1341,7 @@ class TreeUnpickler(reader: TastyReader, } /** Pickled source path at `addr`. */ - def sourcePathAt(addr: Addr)(implicit ctx: Context): String = + def sourcePathAt(addr: Addr)(using Context): String = if (ctx.mode.is(Mode.ReadPositions)) posUnpicklerOpt match { case Some(posUnpickler) => @@ -1354,7 +1354,7 @@ class TreeUnpickler(reader: TastyReader, /** If currentAddr carries a source path, the current context with * the source of that path, otherwise the current context itself. */ - def sourceChangeContext(addr: Addr = currentAddr)(implicit ctx: Context): Context = { + def sourceChangeContext(addr: Addr = currentAddr)(using Context): Context = { val path = sourcePathAt(addr) if (path.nonEmpty) { pickling.println(i"source change at $addr: $path") @@ -1364,7 +1364,7 @@ class TreeUnpickler(reader: TastyReader, } /** Set position of `tree` at given `addr`. */ - def setSpan[T <: untpd.Tree](addr: Addr, tree: T)(implicit ctx: Context): tree.type = { + def setSpan[T <: untpd.Tree](addr: Addr, tree: T)(using Context): tree.type = { val span = spanAt(addr) if (span.exists) tree.span = span tree @@ -1374,7 +1374,7 @@ class TreeUnpickler(reader: TastyReader, class LazyReader[T <: AnyRef]( reader: TreeReader, owner: Symbol, mode: Mode, source: SourceFile, op: TreeReader => Context => T) extends Trees.Lazy[T] { - def complete(implicit ctx: Context): T = { + def complete(using Context): T = { pickling.println(i"starting to read at ${reader.reader.currentAddr} with owner $owner") op(reader)(ctx .withPhaseNoLater(ctx.picklerPhase) @@ -1411,7 +1411,7 @@ class TreeUnpickler(reader: TastyReader, } /** Find the owner of definition at `addr` */ - def findOwner(addr: Addr)(implicit ctx: Context): Symbol = { + def findOwner(addr: Addr)(using Context): Symbol = { def search(cs: List[OwnerTree], current: Symbol): Symbol = try cs match { case ot :: cs1 => diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index c71f1b942591..72890bc0b259 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -44,7 +44,7 @@ object Scala2Unpickler { case class TempClassInfoType(parentTypes: List[Type], decls: Scope, clazz: Symbol) extends UncachedGroundType /** Convert temp poly type to poly type and leave other types alone. */ - def translateTempPoly(tp: Type)(implicit ctx: Context): Type = tp match { + def translateTempPoly(tp: Type)(using Context): Type = tp match { case TempPolyType(tparams, restpe) => // This check used to read `owner.isTerm` but that wasn't always correct, // I'm not sure `owner.is(Method)` is 100% correct either but it seems to @@ -55,7 +55,7 @@ object Scala2Unpickler { case tp => tp } - def addConstructorTypeParams(denot: SymDenotation)(implicit ctx: Context): Unit = { + def addConstructorTypeParams(denot: SymDenotation)(using Context): Unit = { assert(denot.isConstructor) denot.info = PolyType.fromParams(denot.owner.typeParams, denot.info) } @@ -63,7 +63,7 @@ object Scala2Unpickler { /** Convert array parameters denoting a repeated parameter of a Java method * to `RepeatedParamClass` types. */ - def arrayToRepeated(tp: Type)(implicit ctx: Context): Type = tp match { + def arrayToRepeated(tp: Type)(using Context): Type = tp match { case tp: MethodType => val lastArg = tp.paramInfos.last assert(lastArg isRef defn.ArrayClass) @@ -75,7 +75,7 @@ object Scala2Unpickler { tp.derivedLambdaType(tp.paramNames, tp.paramInfos, arrayToRepeated(tp.resultType)) } - def ensureConstructor(cls: ClassSymbol, scope: Scope)(implicit ctx: Context): Unit = { + def ensureConstructor(cls: ClassSymbol, scope: Scope)(using Context): Unit = { if (scope.lookup(nme.CONSTRUCTOR) == NoSymbol) { val constr = ctx.newDefaultConstructor(cls) addConstructorTypeParams(constr) @@ -83,7 +83,7 @@ object Scala2Unpickler { } } - def setClassInfo(denot: ClassDenotation, info: Type, fromScala2: Boolean, selfInfo: Type = NoType)(implicit ctx: Context): Unit = { + def setClassInfo(denot: ClassDenotation, info: Type, fromScala2: Boolean, selfInfo: Type = NoType)(using Context): Unit = { val cls = denot.classSymbol val (tparams, TempClassInfoType(parents, decls, clazz)) = info match { case TempPolyType(tps, cinfo) => (tps, cinfo) @@ -150,7 +150,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas val moduleRoot: SymDenotation = inContext(ictx) { moduleClassRoot.sourceModule.denot } assert(moduleRoot.isTerm) - checkVersion(ictx) + checkVersion(using ictx) private val loadingMirror = defn(using ictx) // was: mirrorThatLoaded(classRoot) @@ -166,7 +166,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas /** A mapping from method types to the parameters used in constructing them */ private val paramsOfMethodType = new java.util.IdentityHashMap[MethodType, List[Symbol]] - protected def errorBadSignature(msg: String, original: Option[RuntimeException] = None)(implicit ctx: Context): Nothing = { + protected def errorBadSignature(msg: String, original: Option[RuntimeException] = None)(using Context): Nothing = { val ex = new BadSignature( i"""error reading Scala signature of $classRoot from $source: |error occurred at position $readIndex: $msg""") @@ -174,12 +174,12 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas throw ex } - protected def handleRuntimeException(ex: RuntimeException)(implicit ctx: Context): Nothing = ex match { + protected def handleRuntimeException(ex: RuntimeException)(using Context): Nothing = ex match { case ex: BadSignature => throw ex case _ => errorBadSignature(s"a runtime exception occurred: $ex", Some(ex)) } - def run()(implicit ctx: Context): Unit = + def run()(using Context): Unit = try { var i = 0 while (i < index.length) { @@ -221,12 +221,12 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas case ex: RuntimeException => handleRuntimeException(ex) } - def source(implicit ctx: Context): AbstractFile = { + def source(using Context): AbstractFile = { val f = classRoot.symbol.associatedFile if (f != null) f else moduleClassRoot.symbol.associatedFile } - private def checkVersion(implicit ctx: Context): Unit = { + private def checkVersion(using Context): Unit = { val major = readNat() val minor = readNat() if (major != MajorVersion || minor > MinorVersion) @@ -241,7 +241,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas protected def symScope(sym: Symbol): Scope = symScopes.getOrElseUpdate(sym, newScope) /** Does entry represent an (internal) symbol */ - protected def isSymbolEntry(i: Int)(implicit ctx: Context): Boolean = { + protected def isSymbolEntry(i: Int)(using Context): Boolean = { val tag = bytes(index(i)).toInt (firstSymTag <= tag && tag <= lastSymTag && (tag != CLASSsym || !isRefinementSymbolEntry(i))) @@ -274,7 +274,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas /** Does entry represent a refinement symbol? * pre: Entry is a class symbol */ - protected def isRefinementSymbolEntry(i: Int)(implicit ctx: Context): Boolean = { + protected def isRefinementSymbolEntry(i: Int)(using Context): Boolean = { val savedIndex = readIndex readIndex = index(i) val tag = readByte().toInt @@ -286,12 +286,12 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas result } - protected def isRefinementClass(sym: Symbol)(implicit ctx: Context): Boolean = + protected def isRefinementClass(sym: Symbol)(using Context): Boolean = sym.name == tpnme.REFINE_CLASS - protected def isLocal(sym: Symbol)(implicit ctx: Context): Boolean = isUnpickleRoot(sym.topLevelClass) + protected def isLocal(sym: Symbol)(using Context): Boolean = isUnpickleRoot(sym.topLevelClass) - protected def isUnpickleRoot(sym: Symbol)(implicit ctx: Context): Boolean = { + protected def isUnpickleRoot(sym: Symbol)(using Context): Boolean = { val d = sym.denot d == moduleRoot || d == moduleClassRoot || d == classRoot } @@ -318,7 +318,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } /** Read a name */ - protected def readName()(implicit ctx: Context): Name = { + protected def readName()(using Context): Name = { val tag = readByte() val len = readNat() tag match { @@ -327,14 +327,14 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas case _ => errorBadSignature("bad name tag: " + tag) } } - protected def readTermName()(implicit ctx: Context): TermName = readName().toTermName - protected def readTypeName()(implicit ctx: Context): TypeName = readName().toTypeName + protected def readTermName()(using Context): TermName = readName().toTermName + protected def readTypeName()(using Context): TypeName = readName().toTypeName /** Read a symbol */ - protected def readSymbol()(implicit ctx: Context): Symbol = readDisambiguatedSymbol(alwaysTrue)() + protected def readSymbol()(using Context): Symbol = readDisambiguatedSymbol(alwaysTrue)() /** Read a symbol, with possible disambiguation */ - protected def readDisambiguatedSymbol(p: Symbol => Boolean)()(implicit ctx: Context): Symbol = { + protected def readDisambiguatedSymbol(p: Symbol => Boolean)()(using Context): Symbol = { val start = indexCoord(readIndex) val tag = readByte() val end = readNat() + readIndex @@ -559,8 +559,8 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas if params == null then rest else params :: rest case _ => Nil - def complete(denot: SymDenotation)(implicit ctx: Context): Unit = try { - def parseToCompletion(denot: SymDenotation)(implicit ctx: Context) = { + def complete(denot: SymDenotation)(using Context): Unit = try { + def parseToCompletion(denot: SymDenotation)(using Context) = { val tag = readByte() val end = readNat() + readIndex def atEnd = readIndex == end @@ -608,7 +608,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } atReadPos(startCoord(denot).toIndex, () => parseToCompletion(denot)( - ctx.addMode(Mode.Scala2Unpickling).withPhaseNoLater(ctx.picklerPhase))) + using ctx.addMode(Mode.Scala2Unpickling).withPhaseNoLater(ctx.picklerPhase))) } catch { case ex: RuntimeException => handleRuntimeException(ex) @@ -618,7 +618,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas object localMemberUnpickler extends LocalUnpickler class ClassUnpickler(infoRef: Int) extends LocalUnpickler with TypeParamsCompleter { - private def readTypeParams()(implicit ctx: Context): List[TypeSymbol] = { + private def readTypeParams()(using Context): List[TypeSymbol] = { val tag = readByte() val end = readNat() + readIndex if (tag == POLYtpe) { @@ -627,13 +627,13 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } else Nil } - private def loadTypeParams(implicit ctx: Context) = + private def loadTypeParams(using Context) = atReadPos(index(infoRef), () => readTypeParams()(using ctx)) /** Force reading type params early, we need them in setClassInfo of subclasses. */ - def init()(implicit ctx: Context): List[TypeSymbol] = loadTypeParams + def init()(using Context): List[TypeSymbol] = loadTypeParams - override def completerTypeParams(sym: Symbol)(implicit ctx: Context): List[TypeSymbol] = + override def completerTypeParams(sym: Symbol)(using Context): List[TypeSymbol] = loadTypeParams } @@ -651,7 +651,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas * to * tp { name: T } */ - def elimExistentials(boundSyms: List[Symbol], tp: Type)(implicit ctx: Context): Type = { + def elimExistentials(boundSyms: List[Symbol], tp: Type)(using Context): Type = { // Need to be careful not to run into cyclic references here (observed when // compiling t247.scala). That's why we avoid taking `symbol` of a TypeRef // unless names match up. @@ -713,7 +713,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas * Package references should be TermRefs or ThisTypes but it was observed that * nsc sometimes pickles them as TypeRefs instead. */ - private def readPrefix()(implicit ctx: Context): Type = readTypeRef() match { + private def readPrefix()(using Context): Type = readTypeRef() match { case pre: TypeRef if pre.symbol.is(Package) => pre.symbol.thisType case pre => pre } @@ -724,7 +724,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas * the flag say that a type of kind * is expected, so that PolyType(tps, restpe) can be disambiguated to PolyType(tps, NullaryMethodType(restpe)) * (if restpe is not a ClassInfoType, a MethodType or a NullaryMethodType, which leaves TypeRef/SingletonType -- the latter would make the polytype a type constructor) */ - protected def readType()(implicit ctx: Context): Type = { + protected def readType()(using Context): Type = { val tag = readByte() val end = readNat() + readIndex (tag: @switch) match { @@ -816,7 +816,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } } - def readTypeParams()(implicit ctx: Context): List[Symbol] = { + def readTypeParams()(using Context): List[Symbol] = { val tag = readByte() val end = readNat() + readIndex if (tag == POLYtpe) { @@ -826,11 +826,11 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas else Nil } - def noSuchTypeTag(tag: Int, end: Int)(implicit ctx: Context): Type = + def noSuchTypeTag(tag: Int, end: Int)(using Context): Type = errorBadSignature("bad type tag: " + tag) /** Read a constant */ - protected def readConstant()(implicit ctx: Context): Constant = { + protected def readConstant()(using Context): Constant = { val tag = readByte().toInt val len = readNat() (tag: @switch) match { @@ -851,12 +851,12 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } } - def noSuchConstantTag(tag: Int, len: Int)(implicit ctx: Context): Constant = + def noSuchConstantTag(tag: Int, len: Int)(using Context): Constant = errorBadSignature("bad constant tag: " + tag) /** Read children and store them into the corresponding symbol. */ - protected def readChildren()(implicit ctx: Context): Unit = { + protected def readChildren()(using Context): Unit = { val tag = readByte() assert(tag == CHILDREN) val end = readNat() + readIndex @@ -870,7 +870,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } /* Read a reference to a pickled item */ - protected def readSymbolRef()(implicit ctx: Context): Symbol = { //OPT inlined from: at(readNat(), readSymbol) to save on closure creation + protected def readSymbolRef()(using Context): Symbol = { //OPT inlined from: at(readNat(), readSymbol) to save on closure creation val i = readNat() var r = entries(i) if (r eq null) { @@ -884,32 +884,32 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas r.asInstanceOf[Symbol] } - protected def readDisambiguatedSymbolRef(p: Symbol => Boolean)(implicit ctx: Context): Symbol = + protected def readDisambiguatedSymbolRef(p: Symbol => Boolean)(using Context): Symbol = at(readNat(), () => readDisambiguatedSymbol(p)()) - protected def readNameRef()(implicit ctx: Context): Name = at(readNat(), () => readName()) - protected def readTypeRef()(implicit ctx: Context): Type = at(readNat(), () => readType()) // after the NMT_TRANSITION period, we can leave off the () => ... () - protected def readConstantRef()(implicit ctx: Context): Constant = at(readNat(), () => readConstant()) + protected def readNameRef()(using Context): Name = at(readNat(), () => readName()) + protected def readTypeRef()(using Context): Type = at(readNat(), () => readType()) // after the NMT_TRANSITION period, we can leave off the () => ... () + protected def readConstantRef()(using Context): Constant = at(readNat(), () => readConstant()) - protected def readTypeNameRef()(implicit ctx: Context): TypeName = readNameRef().toTypeName - protected def readTermNameRef()(implicit ctx: Context): TermName = readNameRef().toTermName + protected def readTypeNameRef()(using Context): TypeName = readNameRef().toTypeName + protected def readTermNameRef()(using Context): TermName = readNameRef().toTermName - protected def readAnnotationRef()(implicit ctx: Context): Annotation = at(readNat(), () => readAnnotation()) + protected def readAnnotationRef()(using Context): Annotation = at(readNat(), () => readAnnotation()) - protected def readModifiersRef(isType: Boolean)(implicit ctx: Context): Modifiers = at(readNat(), () => readModifiers(isType)) - protected def readTreeRef()(implicit ctx: Context): Tree = at(readNat(), () => readTree()) + protected def readModifiersRef(isType: Boolean)(using Context): Modifiers = at(readNat(), () => readModifiers(isType)) + protected def readTreeRef()(using Context): Tree = at(readNat(), () => readTree()) /** Read an annotation argument, which is pickled either * as a Constant or a Tree. */ - protected def readAnnotArg(i: Int)(implicit ctx: Context): Tree = bytes(index(i)) match { + protected def readAnnotArg(i: Int)(using Context): Tree = bytes(index(i)) match { case TREE => at(i, () => readTree()) case _ => Literal(at(i, () => readConstant())) } /** Read a ClassfileAnnotArg (argument to a classfile annotation) */ - private def readArrayAnnotArg()(implicit ctx: Context): Tree = { + private def readArrayAnnotArg()(using Context): Tree = { readByte() // skip the `annotargarray` tag val end = readNat() + readIndex // array elements are trees representing instances of scala.annotation.Annotation @@ -918,13 +918,13 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas TypeTree(defn.AnnotationClass.typeRef)) } - private def readAnnotInfoArg()(implicit ctx: Context): Tree = { + private def readAnnotInfoArg()(using Context): Tree = { readByte() // skip the `annotinfo` tag val end = readNat() + readIndex readAnnotationContents(end) } - protected def readClassfileAnnotArg(i: Int)(implicit ctx: Context): Tree = bytes(index(i)) match { + protected def readClassfileAnnotArg(i: Int)(using Context): Tree = bytes(index(i)) match { case ANNOTINFO => at(i, () => readAnnotInfoArg()) case ANNOTARGARRAY => at(i, () => readArrayAnnotArg()) case _ => readAnnotArg(i) @@ -933,7 +933,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas /** Read an annotation's contents. Not to be called directly, use * readAnnotation, readSymbolAnnotation, or readAnnotInfoArg */ - protected def readAnnotationContents(end: Int)(implicit ctx: Context): Tree = { + protected def readAnnotationContents(end: Int)(using Context): Tree = { val atp = readTypeRef() val args = { val t = new ListBuffer[Tree] @@ -958,7 +958,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas * the symbol it requests. Called at top-level, for all * (symbol, annotInfo) entries. */ - protected def readSymbolAnnotation()(implicit ctx: Context): Unit = { + protected def readSymbolAnnotation()(using Context): Unit = { val tag = readByte() if (tag != SYMANNOT) errorBadSignature("symbol annotation expected (" + tag + ")") @@ -970,7 +970,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas /** Read an annotation and return it. Used when unpickling * an ANNOTATED(WSELF)tpe or a NestedAnnotArg */ - protected def readAnnotation()(implicit ctx: Context): Annotation = { + protected def readAnnotation()(using Context): Annotation = { val tag = readByte() if (tag != ANNOTINFO) errorBadSignature("annotation expected (" + tag + ")") @@ -981,16 +981,16 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas /** A deferred annotation that can be completed by reading * the bytes between `readIndex` and `end`. */ - protected def deferredAnnot(end: Int)(implicit ctx: Context): Annotation = { + protected def deferredAnnot(end: Int)(using Context): Annotation = { val start = readIndex val atp = readTypeRef() val phase = ctx.phase Annotation.deferred(atp.typeSymbol)( - atReadPos(start, () => readAnnotationContents(end)(summon[Context].withPhase(phase)))) + atReadPos(start, () => readAnnotationContents(end)(using ctx.withPhase(phase)))) } /* Read an abstract syntax tree */ - protected def readTree()(implicit ctx: Context): Tree = { + protected def readTree()(using Context): Tree = { val outerTag = readByte() if (outerTag != TREE) errorBadSignature("tree expected (" + outerTag + ")") @@ -1258,13 +1258,13 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } } - def noSuchTreeTag(tag: Int, end: Int)(implicit ctx: Context): Nothing = + def noSuchTreeTag(tag: Int, end: Int)(using Context): Nothing = errorBadSignature("unknown tree type (" + tag + ")") - def unimplementedTree(what: String)(implicit ctx: Context): Nothing = + def unimplementedTree(what: String)(using Context): Nothing = errorBadSignature(s"cannot read $what trees from Scala 2.x signatures") - def readModifiers(isType: Boolean)(implicit ctx: Context): Modifiers = { + def readModifiers(isType: Boolean)(using Context): Modifiers = { val tag = readNat() if (tag != MODIFIERS) errorBadSignature("expected a modifiers tag (" + tag + ")") @@ -1277,31 +1277,31 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas Modifiers(flags, privateWithin, Nil) } - protected def readTemplateRef()(implicit ctx: Context): Template = + protected def readTemplateRef()(using Context): Template = readTreeRef() match { case templ: Template => templ case other => errorBadSignature("expected a template (" + other + ")") } - protected def readCaseDefRef()(implicit ctx: Context): CaseDef = + protected def readCaseDefRef()(using Context): CaseDef = readTreeRef() match { case tree: CaseDef => tree case other => errorBadSignature("expected a case def (" + other + ")") } - protected def readValDefRef()(implicit ctx: Context): ValDef = + protected def readValDefRef()(using Context): ValDef = readTreeRef() match { case tree: ValDef => tree case other => errorBadSignature("expected a ValDef (" + other + ")") } - protected def readIdentRef()(implicit ctx: Context): Ident = + protected def readIdentRef()(using Context): Ident = readTreeRef() match { case tree: Ident => tree case other => errorBadSignature("expected an Ident (" + other + ")") } - protected def readTypeDefRef()(implicit ctx: Context): TypeDef = + protected def readTypeDefRef()(using Context): TypeDef = readTreeRef() match { case tree: TypeDef => tree case other => From f76b9b6aa12281b81ea85b9238b130de59818b39 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 15:37:47 +0200 Subject: [PATCH 16/41] Convert ast classes --- .../tools/backend/sjs/JSPrimitives.scala | 2 +- compiler/src/dotty/tools/dotc/Bench.scala | 2 +- compiler/src/dotty/tools/dotc/Driver.scala | 2 +- compiler/src/dotty/tools/dotc/Resident.scala | 2 +- .../tools/dotc/ast/CheckTrees.scala.disabled | 8 +- .../src/dotty/tools/dotc/ast/Desugar.scala | 90 ++--- .../dotty/tools/dotc/ast/DesugarEnums.scala | 40 +- .../dotty/tools/dotc/ast/NavigateAST.scala | 10 +- .../src/dotty/tools/dotc/ast/Positioned.scala | 6 +- .../src/dotty/tools/dotc/ast/TreeInfo.scala | 94 ++--- .../tools/dotc/ast/TreeMapWithImplicits.scala | 18 +- .../dotty/tools/dotc/ast/TreeTypeMap.scala | 10 +- compiler/src/dotty/tools/dotc/ast/Trees.scala | 168 ++++---- compiler/src/dotty/tools/dotc/ast/tpd.scala | 360 +++++++++--------- compiler/src/dotty/tools/dotc/ast/untpd.scala | 106 +++--- .../dotc/classpath/ClassPathFactory.scala | 2 +- .../ZipAndJarFileLookupFactory.scala | 2 +- .../tools/dotc/config/ScalaSettings.scala | 2 +- .../src/dotty/tools/dotc/core/ParamInfo.scala | 2 +- .../tools/dotc/fromtasty/ReadTasty.scala | 2 +- .../tools/dotc/fromtasty/TastyFileUtil.scala | 2 +- .../tools/dotc/interactive/Interactive.scala | 2 +- .../tools/dotc/printing/Highlighting.scala | 2 +- .../dotty/tools/dotc/printing/Printers.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 +- .../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 | 2 +- .../dotty/tools/dotc/reporting/trace.scala | 2 +- .../dotty/tools/dotc/semanticdb/Scala3.scala | 2 +- .../tools/dotc/tastyreflect/FromSymbol.scala | 2 +- .../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/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 +- .../tools/dotc/transform/FirstTransform.scala | 2 +- .../transform/FunctionXXLForwarders.scala | 4 +- .../dotc/transform/GenericSignatures.scala | 2 +- .../dotty/tools/dotc/transform/Getters.scala | 2 +- .../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 +- .../tools/dotc/transform/MacroTransform.scala | 2 +- .../dotty/tools/dotc/transform/Memoize.scala | 2 +- .../dotty/tools/dotc/transform/Mixin.scala | 2 +- .../tools/dotc/transform/MoveStatics.scala | 2 +- .../dotty/tools/dotc/transform/Pickler.scala | 2 +- .../dotc/transform/ProtectedAccessors.scala | 2 +- .../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/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 +- .../dotty/tools/dotc/typer/Implicits.scala | 2 +- .../src/dotty/tools/dotc/typer/Inliner.scala | 6 +- .../dotty/tools/dotc/typer/ProtoTypes.scala | 2 +- .../src/dotty/tools/dotc/typer/Typer.scala | 6 +- .../dotty/tools/dotc/util/ParsedComment.scala | 2 +- .../dotty/tools/dotc/util/Signatures.scala | 2 +- .../dotty/tools/dotc/util/SourceFile.scala | 4 +- .../tools/repl/CollectTopLevelImports.scala | 2 +- .../src/dotty/tools/repl/JLineTerminal.scala | 2 +- compiler/src/dotty/tools/repl/Rendering.scala | 2 +- .../src/dotty/tools/repl/ReplFrontEnd.scala | 2 +- .../dotc/core/tasty/CommentPicklingTest.scala | 4 +- .../tools/dotc/parsing/DeSugarTest.scala | 2 +- 105 files changed, 556 insertions(+), 556 deletions(-) diff --git a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala index a5091517b598..214f617772f0 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala @@ -59,7 +59,7 @@ class JSPrimitives(ctx: Context) extends DottyPrimitives(ctx) { jsPrimitives.getOrElse(app.fun.symbol, super.getPrimitive(app, tpe)) override def isPrimitive(fun: Tree): Boolean = - jsPrimitives.contains(fun.symbol(ctx)) || super.isPrimitive(fun) + jsPrimitives.contains(fun.symbol(using ctx)) || super.isPrimitive(fun) /** Initialize the primitive map */ private def initJSPrimitives(implicit ctx: Context): Map[Symbol, Int] = { diff --git a/compiler/src/dotty/tools/dotc/Bench.scala b/compiler/src/dotty/tools/dotc/Bench.scala index dfdbc9f2fc26..97c00108fc84 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 +import core.Contexts.{Context, ctx} import reporting.Reporter import scala.annotation.internal.sharable diff --git a/compiler/src/dotty/tools/dotc/Driver.scala b/compiler/src/dotty/tools/dotc/Driver.scala index 187203ee68de..bb88f1448826 100644 --- a/compiler/src/dotty/tools/dotc/Driver.scala +++ b/compiler/src/dotty/tools/dotc/Driver.scala @@ -70,7 +70,7 @@ class Driver { val summary = CompilerCommand.distill(args)(ictx) ictx.setSettings(summary.sstate) MacroClassLoader.init(ictx) - Positioned.updateDebugPos(ictx) + Positioned.updateDebugPos(using ictx) inContext(ictx) { if !ctx.settings.YdropComments.value || ctx.mode.is(Mode.ReadComments) then diff --git a/compiler/src/dotty/tools/dotc/Resident.scala b/compiler/src/dotty/tools/dotc/Resident.scala index 0b971dd05953..7ddae4ab9787 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 +import core.Contexts.{Context, ctx} import reporting.Reporter import java.io.EOFException import scala.annotation.tailrec diff --git a/compiler/src/dotty/tools/dotc/ast/CheckTrees.scala.disabled b/compiler/src/dotty/tools/dotc/ast/CheckTrees.scala.disabled index e05de4f5af4c..6eddf64fff15 100644 --- a/compiler/src/dotty/tools/dotc/ast/CheckTrees.scala.disabled +++ b/compiler/src/dotty/tools/dotc/ast/CheckTrees.scala.disabled @@ -11,14 +11,14 @@ object CheckTrees { import tpd._ - def check(p: Boolean, msg: => String = "")(implicit ctx: Context): Unit = assert(p, msg) + def check(p: Boolean, msg: => String = "")(using Context): Unit = assert(p, msg) - def checkTypeArg(arg: Tree, bounds: TypeBounds)(implicit ctx: Context): Unit = { + def checkTypeArg(arg: Tree, bounds: TypeBounds)(using Context): Unit = { check(arg.isValueType) check(bounds contains arg.tpe) } - def escapingRefs(block: Block)(implicit ctx: Context): collection.Set[NamedType] = { + def escapingRefs(block: Block)(using Context): collection.Set[NamedType] = { var hoisted: Set[Symbol] = Set() lazy val locals = ctx.typeAssigner.localSyms(block.stats).toSet def isLocal(sym: Symbol): Boolean = @@ -40,7 +40,7 @@ object CheckTrees { leakingTypes(block.tpe) } - def checkType(tree: Tree)(implicit ctx: Context): Unit = tree match { + def checkType(tree: Tree)(using Context): Unit = tree match { case Ident(name) => case Select(qualifier, name) => check(qualifier.isValue) diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index 7a0adf49e4ea..e96ef12f931a 100644 --- a/compiler/src/dotty/tools/dotc/ast/Desugar.scala +++ b/compiler/src/dotty/tools/dotc/ast/Desugar.scala @@ -53,28 +53,28 @@ object desugar { /** Is `name` the name of a method that can be invalidated as a compiler-generated * case class method if it clashes with a user-defined method? */ - def isRetractableCaseClassMethodName(name: Name)(implicit ctx: Context): Boolean = name match { + def isRetractableCaseClassMethodName(name: Name)(using Context): Boolean = name match { case nme.apply | nme.unapply | nme.unapplySeq | nme.copy => true case DefaultGetterName(nme.copy, _) => true case _ => false } /** Is `name` the name of a method that is added unconditionally to case classes? */ - def isDesugaredCaseClassMethodName(name: Name)(implicit ctx: Context): Boolean = + def isDesugaredCaseClassMethodName(name: Name)(using Context): Boolean = isRetractableCaseClassMethodName(name) || name.isSelectorName // ----- DerivedTypeTrees ----------------------------------- class SetterParamTree(implicit @constructorOnly src: SourceFile) extends DerivedTypeTree { - def derivedTree(sym: Symbol)(implicit ctx: Context): tpd.TypeTree = tpd.TypeTree(sym.info.resultType) + def derivedTree(sym: Symbol)(using Context): tpd.TypeTree = tpd.TypeTree(sym.info.resultType) } class TypeRefTree(implicit @constructorOnly src: SourceFile) extends DerivedTypeTree { - def derivedTree(sym: Symbol)(implicit ctx: Context): tpd.TypeTree = tpd.TypeTree(sym.typeRef) + def derivedTree(sym: Symbol)(using Context): tpd.TypeTree = tpd.TypeTree(sym.typeRef) } class TermRefTree(implicit @constructorOnly src: SourceFile) extends DerivedTypeTree { - def derivedTree(sym: Symbol)(implicit ctx: Context): tpd.Tree = tpd.ref(sym) + def derivedTree(sym: Symbol)(using Context): tpd.Tree = tpd.ref(sym) } /** A type tree that computes its type from an existing parameter. */ @@ -83,7 +83,7 @@ object desugar { /** Complete the appropriate constructors so that OriginalSymbol attachments are * pushed to DerivedTypeTrees. */ - override def ensureCompletions(implicit ctx: Context): Unit = { + override def ensureCompletions(using Context): Unit = { def completeConstructor(sym: Symbol) = sym.infoOrCompleter match { case completer: Namer#ClassCompleter => @@ -97,7 +97,7 @@ object desugar { if (ctx.owner.is(ModuleClass)) completeConstructor(ctx.owner.linkedClass) } - else ensureCompletions(ctx.outer) + else ensureCompletions(using ctx.outer) } /** Return info of original symbol, where all references to siblings of the @@ -109,7 +109,7 @@ object desugar { * accessor of a type parameter is a private type alias that cannot be accessed * from subclasses. */ - def derivedTree(sym: Symbol)(implicit ctx: Context): tpd.TypeTree = { + def derivedTree(sym: Symbol)(using Context): tpd.TypeTree = { val relocate = new TypeMap { val originalOwner = sym.owner def apply(tp: Type) = tp match { @@ -131,17 +131,17 @@ object desugar { } /** A type definition copied from `tdef` with a rhs typetree derived from it */ - def derivedTypeParam(tdef: TypeDef)(implicit ctx: Context): TypeDef = + def derivedTypeParam(tdef: TypeDef)(using Context): TypeDef = cpy.TypeDef(tdef)( rhs = DerivedFromParamTree().withSpan(tdef.rhs.span).watching(tdef) ) /** A derived type definition watching `sym` */ - def derivedTypeParam(sym: TypeSymbol)(implicit ctx: Context): TypeDef = + def derivedTypeParam(sym: TypeSymbol)(using Context): TypeDef = TypeDef(sym.name, DerivedFromParamTree().watching(sym)).withFlags(TypeParam) /** A value definition copied from `vdef` with a tpt typetree derived from it */ - def derivedTermParam(vdef: ValDef)(implicit ctx: Context): ValDef = + def derivedTermParam(vdef: ValDef)(using Context): ValDef = cpy.ValDef(vdef)( tpt = DerivedFromParamTree().withSpan(vdef.tpt.span).watching(vdef)) @@ -157,7 +157,7 @@ object desugar { * - all trait members * - all package object members */ - def valDef(vdef0: ValDef)(implicit ctx: Context): Tree = { + def valDef(vdef0: ValDef)(using Context): Tree = { val vdef @ ValDef(name, tpt, rhs) = vdef0 val mods = vdef.mods val setterNeeded = @@ -184,7 +184,7 @@ object desugar { else vdef } - def makeImplicitParameters(tpts: List[Tree], implicitFlag: FlagSet, forPrimaryConstructor: Boolean = false)(implicit ctx: Context): List[ValDef] = + def makeImplicitParameters(tpts: List[Tree], implicitFlag: FlagSet, forPrimaryConstructor: Boolean = false)(using Context): List[ValDef] = for (tpt <- tpts) yield { val paramFlags: FlagSet = if (forPrimaryConstructor) LocalParamAccessor else Param val epname = EvidenceParamName.fresh() @@ -205,7 +205,7 @@ object desugar { * def f$default$1[T] = 1 * def f$default$2[T](x: Int) = x + "m" */ - private def defDef(meth0: DefDef, isPrimaryConstructor: Boolean = false)(implicit ctx: Context): Tree = { + private def defDef(meth0: DefDef, isPrimaryConstructor: Boolean = false)(using Context): Tree = { val meth @ DefDef(_, tparams, vparamss, tpt, rhs) = meth0 val methName = normalizeName(meth, tpt).asTermName val mods = meth.mods @@ -291,7 +291,7 @@ object desugar { * * Note that the splice `$t: T` will be typed as `${t: Expr[T]}` */ - def quotedPattern(tree: untpd.Tree, expectedTpt: untpd.Tree)(implicit ctx: Context): untpd.Tree = { + def quotedPattern(tree: untpd.Tree, expectedTpt: untpd.Tree)(using Context): untpd.Tree = { def adaptToExpectedTpt(tree: untpd.Tree): untpd.Tree = tree match { // Add the expected type as an ascription case _: untpd.Splice => @@ -320,7 +320,7 @@ object desugar { } // Add all evidence parameters in `params` as implicit parameters to `meth` */ - private def addEvidenceParams(meth: DefDef, params: List[ValDef])(implicit ctx: Context): DefDef = + private def addEvidenceParams(meth: DefDef, params: List[ValDef])(using Context): DefDef = params match { case Nil => meth @@ -335,7 +335,7 @@ object desugar { } /** The implicit evidence parameters of `meth`, as generated by `desugar.defDef` */ - private def evidenceParams(meth: DefDef)(implicit ctx: Context): List[ValDef] = + private def evidenceParams(meth: DefDef)(using Context): List[ValDef] = meth.vparamss.reverse match { case (vparams @ (vparam :: _)) :: _ if vparam.mods.isOneOf(GivenOrImplicit) => vparams.dropWhile(!_.name.is(EvidenceParamName)) @@ -358,7 +358,7 @@ object desugar { } /** The expansion of a class definition. See inline comments for what is involved */ - def classDef(cdef: TypeDef)(implicit ctx: Context): Tree = { + def classDef(cdef: TypeDef)(using Context): Tree = { val impl @ Template(constr0, _, self, _) = cdef.rhs val className = normalizeName(cdef, impl).asTypeName val parents = impl.parents @@ -820,7 +820,7 @@ object desugar { * object `package` { body } * } */ - def packageModuleDef(mdef: ModuleDef)(implicit ctx: Context): Tree = + def packageModuleDef(mdef: ModuleDef)(using Context): Tree = val impl = mdef.impl val mods = mdef.mods val moduleName = normalizeName(mdef, impl).asTermName @@ -852,7 +852,7 @@ object desugar { * See: collectiveExtensionBody * TODO: drop this part */ - def moduleDef(mdef: ModuleDef)(implicit ctx: Context): Tree = { + def moduleDef(mdef: ModuleDef)(using Context): Tree = { val impl = mdef.impl val mods = mdef.mods impl.constr match { @@ -972,7 +972,7 @@ object desugar { * * if the type is a type splice. */ - def quotedPatternTypeDef(tree: TypeDef)(implicit ctx: Context): TypeDef = { + def quotedPatternTypeDef(tree: TypeDef)(using Context): TypeDef = { assert(ctx.mode.is(Mode.QuotedPattern)) if (tree.name.startsWith("$") && !tree.isBackquoted) { val patternBindHoleAnnot = New(ref(defn.InternalQuotedMatcher_patternTypeAnnot.typeRef)).withSpan(tree.span) @@ -989,7 +989,7 @@ object desugar { * method is an extension method. * 3. If the name is missing (this can be the case for instance definitions), invent one instead. */ - def normalizeName(mdef: MemberDef, impl: Tree)(implicit ctx: Context): Name = { + def normalizeName(mdef: MemberDef, impl: Tree)(using Context): Name = { var name = mdef.name if (name.isEmpty) name = name.likeSpaced(inventGivenOrExtensionName(impl)) def errPos = mdef.source.atSpan(mdef.nameSpan) @@ -1025,9 +1025,9 @@ object desugar { str.toTermName.asSimpleName private class NameExtractor(followArgs: Boolean) extends UntypedTreeAccumulator[String] { - private def extractArgs(args: List[Tree])(implicit ctx: Context): String = + private def extractArgs(args: List[Tree])(using Context): String = args.map(argNameExtractor.apply("", _)).mkString("_") - override def apply(x: String, tree: Tree)(implicit ctx: Context): String = + override def apply(x: String, tree: Tree)(using Context): String = if (x.isEmpty) tree match { case Select(pre, nme.CONSTRUCTOR) => foldOver(x, pre) @@ -1048,7 +1048,7 @@ object desugar { private val typeNameExtractor = NameExtractor(followArgs = true) private val argNameExtractor = NameExtractor(followArgs = false) - private def inventTypeName(tree: Tree)(implicit ctx: Context): String = typeNameExtractor("", tree) + private def inventTypeName(tree: Tree)(using Context): String = typeNameExtractor("", tree) /** val p1, ..., pN: T = E * ==> @@ -1058,7 +1058,7 @@ object desugar { * ==> * expandSimpleEnumCase([case e1]); ...; expandSimpleEnumCase([case eN]) */ - def patDef(pdef: PatDef)(implicit ctx: Context): Tree = flatTree { + def patDef(pdef: PatDef)(using Context): Tree = flatTree { val PatDef(mods, pats, tpt, rhs) = pdef if (mods.isEnumCase) pats map { @@ -1080,7 +1080,7 @@ object desugar { * - IrrefutablePatDef, * IrrefutableGenFrom: sel @unchecked with attachment `CheckIrrefutable -> checkMode` */ - def makeSelector(sel: Tree, checkMode: MatchCheck)(implicit ctx: Context): Tree = + def makeSelector(sel: Tree, checkMode: MatchCheck)(using Context): Tree = if (checkMode == MatchCheck.Exhaustive) sel else { val sel1 = Annotated(sel, New(ref(defn.UncheckedAnnot.typeRef))) @@ -1103,7 +1103,7 @@ object desugar { * If the original pattern variable carries a type annotation, so does the corresponding * ValDef or DefDef. */ - def makePatDef(original: Tree, mods: Modifiers, pat: Tree, rhs: Tree)(implicit ctx: Context): Tree = pat match { + def makePatDef(original: Tree, mods: Modifiers, pat: Tree, rhs: Tree)(using Context): Tree = pat match { case IdPattern(named, tpt) => derivedValDef(original, named, tpt, rhs, mods) case _ => @@ -1161,7 +1161,7 @@ object desugar { } /** Expand variable identifier x to x @ _ */ - def patternVar(tree: Tree)(implicit ctx: Context): Bind = { + def patternVar(tree: Tree)(using Context): Bind = { val Ident(name) = unsplice(tree) Bind(name, Ident(nme.WILDCARD)).withSpan(tree.span) } @@ -1185,7 +1185,7 @@ object desugar { /** Check that modifiers are legal for the definition `tree`. * Right now, we only check for `opaque`. TODO: Move other modifier checks here. */ - def checkModifiers(tree: Tree)(implicit ctx: Context): Tree = tree match { + def checkModifiers(tree: Tree)(using Context): Tree = tree match { case tree: MemberDef => var tested: MemberDef = tree def checkApplicable(flag: Flag, test: MemberDefTest): Unit = @@ -1199,7 +1199,7 @@ object desugar { tree } - def defTree(tree: Tree)(implicit ctx: Context): Tree = + def defTree(tree: Tree)(using Context): Tree = checkModifiers(tree) match { case tree: ValDef => valDef(tree) case tree: TypeDef => @@ -1217,7 +1217,7 @@ object desugar { * ==> * { stats; () } */ - def block(tree: Block)(implicit ctx: Context): Block = tree.expr match { + def block(tree: Block)(using Context): Block = tree.expr match { case EmptyTree => cpy.Block(tree)(tree.stats, unitLiteral.withSpan(if (tree.stats.isEmpty) tree.span else tree.span.endPos)) @@ -1230,7 +1230,7 @@ object desugar { * l op r ==> l.op(r) if op is left-associative * ==> r.op(l) if op is right-associative */ - def binop(left: Tree, op: Ident, right: Tree)(implicit ctx: Context): Apply = { + def binop(left: Tree, op: Ident, right: Tree)(using Context): Apply = { def assignToNamedArg(arg: Tree) = arg match { case Assign(Ident(name), rhs) => cpy.NamedArg(arg)(name, rhs) case _ => arg @@ -1261,7 +1261,7 @@ object desugar { * (t) ==> t * (t1, ..., tN) ==> TupleN(t1, ..., tN) */ - def smallTuple(tree: Tuple)(implicit ctx: Context): Tree = { + def smallTuple(tree: Tuple)(using Context): Tree = { val ts = tree.trees val arity = ts.length assert(arity <= Definitions.MaxTupleArity) @@ -1299,7 +1299,7 @@ object desugar { * - "companion objects" of wrapped type definitions * (i.e. objects having the same name as a wrapped type) */ - def packageDef(pdef: PackageDef)(implicit ctx: Context): PackageDef = { + def packageDef(pdef: PackageDef)(using Context): PackageDef = { val wrappedTypeNames = pdef.stats.collect { case stat: TypeDef if isTopLevelDef(stat) => stat.name } @@ -1326,7 +1326,7 @@ object desugar { * def $anonfun(params) = body * Closure($anonfun) */ - def makeClosure(params: List[ValDef], body: Tree, tpt: Tree = null, isContextual: Boolean)(implicit ctx: Context): Block = + def makeClosure(params: List[ValDef], body: Tree, tpt: Tree = null, isContextual: Boolean)(using Context): Block = Block( DefDef(nme.ANON_FUN, Nil, params :: Nil, if (tpt == null) TypeTree() else tpt, body) .withMods(synthetic | Artifact), @@ -1342,7 +1342,7 @@ object desugar { * * (x$1, ..., x$n) => (x$0, ..., x${n-1} @unchecked?) match { cases } */ - def makeCaseLambda(cases: List[CaseDef], checkMode: MatchCheck, nparams: Int = 1)(implicit ctx: Context): Function = { + def makeCaseLambda(cases: List[CaseDef], checkMode: MatchCheck, nparams: Int = 1)(using Context): Function = { val params = (1 to nparams).toList.map(makeSyntheticParameter(_)) val selector = makeTuple(params.map(p => Ident(p.name))) Function(params, Match(makeSelector(selector, checkMode), cases)) @@ -1369,7 +1369,7 @@ object desugar { * If some of the Ti's are absent, omit the : (T1, ..., Tn) type ascription * in the selector. */ - def makeTupledFunction(params: List[ValDef], body: Tree, isGenericTuple: Boolean)(implicit ctx: Context): Tree = { + def makeTupledFunction(params: List[ValDef], body: Tree, isGenericTuple: Boolean)(using Context): Tree = { val param = makeSyntheticParameter( tpt = if params.exists(_.tpt.isEmpty) then TypeTree() @@ -1385,7 +1385,7 @@ object desugar { Function(param :: Nil, Block(vdefs, body)) } - def makeContextualFunction(formals: List[Tree], body: Tree, isErased: Boolean)(implicit ctx: Context): Function = { + def makeContextualFunction(formals: List[Tree], body: Tree, isErased: Boolean)(using Context): Function = { val mods = if (isErased) Given | Erased else Given val params = makeImplicitParameters(formals, mods) FunctionWithMods(params, body, Modifiers(mods)) @@ -1400,7 +1400,7 @@ object desugar { * following `fullName`. This is necessary so that we avoid reading an annotation from * the classpath that is also compiled from source. */ - def makeAnnotated(fullName: String, tree: Tree)(implicit ctx: Context): Annotated = { + def makeAnnotated(fullName: String, tree: Tree)(using Context): Annotated = { val parts = fullName.split('.') val ttree = ctx.typerPhase match { case phase: FrontEnd if phase.stillToBeEntered(parts.last) => @@ -1414,7 +1414,7 @@ object desugar { Annotated(tree, New(ttree, Nil)) } - private def derivedValDef(original: Tree, named: NameTree, tpt: Tree, rhs: Tree, mods: Modifiers)(implicit ctx: Context) = { + private def derivedValDef(original: Tree, named: NameTree, tpt: Tree, rhs: Tree, mods: Modifiers)(using Context) = { val vdef = ValDef(named.name.asTermName, tpt, rhs) .withMods(mods) .withSpan(original.span.withPoint(named.span.start)) @@ -1428,7 +1428,7 @@ object desugar { .withSpan(original.span.withPoint(named.span.start)) /** Main desugaring method */ - def apply(tree: Tree)(implicit ctx: Context): Tree = { + def apply(tree: Tree)(using Context): Tree = { /** Create tree for for-comprehension `` or * `` where mapName and flatMapName are chosen @@ -1772,7 +1772,7 @@ object desugar { * The result of this method is used for validity checking, is thrown away afterwards. * @param parent The type of `parent` */ - def refinedTypeToClass(parent: tpd.Tree, refinements: List[Tree])(implicit ctx: Context): TypeDef = { + def refinedTypeToClass(parent: tpd.Tree, refinements: List[Tree])(using Context): TypeDef = { def stripToCore(tp: Type): List[Type] = tp match { case tp: AppliedType => tp :: Nil case tp: TypeRef if tp.symbol.isClass => tp :: Nil // monomorphic class type @@ -1792,7 +1792,7 @@ object desugar { /** Returns list of all pattern variables, possibly with their types, * without duplicates */ - private def getVariables(tree: Tree)(implicit ctx: Context): List[VarInfo] = { + private def getVariables(tree: Tree)(using Context): List[VarInfo] = { val buf = ListBuffer[VarInfo]() def seenName(name: Name) = buf exists (_._1.name == name) def add(named: NameTree, t: Tree): Unit = @@ -1840,7 +1840,7 @@ object desugar { collect(expr) case Quote(expr) => new UntypedTreeTraverser { - def traverse(tree: untpd.Tree)(implicit ctx: Context): Unit = tree match { + def traverse(tree: untpd.Tree)(using Context): Unit = tree match { case Splice(expr) => collect(expr) case TypSplice(expr) => ctx.error(TypeSpliceInValPattern(expr), tree.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala b/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala index b130e7cb9aea..328562431042 100644 --- a/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala +++ b/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala @@ -27,13 +27,13 @@ object DesugarEnums { * whether the case is still in the enum class or it has been transferred to the * companion object. */ - def enumClass(implicit ctx: Context): Symbol = { + def enumClass(using Context): Symbol = { val cls = ctx.owner if (cls.is(Module)) cls.linkedClass else cls } /** Is `tree` an (untyped) enum case? */ - def isEnumCase(tree: Tree)(implicit ctx: Context): Boolean = tree match { + def isEnumCase(tree: Tree)(using Context): Boolean = tree match { case tree: MemberDef => tree.mods.isEnumCase case PatDef(mods, _, _, _) => mods.isEnumCase case _ => false @@ -45,7 +45,7 @@ object DesugarEnums { * It is an error if a type parameter is non-variant, or if its approximation * refers to pther type parameters. */ - def interpolatedEnumParent(span: Span)(implicit ctx: Context): Tree = { + def interpolatedEnumParent(span: Span)(using Context): Tree = { val tparams = enumClass.typeParams def isGround(tp: Type) = tp.subst(tparams, tparams.map(_ => NoType)) eq tp val targs = tparams map { tparam => @@ -65,11 +65,11 @@ object DesugarEnums { } /** A type tree referring to `enumClass` */ - def enumClassRef(implicit ctx: Context): Tree = + def enumClassRef(using Context): Tree = if (enumClass.exists) TypeTree(enumClass.typeRef) else TypeTree() /** Add implied flags to an enum class or an enum case */ - def addEnumFlags(cdef: TypeDef)(implicit ctx: Context): TypeDef = + def addEnumFlags(cdef: TypeDef)(using Context): TypeDef = if (cdef.mods.isEnumClass) cdef.withMods(cdef.mods.withAddedFlags(Abstract | Sealed, cdef.span)) else if (isEnumCase(cdef)) cdef.withMods(cdef.mods.withAddedFlags(Final, cdef.span)) else cdef @@ -77,7 +77,7 @@ object DesugarEnums { private def valuesDot(name: PreName)(implicit src: SourceFile) = Select(Ident(nme.DOLLAR_VALUES), name.toTermName) - private def registerCall(implicit ctx: Context): List[Tree] = + private def registerCall(using Context): List[Tree] = if (enumClass.typeParams.nonEmpty) Nil else Apply(valuesDot("register"), This(EmptyTypeIdent) :: Nil) :: Nil @@ -92,7 +92,7 @@ object DesugarEnums { * throw new IllegalArgumentException("key not found: ".concat(name)) * } */ - private def enumScaffolding(implicit ctx: Context): List[Tree] = { + private def enumScaffolding(using Context): List[Tree] = { val valuesDef = DefDef(nme.values, Nil, Nil, TypeTree(defn.ArrayOf(enumClass.typeRef)), Select(valuesDot(nme.values), nme.toArray)) .withFlags(Synthetic) @@ -130,7 +130,7 @@ object DesugarEnums { * $values.register(this) * } */ - private def enumValueCreator(implicit ctx: Context) = { + private def enumValueCreator(using Context) = { val ordinalDef = ordinalMeth(Ident(nme.ordinalDollar_)) val toStringDef = toStringMeth(Ident(nme.nameDollar)) val creator = New(Template( @@ -163,7 +163,7 @@ object DesugarEnums { cdef: TypeDef, parents: List[Tree], tparams: List[TypeDef], - appliedEnumRef: Tree)(implicit ctx: Context): (Tree, List[DefDef]) = { + appliedEnumRef: Tree)(using Context): (Tree, List[DefDef]) = { def extractType(t: Tree): Tree = t match { case Apply(t1, _) => extractType(t1) @@ -202,7 +202,7 @@ object DesugarEnums { enumTypeParams: List[TypeSymbol], caseTypeParams: List[TypeDef], vparamss: List[List[ValDef]], - parents: List[Tree])(implicit ctx: Context): Boolean = { + parents: List[Tree])(using Context): Boolean = { object searchRef extends UntypedTreeAccumulator[Boolean] { var tparamNames = enumTypeParams.map(_.name).toSet[Name] @@ -212,7 +212,7 @@ object DesugarEnums { try op finally tparamNames = saved } - def apply(x: Boolean, tree: Tree)(implicit ctx: Context): Boolean = x || { + def apply(x: Boolean, tree: Tree)(using Context): Boolean = x || { tree match { case Ident(name) => val matches = tparamNames.contains(name) @@ -227,7 +227,7 @@ object DesugarEnums { case _ => foldOver(x, tree) } } - def apply(tree: Tree)(implicit ctx: Context): Boolean = + def apply(tree: Tree)(using Context): Boolean = underBinders(caseTypeParams, apply(false, tree)) } @@ -249,7 +249,7 @@ object DesugarEnums { * - scaffolding containing the necessary definitions for singleton enum cases * unless that scaffolding was already generated by a previous call to `nextEnumKind`. */ - def nextOrdinal(kind: CaseKind.Value)(implicit ctx: Context): (Int, List[Tree]) = { + def nextOrdinal(kind: CaseKind.Value)(using Context): (Int, List[Tree]) = { val (count, seenKind) = ctx.tree.removeAttachment(EnumCaseCount).getOrElse((0, CaseKind.Class)) val minKind = if (kind < seenKind) kind else seenKind ctx.tree.pushAttachment(EnumCaseCount, (count + 1, minKind)) @@ -261,23 +261,23 @@ object DesugarEnums { (count, scaffolding) } - def param(name: TermName, typ: Type)(implicit ctx: Context) = + def param(name: TermName, typ: Type)(using Context) = ValDef(name, TypeTree(typ), EmptyTree).withFlags(Param) - def ordinalMeth(body: Tree)(implicit ctx: Context): DefDef = + def ordinalMeth(body: Tree)(using Context): DefDef = DefDef(nme.ordinalDollar, Nil, Nil, TypeTree(defn.IntType), body) - def toStringMeth(body: Tree)(implicit ctx: Context): DefDef = + def toStringMeth(body: Tree)(using Context): DefDef = DefDef(nme.toString_, Nil, Nil, TypeTree(defn.StringType), body).withFlags(Override) - def ordinalMethLit(ord: Int)(implicit ctx: Context): DefDef = + def ordinalMethLit(ord: Int)(using Context): DefDef = ordinalMeth(Literal(Constant(ord))) - def toStringMethLit(name: String)(implicit ctx: Context): DefDef = + def toStringMethLit(name: String)(using Context): DefDef = toStringMeth(Literal(Constant(name))) /** Expand a module definition representing a parameterless enum case */ - def expandEnumModule(name: TermName, impl: Template, mods: Modifiers, span: Span)(implicit ctx: Context): Tree = { + def expandEnumModule(name: TermName, impl: Template, mods: Modifiers, span: Span)(using Context): Tree = { assert(impl.body.isEmpty) if (!enumClass.exists) EmptyTree else if (impl.parents.isEmpty) @@ -296,7 +296,7 @@ object DesugarEnums { } /** Expand a simple enum case */ - def expandSimpleEnumCase(name: TermName, mods: Modifiers, span: Span)(implicit ctx: Context): Tree = + def expandSimpleEnumCase(name: TermName, mods: Modifiers, span: Span)(using Context): Tree = if (!enumClass.exists) EmptyTree else if (enumClass.typeParams.nonEmpty) { val parent = interpolatedEnumParent(span) diff --git a/compiler/src/dotty/tools/dotc/ast/NavigateAST.scala b/compiler/src/dotty/tools/dotc/ast/NavigateAST.scala index a8a1ecf35869..ffb1ac3b5c80 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 +import core.Contexts.{Context, ctx} import core.Decorators._ import util.Spans._ import Trees.{MemberDef, DefTree, WithLazyField} @@ -13,7 +13,7 @@ object NavigateAST { /** The untyped tree corresponding to typed tree `tree` in the compilation * unit specified by `ctx` */ - def toUntyped(tree: tpd.Tree)(implicit ctx: Context): untpd.Tree = + def toUntyped(tree: tpd.Tree)(using Context): untpd.Tree = untypedPath(tree, exactMatch = true) match { case (utree: untpd.Tree) :: _ => utree @@ -37,7 +37,7 @@ object NavigateAST { * defined and nothing else. So we look instead for an untyped tree approximating the * envelope of the definition, and declare success if we find another DefTree. */ - def untypedPath(tree: tpd.Tree, exactMatch: Boolean = false)(implicit ctx: Context): List[Positioned] = + def untypedPath(tree: tpd.Tree, exactMatch: Boolean = false)(using Context): List[Positioned] = tree match { case tree: MemberDef[?] => untypedPath(tree.span) match { @@ -55,7 +55,7 @@ object NavigateAST { /** The reverse part of the untyped root of the compilation unit of `ctx` to * the given `span`. */ - def untypedPath(span: Span)(implicit ctx: Context): List[Positioned] = + def untypedPath(span: Span)(using Context): List[Positioned] = pathTo(span, ctx.compilationUnit.untpdTree) @@ -68,7 +68,7 @@ object NavigateAST { * end point are the same, so this is useful when trying to reconcile * nodes with source code. */ - def pathTo(span: Span, from: Positioned, skipZeroExtent: Boolean = false)(implicit ctx: Context): List[Positioned] = { + def pathTo(span: Span, from: Positioned, skipZeroExtent: Boolean = false)(using Context): List[Positioned] = { def childPath(it: Iterator[Any], path: List[Positioned]): List[Positioned] = { var bestFit: List[Positioned] = path while (it.hasNext) { diff --git a/compiler/src/dotty/tools/dotc/ast/Positioned.scala b/compiler/src/dotty/tools/dotc/ast/Positioned.scala index d76cde8b15cb..28690a242417 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 +import core.Contexts.{Context, ctx} import core.Decorators._ import core.Flags.{JavaDefined, Extension} import core.StdNames.nme @@ -156,7 +156,7 @@ abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Pro * - Parent spans contain child spans * - If item is a non-empty tree, it has a position */ - def checkPos(nonOverlapping: Boolean)(implicit ctx: Context): Unit = try { + def checkPos(nonOverlapping: Boolean)(using Context): Unit = try { import untpd._ var lastPositioned: Positioned = null var lastSpan = NoSpan @@ -239,6 +239,6 @@ abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Pro object Positioned { @sharable private[Positioned] var debugId = Int.MinValue - def updateDebugPos(implicit ctx: Context): Unit = + def updateDebugPos(using Context): Unit = debugId = ctx.settings.YdebugTreeWithId.value } diff --git a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala index 22f4859781a9..07a5b15f3f1a 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala @@ -36,7 +36,7 @@ trait TreeInfo[T >: Untyped <: Type] { self: Trees.Instance[T] => case _ => false } - class MatchingArgs(params: List[Symbol], args: List[Tree])(implicit ctx: Context) { + class MatchingArgs(params: List[Symbol], args: List[Tree])(using Context) { def foreach(f: (Symbol, Tree) => Unit): Boolean = { def recur(params: List[Symbol], args: List[Tree]): Boolean = params match { case Nil => args.isEmpty @@ -177,7 +177,7 @@ trait TreeInfo[T >: Untyped <: Type] { self: Trees.Instance[T] => } /** Is tpt a vararg type of the form T* or => T*? */ - def isRepeatedParamType(tpt: Tree)(implicit ctx: Context): Boolean = tpt match { + def isRepeatedParamType(tpt: Tree)(using Context): Boolean = tpt match { case ByNameTypeTree(tpt1) => isRepeatedParamType(tpt1) case tpt: TypeTree => tpt.typeOpt.isRepeatedParam case AppliedTypeTree(Select(_, tpnme.REPEATED_PARAM_CLASS), _) => true @@ -190,7 +190,7 @@ trait TreeInfo[T >: Untyped <: Type] { self: Trees.Instance[T] => /** Is this argument node of the form : _*, or is it a reference to * such an argument ? The latter case can happen when an argument is lifted. */ - def isWildcardStarArg(tree: Tree)(implicit ctx: Context): Boolean = unbind(tree) match { + def isWildcardStarArg(tree: Tree)(using Context): Boolean = unbind(tree) match { case Typed(Ident(nme.WILDCARD_STAR), _) => true case Typed(_, Ident(tpnme.WILDCARD_STAR)) => true case Typed(_, tpt: TypeTree) => tpt.typeOpt.isRepeatedParam @@ -203,7 +203,7 @@ trait TreeInfo[T >: Untyped <: Type] { self: Trees.Instance[T] => (ddef.tparams ::: ddef.vparamss.flatten).map(_.symbol) /** Does this argument list end with an argument of the form : _* ? */ - def isWildcardStarArgList(trees: List[Tree])(implicit ctx: Context): Boolean = + def isWildcardStarArgList(trees: List[Tree])(using Context): Boolean = trees.nonEmpty && isWildcardStarArg(trees.last) /** Is the argument a wildcard argument of the form `_` or `x @ _`? @@ -231,11 +231,11 @@ trait TreeInfo[T >: Untyped <: Type] { self: Trees.Instance[T] => } /** Does this CaseDef catch Throwable? */ - def catchesThrowable(cdef: CaseDef)(implicit ctx: Context): Boolean = + def catchesThrowable(cdef: CaseDef)(using Context): Boolean = catchesAllOf(cdef, defn.ThrowableType) /** Does this CaseDef catch everything of a certain Type? */ - def catchesAllOf(cdef: CaseDef, threshold: Type)(implicit ctx: Context): Boolean = + def catchesAllOf(cdef: CaseDef, threshold: Type)(using Context): Boolean = isDefaultCase(cdef) || cdef.guard.isEmpty && { unbind(cdef.pat) match { @@ -256,7 +256,7 @@ trait TreeInfo[T >: Untyped <: Type] { self: Trees.Instance[T] => /** The largest subset of {NoInits, PureInterface} that a * trait or class with these parents can have as flags. */ - def parentsKind(parents: List[Tree])(implicit ctx: Context): FlagSet = parents match { + def parentsKind(parents: List[Tree])(using Context): FlagSet = parents match { case Nil => NoInitsInterface case Apply(_, _ :: _) :: _ => EmptyFlags case _ :: parents1 => parentsKind(parents1) @@ -302,7 +302,7 @@ trait UntypedTreeInfo extends TreeInfo[Untyped] { self: Trees.Instance[Untyped] functionWithUnknownParamType(tree).isDefined /** Is `tree` an context function or closure, possibly nested in a block? */ - def isContextualClosure(tree: Tree)(implicit ctx: Context): Boolean = unsplice(tree) match { + def isContextualClosure(tree: Tree)(using Context): Boolean = unsplice(tree) match { case tree: FunctionWithMods => tree.mods.is(Given) case Function((param: untpd.ValDef) :: _, _) => param.mods.is(Given) case Closure(_, meth, _) => true @@ -318,7 +318,7 @@ trait UntypedTreeInfo extends TreeInfo[Untyped] { self: Trees.Instance[Untyped] /** The largest subset of {NoInits, PureInterface} that a * trait or class enclosing this statement can have as flags. */ - def defKind(tree: Tree)(implicit ctx: Context): FlagSet = unsplice(tree) match { + def defKind(tree: Tree)(using Context): FlagSet = unsplice(tree) match { case EmptyTree | _: Import => NoInitsInterface case tree: TypeDef => if (tree.isClassDef) NoInits else NoInitsInterface case tree: DefDef => @@ -334,7 +334,7 @@ trait UntypedTreeInfo extends TreeInfo[Untyped] { self: Trees.Instance[Untyped] /** The largest subset of {NoInits, PureInterface} that a * trait or class with this body can have as flags. */ - def bodyKind(body: List[Tree])(implicit ctx: Context): FlagSet = + def bodyKind(body: List[Tree])(using Context): FlagSet = body.foldLeft(NoInitsInterface)((fs, stat) => fs & defKind(stat)) /** Info of a variable in a pattern: The named tree and its type */ @@ -342,7 +342,7 @@ trait UntypedTreeInfo extends TreeInfo[Untyped] { self: Trees.Instance[Untyped] /** An extractor for trees of the form `id` or `id: T` */ object IdPattern { - def unapply(tree: Tree)(implicit ctx: Context): Option[VarInfo] = tree match { + def unapply(tree: Tree)(using Context): Option[VarInfo] = tree match { case id: Ident if id.name != nme.WILDCARD => Some(id, TypeTree()) case Typed(id: Ident, tpt) => Some((id, tpt)) case _ => None @@ -361,7 +361,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * Idempotent if running the statement a second time has no side effects * Impure otherwise */ - def statPurity(tree: Tree)(implicit ctx: Context): PurityLevel = unsplice(tree) match { + def statPurity(tree: Tree)(using Context): PurityLevel = unsplice(tree) match { case EmptyTree | TypeDef(_, _) | Import(_, _) @@ -383,7 +383,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * takes a different code path than all to follow; but they are idempotent * because running the expression a second time gives the cached result. */ - def exprPurity(tree: Tree)(implicit ctx: Context): PurityLevel = unsplice(tree) match { + def exprPurity(tree: Tree)(using Context): PurityLevel = unsplice(tree) match { case EmptyTree | This(_) | Super(_, _) @@ -425,23 +425,23 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => private def minOf(l0: PurityLevel, ls: List[PurityLevel]) = ls.foldLeft(l0)(_ `min` _) - def isPurePath(tree: Tree)(implicit ctx: Context): Boolean = tree.tpe match { + def isPurePath(tree: Tree)(using Context): Boolean = tree.tpe match { case tpe: ConstantType => exprPurity(tree) >= Pure case _ => exprPurity(tree) == PurePath } - def isPureExpr(tree: Tree)(implicit ctx: Context): Boolean = + def isPureExpr(tree: Tree)(using Context): Boolean = exprPurity(tree) >= Pure - def isIdempotentPath(tree: Tree)(implicit ctx: Context): Boolean = tree.tpe match { + def isIdempotentPath(tree: Tree)(using Context): Boolean = tree.tpe match { case tpe: ConstantType => exprPurity(tree) >= Idempotent case _ => exprPurity(tree) >= IdempotentPath } - def isIdempotentExpr(tree: Tree)(implicit ctx: Context): Boolean = + def isIdempotentExpr(tree: Tree)(using Context): Boolean = exprPurity(tree) >= Idempotent - def isPureBinding(tree: Tree)(implicit ctx: Context): Boolean = statPurity(tree) >= Pure + def isPureBinding(tree: Tree)(using Context): Boolean = statPurity(tree) >= Pure /** The purity level of this reference. * @return @@ -453,7 +453,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * @DarkDimius: need to make sure that lazy accessor methods have Lazy and Stable * flags set. */ - def refPurity(tree: Tree)(implicit ctx: Context): PurityLevel = { + def refPurity(tree: Tree)(using Context): PurityLevel = { val sym = tree.symbol if (!tree.hasType) Impure else if (!tree.tpe.widen.isParameterless || sym.isEffectivelyErased) PurePath @@ -465,9 +465,9 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => else PurePath } - def isPureRef(tree: Tree)(implicit ctx: Context): Boolean = + def isPureRef(tree: Tree)(using Context): Boolean = refPurity(tree) == PurePath - def isIdempotentRef(tree: Tree)(implicit ctx: Context): Boolean = + def isIdempotentRef(tree: Tree)(using Context): Boolean = refPurity(tree) >= IdempotentPath /** (1) If `tree` is a constant expression, its value as a Literal, @@ -520,7 +520,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * * This avoids the situation where we have a Select node that does not have a symbol. */ - def constToLiteral(tree: Tree)(implicit ctx: Context): Tree = { + def constToLiteral(tree: Tree)(using Context): Tree = { val tree1 = ConstFold(tree) tree1.tpe.widenTermRefExpr.dealias.normalized match { case ConstantType(Constant(_: Type)) if tree.isInstanceOf[Block] => @@ -549,7 +549,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** Is symbol potentially a getter of a mutable variable? */ - def mayBeVarGetter(sym: Symbol)(implicit ctx: Context): Boolean = { + def mayBeVarGetter(sym: Symbol)(using Context): Boolean = { def maybeGetterType(tpe: Type): Boolean = tpe match { case _: ExprType => true case tpe: MethodType => tpe.isImplicitMethod @@ -562,7 +562,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** Is tree a reference to a mutable variable, or to a potential getter * that has a setter in the same class? */ - def isVariableOrGetter(tree: Tree)(implicit ctx: Context): Boolean = { + def isVariableOrGetter(tree: Tree)(using Context): Boolean = { def sym = tree.symbol def isVar = sym.is(Mutable) def isGetter = @@ -581,7 +581,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => } /** Is tree a `this` node which belongs to `enclClass`? */ - def isSelf(tree: Tree, enclClass: Symbol)(implicit ctx: Context): Boolean = unsplice(tree) match { + def isSelf(tree: Tree, enclClass: Symbol)(using Context): Boolean = unsplice(tree) match { case This(_) => tree.symbol == enclClass case _ => false } @@ -595,7 +595,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => } /** Strips layers of `.asInstanceOf[T]` / `_.$asInstanceOf[T]()` from an expression */ - def stripCast(tree: Tree)(implicit ctx: Context): Tree = { + def stripCast(tree: Tree)(using Context): Tree = { def isCast(sel: Tree) = sel.symbol.isTypeCast unsplice(tree) match { case TypeApply(sel @ Select(inner, _), _) if isCast(sel) => @@ -627,7 +627,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => } /** Decompose a template body into parameters and other statements */ - def decomposeTemplateBody(body: List[Tree])(implicit ctx: Context): (List[Tree], List[Tree]) = + def decomposeTemplateBody(body: List[Tree])(using Context): (List[Tree], List[Tree]) = body.partition { case stat: TypeDef => stat.symbol is Flags.Param case stat: ValOrDefDef => @@ -648,7 +648,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** An extractor for def of a closure contained the block of the closure. */ object closureDef { - def unapply(tree: Tree)(implicit ctx: Context): Option[DefDef] = tree match { + def unapply(tree: Tree)(using Context): Option[DefDef] = tree match { case Block((meth : DefDef) :: Nil, closure: Closure) if meth.symbol == closure.meth.symbol => Some(meth) case Block(Nil, expr) => @@ -661,15 +661,15 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => } /** If tree is a closure, its body, otherwise tree itself */ - def closureBody(tree: Tree)(implicit ctx: Context): Tree = tree match { + def closureBody(tree: Tree)(using Context): Tree = tree match { case closureDef(meth) => meth.rhs case _ => tree } /** The variables defined by a pattern, in reverse order of their appearance. */ - def patVars(tree: Tree)(implicit ctx: Context): List[Symbol] = { + def patVars(tree: Tree)(using Context): List[Symbol] = { val acc = new TreeAccumulator[List[Symbol]] { - def apply(syms: List[Symbol], tree: Tree)(implicit ctx: Context) = tree match { + def apply(syms: List[Symbol], tree: Tree)(using Context) = tree match { case Bind(_, body) => apply(tree.symbol :: syms, body) case Annotated(tree, id @ Ident(tpnme.BOUNDTYPE_ANNOT)) => apply(id.symbol :: syms, tree) case _ => foldOver(syms, tree) @@ -679,7 +679,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => } /** Is this pattern node a catch-all or type-test pattern? */ - def isCatchCase(cdef: CaseDef)(implicit ctx: Context): Boolean = cdef match { + def isCatchCase(cdef: CaseDef)(using Context): Boolean = cdef match { case CaseDef(Typed(Ident(nme.WILDCARD), tpt), EmptyTree, _) => isSimpleThrowable(tpt.tpe) case CaseDef(Bind(_, Typed(Ident(nme.WILDCARD), tpt)), EmptyTree, _) => @@ -688,7 +688,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => isDefaultCase(cdef) } - private def isSimpleThrowable(tp: Type)(implicit ctx: Context): Boolean = tp match { + private def isSimpleThrowable(tp: Type)(using Context): Boolean = tp match { case tp @ TypeRef(pre, _) => (pre == NoPrefix || pre.widen.typeSymbol.isStatic) && (tp.symbol derivesFrom defn.ThrowableClass) && !tp.symbol.is(Trait) @@ -697,11 +697,11 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => } /** The symbols defined locally in a statement list */ - def localSyms(stats: List[Tree])(implicit ctx: Context): List[Symbol] = + def localSyms(stats: List[Tree])(using Context): List[Symbol] = for (stat <- stats if stat.isDef && stat.symbol.exists) yield stat.symbol /** If `tree` is a DefTree, the symbol defined by it, otherwise NoSymbol */ - def definedSym(tree: Tree)(implicit ctx: Context): Symbol = + def definedSym(tree: Tree)(using Context): Symbol = if (tree.isDef) tree.symbol else NoSymbol /** Going from child to parent, the path of tree nodes that starts @@ -709,10 +709,10 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * if no such path exists. * Pre: `sym` must have a position. */ - def defPath(sym: Symbol, root: Tree)(implicit ctx: Context): List[Tree] = trace.onDebug(s"defpath($sym with position ${sym.span}, ${root.show})") { + def defPath(sym: Symbol, root: Tree)(using Context): List[Tree] = trace.onDebug(s"defpath($sym with position ${sym.span}, ${root.show})") { require(sym.span.exists, sym) object accum extends TreeAccumulator[List[Tree]] { - def apply(x: List[Tree], tree: Tree)(implicit ctx: Context): List[Tree] = + def apply(x: List[Tree], tree: Tree)(using Context): List[Tree] = if (tree.span.contains(sym.span)) if (definedSym(tree) == sym) tree :: x else { @@ -727,14 +727,14 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** The top level classes in this tree, including only those module classes that * are not a linked class of some other class in the result. */ - def topLevelClasses(tree: Tree)(implicit ctx: Context): List[ClassSymbol] = tree match { + def topLevelClasses(tree: Tree)(using Context): List[ClassSymbol] = tree match { case PackageDef(_, stats) => stats.flatMap(topLevelClasses) case tdef: TypeDef if tdef.symbol.isClass => tdef.symbol.asClass :: Nil case _ => Nil } /** The tree containing only the top-level classes and objects matching either `cls` or its companion object */ - def sliceTopLevel(tree: Tree, cls: ClassSymbol)(implicit ctx: Context): List[Tree] = tree match { + def sliceTopLevel(tree: Tree, cls: ClassSymbol)(using Context): List[Tree] = tree match { case PackageDef(pid, stats) => val slicedStats = stats.flatMap(sliceTopLevel(_, cls)) if (!slicedStats.isEmpty) @@ -760,7 +760,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * For a tree to be found, The symbol must have a position and its definition * tree must be reachable from come tree stored in an enclosing context. */ - def definingStats(sym: Symbol)(implicit ctx: Context): List[Tree] = + def definingStats(sym: Symbol)(using Context): List[Tree] = if (!sym.span.exists || (ctx eq NoContext) || ctx.compilationUnit == null) Nil else defPath(sym, ctx.compilationUnit.tpdTree) match { case defn :: encl :: _ => @@ -779,7 +779,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** If `tree` is an instance of `TupleN[...](e1, ..., eN)`, the arguments `e1, ..., eN` * otherwise the empty list. */ - def tupleArgs(tree: Tree)(implicit ctx: Context): List[Tree] = tree match { + def tupleArgs(tree: Tree)(using Context): List[Tree] = tree match { case Block(Nil, expr) => tupleArgs(expr) case Inlined(_, Nil, expr) => tupleArgs(expr) case Apply(fn, args) @@ -792,7 +792,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** The qualifier part of a Select or Ident. * For an Ident, this is the `This` of the current class. */ - def qualifier(tree: Tree)(implicit ctx: Context): Tree = tree match { + def qualifier(tree: Tree)(using Context): Tree = tree match { case Select(qual, _) => qual case tree: Ident => desugarIdentPrefix(tree) case _ => This(ctx.owner.enclosingClass.asClass) @@ -801,7 +801,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** Is this a (potentially applied) selection of a member of a structural type * that is not a member of an underlying class or trait? */ - def isStructuralTermSelectOrApply(tree: Tree)(implicit ctx: Context): Boolean = { + def isStructuralTermSelectOrApply(tree: Tree)(using Context): Boolean = { def isStructuralTermSelect(tree: Select) = { def hasRefinement(qualtpe: Type): Boolean = qualtpe.dealias match { case RefinedType(parent, rname, rinfo) => @@ -832,7 +832,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * For the moment, only Ident, Select, Literal, Apply and TypeApply are supported */ implicit class StructuralEqDeco(t1: Tree) { - def === (t2: Tree)(implicit ctx: Context): Boolean = (t1, t2) match { + def === (t2: Tree)(using Context): Boolean = (t1, t2) match { case (t1: Ident, t2: Ident) => t1.symbol == t2.symbol case (t1 @ Select(q1, _), t2 @ Select(q2, _)) => @@ -846,7 +846,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => case _ => false } - def hash(implicit ctx: Context): Int = + def hash(using Context): Int = t1.getClass.hashCode * 37 + { t1 match { case t1: Ident => t1.symbol.hashCode @@ -871,7 +871,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * The result can be the contents of a term or type quote, which * will return a term or type tree respectively. */ - def unapply(tree: tpd.Tree)(implicit ctx: Context): Option[tpd.Tree] = tree match { + def unapply(tree: tpd.Tree)(using Context): Option[tpd.Tree] = tree match { case tree: GenericApply[Type] if tree.symbol.isQuote => Some(tree.args.head) case _ => None } @@ -883,7 +883,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * The result can be the contents of a term or type splice, which * will return a term or type tree respectively. */ - def unapply(tree: tpd.Tree)(implicit ctx: Context): Option[tpd.Tree] = tree match { + def unapply(tree: tpd.Tree)(using Context): Option[tpd.Tree] = tree match { case tree: tpd.Apply if tree.symbol.isSplice => Some(tree.args.head) case tree: tpd.Select if tree.symbol.isSplice => Some(tree.qualifier) case _ => None diff --git a/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala b/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala index 573cda5c744b..c677ecd46be8 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala @@ -16,7 +16,7 @@ import scala.annotation.tailrec class TreeMapWithImplicits extends tpd.TreeMap { import tpd._ - def transformSelf(vd: ValDef)(implicit ctx: Context): ValDef = + def transformSelf(vd: ValDef)(using Context): ValDef = cpy.ValDef(vd)(tpt = transform(vd.tpt)) /** Transform statements, while maintaining import contexts and expression contexts @@ -24,11 +24,11 @@ class TreeMapWithImplicits extends tpd.TreeMap { * - be tail-recursive where possible * - don't re-allocate trees where nothing has changed */ - def transformStats(stats: List[Tree], exprOwner: Symbol)(implicit ctx: Context): List[Tree] = { + def transformStats(stats: List[Tree], exprOwner: Symbol)(using Context): List[Tree] = { - @tailrec def traverse(curStats: List[Tree])(implicit ctx: Context): List[Tree] = { + @tailrec def traverse(curStats: List[Tree])(using Context): List[Tree] = { - def recur(stats: List[Tree], changed: Tree, rest: List[Tree])(implicit ctx: Context): List[Tree] = + def recur(stats: List[Tree], changed: Tree, rest: List[Tree])(using Context): List[Tree] = if (stats eq curStats) { val rest1 = transformStats(rest, exprOwner) changed match { @@ -49,8 +49,8 @@ class TreeMapWithImplicits extends tpd.TreeMap { case _ => ctx } val stat1 = transform(stat)(using statCtx) - if (stat1 ne stat) recur(stats, stat1, rest)(restCtx) - else traverse(rest)(restCtx) + if (stat1 ne stat) recur(stats, stat1, rest)(using restCtx) + else traverse(rest)(using restCtx) case nil => stats } @@ -58,7 +58,7 @@ class TreeMapWithImplicits extends tpd.TreeMap { traverse(stats) } - private def nestedScopeCtx(defs: List[Tree])(implicit ctx: Context): Context = { + private def nestedScopeCtx(defs: List[Tree])(using Context): Context = { val nestedCtx = ctx.fresh.setNewScope defs foreach { case d: DefTree if d.symbol.isOneOf(GivenOrImplicit) => nestedCtx.enter(d.symbol) @@ -67,10 +67,10 @@ class TreeMapWithImplicits extends tpd.TreeMap { nestedCtx } - private def patternScopeCtx(pattern: Tree)(implicit ctx: Context): Context = { + private def patternScopeCtx(pattern: Tree)(using Context): Context = { val nestedCtx = ctx.fresh.setNewScope new TreeTraverser { - def traverse(tree: Tree)(implicit ctx: Context): Unit = { + def traverse(tree: Tree)(using Context): Unit = { tree match { case d: DefTree if d.symbol.isOneOf(GivenOrImplicit) => nestedCtx.enter(d.symbol) case _ => diff --git a/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala b/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala index 3245e5b12e5e..2a4e5a40f107 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala @@ -38,7 +38,7 @@ class TreeTypeMap( val oldOwners: List[Symbol] = Nil, val newOwners: List[Symbol] = Nil, val substFrom: List[Symbol] = Nil, - val substTo: List[Symbol] = Nil)(implicit ctx: Context) extends tpd.TreeMap { + val substTo: List[Symbol] = Nil)(using Context) extends tpd.TreeMap { import tpd._ /** If `sym` is one of `oldOwners`, replace by corresponding symbol in `newOwners` */ @@ -76,7 +76,7 @@ class TreeTypeMap( updateDecls(prevStats.tail, newStats.tail) } - override def transform(tree: tpd.Tree)(implicit ctx: Context): tpd.Tree = treeMap(tree) match { + override def transform(tree: tpd.Tree)(using Context): tpd.Tree = treeMap(tree) match { case impl @ Template(constr, parents, self, _) => val tmap = withMappedSyms(localSyms(impl :: self :: Nil)) cpy.Template(impl)( @@ -84,7 +84,7 @@ class TreeTypeMap( parents = parents.mapconserve(transform), self = tmap.transformSub(self), body = impl.body mapconserve - (tmap.transform(_)(ctx.withOwner(mapOwner(impl.symbol.owner)))) + (tmap.transform(_)(using ctx.withOwner(mapOwner(impl.symbol.owner)))) ).withType(tmap.mapType(impl.tpe)) case tree1 => tree1.withType(mapType(tree1.tpe)) match { @@ -129,10 +129,10 @@ class TreeTypeMap( } } - override def transformStats(trees: List[tpd.Tree])(implicit ctx: Context): List[Tree] = + override def transformStats(trees: List[tpd.Tree])(using Context): List[Tree] = transformDefs(trees)._2 - def transformDefs[TT <: tpd.Tree](trees: List[TT])(implicit ctx: Context): (TreeTypeMap, List[TT]) = { + def transformDefs[TT <: tpd.Tree](trees: List[TT])(using Context): (TreeTypeMap, List[TT]) = { val tmap = withMappedSyms(tpd.localSyms(trees)) (tmap, tmap.transformSub(trees)) } diff --git a/compiler/src/dotty/tools/dotc/ast/Trees.scala b/compiler/src/dotty/tools/dotc/ast/Trees.scala index 8801f2a92159..65646decbd77 100644 --- a/compiler/src/dotty/tools/dotc/ast/Trees.scala +++ b/compiler/src/dotty/tools/dotc/ast/Trees.scala @@ -102,7 +102,7 @@ object Trees { /** Return a typed tree that's isomorphic to this tree, but has given * type. (Overridden by empty trees) */ - def withType(tpe: Type)(implicit ctx: Context): ThisTree[Type] = { + def withType(tpe: Type)(using Context): ThisTree[Type] = { if (tpe.isInstanceOf[ErrorType]) assert(!Config.checkUnreportedErrors || ctx.reporter.errorsReported || @@ -119,7 +119,7 @@ object Trees { * - the child tree is an identifier, or * - errors were reported */ - private def checkChildrenTyped(it: Iterator[Any])(implicit ctx: Context): Unit = + private def checkChildrenTyped(it: Iterator[Any])(using Context): Unit = if (!this.isInstanceOf[Import[?]]) while (it.hasNext) it.next() match { @@ -156,10 +156,10 @@ object Trees { * Defined for `DenotingTree`s and `ProxyTree`s, NoDenotation for other * kinds of trees */ - def denot(implicit ctx: Context): Denotation = NoDenotation + def denot(using Context): Denotation = NoDenotation /** Shorthand for `denot.symbol`. */ - final def symbol(implicit ctx: Context): Symbol = denot.symbol + final def symbol(using Context): Symbol = denot.symbol /** Does this tree represent a type? */ def isType: Boolean = false @@ -269,7 +269,7 @@ object Trees { /** Tree's denotation can be derived from its type */ abstract class DenotingTree[-T >: Untyped](implicit @constructorOnly src: SourceFile) extends Tree[T] { type ThisTree[-T >: Untyped] <: DenotingTree[T] - override def denot(implicit ctx: Context): Denotation = typeOpt match { + override def denot(using Context): Denotation = typeOpt match { case tpe: NamedType => tpe.denot case tpe: ThisType => tpe.cls.denot case tpe: AnnotatedType => tpe.stripAnnots match { @@ -287,7 +287,7 @@ object Trees { abstract class ProxyTree[-T >: Untyped](implicit @constructorOnly src: SourceFile) extends Tree[T] { type ThisTree[-T >: Untyped] <: ProxyTree[T] def forwardTo: Tree[T] - override def denot(implicit ctx: Context): Denotation = forwardTo.denot + override def denot(using Context): Denotation = forwardTo.denot override def isTerm: Boolean = forwardTo.isTerm override def isType: Boolean = forwardTo.isType } @@ -387,7 +387,7 @@ object Trees { def name: TermName def tpt: Tree[T] def unforcedRhs: LazyTree[T] = unforced - def rhs(implicit ctx: Context): Tree[T] = forceIfLazy + def rhs(using Context): Tree[T] = forceIfLazy } // ----------- Tree case classes ------------------------------------ @@ -422,7 +422,7 @@ object Trees { extends DenotingTree[T] with TermTree[T] { type ThisTree[-T >: Untyped] = This[T] // Denotation of a This tree is always the underlying class; needs correction for modules. - override def denot(implicit ctx: Context): Denotation = + override def denot(using Context): Denotation = typeOpt match { case tpe @ TermRef(pre, _) if tpe.symbol.is(Module) => tpe.symbol.moduleClass.denot.asSeenFrom(pre) @@ -795,7 +795,7 @@ object Trees { def unforcedBody: LazyTreeList[T] = unforced def unforced: LazyTreeList[T] = preBody protected def force(x: List[Tree[T @uncheckedVariance]]): Unit = preBody = x - def body(implicit ctx: Context): List[Tree[T]] = forceIfLazy + def body(using Context): List[Tree[T]] = forceIfLazy def parents: List[Tree[T]] = parentsOrDerived // overridden by DerivingTemplate def derived: List[untpd.Tree] = Nil // overridden by DerivingTemplate @@ -914,7 +914,7 @@ object Trees { trait WithLazyField[+T <: AnyRef] { def unforced: T | Lazy[T] protected def force(x: T @uncheckedVariance): Unit - def forceIfLazy(implicit ctx: Context): T = unforced match { + def forceIfLazy(using Context): T = unforced match { case lzy: Lazy[T @unchecked] => val x = lzy.complete force(x) @@ -928,7 +928,7 @@ object Trees { * can delay tree construction until the field is first demanded. */ trait Lazy[+T <: AnyRef] { - def complete(implicit ctx: Context): T + def complete(using Context): T } // ----- Generic Tree Instances, inherited from `tpt` and `untpd`. @@ -1036,11 +1036,11 @@ object Trees { protected def finalize(tree: Tree, copied: untpd.MemberDef): copied.ThisTree[T] = postProcess(tree, copied.withSpan(tree.span).withAttachmentsFrom(tree)) - def Ident(tree: Tree)(name: Name)(implicit ctx: Context): Ident = tree match { + def Ident(tree: Tree)(name: Name)(using Context): Ident = tree match { case tree: Ident if name == tree.name => tree case _ => finalize(tree, untpd.Ident(name)(sourceFile(tree))) } - def Select(tree: Tree)(qualifier: Tree, name: Name)(implicit ctx: Context): Select = tree match { + def Select(tree: Tree)(qualifier: Tree, name: Name)(using Context): Select = tree match { case tree: SelectWithSig => if ((qualifier eq tree.qualifier) && (name == tree.name)) tree else finalize(tree, SelectWithSig(qualifier, name, tree.sig)(sourceFile(tree))) @@ -1048,204 +1048,204 @@ object Trees { case _ => finalize(tree, untpd.Select(qualifier, name)(sourceFile(tree))) } /** Copy Ident or Select trees */ - def Ref(tree: RefTree)(name: Name)(implicit ctx: Context): RefTree = tree match { + def Ref(tree: RefTree)(name: Name)(using Context): RefTree = tree match { case Ident(_) => Ident(tree)(name) case Select(qual, _) => Select(tree)(qual, name) } - def This(tree: Tree)(qual: untpd.Ident)(implicit ctx: Context): This = tree match { + def This(tree: Tree)(qual: untpd.Ident)(using Context): This = tree match { case tree: This if (qual eq tree.qual) => tree case _ => finalize(tree, untpd.This(qual)(sourceFile(tree))) } - def Super(tree: Tree)(qual: Tree, mix: untpd.Ident)(implicit ctx: Context): Super = tree match { + def Super(tree: Tree)(qual: Tree, mix: untpd.Ident)(using Context): Super = tree match { case tree: Super if (qual eq tree.qual) && (mix eq tree.mix) => tree case _ => finalize(tree, untpd.Super(qual, mix)(sourceFile(tree))) } - def Apply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): Apply = tree match { + def Apply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): Apply = tree match { case tree: Apply if (fun eq tree.fun) && (args eq tree.args) => tree case _ => finalize(tree, untpd.Apply(fun, args)(sourceFile(tree))) //.ensuring(res => res.uniqueId != 2213, s"source = $tree, ${tree.uniqueId}, ${tree.span}") } - def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): TypeApply = tree match { + def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): TypeApply = tree match { case tree: TypeApply if (fun eq tree.fun) && (args eq tree.args) => tree case _ => finalize(tree, untpd.TypeApply(fun, args)(sourceFile(tree))) } - def Literal(tree: Tree)(const: Constant)(implicit ctx: Context): Literal = tree match { + def Literal(tree: Tree)(const: Constant)(using Context): Literal = tree match { case tree: Literal if const == tree.const => tree case _ => finalize(tree, untpd.Literal(const)(sourceFile(tree))) } - def New(tree: Tree)(tpt: Tree)(implicit ctx: Context): New = tree match { + def New(tree: Tree)(tpt: Tree)(using Context): New = tree match { case tree: New if (tpt eq tree.tpt) => tree case _ => finalize(tree, untpd.New(tpt)(sourceFile(tree))) } - def Typed(tree: Tree)(expr: Tree, tpt: Tree)(implicit ctx: Context): Typed = tree match { + def Typed(tree: Tree)(expr: Tree, tpt: Tree)(using Context): Typed = tree match { case tree: Typed if (expr eq tree.expr) && (tpt eq tree.tpt) => tree case tree => finalize(tree, untpd.Typed(expr, tpt)(sourceFile(tree))) } - def NamedArg(tree: Tree)(name: Name, arg: Tree)(implicit ctx: Context): NamedArg = tree match { + def NamedArg(tree: Tree)(name: Name, arg: Tree)(using Context): NamedArg = tree match { case tree: NamedArg if (name == tree.name) && (arg eq tree.arg) => tree case _ => finalize(tree, untpd.NamedArg(name, arg)(sourceFile(tree))) } - def Assign(tree: Tree)(lhs: Tree, rhs: Tree)(implicit ctx: Context): Assign = tree match { + def Assign(tree: Tree)(lhs: Tree, rhs: Tree)(using Context): Assign = tree match { case tree: Assign if (lhs eq tree.lhs) && (rhs eq tree.rhs) => tree case _ => finalize(tree, untpd.Assign(lhs, rhs)(sourceFile(tree))) } - def Block(tree: Tree)(stats: List[Tree], expr: Tree)(implicit ctx: Context): Block = tree match { + def Block(tree: Tree)(stats: List[Tree], expr: Tree)(using Context): Block = tree match { case tree: Block if (stats eq tree.stats) && (expr eq tree.expr) => tree case _ => finalize(tree, untpd.Block(stats, expr)(sourceFile(tree))) } - def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = tree match { + def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(using Context): If = tree match { case tree: If if (cond eq tree.cond) && (thenp eq tree.thenp) && (elsep eq tree.elsep) => tree case tree: InlineIf => finalize(tree, untpd.InlineIf(cond, thenp, elsep)(sourceFile(tree))) case _ => finalize(tree, untpd.If(cond, thenp, elsep)(sourceFile(tree))) } - def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(implicit ctx: Context): Closure = tree match { + def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(using Context): Closure = tree match { case tree: Closure if (env eq tree.env) && (meth eq tree.meth) && (tpt eq tree.tpt) => tree case _ => finalize(tree, untpd.Closure(env, meth, tpt)(sourceFile(tree))) } - def Match(tree: Tree)(selector: Tree, cases: List[CaseDef])(implicit ctx: Context): Match = tree match { + def Match(tree: Tree)(selector: Tree, cases: List[CaseDef])(using Context): Match = tree match { case tree: Match if (selector eq tree.selector) && (cases eq tree.cases) => tree case tree: InlineMatch => finalize(tree, untpd.InlineMatch(selector, cases)(sourceFile(tree))) case _ => finalize(tree, untpd.Match(selector, cases)(sourceFile(tree))) } - def CaseDef(tree: Tree)(pat: Tree, guard: Tree, body: Tree)(implicit ctx: Context): CaseDef = tree match { + def CaseDef(tree: Tree)(pat: Tree, guard: Tree, body: Tree)(using Context): CaseDef = tree match { case tree: CaseDef if (pat eq tree.pat) && (guard eq tree.guard) && (body eq tree.body) => tree case _ => finalize(tree, untpd.CaseDef(pat, guard, body)(sourceFile(tree))) } - def Labeled(tree: Tree)(bind: Bind, expr: Tree)(implicit ctx: Context): Labeled = tree match { + def Labeled(tree: Tree)(bind: Bind, expr: Tree)(using Context): Labeled = tree match { case tree: Labeled if (bind eq tree.bind) && (expr eq tree.expr) => tree case _ => finalize(tree, untpd.Labeled(bind, expr)(sourceFile(tree))) } - def Return(tree: Tree)(expr: Tree, from: Tree)(implicit ctx: Context): Return = tree match { + def Return(tree: Tree)(expr: Tree, from: Tree)(using Context): Return = tree match { case tree: Return if (expr eq tree.expr) && (from eq tree.from) => tree case _ => finalize(tree, untpd.Return(expr, from)(sourceFile(tree))) } - def WhileDo(tree: Tree)(cond: Tree, body: Tree)(implicit ctx: Context): WhileDo = tree match { + def WhileDo(tree: Tree)(cond: Tree, body: Tree)(using Context): WhileDo = tree match { case tree: WhileDo if (cond eq tree.cond) && (body eq tree.body) => tree case _ => finalize(tree, untpd.WhileDo(cond, body)(sourceFile(tree))) } - def Try(tree: Tree)(expr: Tree, cases: List[CaseDef], finalizer: Tree)(implicit ctx: Context): Try = tree match { + def Try(tree: Tree)(expr: Tree, cases: List[CaseDef], finalizer: Tree)(using Context): Try = tree match { case tree: Try if (expr eq tree.expr) && (cases eq tree.cases) && (finalizer eq tree.finalizer) => tree case _ => finalize(tree, untpd.Try(expr, cases, finalizer)(sourceFile(tree))) } - def SeqLiteral(tree: Tree)(elems: List[Tree], elemtpt: Tree)(implicit ctx: Context): SeqLiteral = tree match { + def SeqLiteral(tree: Tree)(elems: List[Tree], elemtpt: Tree)(using Context): SeqLiteral = tree match { case tree: JavaSeqLiteral => if ((elems eq tree.elems) && (elemtpt eq tree.elemtpt)) tree else finalize(tree, untpd.JavaSeqLiteral(elems, elemtpt)) case tree: SeqLiteral if (elems eq tree.elems) && (elemtpt eq tree.elemtpt) => tree case _ => finalize(tree, untpd.SeqLiteral(elems, elemtpt)(sourceFile(tree))) } - def Inlined(tree: Tree)(call: tpd.Tree, bindings: List[MemberDef], expansion: Tree)(implicit ctx: Context): Inlined = tree match { + def Inlined(tree: Tree)(call: tpd.Tree, bindings: List[MemberDef], expansion: Tree)(using Context): Inlined = tree match { case tree: Inlined if (call eq tree.call) && (bindings eq tree.bindings) && (expansion eq tree.expansion) => tree case _ => finalize(tree, untpd.Inlined(call, bindings, expansion)(sourceFile(tree))) } - def SingletonTypeTree(tree: Tree)(ref: Tree)(implicit ctx: Context): SingletonTypeTree = tree match { + def SingletonTypeTree(tree: Tree)(ref: Tree)(using Context): SingletonTypeTree = tree match { case tree: SingletonTypeTree if (ref eq tree.ref) => tree case _ => finalize(tree, untpd.SingletonTypeTree(ref)(sourceFile(tree))) } - def RefinedTypeTree(tree: Tree)(tpt: Tree, refinements: List[Tree])(implicit ctx: Context): RefinedTypeTree = tree match { + def RefinedTypeTree(tree: Tree)(tpt: Tree, refinements: List[Tree])(using Context): RefinedTypeTree = tree match { case tree: RefinedTypeTree if (tpt eq tree.tpt) && (refinements eq tree.refinements) => tree case _ => finalize(tree, untpd.RefinedTypeTree(tpt, refinements)(sourceFile(tree))) } - def AppliedTypeTree(tree: Tree)(tpt: Tree, args: List[Tree])(implicit ctx: Context): AppliedTypeTree = tree match { + def AppliedTypeTree(tree: Tree)(tpt: Tree, args: List[Tree])(using Context): AppliedTypeTree = tree match { case tree: AppliedTypeTree if (tpt eq tree.tpt) && (args eq tree.args) => tree case _ => finalize(tree, untpd.AppliedTypeTree(tpt, args)(sourceFile(tree))) } - def LambdaTypeTree(tree: Tree)(tparams: List[TypeDef], body: Tree)(implicit ctx: Context): LambdaTypeTree = tree match { + def LambdaTypeTree(tree: Tree)(tparams: List[TypeDef], body: Tree)(using Context): LambdaTypeTree = tree match { case tree: LambdaTypeTree if (tparams eq tree.tparams) && (body eq tree.body) => tree case _ => finalize(tree, untpd.LambdaTypeTree(tparams, body)(sourceFile(tree))) } - def TermLambdaTypeTree(tree: Tree)(params: List[ValDef], body: Tree)(implicit ctx: Context): TermLambdaTypeTree = tree match { + def TermLambdaTypeTree(tree: Tree)(params: List[ValDef], body: Tree)(using Context): TermLambdaTypeTree = tree match { case tree: TermLambdaTypeTree if (params eq tree.params) && (body eq tree.body) => tree case _ => finalize(tree, untpd.TermLambdaTypeTree(params, body)(sourceFile(tree))) } - def MatchTypeTree(tree: Tree)(bound: Tree, selector: Tree, cases: List[CaseDef])(implicit ctx: Context): MatchTypeTree = tree match { + def MatchTypeTree(tree: Tree)(bound: Tree, selector: Tree, cases: List[CaseDef])(using Context): MatchTypeTree = tree match { case tree: MatchTypeTree if (bound eq tree.bound) && (selector eq tree.selector) && (cases eq tree.cases) => tree case _ => finalize(tree, untpd.MatchTypeTree(bound, selector, cases)(sourceFile(tree))) } - def ByNameTypeTree(tree: Tree)(result: Tree)(implicit ctx: Context): ByNameTypeTree = tree match { + def ByNameTypeTree(tree: Tree)(result: Tree)(using Context): ByNameTypeTree = tree match { case tree: ByNameTypeTree if (result eq tree.result) => tree case _ => finalize(tree, untpd.ByNameTypeTree(result)(sourceFile(tree))) } - def TypeBoundsTree(tree: Tree)(lo: Tree, hi: Tree, alias: Tree)(implicit ctx: Context): TypeBoundsTree = tree match { + def TypeBoundsTree(tree: Tree)(lo: Tree, hi: Tree, alias: Tree)(using Context): TypeBoundsTree = tree match { case tree: TypeBoundsTree if (lo eq tree.lo) && (hi eq tree.hi) && (alias eq tree.alias) => tree case _ => finalize(tree, untpd.TypeBoundsTree(lo, hi, alias)(sourceFile(tree))) } - def Bind(tree: Tree)(name: Name, body: Tree)(implicit ctx: Context): Bind = tree match { + def Bind(tree: Tree)(name: Name, body: Tree)(using Context): Bind = tree match { case tree: Bind if (name eq tree.name) && (body eq tree.body) => tree case _ => finalize(tree, untpd.Bind(name, body)(sourceFile(tree))) } - def Alternative(tree: Tree)(trees: List[Tree])(implicit ctx: Context): Alternative = tree match { + def Alternative(tree: Tree)(trees: List[Tree])(using Context): Alternative = tree match { case tree: Alternative if (trees eq tree.trees) => tree case _ => finalize(tree, untpd.Alternative(trees)(sourceFile(tree))) } - def UnApply(tree: Tree)(fun: Tree, implicits: List[Tree], patterns: List[Tree])(implicit ctx: Context): UnApply = tree match { + def UnApply(tree: Tree)(fun: Tree, implicits: List[Tree], patterns: List[Tree])(using Context): UnApply = tree match { case tree: UnApply if (fun eq tree.fun) && (implicits eq tree.implicits) && (patterns eq tree.patterns) => tree case _ => finalize(tree, untpd.UnApply(fun, implicits, patterns)(sourceFile(tree))) } - def ValDef(tree: Tree)(name: TermName, tpt: Tree, rhs: LazyTree)(implicit ctx: Context): ValDef = tree match { + def ValDef(tree: Tree)(name: TermName, tpt: Tree, rhs: LazyTree)(using Context): ValDef = tree match { case tree: ValDef if (name == tree.name) && (tpt eq tree.tpt) && (rhs eq tree.unforcedRhs) => tree case _ => finalize(tree, untpd.ValDef(name, tpt, rhs)(sourceFile(tree))) } - def DefDef(tree: Tree)(name: TermName, tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: LazyTree)(implicit ctx: Context): DefDef = tree match { + def DefDef(tree: Tree)(name: TermName, tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: LazyTree)(using Context): DefDef = tree match { case tree: DefDef if (name == tree.name) && (tparams eq tree.tparams) && (vparamss eq tree.vparamss) && (tpt eq tree.tpt) && (rhs eq tree.unforcedRhs) => tree case _ => finalize(tree, untpd.DefDef(name, tparams, vparamss, tpt, rhs)(sourceFile(tree))) } - def TypeDef(tree: Tree)(name: TypeName, rhs: Tree)(implicit ctx: Context): TypeDef = tree match { + def TypeDef(tree: Tree)(name: TypeName, rhs: Tree)(using Context): TypeDef = tree match { case tree: TypeDef if (name == tree.name) && (rhs eq tree.rhs) => tree case _ => finalize(tree, untpd.TypeDef(name, rhs)(sourceFile(tree))) } - def Template(tree: Tree)(constr: DefDef, parents: List[Tree], derived: List[untpd.Tree], self: ValDef, body: LazyTreeList)(implicit ctx: Context): Template = tree match { + def Template(tree: Tree)(constr: DefDef, parents: List[Tree], derived: List[untpd.Tree], self: ValDef, body: LazyTreeList)(using Context): Template = tree match { case tree: Template if (constr eq tree.constr) && (parents eq tree.parents) && (derived eq tree.derived) && (self eq tree.self) && (body eq tree.unforcedBody) => tree case tree => finalize(tree, untpd.Template(constr, parents, derived, self, body)(sourceFile(tree))) } - def Import(tree: Tree)(expr: Tree, selectors: List[untpd.ImportSelector])(implicit ctx: Context): Import = tree match { + def Import(tree: Tree)(expr: Tree, selectors: List[untpd.ImportSelector])(using Context): Import = tree match { case tree: Import if (expr eq tree.expr) && (selectors eq tree.selectors) => tree case _ => finalize(tree, untpd.Import(expr, selectors)(sourceFile(tree))) } - def PackageDef(tree: Tree)(pid: RefTree, stats: List[Tree])(implicit ctx: Context): PackageDef = tree match { + def PackageDef(tree: Tree)(pid: RefTree, stats: List[Tree])(using Context): PackageDef = tree match { case tree: PackageDef if (pid eq tree.pid) && (stats eq tree.stats) => tree case _ => finalize(tree, untpd.PackageDef(pid, stats)(sourceFile(tree))) } - def Annotated(tree: Tree)(arg: Tree, annot: Tree)(implicit ctx: Context): Annotated = tree match { + def Annotated(tree: Tree)(arg: Tree, annot: Tree)(using Context): Annotated = tree match { case tree: Annotated if (arg eq tree.arg) && (annot eq tree.annot) => tree case _ => finalize(tree, untpd.Annotated(arg, annot)(sourceFile(tree))) } - def Thicket(tree: Tree)(trees: List[Tree])(implicit ctx: Context): Thicket = tree match { + def Thicket(tree: Tree)(trees: List[Tree])(using Context): Thicket = tree match { case tree: Thicket if (trees eq tree.trees) => tree case _ => finalize(tree, untpd.Thicket(trees)(sourceFile(tree))) } // Copier methods with default arguments; these demand that the original tree // is of the same class as the copy. We only include trees with more than 2 elements here. - def If(tree: If)(cond: Tree = tree.cond, thenp: Tree = tree.thenp, elsep: Tree = tree.elsep)(implicit ctx: Context): If = + def If(tree: If)(cond: Tree = tree.cond, thenp: Tree = tree.thenp, elsep: Tree = tree.elsep)(using Context): If = If(tree: Tree)(cond, thenp, elsep) - def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(implicit ctx: Context): Closure = + def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(using Context): Closure = Closure(tree: Tree)(env, meth, tpt) - def CaseDef(tree: CaseDef)(pat: Tree = tree.pat, guard: Tree = tree.guard, body: Tree = tree.body)(implicit ctx: Context): CaseDef = + def CaseDef(tree: CaseDef)(pat: Tree = tree.pat, guard: Tree = tree.guard, body: Tree = tree.body)(using Context): CaseDef = CaseDef(tree: Tree)(pat, guard, body) - def Try(tree: Try)(expr: Tree = tree.expr, cases: List[CaseDef] = tree.cases, finalizer: Tree = tree.finalizer)(implicit ctx: Context): Try = + def Try(tree: Try)(expr: Tree = tree.expr, cases: List[CaseDef] = tree.cases, finalizer: Tree = tree.finalizer)(using Context): Try = Try(tree: Tree)(expr, cases, finalizer) - def UnApply(tree: UnApply)(fun: Tree = tree.fun, implicits: List[Tree] = tree.implicits, patterns: List[Tree] = tree.patterns)(implicit ctx: Context): UnApply = + def UnApply(tree: UnApply)(fun: Tree = tree.fun, implicits: List[Tree] = tree.implicits, patterns: List[Tree] = tree.patterns)(using Context): UnApply = UnApply(tree: Tree)(fun, implicits, patterns) - def ValDef(tree: ValDef)(name: TermName = tree.name, tpt: Tree = tree.tpt, rhs: LazyTree = tree.unforcedRhs)(implicit ctx: Context): ValDef = + def ValDef(tree: ValDef)(name: TermName = tree.name, tpt: Tree = tree.tpt, rhs: LazyTree = tree.unforcedRhs)(using Context): ValDef = ValDef(tree: Tree)(name, tpt, rhs) - def DefDef(tree: DefDef)(name: TermName = tree.name, tparams: List[TypeDef] = tree.tparams, vparamss: List[List[ValDef]] = tree.vparamss, tpt: Tree = tree.tpt, rhs: LazyTree = tree.unforcedRhs)(implicit ctx: Context): DefDef = + def DefDef(tree: DefDef)(name: TermName = tree.name, tparams: List[TypeDef] = tree.tparams, vparamss: List[List[ValDef]] = tree.vparamss, tpt: Tree = tree.tpt, rhs: LazyTree = tree.unforcedRhs)(using Context): DefDef = DefDef(tree: Tree)(name, tparams, vparamss, tpt, rhs) - def TypeDef(tree: TypeDef)(name: TypeName = tree.name, rhs: Tree = tree.rhs)(implicit ctx: Context): TypeDef = + def TypeDef(tree: TypeDef)(name: TypeName = tree.name, rhs: Tree = tree.rhs)(using Context): TypeDef = TypeDef(tree: Tree)(name, rhs) - def Template(tree: Template)(constr: DefDef = tree.constr, parents: List[Tree] = tree.parents, derived: List[untpd.Tree] = tree.derived, self: ValDef = tree.self, body: LazyTreeList = tree.unforcedBody)(implicit ctx: Context): Template = + def Template(tree: Template)(constr: DefDef = tree.constr, parents: List[Tree] = tree.parents, derived: List[untpd.Tree] = tree.derived, self: ValDef = tree.self, body: LazyTreeList = tree.unforcedBody)(using Context): Template = Template(tree: Tree)(constr, parents, derived, self, body) } /** Hook to indicate that a transform of some subtree should be skipped */ - protected def skipTransform(tree: Tree)(implicit ctx: Context): Boolean = false + protected def skipTransform(tree: Tree)(using Context): Boolean = false /** For untyped trees, this is just the identity. * For typed trees, a context derived form `ctx` that records `call` as the * innermost enclosing call for which the inlined version is currently * processed. */ - protected def inlineContext(call: Tree)(implicit ctx: Context): Context = ctx + protected def inlineContext(call: Tree)(using Context): Context = ctx abstract class TreeMap(val cpy: TreeCopier = inst.cpy) { self => def transform(tree: Tree)(using Context): Tree = { @@ -1353,7 +1353,7 @@ object Trees { case Import(expr, selectors) => cpy.Import(tree)(transform(expr), selectors) case PackageDef(pid, stats) => - cpy.PackageDef(tree)(transformSub(pid), transformStats(stats)(localCtx)) + cpy.PackageDef(tree)(transformSub(pid), transformStats(stats)(using localCtx)) case Annotated(arg, annot) => cpy.Annotated(tree)(transform(arg), transform(annot)) case Thicket(trees) => @@ -1365,16 +1365,16 @@ object Trees { } } - def transformStats(trees: List[Tree])(implicit ctx: Context): List[Tree] = + def transformStats(trees: List[Tree])(using Context): List[Tree] = transform(trees) - def transform(trees: List[Tree])(implicit ctx: Context): List[Tree] = + def transform(trees: List[Tree])(using Context): List[Tree] = flatten(trees mapConserve (transform(_))) - def transformSub[Tr <: Tree](tree: Tr)(implicit ctx: Context): Tr = + def transformSub[Tr <: Tree](tree: Tr)(using Context): Tr = transform(tree).asInstanceOf[Tr] - def transformSub[Tr <: Tree](trees: List[Tr])(implicit ctx: Context): List[Tr] = + def transformSub[Tr <: Tree](trees: List[Tr])(using Context): List[Tr] = transform(trees).asInstanceOf[List[Tr]] - protected def transformMoreCases(tree: Tree)(implicit ctx: Context): Tree = { + protected def transformMoreCases(tree: Tree)(using Context): Tree = { assert(ctx.reporter.errorsReported) tree } @@ -1382,12 +1382,12 @@ object Trees { abstract class TreeAccumulator[X] { self => // Ties the knot of the traversal: call `foldOver(x, tree))` to dive in the `tree` node. - def apply(x: X, tree: Tree)(implicit ctx: Context): X + def apply(x: X, tree: Tree)(using Context): X - def apply(x: X, trees: Traversable[Tree])(implicit ctx: Context): X = trees.foldLeft(x)(apply) - def foldOver(x: X, tree: Tree)(implicit ctx: Context): X = + def apply(x: X, trees: Traversable[Tree])(using Context): X = trees.foldLeft(x)(apply) + def foldOver(x: X, tree: Tree)(using Context): X = if (tree.source != ctx.source && tree.source.exists) - foldOver(x, tree)(ctx.withSource(tree.source)) + foldOver(x, tree)(using ctx.withSource(tree.source)) else { Stats.record(s"TreeAccumulator.foldOver/$getClass") def localCtx = @@ -1436,7 +1436,7 @@ object Trees { case SeqLiteral(elems, elemtpt) => this(this(x, elems), elemtpt) case Inlined(call, bindings, expansion) => - this(this(x, bindings), expansion)(inlineContext(call)) + this(this(x, bindings), expansion)(using inlineContext(call)) case TypeTree() => x case SingletonTypeTree(ref) => @@ -1482,7 +1482,7 @@ object Trees { case Import(expr, _) => this(x, expr) case PackageDef(pid, stats) => - this(this(x, pid), stats)(localCtx) + this(this(x, pid), stats)(using localCtx) case Annotated(arg, annot) => this(this(x, arg), annot) case Thicket(ts) => @@ -1494,7 +1494,7 @@ object Trees { } } - def foldMoreCases(x: X, tree: Tree)(implicit ctx: Context): X = { + def foldMoreCases(x: X, tree: Tree)(using Context): X = { assert(ctx.reporter.errorsReported || ctx.mode.is(Mode.Interactive), tree) // In interactive mode, errors might come from previous runs. // In case of errors it may be that typed trees point to untyped ones. @@ -1505,28 +1505,28 @@ object Trees { } abstract class TreeTraverser extends TreeAccumulator[Unit] { - def traverse(tree: Tree)(implicit ctx: Context): Unit - def apply(x: Unit, tree: Tree)(implicit ctx: Context): Unit = traverse(tree) - protected def traverseChildren(tree: Tree)(implicit ctx: Context): Unit = foldOver((), tree) + def traverse(tree: Tree)(using Context): Unit + def apply(x: Unit, tree: Tree)(using Context): Unit = traverse(tree) + protected def traverseChildren(tree: Tree)(using Context): Unit = foldOver((), tree) } /** Fold `f` over all tree nodes, in depth-first, prefix order */ class DeepFolder[X](f: (X, Tree) => X) extends TreeAccumulator[X] { - def apply(x: X, tree: Tree)(implicit ctx: Context): X = foldOver(f(x, tree), tree) + def apply(x: X, tree: Tree)(using Context): X = foldOver(f(x, tree), tree) } /** Fold `f` over all tree nodes, in depth-first, prefix order, but don't visit * subtrees where `f` returns a different result for the root, i.e. `f(x, root) ne x`. */ class ShallowFolder[X](f: (X, Tree) => X) extends TreeAccumulator[X] { - def apply(x: X, tree: Tree)(implicit ctx: Context): X = { + def apply(x: X, tree: Tree)(using Context): X = { val x1 = f(x, tree) if (x1.asInstanceOf[AnyRef] ne x.asInstanceOf[AnyRef]) x1 else foldOver(x1, tree) } } - def rename(tree: NameTree, newName: Name)(implicit ctx: Context): tree.ThisTree[T] = { + def rename(tree: NameTree, newName: Name)(using Context): tree.ThisTree[T] = { tree match { case tree: Ident => cpy.Ident(tree)(newName) case tree: Select => cpy.Select(tree)(tree.qualifier, newName) @@ -1586,7 +1586,7 @@ object Trees { } - def resolveConstructor(atp: Type, args: List[Tree])(implicit ctx: Context): tpd.Tree = { + def resolveConstructor(atp: Type, args: List[Tree])(using Context): tpd.Tree = { val targs = atp.argTypes applyOverloaded(tpd.New(atp.typeConstructor), nme.CONSTRUCTOR, args, targs, atp) } diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 844b29d4e33b..57227b2eb3e5 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -21,64 +21,64 @@ import scala.io.Codec /** Some creators for typed trees */ object tpd extends Trees.Instance[Type] with TypedTreeInfo { - private def ta(implicit ctx: Context) = ctx.typeAssigner + private def ta(using Context) = ctx.typeAssigner - def Ident(tp: NamedType)(implicit ctx: Context): Ident = + def Ident(tp: NamedType)(using Context): Ident = ta.assignType(untpd.Ident(tp.name), tp) - def Select(qualifier: Tree, name: Name)(implicit ctx: Context): Select = + def Select(qualifier: Tree, name: Name)(using Context): Select = ta.assignType(untpd.Select(qualifier, name), qualifier) - def Select(qualifier: Tree, tp: NamedType)(implicit ctx: Context): Select = + def Select(qualifier: Tree, tp: NamedType)(using Context): Select = untpd.Select(qualifier, tp.name).withType(tp) - def This(cls: ClassSymbol)(implicit ctx: Context): This = + def This(cls: ClassSymbol)(using Context): This = untpd.This(untpd.Ident(cls.name)).withType(cls.thisType) - def Super(qual: Tree, mix: untpd.Ident, mixinClass: Symbol)(implicit ctx: Context): Super = + def Super(qual: Tree, mix: untpd.Ident, mixinClass: Symbol)(using Context): Super = ta.assignType(untpd.Super(qual, mix), qual, mixinClass) - def Super(qual: Tree, mixName: TypeName, mixinClass: Symbol = NoSymbol)(implicit ctx: Context): Super = + def Super(qual: Tree, mixName: TypeName, mixinClass: Symbol = NoSymbol)(using Context): Super = Super(qual, if (mixName.isEmpty) untpd.EmptyTypeIdent else untpd.Ident(mixName), mixinClass) - def Apply(fn: Tree, args: List[Tree])(implicit ctx: Context): Apply = { + def Apply(fn: Tree, args: List[Tree])(using Context): Apply = { assert(fn.isInstanceOf[RefTree] || fn.isInstanceOf[GenericApply[_]] || fn.isInstanceOf[Inlined] || fn.isInstanceOf[tasty.TreePickler.Hole]) ta.assignType(untpd.Apply(fn, args), fn, args) } - def TypeApply(fn: Tree, args: List[Tree])(implicit ctx: Context): TypeApply = { + def TypeApply(fn: Tree, args: List[Tree])(using Context): TypeApply = { assert(fn.isInstanceOf[RefTree] || fn.isInstanceOf[GenericApply[_]]) ta.assignType(untpd.TypeApply(fn, args), fn, args) } - def Literal(const: Constant)(implicit ctx: Context): Literal = + def Literal(const: Constant)(using Context): Literal = ta.assignType(untpd.Literal(const)) - def unitLiteral(implicit ctx: Context): Literal = + def unitLiteral(using Context): Literal = Literal(Constant(())) - def nullLiteral(implicit ctx: Context): Literal = + def nullLiteral(using Context): Literal = Literal(Constant(null)) - def New(tpt: Tree)(implicit ctx: Context): New = + def New(tpt: Tree)(using Context): New = ta.assignType(untpd.New(tpt), tpt) - def New(tp: Type)(implicit ctx: Context): New = New(TypeTree(tp)) + def New(tp: Type)(using Context): New = New(TypeTree(tp)) - def Typed(expr: Tree, tpt: Tree)(implicit ctx: Context): Typed = + def Typed(expr: Tree, tpt: Tree)(using Context): Typed = ta.assignType(untpd.Typed(expr, tpt), tpt) - def NamedArg(name: Name, arg: Tree)(implicit ctx: Context): NamedArg = + def NamedArg(name: Name, arg: Tree)(using Context): NamedArg = ta.assignType(untpd.NamedArg(name, arg), arg) - def Assign(lhs: Tree, rhs: Tree)(implicit ctx: Context): Assign = + def Assign(lhs: Tree, rhs: Tree)(using Context): Assign = ta.assignType(untpd.Assign(lhs, rhs)) - def Block(stats: List[Tree], expr: Tree)(implicit ctx: Context): Block = + def Block(stats: List[Tree], expr: Tree)(using Context): Block = ta.assignType(untpd.Block(stats, expr), stats, expr) /** Join `stats` in front of `expr` creating a new block if necessary */ - def seq(stats: List[Tree], expr: Tree)(implicit ctx: Context): Tree = + def seq(stats: List[Tree], expr: Tree)(using Context): Tree = if (stats.isEmpty) expr else expr match { case Block(_, _: Closure) => @@ -89,13 +89,13 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { Block(stats, expr) } - def If(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = + def If(cond: Tree, thenp: Tree, elsep: Tree)(using Context): If = ta.assignType(untpd.If(cond, thenp, elsep), thenp, elsep) - def InlineIf(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = + def InlineIf(cond: Tree, thenp: Tree, elsep: Tree)(using Context): If = ta.assignType(untpd.InlineIf(cond, thenp, elsep), thenp, elsep) - def Closure(env: List[Tree], meth: Tree, tpt: Tree)(implicit ctx: Context): Closure = + def Closure(env: List[Tree], meth: Tree, tpt: Tree)(using Context): Closure = ta.assignType(untpd.Closure(env, meth, tpt), meth, tpt) /** A function def @@ -109,7 +109,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * where the closure's type is the target type of the expression (FunctionN, unless * otherwise specified). */ - def Closure(meth: TermSymbol, rhsFn: List[List[Tree]] => Tree, targs: List[Tree] = Nil, targetType: Type = NoType)(implicit ctx: Context): Block = { + def Closure(meth: TermSymbol, rhsFn: List[List[Tree]] => Tree, targs: List[Tree] = Nil, targetType: Type = NoType)(using Context): Block = { val targetTpt = if (targetType.exists) TypeTree(targetType) else EmptyTree val call = if (targs.isEmpty) Ident(TermRef(NoPrefix, meth)) @@ -120,94 +120,94 @@ 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)(implicit ctx: Context): Block = { + def Lambda(tpe: MethodType, rhsFn: List[Tree] => Tree)(using Context): Block = { val meth = ctx.newSymbol(ctx.owner, nme.ANON_FUN, Synthetic | Method, tpe) Closure(meth, tss => rhsFn(tss.head).changeOwner(ctx.owner, meth)) } - def CaseDef(pat: Tree, guard: Tree, body: Tree)(implicit ctx: Context): CaseDef = + def CaseDef(pat: Tree, guard: Tree, body: Tree)(using Context): CaseDef = ta.assignType(untpd.CaseDef(pat, guard, body), pat, body) - def Match(selector: Tree, cases: List[CaseDef])(implicit ctx: Context): Match = + def Match(selector: Tree, cases: List[CaseDef])(using Context): Match = ta.assignType(untpd.Match(selector, cases), selector, cases) - def InlineMatch(selector: Tree, cases: List[CaseDef])(implicit ctx: Context): Match = + def InlineMatch(selector: Tree, cases: List[CaseDef])(using Context): Match = ta.assignType(untpd.InlineMatch(selector, cases), selector, cases) - def Labeled(bind: Bind, expr: Tree)(implicit ctx: Context): Labeled = + def Labeled(bind: Bind, expr: Tree)(using Context): Labeled = ta.assignType(untpd.Labeled(bind, expr)) - def Labeled(sym: TermSymbol, expr: Tree)(implicit ctx: Context): Labeled = + def Labeled(sym: TermSymbol, expr: Tree)(using Context): Labeled = Labeled(Bind(sym, EmptyTree), expr) - def Return(expr: Tree, from: Tree)(implicit ctx: Context): Return = + def Return(expr: Tree, from: Tree)(using Context): Return = ta.assignType(untpd.Return(expr, from)) - def Return(expr: Tree, from: Symbol)(implicit ctx: Context): Return = + def Return(expr: Tree, from: Symbol)(using Context): Return = Return(expr, Ident(from.termRef)) - def WhileDo(cond: Tree, body: Tree)(implicit ctx: Context): WhileDo = + def WhileDo(cond: Tree, body: Tree)(using Context): WhileDo = ta.assignType(untpd.WhileDo(cond, body)) - def Try(block: Tree, cases: List[CaseDef], finalizer: Tree)(implicit ctx: Context): Try = + def Try(block: Tree, cases: List[CaseDef], finalizer: Tree)(using Context): Try = ta.assignType(untpd.Try(block, cases, finalizer), block, cases) - def SeqLiteral(elems: List[Tree], elemtpt: Tree)(implicit ctx: Context): SeqLiteral = + def SeqLiteral(elems: List[Tree], elemtpt: Tree)(using Context): SeqLiteral = ta.assignType(untpd.SeqLiteral(elems, elemtpt), elems, elemtpt) - def JavaSeqLiteral(elems: List[Tree], elemtpt: Tree)(implicit ctx: Context): JavaSeqLiteral = + def JavaSeqLiteral(elems: List[Tree], elemtpt: Tree)(using Context): JavaSeqLiteral = ta.assignType(untpd.JavaSeqLiteral(elems, elemtpt), elems, elemtpt).asInstanceOf[JavaSeqLiteral] - def Inlined(call: Tree, bindings: List[MemberDef], expansion: Tree)(implicit ctx: Context): Inlined = + def Inlined(call: Tree, bindings: List[MemberDef], expansion: Tree)(using Context): Inlined = ta.assignType(untpd.Inlined(call, bindings, expansion), bindings, expansion) - def TypeTree(tp: Type)(implicit ctx: Context): TypeTree = + def TypeTree(tp: Type)(using Context): TypeTree = untpd.TypeTree().withType(tp) - def SingletonTypeTree(ref: Tree)(implicit ctx: Context): SingletonTypeTree = + def SingletonTypeTree(ref: Tree)(using Context): SingletonTypeTree = ta.assignType(untpd.SingletonTypeTree(ref), ref) - def RefinedTypeTree(parent: Tree, refinements: List[Tree], refineCls: ClassSymbol)(implicit ctx: Context): Tree = + def RefinedTypeTree(parent: Tree, refinements: List[Tree], refineCls: ClassSymbol)(using Context): Tree = ta.assignType(untpd.RefinedTypeTree(parent, refinements), parent, refinements, refineCls) - def AppliedTypeTree(tycon: Tree, args: List[Tree])(implicit ctx: Context): AppliedTypeTree = + def AppliedTypeTree(tycon: Tree, args: List[Tree])(using Context): AppliedTypeTree = ta.assignType(untpd.AppliedTypeTree(tycon, args), tycon, args) - def ByNameTypeTree(result: Tree)(implicit ctx: Context): ByNameTypeTree = + def ByNameTypeTree(result: Tree)(using Context): ByNameTypeTree = ta.assignType(untpd.ByNameTypeTree(result), result) - def LambdaTypeTree(tparams: List[TypeDef], body: Tree)(implicit ctx: Context): LambdaTypeTree = + def LambdaTypeTree(tparams: List[TypeDef], body: Tree)(using Context): LambdaTypeTree = ta.assignType(untpd.LambdaTypeTree(tparams, body), tparams, body) - def MatchTypeTree(bound: Tree, selector: Tree, cases: List[CaseDef])(implicit ctx: Context): MatchTypeTree = + def MatchTypeTree(bound: Tree, selector: Tree, cases: List[CaseDef])(using Context): MatchTypeTree = ta.assignType(untpd.MatchTypeTree(bound, selector, cases), bound, selector, cases) - def TypeBoundsTree(lo: Tree, hi: Tree, alias: Tree = EmptyTree)(implicit ctx: Context): TypeBoundsTree = + def TypeBoundsTree(lo: Tree, hi: Tree, alias: Tree = EmptyTree)(using Context): TypeBoundsTree = ta.assignType(untpd.TypeBoundsTree(lo, hi, alias), lo, hi, alias) - def Bind(sym: Symbol, body: Tree)(implicit ctx: Context): Bind = + def Bind(sym: Symbol, body: Tree)(using Context): Bind = ta.assignType(untpd.Bind(sym.name, body), sym) /** A pattern corresponding to `sym: tpe` */ - def BindTyped(sym: TermSymbol, tpe: Type)(implicit ctx: Context): Bind = + def BindTyped(sym: TermSymbol, tpe: Type)(using Context): Bind = Bind(sym, Typed(Underscore(tpe), TypeTree(tpe))) - def Alternative(trees: List[Tree])(implicit ctx: Context): Alternative = + def Alternative(trees: List[Tree])(using Context): Alternative = ta.assignType(untpd.Alternative(trees), trees) - def UnApply(fun: Tree, implicits: List[Tree], patterns: List[Tree], proto: Type)(implicit ctx: Context): UnApply = { + def UnApply(fun: Tree, implicits: List[Tree], patterns: List[Tree], proto: Type)(using Context): UnApply = { assert(fun.isInstanceOf[RefTree] || fun.isInstanceOf[GenericApply[_]]) ta.assignType(untpd.UnApply(fun, implicits, patterns), proto) } - def ValDef(sym: TermSymbol, rhs: LazyTree = EmptyTree)(implicit ctx: Context): ValDef = + def ValDef(sym: TermSymbol, rhs: LazyTree = EmptyTree)(using Context): ValDef = ta.assignType(untpd.ValDef(sym.name, TypeTree(sym.info), rhs), sym) - def SyntheticValDef(name: TermName, rhs: Tree)(implicit ctx: Context): ValDef = + def SyntheticValDef(name: TermName, rhs: Tree)(using Context): ValDef = ValDef(ctx.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)(implicit ctx: Context): DefDef = + resultType: Type, rhs: Tree)(using Context): DefDef = sym.setParamss(tparams, vparamss) ta.assignType( untpd.DefDef( @@ -218,10 +218,10 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { rhs), sym) - def DefDef(sym: TermSymbol, rhs: Tree = EmptyTree)(implicit ctx: Context): DefDef = + def DefDef(sym: TermSymbol, rhs: Tree = EmptyTree)(using Context): DefDef = ta.assignType(DefDef(sym, Function.const(rhs) _), sym) - def DefDef(sym: TermSymbol, rhsFn: List[List[Tree]] => Tree)(implicit ctx: Context): DefDef = + def DefDef(sym: TermSymbol, rhsFn: List[List[Tree]] => Tree)(using Context): DefDef = polyDefDef(sym, Function.const(rhsFn)) /** A DefDef with given method symbol `sym`. @@ -230,7 +230,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * Parameter symbols are taken from the `rawParamss` field of `sym`, or * are freshly generated if `rawParamss` is empty. */ - def polyDefDef(sym: TermSymbol, rhsFn: List[Type] => List[List[Tree]] => Tree)(implicit ctx: Context): DefDef = { + def polyDefDef(sym: TermSymbol, rhsFn: List[Type] => List[List[Tree]] => Tree)(using Context): DefDef = { val (tparams, existingParamss, mtp) = sym.info match { case tp: PolyType => @@ -287,10 +287,10 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { DefDef(sym, tparams, vparamss, rtp, rhsFn(targs)(argss)) } - def TypeDef(sym: TypeSymbol)(implicit ctx: Context): TypeDef = + def TypeDef(sym: TypeSymbol)(using Context): TypeDef = ta.assignType(untpd.TypeDef(sym.name, TypeTree(sym.info)), sym) - def ClassDef(cls: ClassSymbol, constr: DefDef, body: List[Tree], superArgs: List[Tree] = Nil)(implicit ctx: Context): TypeDef = { + def ClassDef(cls: ClassSymbol, constr: DefDef, body: List[Tree], superArgs: List[Tree] = Nil)(using Context): TypeDef = { val firstParent :: otherParents = cls.info.parents val superRef = if (cls.is(Trait)) TypeTree(firstParent) @@ -309,7 +309,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { ClassDefWithParents(cls, constr, superRef :: otherParents.map(TypeTree(_)), body) } - def ClassDefWithParents(cls: ClassSymbol, constr: DefDef, parents: List[Tree], body: List[Tree])(implicit ctx: Context): TypeDef = { + 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)) else EmptyValDef @@ -337,7 +337,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * The class has the same owner as the first function in `fns`. * Its position is the union of all functions in `fns`. */ - def AnonClass(parents: List[Type], fns: List[TermSymbol], methNames: List[TermName])(implicit ctx: Context): Block = { + def AnonClass(parents: List[Type], fns: List[TermSymbol], methNames: List[TermName])(using Context): Block = { val owner = fns.head.owner val parents1 = if (parents.head.classSymbol.is(Trait)) { @@ -358,21 +358,21 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { Block(cdef :: Nil, New(cls.typeRef, Nil)) } - def Import(expr: Tree, selectors: List[untpd.ImportSelector])(implicit ctx: Context): Import = + def Import(expr: Tree, selectors: List[untpd.ImportSelector])(using Context): Import = ta.assignType(untpd.Import(expr, selectors), ctx.newImportSymbol(ctx.owner, expr)) - def PackageDef(pid: RefTree, stats: List[Tree])(implicit ctx: Context): PackageDef = + def PackageDef(pid: RefTree, stats: List[Tree])(using Context): PackageDef = ta.assignType(untpd.PackageDef(pid, stats), pid) - def Annotated(arg: Tree, annot: Tree)(implicit ctx: Context): Annotated = + def Annotated(arg: Tree, annot: Tree)(using Context): Annotated = ta.assignType(untpd.Annotated(arg, annot), arg, annot) - def Throw(expr: Tree)(implicit ctx: Context): Tree = + def Throw(expr: Tree)(using Context): Tree = ref(defn.throwMethod).appliedTo(expr) // ------ Making references ------------------------------------------------------ - def prefixIsElidable(tp: NamedType)(implicit ctx: Context): Boolean = { + def prefixIsElidable(tp: NamedType)(using Context): Boolean = { val typeIsElidable = tp.prefix match { case pre: ThisType => tp.isType || @@ -391,13 +391,13 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { tp.symbol.hasAnnotation(defn.ScalaStaticAnnot) } - def needsSelect(tp: Type)(implicit ctx: Context): Boolean = tp match { + def needsSelect(tp: Type)(using Context): Boolean = tp match { case tp: TermRef => !prefixIsElidable(tp) case _ => false } /** A tree representing the same reference as the given type */ - def ref(tp: NamedType)(implicit ctx: Context): Tree = + def ref(tp: NamedType)(using Context): Tree = if (tp.isType) TypeTree(tp) else if (prefixIsElidable(tp)) Ident(tp) else if (tp.symbol.is(Module) && ctx.owner.isContainedIn(tp.symbol.moduleClass)) @@ -410,10 +410,10 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { else Select(TypeTree(pre), tp) } - def ref(sym: Symbol)(implicit ctx: Context): Tree = + def ref(sym: Symbol)(using Context): Tree = ref(NamedType(sym.owner.thisType, sym.name, sym.denot)) - private def followOuterLinks(t: Tree)(implicit ctx: Context) = t match { + private def followOuterLinks(t: Tree)(using Context) = t match { 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) @@ -421,7 +421,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { t } - def singleton(tp: Type)(implicit ctx: Context): Tree = tp.dealias match { + def singleton(tp: Type)(using Context): Tree = tp.dealias match { case tp: TermRef => ref(tp) case tp: ThisType => This(tp.cls) case tp: SkolemType => singleton(tp.narrow) @@ -432,7 +432,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** A path that corresponds to the given type `tp`. Error if `tp` is not a refinement * of an addressable singleton type. */ - def pathFor(tp: Type)(implicit ctx: Context): Tree = { + def pathFor(tp: Type)(using Context): Tree = { def recur(tp: Type): Tree = tp match { case tp: NamedType => tp.info match { @@ -453,7 +453,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * kind for the given element type in `elemTpe`. No type arguments or * `length` arguments are given. */ - def newArray(elemTpe: Type, returnTpe: Type, span: Span, dims: JavaSeqLiteral)(implicit ctx: Context): Tree = { + def newArray(elemTpe: Type, returnTpe: Type, span: Span, dims: JavaSeqLiteral)(using Context): Tree = { val elemClass = elemTpe.classSymbol def newArr = ref(defn.DottyArraysModule).select(defn.newArrayMethod).withSpan(span) @@ -467,7 +467,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** The wrapped array method name for an array of type elemtp */ - def wrapArrayMethodName(elemtp: Type)(implicit ctx: Context): TermName = { + def wrapArrayMethodName(elemtp: Type)(using Context): TermName = { val elemCls = elemtp.classSymbol if (elemCls.isPrimitiveValueClass) nme.wrapXArray(elemCls.name) else if (elemCls.derivesFrom(defn.ObjectClass) && !elemCls.isNotRuntimeClass) nme.wrapRefArray @@ -477,7 +477,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** A tree representing a `wrapXYZArray(tree)` operation of the right * kind for the given element type in `elemTpe`. */ - def wrapArray(tree: Tree, elemtp: Type)(implicit ctx: Context): Tree = + def wrapArray(tree: Tree, elemtp: Type)(using Context): Tree = val wrapper = ref(defn.getWrapVarargsArrayModule) .select(wrapArrayMethodName(elemtp)) .appliedToTypes(if (elemtp.isPrimitiveValueType) Nil else elemtp :: Nil) @@ -487,11 +487,11 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { // ------ Creating typed equivalents of trees that exist only in untyped form ------- /** new C(args), calling the primary constructor of C */ - def New(tp: Type, args: List[Tree])(implicit ctx: Context): Apply = + def New(tp: Type, args: List[Tree])(using Context): Apply = New(tp, tp.dealias.typeSymbol.primaryConstructor.asTerm, args) /** new C(args), calling given constructor `constr` of C */ - def New(tp: Type, constr: TermSymbol, args: List[Tree])(implicit ctx: Context): Apply = { + def New(tp: Type, constr: TermSymbol, args: List[Tree])(using Context): Apply = { val targs = tp.argTypes val tycon = tp.typeConstructor New(tycon) @@ -526,7 +526,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * the RHS of a method contains a class owned by the method, this would be * an error.) */ - def ModuleDef(sym: TermSymbol, body: List[Tree])(implicit ctx: Context): tpd.Thicket = { + 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 constr = DefDef(constrSym.asTerm, EmptyTree) @@ -536,9 +536,9 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** A `_` with given type */ - def Underscore(tp: Type)(implicit ctx: Context): Ident = untpd.Ident(nme.WILDCARD).withType(tp) + def Underscore(tp: Type)(using Context): Ident = untpd.Ident(nme.WILDCARD).withType(tp) - def defaultValue(tpe: Type)(implicit ctx: Context): Tree = { + def defaultValue(tpe: Type)(using Context): Tree = { val tpw = tpe.widen if (tpw isRef defn.IntClass) Literal(Constant(0)) @@ -552,8 +552,8 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { else nullLiteral.select(defn.Any_asInstanceOf).appliedToType(tpe) } - private class FindLocalDummyAccumulator(cls: ClassSymbol)(implicit ctx: Context) extends TreeAccumulator[Symbol] { - def apply(sym: Symbol, tree: Tree)(implicit ctx: Context) = + private class FindLocalDummyAccumulator(cls: ClassSymbol)(using Context) extends TreeAccumulator[Symbol] { + def apply(sym: Symbol, tree: Tree)(using Context) = if (sym.exists) sym else if (tree.isDef) { val owner = tree.symbol.owner @@ -577,7 +577,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { protected val untpdCpy = untpd.cpy - override def Select(tree: Tree)(qualifier: Tree, name: Name)(implicit ctx: Context): Select = { + override def Select(tree: Tree)(qualifier: Tree, name: Name)(using Context): Select = { val tree1 = untpdCpy.Select(tree)(qualifier, name) tree match { case tree: Select if qualifier.tpe eq tree.qualifier.tpe => @@ -591,7 +591,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Apply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): Apply = { + override def Apply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): Apply = { val tree1 = untpdCpy.Apply(tree)(fun, args) tree match { case tree: Apply @@ -601,7 +601,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): TypeApply = { + override def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): TypeApply = { val tree1 = untpdCpy.TypeApply(tree)(fun, args) tree match { case tree: TypeApply @@ -611,22 +611,22 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Literal(tree: Tree)(const: Constant)(implicit ctx: Context): Literal = + override def Literal(tree: Tree)(const: Constant)(using Context): Literal = ta.assignType(untpdCpy.Literal(tree)(const)) - override def New(tree: Tree)(tpt: Tree)(implicit ctx: Context): New = + override def New(tree: Tree)(tpt: Tree)(using Context): New = ta.assignType(untpdCpy.New(tree)(tpt), tpt) - override def Typed(tree: Tree)(expr: Tree, tpt: Tree)(implicit ctx: Context): Typed = + override def Typed(tree: Tree)(expr: Tree, tpt: Tree)(using Context): Typed = ta.assignType(untpdCpy.Typed(tree)(expr, tpt), tpt) - override def NamedArg(tree: Tree)(name: Name, arg: Tree)(implicit ctx: Context): NamedArg = + override def NamedArg(tree: Tree)(name: Name, arg: Tree)(using Context): NamedArg = ta.assignType(untpdCpy.NamedArg(tree)(name, arg), arg) - override def Assign(tree: Tree)(lhs: Tree, rhs: Tree)(implicit ctx: Context): Assign = + override def Assign(tree: Tree)(lhs: Tree, rhs: Tree)(using Context): Assign = ta.assignType(untpdCpy.Assign(tree)(lhs, rhs)) - override def Block(tree: Tree)(stats: List[Tree], expr: Tree)(implicit ctx: Context): Block = { + override def Block(tree: Tree)(stats: List[Tree], expr: Tree)(using Context): Block = { val tree1 = untpdCpy.Block(tree)(stats, expr) tree match { case tree: Block if (expr.tpe eq tree.expr.tpe) && (expr.tpe eq tree.tpe) => @@ -641,7 +641,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = { + override def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(using Context): If = { val tree1 = untpdCpy.If(tree)(cond, thenp, elsep) tree match { case tree: If if (thenp.tpe eq tree.thenp.tpe) && (elsep.tpe eq tree.elsep.tpe) && @@ -655,7 +655,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(implicit ctx: Context): Closure = { + override def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(using Context): Closure = { val tree1 = untpdCpy.Closure(tree)(env, meth, tpt) tree match { case tree: Closure if sameTypes(env, tree.env) && (meth.tpe eq tree.meth.tpe) && (tpt.tpe eq tree.tpt.tpe) => @@ -664,7 +664,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Match(tree: Tree)(selector: Tree, cases: List[CaseDef])(implicit ctx: Context): Match = { + override def Match(tree: Tree)(selector: Tree, cases: List[CaseDef])(using Context): Match = { val tree1 = untpdCpy.Match(tree)(selector, cases) tree match { case tree: Match if sameTypes(cases, tree.cases) => tree1.withTypeUnchecked(tree.tpe) @@ -672,7 +672,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def CaseDef(tree: Tree)(pat: Tree, guard: Tree, body: Tree)(implicit ctx: Context): CaseDef = { + override def CaseDef(tree: Tree)(pat: Tree, guard: Tree, body: Tree)(using Context): CaseDef = { val tree1 = untpdCpy.CaseDef(tree)(pat, guard, body) tree match { case tree: CaseDef if body.tpe eq tree.body.tpe => tree1.withTypeUnchecked(tree.tpe) @@ -680,16 +680,16 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Labeled(tree: Tree)(bind: Bind, expr: Tree)(implicit ctx: Context): Labeled = + override def Labeled(tree: Tree)(bind: Bind, expr: Tree)(using Context): Labeled = ta.assignType(untpdCpy.Labeled(tree)(bind, expr)) - override def Return(tree: Tree)(expr: Tree, from: Tree)(implicit ctx: Context): Return = + override def Return(tree: Tree)(expr: Tree, from: Tree)(using Context): Return = ta.assignType(untpdCpy.Return(tree)(expr, from)) - override def WhileDo(tree: Tree)(cond: Tree, body: Tree)(implicit ctx: Context): WhileDo = + override def WhileDo(tree: Tree)(cond: Tree, body: Tree)(using Context): WhileDo = ta.assignType(untpdCpy.WhileDo(tree)(cond, body)) - override def Try(tree: Tree)(expr: Tree, cases: List[CaseDef], finalizer: Tree)(implicit ctx: Context): Try = { + override def Try(tree: Tree)(expr: Tree, cases: List[CaseDef], finalizer: Tree)(using Context): Try = { val tree1 = untpdCpy.Try(tree)(expr, cases, finalizer) tree match { case tree: Try if (expr.tpe eq tree.expr.tpe) && sameTypes(cases, tree.cases) => tree1.withTypeUnchecked(tree.tpe) @@ -697,7 +697,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Inlined(tree: Tree)(call: Tree, bindings: List[MemberDef], expansion: Tree)(implicit ctx: Context): Inlined = { + override def Inlined(tree: Tree)(call: Tree, bindings: List[MemberDef], expansion: Tree)(using Context): Inlined = { val tree1 = untpdCpy.Inlined(tree)(call, bindings, expansion) tree match { case tree: Inlined if sameTypes(bindings, tree.bindings) && (expansion.tpe eq tree.expansion.tpe) => @@ -706,7 +706,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def SeqLiteral(tree: Tree)(elems: List[Tree], elemtpt: Tree)(implicit ctx: Context): SeqLiteral = { + override def SeqLiteral(tree: Tree)(elems: List[Tree], elemtpt: Tree)(using Context): SeqLiteral = { val tree1 = untpdCpy.SeqLiteral(tree)(elems, elemtpt) tree match { case tree: SeqLiteral @@ -717,7 +717,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def Annotated(tree: Tree)(arg: Tree, annot: Tree)(implicit ctx: Context): Annotated = { + override def Annotated(tree: Tree)(arg: Tree, annot: Tree)(using Context): Annotated = { val tree1 = untpdCpy.Annotated(tree)(arg, annot) tree match { case tree: Annotated if (arg.tpe eq tree.arg.tpe) && (annot eq tree.annot) => tree1.withTypeUnchecked(tree.tpe) @@ -725,18 +725,18 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } } - override def If(tree: If)(cond: Tree = tree.cond, thenp: Tree = tree.thenp, elsep: Tree = tree.elsep)(implicit ctx: Context): If = + override def If(tree: If)(cond: Tree = tree.cond, thenp: Tree = tree.thenp, elsep: Tree = tree.elsep)(using Context): If = If(tree: Tree)(cond, thenp, elsep) - override def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(implicit ctx: Context): Closure = + override def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(using Context): Closure = Closure(tree: Tree)(env, meth, tpt) - override def CaseDef(tree: CaseDef)(pat: Tree = tree.pat, guard: Tree = tree.guard, body: Tree = tree.body)(implicit ctx: Context): CaseDef = + override def CaseDef(tree: CaseDef)(pat: Tree = tree.pat, guard: Tree = tree.guard, body: Tree = tree.body)(using Context): CaseDef = CaseDef(tree: Tree)(pat, guard, body) - override def Try(tree: Try)(expr: Tree = tree.expr, cases: List[CaseDef] = tree.cases, finalizer: Tree = tree.finalizer)(implicit ctx: Context): Try = + override def Try(tree: Try)(expr: Tree = tree.expr, cases: List[CaseDef] = tree.cases, finalizer: Tree = tree.finalizer)(using Context): Try = Try(tree: Tree)(expr, cases, finalizer) } class TimeTravellingTreeCopier extends TypedTreeCopier { - override def Apply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): Apply = + override def Apply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): Apply = tree match case tree: Apply if (tree.fun eq fun) && (tree.args eq args) @@ -751,25 +751,25 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { // However, we keep constant types of pure expressions. This uses the underlying assumptions // that pure functions yielding a constant will not change in later phases. - override def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): TypeApply = + override def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): TypeApply = ta.assignType(untpdCpy.TypeApply(tree)(fun, args), fun, args) // Same remark as for Apply - override def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(implicit ctx: Context): Closure = + override def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(using Context): Closure = ta.assignType(untpdCpy.Closure(tree)(env, meth, tpt), meth, tpt) - override def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(implicit ctx: Context): Closure = + override def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(using Context): Closure = Closure(tree: Tree)(env, meth, tpt) } - override def skipTransform(tree: Tree)(implicit ctx: Context): Boolean = tree.tpe.isError + override def skipTransform(tree: Tree)(using Context): Boolean = tree.tpe.isError implicit class TreeOps[ThisTree <: tpd.Tree](private val tree: ThisTree) extends AnyVal { - def isValue(implicit ctx: Context): Boolean = + def isValue(using Context): Boolean = tree.isTerm && tree.tpe.widen.isValueType - def isValueOrPattern(implicit ctx: Context): Boolean = + def isValueOrPattern(using Context): Boolean = tree.isValue || tree.isPattern def isValueType: Boolean = @@ -780,22 +780,22 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { case _ => false } - def shallowFold[T](z: T)(op: (T, tpd.Tree) => T)(implicit ctx: Context): T = + def shallowFold[T](z: T)(op: (T, tpd.Tree) => T)(using Context): T = ShallowFolder(op).apply(z, tree) - def deepFold[T](z: T)(op: (T, tpd.Tree) => T)(implicit ctx: Context): T = + def deepFold[T](z: T)(op: (T, tpd.Tree) => T)(using Context): T = DeepFolder(op).apply(z, tree) - def find[T](pred: (tpd.Tree) => Boolean)(implicit ctx: Context): Option[tpd.Tree] = + def find[T](pred: (tpd.Tree) => Boolean)(using Context): Option[tpd.Tree] = shallowFold[Option[tpd.Tree]](None)((accum, tree) => if (pred(tree)) Some(tree) else accum) - def subst(from: List[Symbol], to: List[Symbol])(implicit ctx: Context): ThisTree = + def subst(from: List[Symbol], to: List[Symbol])(using Context): ThisTree = TreeTypeMap(substFrom = from, substTo = to).apply(tree) /** Change owner from `from` to `to`. If `from` is a weak owner, also change its * owner to `to`, and continue until a non-weak owner is reached. */ - def changeOwner(from: Symbol, to: Symbol)(implicit ctx: Context): ThisTree = { + def changeOwner(from: Symbol, to: Symbol)(using Context): ThisTree = { @tailrec def loop(from: Symbol, froms: List[Symbol], tos: List[Symbol]): ThisTree = if (from.isWeakOwner && !from.owner.isClass) loop(from.owner, from :: froms, to :: tos) @@ -809,9 +809,9 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * Set the owner of every definition in this tree which is not itself contained in this * tree to be `newowner` */ - def changeNonLocalOwners(newOwner: Symbol)(implicit ctx: Context): Tree = { + def changeNonLocalOwners(newOwner: Symbol)(using Context): Tree = { val ownerAcc = new TreeAccumulator[immutable.Set[Symbol]] { - def apply(ss: immutable.Set[Symbol], tree: Tree)(implicit ctx: Context) = tree match { + def apply(ss: immutable.Set[Symbol], tree: Tree)(using Context) = tree match { case tree: DefTree => if (tree.symbol.exists) ss + tree.symbol.owner else ss @@ -827,10 +827,10 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** After phase `trans`, set the owner of every definition in this tree that was formerly * owner by `from` to `to`. */ - def changeOwnerAfter(from: Symbol, to: Symbol, trans: DenotTransformer)(implicit ctx: Context): ThisTree = + def changeOwnerAfter(from: Symbol, to: Symbol, trans: DenotTransformer)(using Context): ThisTree = if (ctx.phase == trans.next) { val traverser = new TreeTraverser { - def traverse(tree: Tree)(implicit ctx: Context) = tree match { + def traverse(tree: Tree)(using Context) = tree match { case tree: DefTree => val sym = tree.symbol val prevDenot = sym.denot(using ctx.withPhase(trans)) @@ -850,24 +850,24 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { else changeOwnerAfter(from, to, trans)(using ctx.withPhase(trans.next)) /** A select node with the given selector name and a computed type */ - def select(name: Name)(implicit ctx: Context): Select = + def select(name: Name)(using Context): Select = Select(tree, name) /** A select node with the given selector name such that the designated * member satisfies predicate `p`. Useful for disambiguating overloaded members. */ - def select(name: Name, p: Symbol => Boolean)(implicit ctx: Context): Select = + def select(name: Name, p: Symbol => Boolean)(using Context): Select = select(tree.tpe.member(name).suchThat(p).symbol) /** A select node with the given type */ - def select(tp: NamedType)(implicit ctx: Context): Select = + def select(tp: NamedType)(using Context): Select = untpd.Select(tree, tp.name).withType(tp) /** A select node that selects the given symbol. Note: Need to make sure this * is in fact the symbol you would get when you select with the symbol's name, * otherwise a data race may occur which would be flagged by -Yno-double-bindings. */ - def select(sym: Symbol)(implicit ctx: Context): Select = { + def select(sym: Symbol)(using Context): Select = { val tp = if (sym.isType) { assert(!sym.is(TypeParam)) @@ -879,7 +879,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** A select node with the given selector name and signature and a computed type */ - def selectWithSig(name: Name, sig: Signature)(implicit ctx: Context): Tree = + def selectWithSig(name: Name, sig: Signature)(using Context): Tree = untpd.SelectWithSig(tree, name, sig).withType(tree.tpe.select(name.asTermName, sig)) /** A select node with selector name and signature taken from `sym`. @@ -887,19 +887,19 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * might be overridden in the type of the qualifier prefix. See note * on select(sym: Symbol). */ - def selectWithSig(sym: Symbol)(implicit ctx: Context): Tree = + def selectWithSig(sym: Symbol)(using Context): Tree = selectWithSig(sym.name, sym.signature) /** A unary apply node with given argument: `tree(arg)` */ - def appliedTo(arg: Tree)(implicit ctx: Context): Tree = + def appliedTo(arg: Tree)(using Context): Tree = appliedToArgs(arg :: Nil) /** An apply node with given arguments: `tree(arg, args0, ..., argsN)` */ - def appliedTo(arg: Tree, args: Tree*)(implicit ctx: Context): Tree = + def appliedTo(arg: Tree, args: Tree*)(using Context): Tree = appliedToArgs(arg :: args.toList) /** An apply node with given argument list `tree(args(0), ..., args(args.length - 1))` */ - def appliedToArgs(args: List[Tree])(implicit ctx: Context): Apply = + def appliedToArgs(args: List[Tree])(using Context): Apply = Apply(tree, args) /** An applied node that accepts only varargs as arguments */ @@ -909,41 +909,41 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** The current tree applied to given argument lists: * `tree (argss(0)) ... (argss(argss.length -1))` */ - def appliedToArgss(argss: List[List[Tree]])(implicit ctx: Context): Tree = + def appliedToArgss(argss: List[List[Tree]])(using Context): Tree = argss.foldLeft(tree: Tree)(Apply(_, _)) /** The current tree applied to (): `tree()` */ - def appliedToNone(implicit ctx: Context): Apply = appliedToArgs(Nil) + def appliedToNone(using Context): Apply = appliedToArgs(Nil) /** The current tree applied to given type argument: `tree[targ]` */ - def appliedToType(targ: Type)(implicit ctx: Context): Tree = + def appliedToType(targ: Type)(using Context): Tree = appliedToTypes(targ :: Nil) /** The current tree applied to given type arguments: `tree[targ0, ..., targN]` */ - def appliedToTypes(targs: List[Type])(implicit ctx: Context): Tree = + def appliedToTypes(targs: List[Type])(using Context): Tree = appliedToTypeTrees(targs map (TypeTree(_))) /** The current tree applied to given type argument: `tree[targ]` */ - def appliedToTypeTree(targ: Tree)(implicit ctx: Context): Tree = + def appliedToTypeTree(targ: Tree)(using Context): Tree = appliedToTypeTrees(targ :: Nil) /** The current tree applied to given type argument list: `tree[targs(0), ..., targs(targs.length - 1)]` */ - def appliedToTypeTrees(targs: List[Tree])(implicit ctx: Context): Tree = + def appliedToTypeTrees(targs: List[Tree])(using Context): Tree = if (targs.isEmpty) tree else TypeApply(tree, targs) /** Apply to `()` unless tree's widened type is parameterless */ - def ensureApplied(implicit ctx: Context): Tree = + def ensureApplied(using Context): Tree = if (tree.tpe.widen.isParameterless) tree else tree.appliedToNone /** `tree == that` */ - def equal(that: Tree)(implicit ctx: Context): Tree = + def equal(that: Tree)(using Context): Tree = if (that.tpe.widen.isRef(defn.NothingClass)) Literal(Constant(false)) else applyOverloaded(tree, nme.EQ, that :: Nil, Nil, defn.BooleanType) /** `tree.isInstanceOf[tp]`, with special treatment of singleton types */ - def isInstance(tp: Type)(implicit ctx: Context): Tree = tp.dealias match { + def isInstance(tp: Type)(using Context): Tree = tp.dealias match { case tp: SingletonType => if (tp.widen.derivesFrom(defn.ObjectClass)) tree.ensureConforms(defn.ObjectType).select(defn.Object_eq).appliedTo(singleton(tp)) @@ -954,13 +954,13 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** tree.asInstanceOf[`tp`] */ - def asInstance(tp: Type)(implicit ctx: Context): Tree = { + def asInstance(tp: Type)(using Context): Tree = { assert(tp.isValueType, i"bad cast: $tree.asInstanceOf[$tp]") tree.select(defn.Any_asInstanceOf).appliedToType(tp) } /** cast tree to `tp`, assuming no exception is raised, i.e the operation is pure */ - def cast(tp: Type)(implicit ctx: Context): Tree = { + 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) .appliedToType(tp) @@ -970,13 +970,13 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * erasure and value and non-value types are mixed), * unless tree's type already conforms to `tp`. */ - def ensureConforms(tp: Type)(implicit ctx: Context): Tree = + def ensureConforms(tp: Type)(using Context): Tree = if (tree.tpe <:< tp) tree else if (!ctx.erasedTypes) cast(tp) else Erasure.Boxing.adaptToType(tree, tp) /** `tree ne null` (might need a cast to be type correct) */ - def testNotNull(implicit ctx: Context): Tree = { + def testNotNull(using Context): Tree = { val receiver = if (defn.isBottomType(tree.tpe)) // If the receiver is of type `Nothing` or `Null`, add an ascription so that the selection // succeeds: e.g. `null.ne(null)` doesn't type, but `(null: AnyRef).ne(null)` does. @@ -988,21 +988,21 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** If inititializer tree is `_`, the default value of its type, * otherwise the tree itself. */ - def wildcardToDefault(implicit ctx: Context): Tree = + def wildcardToDefault(using Context): Tree = if (isWildcardArg(tree)) defaultValue(tree.tpe) else tree /** `this && that`, for boolean trees `this`, `that` */ - def and(that: Tree)(implicit ctx: Context): Tree = + def and(that: Tree)(using Context): Tree = tree.select(defn.Boolean_&&).appliedTo(that) /** `this || that`, for boolean trees `this`, `that` */ - def or(that: Tree)(implicit ctx: Context): Tree = + def or(that: Tree)(using Context): Tree = tree.select(defn.Boolean_||).appliedTo(that) /** The translation of `tree = rhs`. * This is either the tree as an assignment, or a setter call. */ - def becomes(rhs: Tree)(implicit ctx: Context): Tree = { + def becomes(rhs: Tree)(using Context): Tree = { val sym = tree.symbol if (sym.is(Method)) { val setter = sym.setter.orElse { @@ -1022,7 +1022,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * * works differently for type trees and term trees */ - def annotated(annot: Tree)(implicit ctx: Context): Tree = + def annotated(annot: Tree)(using Context): Tree = if (tree.isTerm) Typed(tree, TypeTree(AnnotatedType(tree.tpe.widenIfUnstable, Annotation(annot)))) else @@ -1032,11 +1032,11 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * @param levels How many outer levels to select * @param tp The type of the destination of the outer path. */ - def outerSelect(levels: Int, tp: Type)(implicit ctx: Context): Tree = + def outerSelect(levels: Int, tp: Type)(using Context): Tree = untpd.Select(tree, OuterSelectName(EmptyTermName, levels)).withType(SkolemType(tp)) /** Replace Inlined nodes and InlineProxy references to underlying arguments */ - def underlyingArgument(implicit ctx: Context): Tree = { + def underlyingArgument(using Context): Tree = { val mapToUnderlying = new MapToUnderlying { /** Should get the rhs of this binding * Returns true if the symbol is a val or def generated by eta-expansion/inline @@ -1048,35 +1048,35 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** Replace Ident nodes references to the underlying tree that defined them */ - def underlying(implicit ctx: Context): Tree = MapToUnderlying().transform(tree) + def underlying(using Context): Tree = MapToUnderlying().transform(tree) // --- Higher order traversal methods ------------------------------- /** Apply `f` to each subtree of this tree */ - def foreachSubTree(f: Tree => Unit)(implicit ctx: Context): Unit = { + def foreachSubTree(f: Tree => Unit)(using Context): Unit = { val traverser = new TreeTraverser { - def traverse(tree: Tree)(implicit ctx: Context) = foldOver(f(tree), tree) + def traverse(tree: Tree)(using Context) = foldOver(f(tree), tree) } traverser.traverse(tree) } /** Is there a subtree of this tree that satisfies predicate `p`? */ - def existsSubTree(p: Tree => Boolean)(implicit ctx: Context): Boolean = { + def existsSubTree(p: Tree => Boolean)(using Context): Boolean = { val acc = new TreeAccumulator[Boolean] { - def apply(x: Boolean, t: Tree)(implicit ctx: Context) = x || p(t) || foldOver(x, t) + def apply(x: Boolean, t: Tree)(using Context) = x || p(t) || foldOver(x, t) } acc(false, tree) } /** All subtrees of this tree that satisfy predicate `p`. */ - def filterSubTrees(f: Tree => Boolean)(implicit ctx: Context): List[Tree] = { + def filterSubTrees(f: Tree => Boolean)(using Context): List[Tree] = { val buf = mutable.ListBuffer[Tree]() foreachSubTree { tree => if (f(tree)) buf += tree } buf.toList } /** Set this tree as the `defTree` of its symbol and return this tree */ - def setDefTree(implicit ctx: Context): ThisTree = { + def setDefTree(using Context): ThisTree = { val sym = tree.symbol if (sym.exists) sym.defTree = tree tree @@ -1087,7 +1087,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * Also drops Inline and Block with no statements. */ class MapToUnderlying extends TreeMap { - override def transform(tree: Tree)(implicit ctx: Context): Tree = tree match { + override def transform(tree: Tree)(using Context): Tree = tree match { case tree: Ident if isBinding(tree.symbol) && skipLocal(tree.symbol) => tree.symbol.defTree match { case defTree: ValOrDefDef => @@ -1106,7 +1106,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { protected def skipLocal(sym: Symbol): Boolean = true /** Is this a symbol that of a local val or parameterless def for which we could get the rhs */ - private def isBinding(sym: Symbol)(implicit ctx: Context): Boolean = + private def isBinding(sym: Symbol)(using Context): Boolean = sym.isTerm && !sym.is(Param) && !sym.owner.isClass && !(sym.is(Method) && sym.info.isInstanceOf[MethodOrPoly]) // if is a method it is parameterless } @@ -1120,12 +1120,12 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** A trait for loaders that compute trees. Currently implemented just by DottyUnpickler. */ trait TreeProvider { - protected def computeRootTrees(implicit ctx: Context): List[Tree] + protected def computeRootTrees(using Context): List[Tree] private var myTrees: List[Tree] = null /** Get trees defined by this provider. Cache them if -Yretain-trees is set. */ - def rootTrees(implicit ctx: Context): List[Tree] = + def rootTrees(using Context): List[Tree] = if (ctx.settings.YretainTrees.value) { if (myTrees == null) myTrees = computeRootTrees myTrees @@ -1133,15 +1133,15 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { else computeRootTrees /** Get first tree defined by this provider, or EmptyTree if none exists */ - def tree(implicit ctx: Context): Tree = + def tree(using Context): Tree = rootTrees.headOption.getOrElse(EmptyTree) /** Is it possible that the tree to load contains a definition of or reference to `id`? */ - def mightContain(id: String)(implicit ctx: Context): Boolean = true + def mightContain(id: String)(using Context): Boolean = true } // convert a numeric with a toXXX method - def primitiveConversion(tree: Tree, numericCls: Symbol)(implicit ctx: Context): Tree = { + def primitiveConversion(tree: Tree, numericCls: Symbol)(using Context): Tree = { val mname = ("to" + numericCls.name).toTermName val conversion = tree.tpe member mname if (conversion.symbol.exists) @@ -1155,7 +1155,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** A tree that corresponds to `Predef.classOf[$tp]` in source */ - def clsOf(tp: Type)(implicit ctx: Context): Tree = + def clsOf(tp: Type)(using Context): Tree = if ctx.erasedTypes then def TYPE(module: TermSymbol) = ref(module).select(nme.TYPE_) defn.scalaClassName(tp) match @@ -1188,7 +1188,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * * ~within('tree) */ - def letBindUnless(level: TreeInfo.PurityLevel, tree: Tree)(within: Tree => Tree)(implicit ctx: Context): Tree = + def letBindUnless(level: TreeInfo.PurityLevel, tree: Tree)(within: Tree => Tree)(using Context): Tree = if (exprPurity(tree) >= level) within(tree) else { val vdef = SyntheticValDef(TempResultName.fresh(), tree) @@ -1196,10 +1196,10 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** Let bind `tree` unless `tree` is at least idempotent */ - def evalOnce(tree: Tree)(within: Tree => Tree)(implicit ctx: Context): Tree = + def evalOnce(tree: Tree)(within: Tree => Tree)(using Context): Tree = letBindUnless(TreeInfo.Idempotent, tree)(within) - def runtimeCall(name: TermName, args: List[Tree])(implicit ctx: Context): Tree = + def runtimeCall(name: TermName, args: List[Tree])(using Context): Tree = Ident(defn.ScalaRuntimeModule.requiredMethod(name).termRef).appliedToArgs(args) /** An extractor that pulls out type arguments */ @@ -1223,7 +1223,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * EmptyTree calls (for parameters) cancel the next-enclosing call in the list instead of being added to it. * We assume parameters are never nested inside parameters. */ - override def inlineContext(call: Tree)(implicit ctx: Context): Context = { + override def inlineContext(call: Tree)(using Context): Context = { // We assume enclosingInlineds is already normalized, and only process the new call with the head. val oldIC = enclosingInlineds @@ -1241,15 +1241,15 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** All enclosing calls that are currently inlined, from innermost to outermost. */ - def enclosingInlineds(implicit ctx: Context): List[Tree] = + def enclosingInlineds(using Context): List[Tree] = ctx.property(InlinedCalls).getOrElse(Nil) /** Record inlined trees */ - def addInlinedTrees(n: Int)(implicit ctx: Context): Unit = + def addInlinedTrees(n: Int)(using Context): Unit = ctx.property(InlinedTrees).foreach(_.count += n) /** Check if the limit on the number of inlined trees has been reached */ - def reachedInlinedTreesLimit(implicit ctx: Context): Boolean = + def reachedInlinedTreesLimit(using Context): Boolean = ctx.property(InlinedTrees) match case Some(c) => c.count > ctx.settings.XmaxInlinedTrees.value case None => false @@ -1257,17 +1257,17 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** The source file where the symbol of the `inline` method referred to by `call` * is defined */ - def sourceFile(call: Tree)(implicit ctx: Context): SourceFile = call.symbol.source + def sourceFile(call: Tree)(using Context): SourceFile = call.symbol.source /** Desugar identifier into a select node. Return the tree itself if not possible */ - def desugarIdent(tree: Ident)(implicit ctx: Context): RefTree = { + def desugarIdent(tree: Ident)(using Context): RefTree = { val qual = desugarIdentPrefix(tree) if (qual.isEmpty) tree else qual.select(tree.symbol) } /** Recover identifier prefix (e.g. this) if it exists */ - def desugarIdentPrefix(tree: Ident)(implicit ctx: Context): Tree = tree.tpe match { + def desugarIdentPrefix(tree: Ident)(using Context): Tree = tree.tpe match { case TermRef(prefix: TermRef, _) => ref(prefix) case TermRef(prefix: ThisType, _) => @@ -1283,7 +1283,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * @param name The name that is being imported. * @return All the symbols that would be imported with `expr.name`. */ - def importedSymbols(expr: Tree, name: Name)(implicit ctx: Context): List[Symbol] = { + def importedSymbols(expr: Tree, name: Name)(using Context): List[Symbol] = { def lookup(name: Name): Symbol = expr.tpe.member(name).symbol val symbols = List(lookup(name.toTermName), @@ -1304,7 +1304,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { */ def importedSymbols(imp: Import, selectorPredicate: untpd.ImportSelector => Boolean = util.common.alwaysTrue) - (implicit ctx: Context): List[Symbol] = + (using Context): List[Symbol] = imp.selectors.find(selectorPredicate) match case Some(sel) => importedSymbols(imp.expr, sel.name) case _ => Nil @@ -1313,7 +1313,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * The list of select trees that resolve to the same symbols as the ones that are imported * by `imp`. */ - def importSelections(imp: Import)(implicit ctx: Context): List[Select] = { + def importSelections(imp: Import)(using Context): List[Select] = { def imported(sym: Symbol, id: untpd.Ident, rename: Option[untpd.Ident]): List[Select] = { // Give a zero-extent position to the qualifier to prevent it from being included several // times in results in the language server. @@ -1345,20 +1345,20 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } /** Creates the tuple type tree repesentation of the type trees in `ts` */ - def tupleTypeTree(elems: List[Tree])(implicit ctx: Context): Tree = { + def tupleTypeTree(elems: List[Tree])(using Context): Tree = { val arity = elems.length if (arity <= Definitions.MaxTupleArity && defn.TupleType(arity) != null) AppliedTypeTree(TypeTree(defn.TupleType(arity)), elems) else nestedPairsTypeTree(elems) } /** Creates the nested pairs type tree repesentation of the type trees in `ts` */ - def nestedPairsTypeTree(ts: List[Tree])(implicit ctx: Context): Tree = + def nestedPairsTypeTree(ts: List[Tree])(using Context): Tree = ts.foldRight[Tree](TypeTree(defn.EmptyTupleModule.termRef))((x, acc) => AppliedTypeTree(TypeTree(defn.PairClass.typeRef), x :: acc :: Nil)) /** Replaces all positions in `tree` with zero-extent positions */ - private def focusPositions(tree: Tree)(implicit ctx: Context): Tree = { + private def focusPositions(tree: Tree)(using Context): Tree = { val transformer = new tpd.TreeMap { - override def transform(tree: Tree)(implicit ctx: Context): Tree = + override def transform(tree: Tree)(using Context): Tree = super.transform(tree).withSpan(tree.span.focus) } transformer.transform(tree) diff --git a/compiler/src/dotty/tools/dotc/ast/untpd.scala b/compiler/src/dotty/tools/dotc/ast/untpd.scala index 36ef435764a6..cbf8277378f5 100644 --- a/compiler/src/dotty/tools/dotc/ast/untpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/untpd.scala @@ -31,7 +31,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { } object TypedSplice { - def apply(tree: tpd.Tree)(implicit ctx: Context): TypedSplice = + def apply(tree: tpd.Tree)(using Context): TypedSplice = new TypedSplice(tree)(ctx.owner) {} } @@ -39,7 +39,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { case class ModuleDef(name: TermName, impl: Template)(implicit @constructorOnly src: SourceFile) extends MemberDef { type ThisTree[-T >: Untyped] <: Trees.NameTree[T] with Trees.MemberDef[T] with ModuleDef - def withName(name: Name)(implicit ctx: Context): ModuleDef = cpy.ModuleDef(this)(name.toTermName, impl) + def withName(name: Name)(using Context): ModuleDef = cpy.ModuleDef(this)(name.toTermName, impl) } /** An untyped template with a derives clause. Derived parents are added to the end @@ -328,10 +328,10 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { /** A hook to ensure that all necessary symbols are completed so that * OriginalSymbol attachments are propagated to this tree */ - def ensureCompletions(implicit ctx: Context): Unit = () + def ensureCompletions(using Context): Unit = () /** The method that computes the tree with the derived type */ - def derivedTree(originalSym: Symbol)(implicit ctx: Context): tpd.Tree + def derivedTree(originalSym: Symbol)(using Context): tpd.Tree } /** Property key containing TypeTrees whose type is computed @@ -411,13 +411,13 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { * navigation into these arguments from the IDE, and to do the right thing in * PrepareInlineable. */ - def New(tpt: Tree, argss: List[List[Tree]])(implicit ctx: Context): Tree = + def New(tpt: Tree, argss: List[List[Tree]])(using Context): Tree = ensureApplied(argss.foldLeft(makeNew(tpt))(Apply(_, _))) /** A new expression with constrictor and possibly type arguments. See * `New(tpt, argss)` for details. */ - def makeNew(tpt: Tree)(implicit ctx: Context): Tree = { + def makeNew(tpt: Tree)(using Context): Tree = { val (tycon, targs) = tpt match { case AppliedTypeTree(tycon, targs) => (tycon, targs) @@ -446,11 +446,11 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { def AppliedTypeTree(tpt: Tree, arg: Tree)(implicit src: SourceFile): AppliedTypeTree = AppliedTypeTree(tpt, arg :: Nil) - def TypeTree(tpe: Type)(implicit ctx: Context): TypedSplice = TypedSplice(TypeTree().withTypeUnchecked(tpe)) + def TypeTree(tpe: Type)(using Context): TypedSplice = TypedSplice(TypeTree().withTypeUnchecked(tpe)) def unitLiteral(implicit src: SourceFile): Literal = Literal(Constant(())) - def ref(tp: NamedType)(implicit ctx: Context): Tree = + def ref(tp: NamedType)(using Context): Tree = TypedSplice(tpd.ref(tp)) def rootDot(name: Name)(implicit src: SourceFile): Select = Select(Ident(nme.ROOTPKG), name) @@ -461,35 +461,35 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { def scalaAny(implicit src: SourceFile): Select = scalaDot(tpnme.Any) def javaDotLangDot(name: Name)(implicit src: SourceFile): Select = Select(Select(Ident(nme.java), nme.lang), name) - def makeConstructor(tparams: List[TypeDef], vparamss: List[List[ValDef]], rhs: Tree = EmptyTree)(implicit ctx: Context): DefDef = + def makeConstructor(tparams: List[TypeDef], vparamss: List[List[ValDef]], rhs: Tree = EmptyTree)(using Context): DefDef = DefDef(nme.CONSTRUCTOR, tparams, vparamss, TypeTree(), rhs) - def emptyConstructor(implicit ctx: Context): DefDef = + def emptyConstructor(using Context): DefDef = makeConstructor(Nil, Nil) - def makeSelfDef(name: TermName, tpt: Tree)(implicit ctx: Context): ValDef = + def makeSelfDef(name: TermName, tpt: Tree)(using Context): ValDef = ValDef(name, tpt, EmptyTree).withFlags(PrivateLocal) - def makeTupleOrParens(ts: List[Tree])(implicit ctx: Context): Tree = ts match { + def makeTupleOrParens(ts: List[Tree])(using Context): Tree = ts match { case t :: Nil => Parens(t) case _ => Tuple(ts) } - def makeTuple(ts: List[Tree])(implicit ctx: Context): Tree = ts match { + def makeTuple(ts: List[Tree])(using Context): Tree = ts match { case t :: Nil => t case _ => Tuple(ts) } - def makeAndType(left: Tree, right: Tree)(implicit ctx: Context): AppliedTypeTree = + def makeAndType(left: Tree, right: Tree)(using Context): AppliedTypeTree = AppliedTypeTree(ref(defn.andType.typeRef), left :: right :: Nil) - def makeParameter(pname: TermName, tpe: Tree, mods: Modifiers, isBackquoted: Boolean = false)(implicit ctx: Context): ValDef = { + def makeParameter(pname: TermName, tpe: Tree, mods: Modifiers, isBackquoted: Boolean = false)(using Context): ValDef = { val vdef = ValDef(pname, tpe, EmptyTree) if (isBackquoted) vdef.pushAttachment(Backquoted, ()) vdef.withMods(mods | Param) } - def makeSyntheticParameter(n: Int = 1, tpt: Tree = null, flags: FlagSet = SyntheticTermParam)(implicit ctx: Context): ValDef = + def makeSyntheticParameter(n: Int = 1, tpt: Tree = null, flags: FlagSet = SyntheticTermParam)(using Context): ValDef = ValDef(nme.syntheticParamName(n), if (tpt == null) TypeTree() else tpt, EmptyTree) .withFlags(flags) @@ -505,13 +505,13 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { /** A reference to given definition. If definition is a repeated * parameter, the reference will be a repeated argument. */ - def refOfDef(tree: MemberDef)(implicit ctx: Context): Tree = tree match { + def refOfDef(tree: MemberDef)(using Context): Tree = tree match { case ValDef(_, PostfixOp(_, Ident(tpnme.raw.STAR)), _) => repeated(Ident(tree.name)) case _ => Ident(tree.name) } /** A repeated argument such as `arg: _*` */ - def repeated(arg: Tree)(implicit ctx: Context): Typed = Typed(arg, Ident(tpnme.WILDCARD_STAR)) + def repeated(arg: Tree)(using Context): Typed = Typed(arg, Ident(tpnme.WILDCARD_STAR)) // --------- Copier/Transformer/Accumulator classes for untyped trees ----- @@ -530,117 +530,117 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { } }.asInstanceOf[copied.ThisTree[Untyped]] - def ModuleDef(tree: Tree)(name: TermName, impl: Template)(implicit ctx: Context): ModuleDef = tree match { + def ModuleDef(tree: Tree)(name: TermName, impl: Template)(using Context): ModuleDef = tree match { case tree: ModuleDef if (name eq tree.name) && (impl eq tree.impl) => tree case _ => finalize(tree, untpd.ModuleDef(name, impl)(tree.source)) } - def ParsedTry(tree: Tree)(expr: Tree, handler: Tree, finalizer: Tree)(implicit ctx: Context): TermTree = tree match { + def ParsedTry(tree: Tree)(expr: Tree, handler: Tree, finalizer: Tree)(using Context): TermTree = tree match { case tree: ParsedTry if (expr eq tree.expr) && (handler eq tree.handler) && (finalizer eq tree.finalizer) => tree case _ => finalize(tree, untpd.ParsedTry(expr, handler, finalizer)(tree.source)) } - def SymbolLit(tree: Tree)(str: String)(implicit ctx: Context): TermTree = tree match { + def SymbolLit(tree: Tree)(str: String)(using Context): TermTree = tree match { case tree: SymbolLit if str == tree.str => tree case _ => finalize(tree, untpd.SymbolLit(str)(tree.source)) } - def InterpolatedString(tree: Tree)(id: TermName, segments: List[Tree])(implicit ctx: Context): TermTree = tree match { + def InterpolatedString(tree: Tree)(id: TermName, segments: List[Tree])(using Context): TermTree = tree match { case tree: InterpolatedString if (id eq tree.id) && (segments eq tree.segments) => tree case _ => finalize(tree, untpd.InterpolatedString(id, segments)(tree.source)) } - def Function(tree: Tree)(args: List[Tree], body: Tree)(implicit ctx: Context): Tree = tree match { + def Function(tree: Tree)(args: List[Tree], body: Tree)(using Context): Tree = tree match { case tree: Function if (args eq tree.args) && (body eq tree.body) => tree case _ => finalize(tree, untpd.Function(args, body)(tree.source)) } - def PolyFunction(tree: Tree)(targs: List[Tree], body: Tree)(implicit ctx: Context): Tree = tree match { + def PolyFunction(tree: Tree)(targs: List[Tree], body: Tree)(using Context): Tree = tree match { case tree: PolyFunction if (targs eq tree.targs) && (body eq tree.body) => tree case _ => finalize(tree, untpd.PolyFunction(targs, body)(tree.source)) } - def InfixOp(tree: Tree)(left: Tree, op: Ident, right: Tree)(implicit ctx: Context): Tree = tree match { + def InfixOp(tree: Tree)(left: Tree, op: Ident, right: Tree)(using Context): Tree = tree match { case tree: InfixOp if (left eq tree.left) && (op eq tree.op) && (right eq tree.right) => tree case _ => finalize(tree, untpd.InfixOp(left, op, right)(tree.source)) } - def PostfixOp(tree: Tree)(od: Tree, op: Ident)(implicit ctx: Context): Tree = tree match { + def PostfixOp(tree: Tree)(od: Tree, op: Ident)(using Context): Tree = tree match { case tree: PostfixOp if (od eq tree.od) && (op eq tree.op) => tree case _ => finalize(tree, untpd.PostfixOp(od, op)(tree.source)) } - def PrefixOp(tree: Tree)(op: Ident, od: Tree)(implicit ctx: Context): Tree = tree match { + def PrefixOp(tree: Tree)(op: Ident, od: Tree)(using Context): Tree = tree match { case tree: PrefixOp if (op eq tree.op) && (od eq tree.od) => tree case _ => finalize(tree, untpd.PrefixOp(op, od)(tree.source)) } - def Parens(tree: Tree)(t: Tree)(implicit ctx: Context): ProxyTree = tree match { + def Parens(tree: Tree)(t: Tree)(using Context): ProxyTree = tree match { case tree: Parens if t eq tree.t => tree case _ => finalize(tree, untpd.Parens(t)(tree.source)) } - def Tuple(tree: Tree)(trees: List[Tree])(implicit ctx: Context): Tree = tree match { + def Tuple(tree: Tree)(trees: List[Tree])(using Context): Tree = tree match { case tree: Tuple if trees eq tree.trees => tree case _ => finalize(tree, untpd.Tuple(trees)(tree.source)) } - def Throw(tree: Tree)(expr: Tree)(implicit ctx: Context): TermTree = tree match { + def Throw(tree: Tree)(expr: Tree)(using Context): TermTree = tree match { case tree: Throw if expr eq tree.expr => tree case _ => finalize(tree, untpd.Throw(expr)(tree.source)) } - def Quote(tree: Tree)(quoted: Tree)(implicit ctx: Context): Tree = tree match { + def Quote(tree: Tree)(quoted: Tree)(using Context): Tree = tree match { case tree: Quote if quoted eq tree.quoted => tree case _ => finalize(tree, untpd.Quote(quoted)(tree.source)) } - def Splice(tree: Tree)(expr: Tree)(implicit ctx: Context): Tree = tree match { + def Splice(tree: Tree)(expr: Tree)(using Context): Tree = tree match { case tree: Splice if expr eq tree.expr => tree case _ => finalize(tree, untpd.Splice(expr)(tree.source)) } - def TypSplice(tree: Tree)(expr: Tree)(implicit ctx: Context): Tree = tree match { + def TypSplice(tree: Tree)(expr: Tree)(using Context): Tree = tree match { case tree: TypSplice if expr eq tree.expr => tree case _ => finalize(tree, untpd.TypSplice(expr)(tree.source)) } - def ForYield(tree: Tree)(enums: List[Tree], expr: Tree)(implicit ctx: Context): TermTree = tree match { + def ForYield(tree: Tree)(enums: List[Tree], expr: Tree)(using Context): TermTree = tree match { case tree: ForYield if (enums eq tree.enums) && (expr eq tree.expr) => tree case _ => finalize(tree, untpd.ForYield(enums, expr)(tree.source)) } - def ForDo(tree: Tree)(enums: List[Tree], body: Tree)(implicit ctx: Context): TermTree = tree match { + def ForDo(tree: Tree)(enums: List[Tree], body: Tree)(using Context): TermTree = tree match { case tree: ForDo if (enums eq tree.enums) && (body eq tree.body) => tree case _ => finalize(tree, untpd.ForDo(enums, body)(tree.source)) } - def GenFrom(tree: Tree)(pat: Tree, expr: Tree, checkMode: GenCheckMode)(implicit ctx: Context): Tree = tree match { + def GenFrom(tree: Tree)(pat: Tree, expr: Tree, checkMode: GenCheckMode)(using Context): Tree = tree match { case tree: GenFrom if (pat eq tree.pat) && (expr eq tree.expr) && (checkMode == tree.checkMode) => tree case _ => finalize(tree, untpd.GenFrom(pat, expr, checkMode)(tree.source)) } - def GenAlias(tree: Tree)(pat: Tree, expr: Tree)(implicit ctx: Context): Tree = tree match { + def GenAlias(tree: Tree)(pat: Tree, expr: Tree)(using Context): Tree = tree match { case tree: GenAlias if (pat eq tree.pat) && (expr eq tree.expr) => tree case _ => finalize(tree, untpd.GenAlias(pat, expr)(tree.source)) } - def ContextBounds(tree: Tree)(bounds: TypeBoundsTree, cxBounds: List[Tree])(implicit ctx: Context): TypTree = tree match { + def ContextBounds(tree: Tree)(bounds: TypeBoundsTree, cxBounds: List[Tree])(using Context): TypTree = tree match { case tree: ContextBounds if (bounds eq tree.bounds) && (cxBounds eq tree.cxBounds) => tree case _ => finalize(tree, untpd.ContextBounds(bounds, cxBounds)(tree.source)) } - def PatDef(tree: Tree)(mods: Modifiers, pats: List[Tree], tpt: Tree, rhs: Tree)(implicit ctx: Context): Tree = tree match { + def PatDef(tree: Tree)(mods: Modifiers, pats: List[Tree], tpt: Tree, rhs: Tree)(using Context): Tree = tree match { case tree: PatDef if (mods eq tree.mods) && (pats eq tree.pats) && (tpt eq tree.tpt) && (rhs eq tree.rhs) => tree case _ => finalize(tree, untpd.PatDef(mods, pats, tpt, rhs)(tree.source)) } - def Export(tree: Tree)(expr: Tree, selectors: List[ImportSelector])(implicit ctx: Context): Tree = tree match { + def Export(tree: Tree)(expr: Tree, selectors: List[ImportSelector])(using Context): Tree = tree match { case tree: Export if (expr eq tree.expr) && (selectors eq tree.selectors) => tree case _ => finalize(tree, untpd.Export(expr, selectors)(tree.source)) } def ExtMethods(tree: Tree)(tparams: List[TypeDef], vparamss: List[List[ValDef]], methods: List[DefDef])(using Context): Tree = tree match case tree: ExtMethods if (tparams eq tree.tparams) && (vparamss eq tree.vparamss) && (methods == tree.methods) => tree case _ => finalize(tree, untpd.ExtMethods(tparams, vparamss, methods)(tree.source)) - def ImportSelector(tree: Tree)(imported: Ident, renamed: Tree, bound: Tree)(implicit ctx: Context): Tree = tree match { + def ImportSelector(tree: Tree)(imported: Ident, renamed: Tree, bound: Tree)(using Context): Tree = tree match { case tree: ImportSelector if (imported eq tree.imported) && (renamed eq tree.renamed) && (bound eq tree.bound) => tree case _ => finalize(tree, untpd.ImportSelector(imported, renamed, bound)(tree.source)) } - def Number(tree: Tree)(digits: String, kind: NumberKind)(implicit ctx: Context): Tree = tree match { + def Number(tree: Tree)(digits: String, kind: NumberKind)(using Context): Tree = tree match { case tree: Number if (digits == tree.digits) && (kind == tree.kind) => tree case _ => finalize(tree, untpd.Number(digits, kind)) } - def TypedSplice(tree: Tree)(splice: tpd.Tree)(implicit ctx: Context): ProxyTree = tree match { + def TypedSplice(tree: Tree)(splice: tpd.Tree)(using Context): ProxyTree = tree match { case tree: TypedSplice if splice `eq` tree.splice => tree - case _ => finalize(tree, untpd.TypedSplice(splice)(ctx)) + case _ => finalize(tree, untpd.TypedSplice(splice)(using ctx)) } - def MacroTree(tree: Tree)(expr: Tree)(implicit ctx: Context): Tree = tree match { + def MacroTree(tree: Tree)(expr: Tree)(using Context): Tree = tree match { case tree: MacroTree if expr `eq` tree.expr => tree case _ => finalize(tree, untpd.MacroTree(expr)(tree.source)) } } abstract class UntypedTreeMap(cpy: UntypedTreeCopier = untpd.cpy) extends TreeMap(cpy) { - override def transformMoreCases(tree: Tree)(implicit ctx: Context): Tree = tree match { + override def transformMoreCases(tree: Tree)(using Context): Tree = tree match { case ModuleDef(name, impl) => cpy.ModuleDef(tree)(name, transformSub(impl)) case tree: DerivingTemplate => @@ -701,7 +701,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { } abstract class UntypedTreeAccumulator[X] extends TreeAccumulator[X] { self => - override def foldMoreCases(x: X, tree: Tree)(implicit ctx: Context): X = tree match { + override def foldMoreCases(x: X, tree: Tree)(using Context): X = tree match { case ModuleDef(name, impl) => this(x, impl) case tree: DerivingTemplate => @@ -764,20 +764,20 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { } abstract class UntypedTreeTraverser extends UntypedTreeAccumulator[Unit] { - def traverse(tree: Tree)(implicit ctx: Context): Unit - def apply(x: Unit, tree: Tree)(implicit ctx: Context): Unit = traverse(tree) - protected def traverseChildren(tree: Tree)(implicit ctx: Context): Unit = foldOver((), tree) + def traverse(tree: Tree)(using Context): Unit + def apply(x: Unit, tree: Tree)(using Context): Unit = traverse(tree) + protected def traverseChildren(tree: Tree)(using Context): Unit = foldOver((), tree) } /** Fold `f` over all tree nodes, in depth-first, prefix order */ class UntypedDeepFolder[X](f: (X, Tree) => X) extends UntypedTreeAccumulator[X] { - def apply(x: X, tree: Tree)(implicit ctx: Context): X = foldOver(f(x, tree), tree) + def apply(x: X, tree: Tree)(using Context): X = foldOver(f(x, tree), tree) } /** Is there a subtree of this tree that satisfies predicate `p`? */ - def (tree: Tree) existsSubTree(p: Tree => Boolean)(implicit ctx: Context): Boolean = { + def (tree: Tree) existsSubTree(p: Tree => Boolean)(using Context): Boolean = { val acc = new UntypedTreeAccumulator[Boolean] { - def apply(x: Boolean, t: Tree)(implicit ctx: Context) = x || p(t) || foldOver(x, t) + def apply(x: Boolean, t: Tree)(using Context) = x || p(t) || foldOver(x, t) } acc(false, tree) } diff --git a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala index 305dc88d4e0a..f3625d7eb7ef 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} /** * 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 d80170528894..73c3353518d1 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import FileUtils._ /** diff --git a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala index d4d21d38d1c1..765240b40125 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.io.{ Directory, PlainDirectory, AbstractFile } import PathResolver.Defaults import rewrites.Rewrites diff --git a/compiler/src/dotty/tools/dotc/core/ParamInfo.scala b/compiler/src/dotty/tools/dotc/core/ParamInfo.scala index 9593ba0b5d13..449a30c684b5 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 +import Contexts.{Context, ctx} import Types.Type import Variances.{Variance, varianceToInt} diff --git a/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala b/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala index 4d1731e5d324..cd0eec7f5b8e 100644 --- a/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala +++ b/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala @@ -4,7 +4,7 @@ package fromtasty import core._ import Decorators._ -import Contexts.Context +import Contexts.{Context, ctx} import Symbols.{Symbol, ClassSymbol} import SymDenotations.ClassDenotation import NameOps._ diff --git a/compiler/src/dotty/tools/dotc/fromtasty/TastyFileUtil.scala b/compiler/src/dotty/tools/dotc/fromtasty/TastyFileUtil.scala index a8f4dfce7302..8054387d27cc 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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/Interactive.scala b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala index d05d8772c6cd..5675240abbed 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala @@ -269,7 +269,7 @@ object Interactive { case first :: _ if first eq stat => ctx.exprContext(stat, exprOwner) case (imp: Import) :: rest => - contextOfStat(rest, stat, exprOwner, ctx.importContext(imp, imp.symbol(ctx))) + contextOfStat(rest, stat, exprOwner, ctx.importContext(imp, imp.symbol(using ctx))) case _ :: rest => contextOfStat(rest, stat, exprOwner, ctx) } diff --git a/compiler/src/dotty/tools/dotc/printing/Highlighting.scala b/compiler/src/dotty/tools/dotc/printing/Highlighting.scala index 6f2be8898a81..59c8cccc3571 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 +import core.Contexts.{Context, ctx} object Highlighting { diff --git a/compiler/src/dotty/tools/dotc/printing/Printers.scala b/compiler/src/dotty/tools/dotc/printing/Printers.scala index 1dc286ba590b..c946990b90cf 100644 --- a/compiler/src/dotty/tools/dotc/printing/Printers.scala +++ b/compiler/src/dotty/tools/dotc/printing/Printers.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc package printing -import core.Contexts.Context +import core.Contexts.{Context, ctx} trait Printers { this: Context => diff --git a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala index f8815e62e841..87935b558255 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 857519b9d31b..72c16580c3d8 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} sealed trait AsyncHelper { diff --git a/compiler/src/dotty/tools/dotc/profile/Profiler.scala b/compiler/src/dotty/tools/dotc/profile/Profiler.scala index b3a2016bc6fb..ffaba732ee5d 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 b6b2d269ce67..c279e25c9b3a 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.tastyreflect.ReflectionImpl object QuoteContext { diff --git a/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala b/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala index 0e6fe3fd8bb7..c44306ae2e9e 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 +import core.Contexts.{Context, ctx} /** * 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 c37226d29b1a..74baa2383082 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 +import core.Contexts.{Context, ctx} 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 cb1e020df7e3..cc214b17ddbd 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 +import core.Contexts.{Context, ctx} 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 6668b0c49fea..520ab0ac5bd1 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 +import core.Contexts.{Context, ctx} import Diagnostic.Error /** diff --git a/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala b/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala index 046af50561c8..73fae4b73b6d 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 +import core.Contexts.{Context, ctx} /** 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 da93a31fffef..6250b0a55283 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 +import Contexts.{Context, ctx} import Decorators._, Symbols._, Names._, NameOps._, Types._, Flags._ import Denotations.SingleDenotation import SymDenotations.SymDenotation diff --git a/compiler/src/dotty/tools/dotc/reporting/trace.scala b/compiler/src/dotty/tools/dotc/reporting/trace.scala index cf5380ac0ee8..b9e047febf20 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 +import core.Contexts.{Context, ctx} import config.Config import config.Printers import core.Mode diff --git a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala index 23a75341b963..2842c78bdbf2 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 +import core.Contexts.{Context, ctx} 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 040626b248a9..5132b3fa1743 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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/package.scala b/compiler/src/dotty/tools/dotc/tastyreflect/package.scala index 86d9a962c3df..2ad86a9fa984 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 bbf4b08dbe06..8690acf3be03 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 +import Contexts.{Context, ctx} 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 7cd2964b543e..a8d72b17a98a 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 +import Contexts.{Context, ctx} 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 301817366a22..74044b06b96d 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 +import Contexts.{Context, ctx} 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 803c91862876..afeee713bd0e 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 +import Contexts.{Context, ctx} import Flags._ import SymUtils._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala index 947af8c47978..8f8158279639 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 +import Contexts.{Context, ctx} 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 11040f4872cc..a5ac68e64f9d 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 +import Contexts.{Context, ctx} 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 0fd3bdde12d3..4577f9665d3b 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 1ddf2020c523..eb8796736ba7 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 +import Contexts.{Context, ctx} 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 94a5916fc5be..88c7d4a486da 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 afb80e2a1ee7..b57b6f4ee657 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.typer.Docstrings class CookComments extends MegaPhase.MiniPhase { diff --git a/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala b/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala index 13089a69adba..83b82dc92475 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 3b9ac6740723..187b4ef90d61 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 68dfa7280097..b49db2b61a8c 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 +import core.Contexts.{Context, ctx} /** 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 24e34cbbd336..6def243ab0ff 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 +import Contexts.{Context, ctx} 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 81cecf1329ef..30c90b76033e 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 b8f8b7fdf134..935d89c8949c 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 +import Contexts.{Context, ctx} 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 1814e2b282b4..7347216cc4dd 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 +import Contexts.{Context, ctx} 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 e8b374f432dd..a2e2de4267f2 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala @@ -7,7 +7,7 @@ import Types._ import dotty.tools.dotc.transform.MegaPhase._ import ast.Trees._ import Flags._ -import Contexts.Context +import Contexts.{Context, ctx} import Symbols._ import Constants._ import Decorators._ diff --git a/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala b/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala index abb4611479c5..f0de00316bcb 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 +import Contexts.{Context, ctx} 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 d026a805144f..471b20a79e31 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 +import Contexts.{Context, ctx} 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 aec65969d706..d749c14547c1 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 +import Contexts.{Context, ctx} import Types._ import MegaPhase._ import ast.Trees._ diff --git a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala index 523a06fc2a9c..fd32c22ae276 100644 --- a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala @@ -9,7 +9,7 @@ import ast.untpd import Flags._ import Types._ import Constants.Constant -import Contexts.Context +import Contexts.{Context, ctx} import Symbols._ import Decorators._ import scala.collection.mutable diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala index 018ebdc196c6..d2bb92569586 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 +import Contexts.{Context, ctx} import Flags._ import Definitions._ import DenotTransformers._ @@ -29,7 +29,7 @@ class FunctionXXLForwarders extends MiniPhase with IdentityDenotTransformer { override def transformTemplate(impl: Template)(implicit ctx: Context): Template = { - def forwarderRhs(receiver: Tree, xsTree: Tree): Tree = { + def forwarderRhs(receiver: Tree, xsTree: Tree): Tree = { val argsApply = ref(xsTree.symbol).select(nme.apply) var idx = -1 val argss = receiver.tpe.widenDealias.paramInfoss.map(_.map { param => diff --git a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala index b2ac64e4f230..98a89287d829 100644 --- a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala +++ b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala @@ -3,7 +3,7 @@ package dotc package transform import core.Annotations._ -import core.Contexts.Context +import core.Contexts.{Context, ctx} import core.Definitions import core.Flags._ import core.Names.{DerivedName, Name, SimpleName, TypeName} diff --git a/compiler/src/dotty/tools/dotc/transform/Getters.scala b/compiler/src/dotty/tools/dotc/transform/Getters.scala index 4f7fdcbc2bb9..1e44d7e0ac66 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 +import Contexts.{Context, ctx} import SymDenotations.SymDenotation import Types._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala b/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala index 7301101cbd27..c425fcb2bb1f 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 +import Contexts.{Context, ctx} 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 481d0e23cf8b..8f247f064c58 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, Types._, Constants._, Decorators._, Symbols._ +import Contexts.{Context, ctx}, 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 c15f5aac22a6..11ccd1ef5463 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -5,7 +5,7 @@ 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 +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._ diff --git a/compiler/src/dotty/tools/dotc/transform/LetOverApply.scala b/compiler/src/dotty/tools/dotc/transform/LetOverApply.scala index 2279302ef16e..0d7dfc80f588 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, Symbols._, Decorators._ +import Contexts.{Context, ctx}, 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 d97d51142012..54d464079fb6 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 +import Contexts.{Context, ctx} import Flags._ import SymUtils._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala index 3a91d3eb4e7c..f42f944169a7 100644 --- a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala @@ -55,7 +55,7 @@ abstract class MacroTransform extends Phase { case impl @ Template(constr, parents, self, _) => cpy.Template(tree)( transformSub(constr), - transform(parents)(ctx.superCallContext), + transform(parents)(using ctx.superCallContext), Nil, transformSelf(self), transformStats(impl.body, tree.symbol)) diff --git a/compiler/src/dotty/tools/dotc/transform/Memoize.scala b/compiler/src/dotty/tools/dotc/transform/Memoize.scala index 4ff409226eff..4e48c4fb9f1e 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 +import Contexts.{Context, ctx} import SymDenotations.SymDenotation import Denotations._ import Symbols._ diff --git a/compiler/src/dotty/tools/dotc/transform/Mixin.scala b/compiler/src/dotty/tools/dotc/transform/Mixin.scala index 055e415b9919..078f326647a9 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 +import Contexts.{Context, ctx} 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 8b978a895f5f..574e45873c80 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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/Pickler.scala b/compiler/src/dotty/tools/dotc/transform/Pickler.scala index d536acd76f56..bdca26b52d2e 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 +import Contexts.{Context, ctx} import Decorators._ import tasty._ import config.Printers.{noPrinter, pickling} diff --git a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala index 85873b74670f..2181f99d9432 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 +import core.Contexts.{Context, ctx} import core.NameKinds._ import core.Symbols._ import core.Flags._ diff --git a/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala b/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala index b921bdc57e9b..eeb9614c8a6e 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 8a90e20e17bb..db7d0fd9e23b 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 +import Contexts.{Context, ctx} 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 63d318ea66a6..67cd8e1b59bf 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 +import Contexts.{Context, ctx} 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 226bed2f66ce..b2671258554b 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 e278a3975962..f0930a162091 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 +import Contexts.{Context, ctx} /** 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 d774844c788d..fa72cc90d1a3 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 af2e5818fd8c..51bcd7a91e0f 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 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 +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._ diff --git a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala index 996df0dc5c8b..41f72d838477 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 b379b5dd5ce2..6e63bd16298e 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 +import Contexts.{Context, ctx} import Decorators._ import Flags._ import ast.Trees._ diff --git a/compiler/src/dotty/tools/dotc/transform/init/Checker.scala b/compiler/src/dotty/tools/dotc/transform/init/Checker.scala index 497b6e3f7314..f88faf5c1fb4 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 +import Contexts.{Context, ctx} 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 0fb978c3a570..4ac57714b814 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 +import Contexts.{Context, ctx} 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 66411a964a18..cebbeb4cf0a5 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 +import Contexts.{Context, ctx} 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 f2300b03441e..cbe9c12064d1 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 +import core.Contexts.{Context, ctx} /** 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 924f23444804..2ff0e9dc451f 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 +import Contexts.{Context, ctx} 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 ec5fbd4d3523..c90f90b489cf 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 +import Contexts.{Context, ctx} 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 6f9dc4ada264..7488bbcfebaa 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 +import Contexts.{Context, ctx} 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 19df8cc00353..f7d7db553306 100644 --- a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala +++ b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala @@ -4,7 +4,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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 7b4bb551d349..ab27d1f2aaa7 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index ad9a73c01aa2..e7a7a2222f3d 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -1625,7 +1625,7 @@ final class SearchRoot extends SearchHistory { // Substitute dictionary references into dictionary entry RHSs val rhsMap = new TreeTypeMap(treeMap = { case id: Ident if vsymMap.contains(id.symbol) => - tpd.ref(vsymMap(id.symbol))(ctx.withSource(id.source)).withSpan(id.span) + tpd.ref(vsymMap(id.symbol))(using ctx.withSource(id.source)).withSpan(id.span) case tree => tree }) val nrhss = rhss.map(rhsMap(_)) diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index 6355bd53d34d..313f895b1df0 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -653,7 +653,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { val inlineCtx = inlineContext(call).fresh.setTyper(inlineTyper).setNewScope def inlinedFromOutside(tree: Tree)(span: Span): Tree = - Inlined(EmptyTree, Nil, tree)(ctx.withSource(inlinedMethod.topLevelClass.source)).withSpan(span) + Inlined(EmptyTree, Nil, tree)(using ctx.withSource(inlinedMethod.topLevelClass.source)).withSpan(span) // A tree type map to prepare the inlined body for typechecked. // The translation maps references to `this` and parameters to @@ -701,7 +701,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { }, oldOwners = inlinedMethod :: Nil, newOwners = ctx.owner :: Nil - )(inlineCtx) + )(using inlineCtx) // Apply inliner to `rhsToInline`, split off any implicit bindings from result, and // make them part of `bindingsBuf`. The expansion is then the tree that remains. @@ -718,7 +718,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { // call. This way, a defensively written rewrite methid can always // report bad inputs at the point of call instead of revealing its internals. val callToReport = if (enclosingInlineds.nonEmpty) enclosingInlineds.last else call - val ctxToReport = ctx.outersIterator.dropWhile(enclosingInlineds(_).nonEmpty).next + val ctxToReport = ctx.outersIterator.dropWhile(enclosingInlineds(using _).nonEmpty).next inContext(ctxToReport) { ctx.error(message, callToReport.sourcePos) } diff --git a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala index 1aa1e7353724..75e9caef6c12 100644 --- a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala +++ b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala @@ -446,7 +446,7 @@ object ProtoTypes { } class UnapplyFunProto(argType: Type, typer: Typer)(using Context) extends FunProto( - untpd.TypedSplice(dummyTreeOfType(argType)(ctx.source))(ctx) :: Nil, WildcardType)(typer, applyKind = ApplyKind.Regular) + untpd.TypedSplice(dummyTreeOfType(argType)(ctx.source)) :: Nil, WildcardType)(typer, applyKind = ApplyKind.Regular) /** A prototype for expressions [] that are type-parameterized: * diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 76a84cba6473..b6eed1ca47a1 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -1424,7 +1424,7 @@ class Typer extends Namer val guard1 = typedExpr(tree.guard, defn.BooleanType) var body1 = ensureNoLocalRefs(typedExpr(tree.body, pt1), pt1, ctx.scope.toList) if (pt1.isValueType) // insert a cast if body does not conform to expected type if we disregard gadt bounds - body1 = body1.ensureConforms(pt1)(originalCtx) + body1 = body1.ensureConforms(pt1)(using originalCtx) assignType(cpy.CaseDef(tree)(pat1, guard1, body1), pat1, body1) } @@ -1588,7 +1588,7 @@ class Typer extends Namer def typedInlined(tree: untpd.Inlined, pt: Type)(using Context): Tree = { val (bindings1, exprCtx) = typedBlockStats(tree.bindings) - val expansion1 = typed(tree.expansion, pt)(using inlineContext(tree.call)(exprCtx)) + val expansion1 = typed(tree.expansion, pt)(using inlineContext(tree.call)(using exprCtx)) assignType(cpy.Inlined(tree)(tree.call, bindings1.asInstanceOf[List[MemberDef]], expansion1), bindings1, expansion1) } @@ -1999,7 +1999,7 @@ class Typer extends Namer */ def maybeCall(ref: Tree, psym: Symbol, cinfo: Type): Tree = cinfo.stripPoly match { case cinfo @ MethodType(Nil) if cinfo.resultType.isImplicitMethod => - typedExpr(untpd.New(untpd.TypedSplice(ref)(superCtx), Nil))(using superCtx) + typedExpr(untpd.New(untpd.TypedSplice(ref)(using superCtx), Nil))(using superCtx) case cinfo @ MethodType(Nil) if !cinfo.resultType.isInstanceOf[MethodType] => ref case cinfo: MethodType => diff --git a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala index a56881631586..af219681d942 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 89ed336da185..db43c134f666 100644 --- a/compiler/src/dotty/tools/dotc/util/Signatures.scala +++ b/compiler/src/dotty/tools/dotc/util/Signatures.scala @@ -3,7 +3,7 @@ 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 +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 diff --git a/compiler/src/dotty/tools/dotc/util/SourceFile.scala b/compiler/src/dotty/tools/dotc/util/SourceFile.scala index 5922b9edb0e6..ceab3ac42b96 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 +import core.Contexts.{Context, ctx} import scala.annotation.internal.sharable import java.util.concurrent.atomic.AtomicInteger import scala.collection.mutable @@ -49,7 +49,7 @@ class SourceFile(val file: AbstractFile, computeContent: => Array[Char]) extends } private var _maybeInComplete: Boolean = false - + def maybeIncomplete: Boolean = _maybeInComplete def this(file: AbstractFile, codec: Codec) = diff --git a/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala b/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala index a872bbac022a..53b8ccead3ee 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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 70f5950b4b4f..ac80216c5213 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} 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/Rendering.scala b/compiler/src/dotty/tools/repl/Rendering.scala index 4527fea8ad63..8adffc0c4fa2 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 +import dotc.core.Contexts.{Context, ctx} 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 19af747b01e7..5c73a676baec 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 +import dotc.core.Contexts.{Context, ctx} /** A customized `FrontEnd` for the REPL * diff --git a/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala b/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala index a14c4d1aa4ee..62d95843e0f3 100644 --- a/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala +++ b/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala @@ -61,7 +61,7 @@ class CommentPicklingTest { compileAndUnpickle(sources) { (trees, ctx) => findTreeNamed(treeName)(trees, ctx) match { case Some(md: tpd.MemberDef) => - val symbol = md.symbol(ctx) + val symbol = md.symbol(using ctx) val comment = for { docCtx <- ctx.docCtx comment <- docCtx.docstring(symbol) } yield comment.raw assertEquals(expectedComment, comment) @@ -112,7 +112,7 @@ class CommentPicklingTest { val trees = files.flatMap { f => val unpickler = new DottyUnpickler(f.toByteArray()) unpickler.enter(roots = Set.empty) - unpickler.rootTrees(ctx) + unpickler.rootTrees(using ctx) } fn(trees, ctx) } diff --git a/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala b/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala index e8c9412a49c4..4dcc98868f07 100644 --- a/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala +++ b/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala @@ -35,7 +35,7 @@ class DeSugarTest extends ParserTest { def transform(trees: List[Tree], mode: Mode)(implicit ctx: Context): List[Tree] = withMode(mode) { transform(trees) } override def transform(tree: Tree)(implicit ctx: Context): Tree = { - val tree1 = desugar(tree)(ctx.withModeBits(curMode)) + val tree1 = desugar(tree)(using ctx.withModeBits(curMode)) tree1 match { case TypedSplice(t) => tree1 From b935477733777ed0bcc88a6933ab81f390ff4f69 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 15:52:21 +0200 Subject: [PATCH 17/41] Convert config classes --- compiler/src/dotty/tools/dotc/Driver.scala | 6 +++--- .../dotty/tools/dotc/config/CompilerCommand.scala | 4 ++-- .../src/dotty/tools/dotc/config/JavaPlatform.scala | 12 ++++++------ .../src/dotty/tools/dotc/config/PathResolver.scala | 6 +++--- .../src/dotty/tools/dotc/config/Platform.scala | 14 +++++++------- .../src/dotty/tools/dotc/config/SJSPlatform.scala | 4 ++-- .../dotty/tools/dotc/config/ScalaSettings.scala | 4 ++-- .../src/dotty/tools/dotc/config/Settings.scala | 8 ++++---- .../tools/dotc/interactive/InteractiveDriver.scala | 2 +- .../tastyreflect/ReflectionCompilerInterface.scala | 2 +- compiler/src/dotty/tools/repl/Rendering.scala | 2 +- compiler/src/dotty/tools/repl/ReplDriver.scala | 2 +- doc-tool/src/dotty/tools/dottydoc/DocDriver.scala | 4 ++-- 13 files changed, 35 insertions(+), 35 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Driver.scala b/compiler/src/dotty/tools/dotc/Driver.scala index bb88f1448826..c50029ca96ad 100644 --- a/compiler/src/dotty/tools/dotc/Driver.scala +++ b/compiler/src/dotty/tools/dotc/Driver.scala @@ -67,7 +67,7 @@ class Driver { def setup(args: Array[String], rootCtx: Context): (List[String], Context) = { val ictx = rootCtx.fresh - val summary = CompilerCommand.distill(args)(ictx) + val summary = CompilerCommand.distill(args)(using ictx) ictx.setSettings(summary.sstate) MacroClassLoader.init(ictx) Positioned.updateDebugPos(using ictx) @@ -84,7 +84,7 @@ 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(ctx0)) { + if (ctx0.settings.fromTasty.value(using ctx0)) { // Resolve classpath and class names of tasty files val (classPaths, classNames) = fileNames0.flatMap { name => val path = Paths.get(name) @@ -109,7 +109,7 @@ class Driver { }.unzip val ctx1 = ctx0.fresh val classPaths1 = classPaths.distinct.filter(_ != "") - val fullClassPath = (classPaths1 :+ ctx1.settings.classpath.value(ctx1)).mkString(java.io.File.pathSeparator) + val fullClassPath = (classPaths1 :+ ctx1.settings.classpath.value(using ctx1)).mkString(java.io.File.pathSeparator) ctx1.setSetting(ctx1.settings.classpath, fullClassPath) (classNames, ctx1) } diff --git a/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala b/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala index da29bc768d63..88ddf4aef0bd 100644 --- a/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala +++ b/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala @@ -34,7 +34,7 @@ object CompilerCommand { def versionMsg: String = s"Dotty compiler $versionString -- $copyrightString" /** Distill arguments into summary detailing settings, errors and files to compiler */ - def distill(args: Array[String])(implicit ctx: Context): ArgsSummary = { + def distill(args: Array[String])(using Context): ArgsSummary = { /** * Expands all arguments starting with @ to the contents of the * file named like each argument. @@ -64,7 +64,7 @@ object CompilerCommand { * are already applied in context. * @return The list of files to compile. */ - def checkUsage(summary: ArgsSummary, sourcesRequired: Boolean)(implicit ctx: Context): List[String] = { + def checkUsage(summary: ArgsSummary, sourcesRequired: Boolean)(using Context): List[String] = { val settings = ctx.settings /** Creates a help message for a subset of options based on cond */ diff --git a/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala b/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala index 49d7abe8f31d..bb5da77063a7 100644 --- a/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala +++ b/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala @@ -13,7 +13,7 @@ class JavaPlatform extends Platform { private var currentClassPath: Option[ClassPath] = None - def classPath(implicit ctx: Context): ClassPath = { + def classPath(using Context): ClassPath = { if (currentClassPath.isEmpty) currentClassPath = Some(new PathResolver().result) val cp = currentClassPath.get @@ -21,7 +21,7 @@ class JavaPlatform extends Platform { } // The given symbol is a method with the right name and signature to be a runnable java program. - def isMainMethod(sym: SymDenotation)(implicit ctx: Context): Boolean = + def isMainMethod(sym: SymDenotation)(using Context): Boolean = (sym.name == nme.main) && (sym.info match { case MethodTpe(_, defn.ArrayOf(el) :: Nil, restpe) => el =:= defn.StringType && (restpe isRef defn.UnitClass) case _ => false @@ -35,10 +35,10 @@ class JavaPlatform extends Platform { currentClassPath = Some(subst.getOrElse(cp, cp)) } - def rootLoader(root: TermSymbol)(implicit ctx: Context): SymbolLoader = new SymbolLoaders.PackageLoader(root, classPath) + def rootLoader(root: TermSymbol)(using Context): SymbolLoader = new SymbolLoaders.PackageLoader(root, classPath) /** Is the SAMType `cls` also a SAM under the rules of the JVM? */ - def isSam(cls: ClassSymbol)(implicit ctx: Context): Boolean = + def isSam(cls: ClassSymbol)(using Context): Boolean = cls.isAllOf(NoInitsTrait) && cls.superClass == defn.ObjectClass && cls.directlyInheritedTraits.forall(_.is(NoInits)) && @@ -50,7 +50,7 @@ class JavaPlatform extends Platform { * to anything but other booleans, but it should be present in * case this is put to other uses. */ - def isMaybeBoxed(sym: ClassSymbol)(implicit ctx: Context): Boolean = { + def isMaybeBoxed(sym: ClassSymbol)(using Context): Boolean = { val d = defn import d._ (sym == ObjectClass) || @@ -61,6 +61,6 @@ class JavaPlatform extends Platform { (sym derivesFrom BoxedBooleanClass) } - def newClassLoader(bin: AbstractFile)(implicit ctx: Context): SymbolLoader = + def newClassLoader(bin: AbstractFile)(using Context): SymbolLoader = new ClassfileLoader(bin) } diff --git a/compiler/src/dotty/tools/dotc/config/PathResolver.scala b/compiler/src/dotty/tools/dotc/config/PathResolver.scala index 5a510d43b726..11d733ca4d49 100644 --- a/compiler/src/dotty/tools/dotc/config/PathResolver.scala +++ b/compiler/src/dotty/tools/dotc/config/PathResolver.scala @@ -128,7 +128,7 @@ object PathResolver { ) } - def fromPathString(path: String)(implicit ctx: Context): ClassPath = { + def fromPathString(path: String)(using Context): ClassPath = { val settings = ctx.settings.classpath.update(path) new PathResolver()(using ctx.fresh.setSettings(settings)).result } @@ -159,8 +159,8 @@ object PathResolver { import PathResolver.{Defaults, ppcp} -class PathResolver(implicit ctx: Context) { - import ctx.base.settings +class PathResolver(using c: Context) { + import c.base.settings private val classPathFactory = new ClassPathFactory diff --git a/compiler/src/dotty/tools/dotc/config/Platform.scala b/compiler/src/dotty/tools/dotc/config/Platform.scala index 0dfbc060b6a6..47633d4518d7 100644 --- a/compiler/src/dotty/tools/dotc/config/Platform.scala +++ b/compiler/src/dotty/tools/dotc/config/Platform.scala @@ -14,10 +14,10 @@ import core.Flags.Module abstract class Platform { /** The root symbol loader. */ - def rootLoader(root: TermSymbol)(implicit ctx: Context): SymbolLoader + def rootLoader(root: TermSymbol)(using Context): SymbolLoader /** The compiler classpath. */ - def classPath(implicit ctx: Context): ClassPath + def classPath(using Context): ClassPath /** Update classpath with a substitution that maps entries to entries */ def updateClassPath(subst: Map[ClassPath, ClassPath]): Unit @@ -26,19 +26,19 @@ abstract class Platform { //def platformPhases: List[SubComponent] /** Is the SAMType `cls` also a SAM under the rules of the platform? */ - def isSam(cls: ClassSymbol)(implicit ctx: Context): Boolean + def isSam(cls: ClassSymbol)(using Context): Boolean /** The various ways a boxed primitive might materialize at runtime. */ - def isMaybeBoxed(sym: ClassSymbol)(implicit ctx: Context): Boolean + def isMaybeBoxed(sym: ClassSymbol)(using Context): Boolean /** Create a new class loader to load class file `bin` */ - def newClassLoader(bin: AbstractFile)(implicit ctx: Context): SymbolLoader + def newClassLoader(bin: AbstractFile)(using Context): SymbolLoader /** The given symbol is a method with the right name and signature to be a runnable program. */ - def isMainMethod(sym: SymDenotation)(implicit ctx: Context): Boolean + def isMainMethod(sym: SymDenotation)(using Context): Boolean /** The given class has a main method. */ - final def hasMainMethod(sym: Symbol)(implicit ctx: Context): Boolean = + final def hasMainMethod(sym: Symbol)(using Context): Boolean = sym.info.member(nme.main).hasAltWith { case x: SymDenotation => isMainMethod(x) && (sym.is(Module) || x.isStatic) case _ => false diff --git a/compiler/src/dotty/tools/dotc/config/SJSPlatform.scala b/compiler/src/dotty/tools/dotc/config/SJSPlatform.scala index 883ce31ca741..5987df22d432 100644 --- a/compiler/src/dotty/tools/dotc/config/SJSPlatform.scala +++ b/compiler/src/dotty/tools/dotc/config/SJSPlatform.scala @@ -6,13 +6,13 @@ import Symbols._ import dotty.tools.backend.sjs.JSDefinitions -class SJSPlatform()(implicit ctx: Context) extends JavaPlatform { +class SJSPlatform()(using Context) extends JavaPlatform { /** Scala.js-specific definitions. */ val jsDefinitions: JSDefinitions = new JSDefinitions() /** Is the SAMType `cls` also a SAM under the rules of the Scala.js back-end? */ - override def isSam(cls: ClassSymbol)(implicit ctx: Context): Boolean = + override def isSam(cls: ClassSymbol)(using Context): Boolean = defn.isFunctionClass(cls) || jsDefinitions.isJSFunctionClass(cls) } diff --git a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala index 765240b40125..2e30ec911974 100644 --- a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala +++ b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala @@ -98,8 +98,8 @@ class ScalaSettings extends Settings.SettingGroup { default = "true") object mixinForwarderChoices { - def isTruthy(implicit ctx: Context) = XmixinForceForwarders.value == "true" - def isAtLeastJunit(implicit ctx: Context) = isTruthy || XmixinForceForwarders.value == "junit" + def isTruthy(using Context) = XmixinForceForwarders.value == "true" + def isAtLeastJunit(using Context) = isTruthy || XmixinForceForwarders.value == "junit" } /** -Y "Private" settings */ diff --git a/compiler/src/dotty/tools/dotc/config/Settings.scala b/compiler/src/dotty/tools/dotc/config/Settings.scala index 78097f7868a0..2cbe0ac3aa2e 100644 --- a/compiler/src/dotty/tools/dotc/config/Settings.scala +++ b/compiler/src/dotty/tools/dotc/config/Settings.scala @@ -185,9 +185,9 @@ object Settings { object Setting { implicit class SettingDecorator[T](val setting: Setting[T]) extends AnyVal { - def value(implicit ctx: Context): T = setting.valueIn(ctx.settingsState) - def update(x: T)(implicit ctx: Context): SettingsState = setting.updateIn(ctx.settingsState, x) - def isDefault(implicit ctx: Context): Boolean = setting.isDefaultIn(ctx.settingsState) + def value(using Context): T = setting.valueIn(ctx.settingsState) + def update(x: T)(using Context): SettingsState = setting.updateIn(ctx.settingsState, x) + def isDefault(using Context): Boolean = setting.isDefaultIn(ctx.settingsState) } } @@ -252,7 +252,7 @@ object Settings { } } - def processArguments(arguments: List[String], processAll: Boolean)(implicit ctx: Context): ArgsSummary = + def processArguments(arguments: List[String], processAll: Boolean)(using Context): ArgsSummary = processArguments(ArgsSummary(ctx.settingsState, arguments, Nil, Nil), processAll, Nil) def publish[T](settingf: Int => Setting[T]): Setting[T] = { diff --git a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala index c0cb06acf73a..1c13f12c4181 100644 --- a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala +++ b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala @@ -62,7 +62,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { // We also need something like sbt server-mode to be informed of changes on // the classpath. - private val (zipClassPaths, dirClassPaths) = currentCtx.platform.classPath(currentCtx) match { + private val (zipClassPaths, dirClassPaths) = currentCtx.platform.classPath(using currentCtx) match { case AggregateClassPath(cps) => // FIXME: We shouldn't assume that ClassPath doesn't have other // subclasses. For now, the only other subclass is JrtClassPath on Java diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala index 5d512eafa90c..8067897ce3fe 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala @@ -100,7 +100,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend type Settings = config.ScalaSettings - def Settings_color(self: Settings): Boolean = self.color.value(rootContext) == "always" + def Settings_color(self: Settings): Boolean = self.color.value(using rootContext) == "always" /////////// diff --git a/compiler/src/dotty/tools/repl/Rendering.scala b/compiler/src/dotty/tools/repl/Rendering.scala index 8adffc0c4fa2..9b717ebdf944 100644 --- a/compiler/src/dotty/tools/repl/Rendering.scala +++ b/compiler/src/dotty/tools/repl/Rendering.scala @@ -46,7 +46,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { if (myClassLoader != null) myClassLoader else { val parent = parentClassLoader.getOrElse { - val compilerClasspath = ctx.platform.classPath(ctx).asURLs + val compilerClasspath = ctx.platform.classPath(using ctx).asURLs new java.net.URLClassLoader(compilerClasspath.toArray, null) } diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 54df925758fd..a64fe4181d8c 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -81,7 +81,7 @@ class ReplDriver(settings: Array[String], */ protected def resetToInitial(): Unit = { rootCtx = initialCtx - if (rootCtx.settings.outputDir.isDefault(rootCtx)) + if (rootCtx.settings.outputDir.isDefault(using rootCtx)) rootCtx = rootCtx.fresh .setSetting(rootCtx.settings.outputDir, new VirtualDirectory("")) compiler = new ReplCompiler diff --git a/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala b/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala index ec8609d38134..b531f1c06322 100644 --- a/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala +++ b/doc-tool/src/dotty/tools/dottydoc/DocDriver.scala @@ -21,14 +21,14 @@ class DocDriver extends Driver { override def setup(args: Array[String], rootCtx: Context): (List[String], Context) = { val ctx = rootCtx.fresh - val summary = CompilerCommand.distill(args)(ctx) + val summary = CompilerCommand.distill(args)(using ctx) ctx.setSettings(summary.sstate) ctx.setSetting(ctx.settings.YcookComments, true) ctx.setSetting(ctx.settings.YnoInline, true) ctx.setProperty(ContextDoc, new ContextDottydoc) - val fileNames = CompilerCommand.checkUsage(summary, sourcesRequired)(ctx) + val fileNames = CompilerCommand.checkUsage(summary, sourcesRequired)(using ctx) fromTastySetup(fileNames, ctx) } From 2ab9a588ac09439df56c0bac68d46a146f3aa8fb Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 15:55:54 +0200 Subject: [PATCH 18/41] Convert parser classes --- .../src/dotty/tools/dotc/parsing/JavaParsers.scala | 4 ++-- .../src/dotty/tools/dotc/parsing/JavaScanners.scala | 2 +- compiler/src/dotty/tools/dotc/parsing/Parsers.scala | 10 +++++----- compiler/src/dotty/tools/dotc/parsing/Scanners.scala | 4 ++-- .../src/dotty/tools/dotc/parsing/ScriptParsers.scala | 2 +- .../tools/dotc/parsing/xml/SymbolicXMLBuilder.scala | 2 +- compiler/src/dotty/tools/dotc/typer/Inliner.scala | 2 +- compiler/src/dotty/tools/repl/JLineTerminal.scala | 2 +- staging/src/scala/quoted/staging/QuoteDriver.scala | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala b/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala index 420d2e58ac23..d513122e7ae3 100644 --- a/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala @@ -28,7 +28,7 @@ object JavaParsers { import ast.untpd._ - class JavaParser(source: SourceFile)(implicit ctx: Context) extends ParserCommon(source) { + class JavaParser(source: SourceFile)(using Context) extends ParserCommon(source) { val definitions: Definitions = ctx.definitions import definitions._ @@ -988,7 +988,7 @@ object JavaParsers { * This is necessary even for Java, because the filename defining a non-public classes cannot be determined from the * classname alone. */ - class OutlineJavaParser(source: SourceFile)(implicit ctx: Context) extends JavaParser(source) with OutlineParserCommon { + class OutlineJavaParser(source: SourceFile)(using Context) extends JavaParser(source) with OutlineParserCommon { override def skipBracesHook(): Option[Tree] = None override def typeBody(leadingToken: Int, parentName: Name, parentTParams: List[TypeDef]): (List[Tree], List[Tree]) = { skipBraces() diff --git a/compiler/src/dotty/tools/dotc/parsing/JavaScanners.scala b/compiler/src/dotty/tools/dotc/parsing/JavaScanners.scala index 7816af83474d..850f15f63c95 100644 --- a/compiler/src/dotty/tools/dotc/parsing/JavaScanners.scala +++ b/compiler/src/dotty/tools/dotc/parsing/JavaScanners.scala @@ -12,7 +12,7 @@ import scala.internal.Chars._ object JavaScanners { - class JavaScanner(source: SourceFile, override val startFrom: Offset = 0)(implicit ctx: Context) extends ScannerCommon(source)(ctx) { + class JavaScanner(source: SourceFile, override val startFrom: Offset = 0)(using Context) extends ScannerCommon(source) { override def decodeUni: Boolean = true diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index c0ae8fbc2e76..1d744b6731c8 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -75,14 +75,14 @@ object Parsers { /** The parse starting point depends on whether the source file is self-contained: * if not, the AST will be supplemented. */ - def parser(source: SourceFile)(implicit ctx: Context): Parser = + def parser(source: SourceFile)(using Context): Parser = if source.isSelfContained then new ScriptParser(source) else new Parser(source) private val InCase: Region => Region = Scanners.InCase private val InCond: Region => Region = Scanners.InBraces - abstract class ParserCommon(val source: SourceFile)(implicit ctx: Context) { + abstract class ParserCommon(val source: SourceFile)(using Context) { val in: ScannerCommon @@ -151,7 +151,7 @@ object Parsers { def syntaxError(msg: Message, span: Span): Unit = ctx.error(msg, source.atSpan(span)) - def unimplementedExpr(implicit ctx: Context): Select = + def unimplementedExpr(using Context): Select = Select(Select(rootDot(nme.scala), nme.Predef), nme.???) } @@ -171,7 +171,7 @@ object Parsers { } } - class Parser(source: SourceFile)(implicit ctx: Context) extends ParserCommon(source) { + class Parser(source: SourceFile)(using Context) extends ParserCommon(source) { val in: Scanner = new Scanner(source) @@ -4017,7 +4017,7 @@ object Parsers { /** OutlineParser parses top-level declarations in `source` to find declared classes, ignoring their bodies (which * must only have balanced braces). This is used to map class names to defining sources. */ - class OutlineParser(source: SourceFile)(implicit ctx: Context) extends Parser(source) with OutlineParserCommon { + class OutlineParser(source: SourceFile)(using Context) extends Parser(source) with OutlineParserCommon { def skipBracesHook(): Option[Tree] = if (in.token == XMLSTART) Some(xmlLiteral()) else None diff --git a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala index f8f0d5b2be72..ca564bf50409 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Scanners.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Scanners.scala @@ -107,7 +107,7 @@ object Scanners { def isNestedEnd = token == RBRACE || token == OUTDENT } - abstract class ScannerCommon(source: SourceFile)(implicit ctx: Context) extends CharArrayReader with TokenData { + abstract class ScannerCommon(source: SourceFile)(using Context) extends CharArrayReader with TokenData { val buf: Array[Char] = source.content def nextToken(): Unit @@ -179,7 +179,7 @@ object Scanners { errorButContinue("trailing separator is not allowed", offset + litBuf.length - 1) } - class Scanner(source: SourceFile, override val startFrom: Offset = 0)(implicit ctx: Context) extends ScannerCommon(source)(ctx) { + class Scanner(source: SourceFile, override val startFrom: Offset = 0)(using Context) extends ScannerCommon(source) { val keepComments = !ctx.settings.YdropComments.value /** A switch whether operators at the start of lines can be infix operators */ diff --git a/compiler/src/dotty/tools/dotc/parsing/ScriptParsers.scala b/compiler/src/dotty/tools/dotc/parsing/ScriptParsers.scala index 4d28b21e45ac..d11db73b0455 100644 --- a/compiler/src/dotty/tools/dotc/parsing/ScriptParsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/ScriptParsers.scala @@ -47,7 +47,7 @@ object ScriptParsers { import ast.untpd._ - class ScriptParser(source: SourceFile)(implicit ctx: Context) extends Parser(source) { + class ScriptParser(source: SourceFile)(using Context) extends Parser(source) { /** This is the parse entry point for code which is not self-contained, e.g. * a script which is a series of template statements. They will be diff --git a/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala b/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala index ac350b6b1de4..1dc4505cf9fc 100644 --- a/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala +++ b/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala @@ -23,7 +23,7 @@ import Parsers.Parser * @author Burak Emir * @version 1.0 */ -class SymbolicXMLBuilder(parser: Parser, preserveWS: Boolean)(implicit ctx: Context) { +class SymbolicXMLBuilder(parser: Parser, preserveWS: Boolean)(using Context) { import Constants.Constant import untpd._ diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index 313f895b1df0..2f0be5d202b3 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -295,7 +295,7 @@ object Inliner { case ConstantType(Constant(code: String)) => val source2 = SourceFile.virtual("tasty-reflect", code) val ctx2 = ctx.fresh.setNewTyperState().setTyper(new Typer).setSource(source2) - val tree2 = new Parser(source2)(ctx2).block() + val tree2 = new Parser(source2)(using ctx2).block() val res = collection.mutable.ListBuffer.empty[(ErrorKind, Error)] val parseErrors = ctx2.reporter.allErrors.toList diff --git a/compiler/src/dotty/tools/repl/JLineTerminal.scala b/compiler/src/dotty/tools/repl/JLineTerminal.scala index ac80216c5213..44d423fa3c51 100644 --- a/compiler/src/dotty/tools/repl/JLineTerminal.scala +++ b/compiler/src/dotty/tools/repl/JLineTerminal.scala @@ -116,7 +116,7 @@ final class JLineTerminal extends java.io.Closeable { case class TokenData(token: Token, start: Int, end: Int) def currentToken: TokenData /* | Null */ = { val source = SourceFile.virtual("", input) - val scanner = new Scanner(source)(ctx.fresh.setReporter(Reporter.NoReporter)) + val scanner = new Scanner(source)(using ctx.fresh.setReporter(Reporter.NoReporter)) while (scanner.token != EOF) { val start = scanner.offset val token = scanner.token diff --git a/staging/src/scala/quoted/staging/QuoteDriver.scala b/staging/src/scala/quoted/staging/QuoteDriver.scala index dfd50eabaa5c..9f33570f4187 100644 --- a/staging/src/scala/quoted/staging/QuoteDriver.scala +++ b/staging/src/scala/quoted/staging/QuoteDriver.scala @@ -57,7 +57,7 @@ private class QuoteDriver(appClassloader: ClassLoader) extends Driver: override def initCtx: Context = val ictx = contextBase.initialCtx - ictx.settings.classpath.update(ClasspathFromClassloader(appClassloader))(ictx) + ictx.settings.classpath.update(ClasspathFromClassloader(appClassloader))(using ictx) ictx private def setToolboxSettings(ctx: FreshContext, settings: Toolbox.Settings): ctx.type = From e71a167f3523d309da640644e45e5b25678a2036 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 16:10:18 +0200 Subject: [PATCH 19/41] Convert interactive classes --- .../tools/dotc/interactive/Completion.scala | 40 +++++++++---------- .../tools/dotc/interactive/Interactive.scala | 30 +++++++------- .../dotc/interactive/InteractiveDriver.scala | 12 +++--- .../tools/dotc/interactive/SourceTree.scala | 6 +-- .../languageserver/DottyLanguageServer.scala | 20 +++++----- 5 files changed, 54 insertions(+), 54 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/interactive/Completion.scala b/compiler/src/dotty/tools/dotc/interactive/Completion.scala index 668dd8f078ec..d44c4b710a61 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} +import dotty.tools.dotc.core.Contexts.{Context, NoContext, ctx} import dotty.tools.dotc.core.CheckRealizable import dotty.tools.dotc.core.Decorators.StringInterpolators import dotty.tools.dotc.core.Denotations.SingleDenotation @@ -42,9 +42,9 @@ object Completion { * * @return offset and list of symbols for possible completions */ - def completions(pos: SourcePosition)(implicit ctx: Context): (Int, List[Completion]) = { + def completions(pos: SourcePosition)(using Context): (Int, List[Completion]) = { val path = Interactive.pathTo(ctx.compilationUnit.tpdTree, pos.span) - computeCompletions(pos, path)(Interactive.contextOfPath(path)) + computeCompletions(pos, path)(using Interactive.contextOfPath(path)) } /** @@ -111,7 +111,7 @@ object Completion { new CompletionBuffer(mode, prefix, pos) } - private def computeCompletions(pos: SourcePosition, path: List[Tree])(implicit ctx: Context): (Int, List[Completion]) = { + private def computeCompletions(pos: SourcePosition, path: List[Tree])(using Context): (Int, List[Completion]) = { val offset = completionOffset(path) val buffer = completionBuffer(path, pos) @@ -144,7 +144,7 @@ object Completion { * If several symbols share the same name, the type symbols appear before term symbols inside * the same `Completion`. */ - def getCompletions(implicit ctx: Context): List[Completion] = { + def getCompletions(using Context): List[Completion] = { val nameToSymbols = completions.mappings.toList nameToSymbols.map { case (name, symbols) => val typesFirst = symbols.sortWith((s1, s2) => s1.isType && !s2.isType) @@ -161,7 +161,7 @@ object Completion { * * When there are multiple symbols, show their kinds. */ - private def description(symbols: List[Symbol])(implicit ctx: Context): String = + private def description(symbols: List[Symbol])(using Context): String = symbols match { case sym :: Nil => if (sym.isType) sym.showFullName @@ -178,7 +178,7 @@ object Completion { * Add symbols that are currently in scope to `info`: the members of the current class and the * symbols that have been imported. */ - def addScopeCompletions(implicit ctx: Context): Unit = { + def addScopeCompletions(using Context): Unit = { if (ctx.owner.isClass) { addAccessibleMembers(ctx.owner.thisType) ctx.owner.asClass.classInfo.selfInfo match { @@ -192,10 +192,10 @@ object Completion { var outer = ctx.outer while ((outer.owner `eq` ctx.owner) && (outer.scope `eq` ctx.scope)) { - addImportCompletions(outer) + addImportCompletions(using outer) outer = outer.outer } - if (outer `ne` NoContext) addScopeCompletions(outer) + if (outer `ne` NoContext) addScopeCompletions(using outer) } /** @@ -204,13 +204,13 @@ object Completion { * If `info.mode` is `Import`, the members added via implicit conversion on `qual` are not * considered. */ - def addMemberCompletions(qual: Tree)(implicit ctx: Context): Unit = + def addMemberCompletions(qual: Tree)(using Context): Unit = if (!qual.tpe.widenDealias.isBottomType) { addAccessibleMembers(qual.tpe) if (!mode.is(Mode.Import) && !qual.tpe.isNullType) // Implicit conversions do not kick in when importing // and for `NullClass` they produce unapplicable completions (for unclear reasons) - implicitConversionTargets(qual)(ctx.fresh.setExploreTyperState()) + implicitConversionTargets(qual)(using ctx.fresh.setExploreTyperState()) .foreach(addAccessibleMembers) } @@ -218,7 +218,7 @@ object Completion { * If `sym` exists, no symbol with the same name is already included, and it satisfies the * inclusion filter, then add it to the completions. */ - private def add(sym: Symbol, nameInScope: Name)(implicit ctx: Context) = + private def add(sym: Symbol, nameInScope: Name)(using Context) = if (sym.exists && completionsFilter(NoType, nameInScope) && !completions.lookup(nameInScope).exists && @@ -226,7 +226,7 @@ object Completion { completions.enter(sym, nameInScope) /** Lookup members `name` from `site`, and try to add them to the completion list. */ - private def addMember(site: Type, name: Name, nameInScope: Name)(implicit ctx: Context) = + private def addMember(site: Type, name: Name, nameInScope: Name)(using Context) = if (!completions.lookup(nameInScope).exists) for (alt <- site.member(name).alternatives) add(alt.symbol, nameInScope) @@ -241,7 +241,7 @@ object Completion { * 8. symbol is not an artifact of the compiler * 9. have same term/type kind as name prefix given so far */ - private def include(sym: Symbol, nameInScope: Name)(implicit ctx: Context): Boolean = + private def include(sym: Symbol, nameInScope: Name)(using Context): Boolean = nameInScope.startsWith(prefix) && !sym.isAbsent() && !sym.isPrimaryConstructor && @@ -261,7 +261,7 @@ object Completion { * @param site The type to inspect. * @return The members of `site` that are accessible and pass the include filter of `info`. */ - private def accessibleMembers(site: Type)(implicit ctx: Context): Seq[Symbol] = site match { + private def accessibleMembers(site: Type)(using Context): Seq[Symbol] = site match { case site: NamedType if site.symbol.is(Package) => // Don't look inside package members -- it's too expensive. site.decls.toList.filter(sym => sym.isAccessibleFrom(site, superAccess = false)) @@ -276,14 +276,14 @@ object Completion { } /** Add all the accessible members of `site` in `info`. */ - private def addAccessibleMembers(site: Type)(implicit ctx: Context): Unit = + private def addAccessibleMembers(site: Type)(using Context): Unit = for (mbr <- accessibleMembers(site)) addMember(site, mbr.name, mbr.name) /** * Add in `info` the symbols that are imported by `ctx.importInfo`. If this is a wildcard import, * all the accessible members of the import's `site` are included. */ - private def addImportCompletions(implicit ctx: Context): Unit = { + private def addImportCompletions(using Context): Unit = { val imp = ctx.importInfo if (imp != null) { def addImport(name: TermName, nameInScope: TermName) = { @@ -307,7 +307,7 @@ object Completion { * @param qual The argument to which the implicit conversion should be applied. * @return The set of types that `qual` can be converted to. */ - private def implicitConversionTargets(qual: Tree)(implicit ctx: Context): Set[Type] = { + private def implicitConversionTargets(qual: Tree)(using Context): Set[Type] = { val typer = ctx.typer val conversions = new typer.ImplicitSearch(defn.AnyType, qual, pos.span).allImplicits val targets = conversions.map(_.widen.finalResultType) @@ -317,7 +317,7 @@ object Completion { /** Filter for names that should appear when looking for completions. */ private object completionsFilter extends NameFilter { - def apply(pre: Type, name: Name)(implicit ctx: Context): Boolean = + def apply(pre: Type, name: Name)(using Context): Boolean = !name.isConstructorName && name.toTermName.info.kind == SimpleNameKind } } @@ -352,7 +352,7 @@ object Completion { private val nameToSymbols: mutable.Map[TermName, List[Symbol]] = mutable.Map.empty /** Enter the symbol `sym` in this scope, recording a potential renaming. */ - def enter[T <: Symbol](sym: T, name: Name)(implicit ctx: Context): T = { + def enter[T <: Symbol](sym: T, name: Name)(using Context): T = { val termName = name.stripModuleClassSuffix.toTermName nameToSymbols += termName -> (sym :: nameToSymbols.getOrElse(termName, Nil)) newScopeEntry(name, sym) diff --git a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala index 5675240abbed..e5bffb2428b6 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala @@ -70,7 +70,7 @@ object Interactive { tree.isInstanceOf[NamedDefTree] /** The type of the closest enclosing tree with a type containing position `pos`. */ - def enclosingType(trees: List[SourceTree], pos: SourcePosition)(implicit ctx: Context): Type = { + def enclosingType(trees: List[SourceTree], pos: SourcePosition)(using Context): Type = { val path = pathTo(trees, pos) if (path.isEmpty) NoType else path.head.tpe @@ -78,12 +78,12 @@ object Interactive { /** The closest enclosing tree with a symbol containing position `pos`, or the `EmptyTree`. */ - def enclosingTree(trees: List[SourceTree], pos: SourcePosition)(implicit ctx: Context): Tree = + def enclosingTree(trees: List[SourceTree], pos: SourcePosition)(using Context): Tree = enclosingTree(pathTo(trees, pos)) /** The closes enclosing tree with a symbol, or the `EmptyTree`. */ - def enclosingTree(path: List[Tree])(implicit ctx: Context): Tree = + def enclosingTree(path: List[Tree])(using Context): Tree = path.dropWhile(!_.symbol.exists).headOption.getOrElse(tpd.EmptyTree) /** @@ -97,7 +97,7 @@ object Interactive { * * @see sourceSymbol */ - def enclosingSourceSymbols(path: List[Tree], pos: SourcePosition)(implicit ctx: Context): List[Symbol] = { + def enclosingSourceSymbols(path: List[Tree], pos: SourcePosition)(using Context): List[Symbol] = { val syms = path match { // For a named arg, find the target `DefDef` and jump to the param case NamedArg(name, _) :: Apply(fn, _) :: _ => @@ -140,7 +140,7 @@ object Interactive { * or `include` is `overridden`, and `tree` is overridden by `sym`, * or `include` is `overriding`, and `tree` overrides `sym`. */ - def matchSymbol(tree: Tree, sym: Symbol, include: Include.Set)(implicit ctx: Context): Boolean = { + def matchSymbol(tree: Tree, sym: Symbol, include: Include.Set)(using Context): Boolean = { def overrides(sym1: Symbol, sym2: Symbol) = sym1.owner.derivesFrom(sym2.owner) && sym1.overriddenSymbol(sym2.owner.asClass) == sym2 @@ -161,7 +161,7 @@ object Interactive { * source code. */ def namedTrees(trees: List[SourceTree], include: Include.Set, sym: Symbol) - (implicit ctx: Context): List[SourceTree] = + (using Context): List[SourceTree] = if (!sym.exists) Nil else @@ -177,7 +177,7 @@ object Interactive { def namedTrees(trees: List[SourceTree], include: Include.Set, treePredicate: NameTree => Boolean = util.common.alwaysTrue - )(implicit ctx: Context): List[SourceTree] = safely { + )(using Context): List[SourceTree] = safely { val buf = new mutable.ListBuffer[SourceTree] def traverser(source: SourceFile) = @@ -194,7 +194,7 @@ object Interactive { && treePredicate(tree)) buf += SourceTree(tree, source) } - override def traverse(tree: untpd.Tree)(implicit ctx: Context) = + override def traverse(tree: untpd.Tree)(using Context) = tree match { case imp: untpd.Import if include.isImports && tree.hasType => val tree = imp.asInstanceOf[tpd.Import] @@ -231,7 +231,7 @@ object Interactive { includes: Include.Set, symbol: Symbol, predicate: NameTree => Boolean = util.common.alwaysTrue - )(implicit ctx: Context): List[SourceTree] = { + )(using Context): List[SourceTree] = { val linkedSym = symbol.linkedClass val fullPredicate: NameTree => Boolean = tree => ( (includes.isDefinitions || !Interactive.isDefinition(tree)) @@ -250,13 +250,13 @@ object Interactive { * or `Nil` if no such path exists. If a non-empty path is returned it starts with * the tree closest enclosing `pos` and ends with an element of `trees`. */ - def pathTo(trees: List[SourceTree], pos: SourcePosition)(implicit ctx: Context): List[Tree] = + def pathTo(trees: List[SourceTree], pos: SourcePosition)(using Context): List[Tree] = trees.find(_.pos.contains(pos)) match { case Some(tree) => pathTo(tree.tree, pos.span) case None => Nil } - def pathTo(tree: Tree, span: Span)(implicit ctx: Context): List[Tree] = + def pathTo(tree: Tree, span: Span)(using Context): List[Tree] = if (tree.span.contains(span)) NavigateAST.pathTo(span, tree, skipZeroExtent = true) .collect { case t: untpd.Tree => t } @@ -274,7 +274,7 @@ object Interactive { contextOfStat(rest, stat, exprOwner, ctx) } - def contextOfPath(path: List[Tree])(implicit ctx: Context): Context = path match { + def contextOfPath(path: List[Tree])(using Context): Context = path match { case Nil | _ :: Nil => ctx.run.runContext.fresh.setCompilationUnit(ctx.compilationUnit) case nested :: encl :: rest => @@ -321,7 +321,7 @@ object Interactive { } /** The first tree in the path that is a definition. */ - def enclosingDefinitionInPath(path: List[Tree])(implicit ctx: Context): Tree = + def enclosingDefinitionInPath(path: List[Tree])(using Context): Tree = path.find(_.isInstanceOf[DefTree]).getOrElse(EmptyTree) /** @@ -404,7 +404,7 @@ object Interactive { * @param sym The symbol whose implementations to find. * @return A function that determines whether a `NameTree` is an implementation of `sym`. */ - def implementationFilter(sym: Symbol)(implicit ctx: Context): NameTree => Boolean = + def implementationFilter(sym: Symbol)(using Context): NameTree => Boolean = if (sym.isClass) { case td: TypeDef => val treeSym = td.symbol @@ -426,7 +426,7 @@ object Interactive { * @return True, if this tree's name is different than its symbol's name, indicating that * it uses a renaming introduced by an import statement or an alias for `this`. */ - def isRenamed(tree: NameTree)(implicit ctx: Context): Boolean = { + def isRenamed(tree: NameTree)(using Context): Boolean = { val symbol = tree.symbol symbol.exists && !sameName(tree.name, symbol.name) } diff --git a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala index 1c13f12c4181..d2c8fd8b0892 100644 --- a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala +++ b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala @@ -92,7 +92,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * This includes the trees for the buffers that are presently open in the IDE, and the trees * from the target directory. */ - def sourceTrees(implicit ctx: Context): List[SourceTree] = sourceTreesContaining("") + def sourceTrees(using Context): List[SourceTree] = sourceTreesContaining("") /** * The trees for all the source files in this project that contain `id`. @@ -100,7 +100,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * This includes the trees for the buffers that are presently open in the IDE, and the trees * from the target directory. */ - def sourceTreesContaining(id: String)(implicit ctx: Context): List[SourceTree] = { + def sourceTreesContaining(id: String)(using Context): List[SourceTree] = { val fromBuffers = openedTrees.values.flatten.toList val fromCompilationOutput = { val classNames = new mutable.ListBuffer[TypeName] @@ -122,7 +122,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * This includes the trees of the sources of this project, along with the trees that are found * on this project's classpath. */ - def allTrees(implicit ctx: Context): List[SourceTree] = allTreesContaining("") + def allTrees(using Context): List[SourceTree] = allTreesContaining("") /** * All the trees for this project that contain `id`. @@ -130,7 +130,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * This includes the trees of the sources of this project, along with the trees that are found * on this project's classpath. */ - def allTreesContaining(id: String)(implicit ctx: Context): List[SourceTree] = { + def allTreesContaining(id: String)(using Context): List[SourceTree] = { val fromSource = openedTrees.values.flatten.toList val fromClassPath = (dirClassPathClasses ++ zipClassPathClasses).flatMap { cls => treesFromClassName(cls, id) @@ -182,7 +182,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * * @see SourceTree.fromSymbol */ - private def treesFromClassName(className: TypeName, id: String)(implicit ctx: Context): List[SourceTree] = { + 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) clsd match { @@ -270,7 +270,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * of a previous run. Note that typed trees can have untyped or partially * typed children if the source contains errors. */ - private def cleanup(tree: tpd.Tree)(implicit ctx: Context): Unit = { + private def cleanup(tree: tpd.Tree)(using Context): Unit = { val seen = mutable.Set.empty[tpd.Tree] def cleanupTree(tree: tpd.Tree): Unit = { seen += tree diff --git a/compiler/src/dotty/tools/dotc/interactive/SourceTree.scala b/compiler/src/dotty/tools/dotc/interactive/SourceTree.scala index a86b84e108fa..e77a8aab36b6 100644 --- a/compiler/src/dotty/tools/dotc/interactive/SourceTree.scala +++ b/compiler/src/dotty/tools/dotc/interactive/SourceTree.scala @@ -17,10 +17,10 @@ import util._, util.Spans._ case class SourceTree(tree: tpd.Import | tpd.NameTree, source: SourceFile) { /** The position of `tree` */ - final def pos(implicit ctx: Context): SourcePosition = source.atSpan(tree.span) + final def pos(using Context): SourcePosition = source.atSpan(tree.span) /** The position of the name in `tree` */ - def namePos(implicit ctx: Context): SourcePosition = tree match { + def namePos(using Context): SourcePosition = tree match { case tree: tpd.NameTree => // FIXME: Merge with NameTree#namePos ? val treeSpan = tree.span @@ -51,7 +51,7 @@ case class SourceTree(tree: tpd.Import | tpd.NameTree, source: SourceFile) { } object SourceTree { - def fromSymbol(sym: ClassSymbol, id: String = "")(implicit ctx: Context): List[SourceTree] = + def fromSymbol(sym: ClassSymbol, id: String = "")(using Context): List[SourceTree] = if (sym == defn.SourceFileAnnot || // FIXME: No SourceFile annotation on SourceFile itself !sym.source.exists) // FIXME: We cannot deal with external projects yet Nil diff --git a/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala b/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala index 19fcef82dc37..51db390a028d 100644 --- a/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala +++ b/language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala @@ -307,7 +307,7 @@ class DottyLanguageServer extends LanguageServer val pos = sourcePosition(driver, uri, params.getPosition) val items = driver.compilationUnits.get(uri) match { - case Some(unit) => Completion.completions(pos)(ctx.fresh.setCompilationUnit(unit))._2 + case Some(unit) => Completion.completions(pos)(using ctx.fresh.setCompilationUnit(unit))._2 case None => Nil } @@ -361,9 +361,9 @@ class DottyLanguageServer extends LanguageServer perProjectInfo.flatMap { (remoteDriver, ctx, definitions) => definitions.flatMap { definition => val name = definition.name(using ctx).sourceModuleName.toString - val trees = remoteDriver.sourceTreesContaining(name)(ctx) - val matches = Interactive.findTreesMatching(trees, includes, definition)(ctx) - matches.map(tree => location(tree.namePos(ctx))) + val trees = remoteDriver.sourceTreesContaining(name)(using ctx) + val matches = Interactive.findTreesMatching(trees, includes, definition)(using ctx) + matches.map(tree => location(tree.namePos(using ctx))) } } }.toList @@ -419,11 +419,11 @@ class DottyLanguageServer extends LanguageServer perProjectInfo.flatMap { (remoteDriver, ctx, definitions) => definitions.flatMap { definition => val name = definition.name(using ctx).sourceModuleName.toString - val trees = remoteDriver.sourceTreesContaining(name)(ctx) + val trees = remoteDriver.sourceTreesContaining(name)(using ctx) Interactive.findTreesMatching(trees, include, definition, - t => names.exists(Interactive.sameName(t.name, _)))(ctx) + t => names.exists(Interactive.sameName(t.name, _)))(using ctx) } } } @@ -535,13 +535,13 @@ class DottyLanguageServer extends LanguageServer val perProjectInfo = inProjectsSeeing(driver, definitions, originalSymbols) perProjectInfo.flatMap { (remoteDriver, ctx, definitions) => - val trees = remoteDriver.sourceTrees(ctx) + val trees = remoteDriver.sourceTrees(using ctx) val predicate: NameTree => Boolean = { - val predicates = definitions.map(Interactive.implementationFilter(_)(ctx)) + val predicates = definitions.map(Interactive.implementationFilter(_)(using ctx)) tree => predicates.exists(_(tree)) } - val matches = Interactive.namedTrees(trees, Include.local, predicate)(ctx) - matches.map(tree => location(tree.namePos(ctx))) + val matches = Interactive.namedTrees(trees, Include.local, predicate)(using ctx) + matches.map(tree => location(tree.namePos(using ctx))) } }.toList From f5c30a927dce275cc3f83d3d3351b5ba985c49f3 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 16:37:04 +0200 Subject: [PATCH 20/41] Convert reporting classes --- .../dotc/reporting/ConsoleReporter.scala | 4 +- .../tools/dotc/reporting/Diagnostic.scala | 10 +- .../reporting/HideNonSensicalMessages.scala | 2 +- .../dotc/reporting/MessageRendering.scala | 16 +- .../dotty/tools/dotc/reporting/Reporter.scala | 30 +- .../tools/dotc/reporting/StoreReporter.scala | 4 +- .../dotc/reporting/ThrowingReporter.scala | 2 +- .../reporting/UniqueMessagePositions.scala | 2 +- .../dotty/tools/dotc/reporting/messages.scala | 256 +++++++++--------- .../dotty/tools/dotc/reporting/trace.scala | 22 +- .../tools/dotc/typer/ErrorReporting.scala | 2 +- compiler/src/dotty/tools/repl/Rendering.scala | 2 +- .../src/dotty/tools/repl/ReplCompiler.scala | 2 +- .../src/dotty/tools/repl/ReplDriver.scala | 2 +- .../tools/dotc/parsing/desugarPackage.scala | 2 +- .../tools/dotc/parsing/parsePackage.scala | 2 +- .../dotc/reporting/ErrorMessagesTest.scala | 2 +- tests/pos-with-compiler/A.scala | 2 +- 18 files changed, 182 insertions(+), 182 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/reporting/ConsoleReporter.scala b/compiler/src/dotty/tools/dotc/reporting/ConsoleReporter.scala index 6a7d21e827eb..8d74e06b7d49 100644 --- a/compiler/src/dotty/tools/dotc/reporting/ConsoleReporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/ConsoleReporter.scala @@ -20,7 +20,7 @@ class ConsoleReporter( def printMessage(msg: String): Unit = { writer.print(msg + "\n"); writer.flush() } /** Prints the message with the given position indication. */ - def doReport(dia: Diagnostic)(implicit ctx: Context): Unit = { + def doReport(dia: Diagnostic)(using Context): Unit = { val didPrint = dia match { case dia: Error => printMessage(messageAndPos(dia.msg, dia.pos, diagnosticLevel(dia))) @@ -39,5 +39,5 @@ class ConsoleReporter( printMessage("\nlonger explanation available when compiling with `-explain`") } - override def flush()(implicit ctx: Context): Unit = { writer.flush() } + override def flush()(using Context): Unit = { writer.flush() } } diff --git a/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala b/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala index b2f8ba308d0d..c6d46bd8d502 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Diagnostic.scala @@ -45,35 +45,35 @@ object Diagnostic: msg: Message, pos: SourcePosition ) extends Warning(msg, pos) { - def enablingOption(implicit ctx: Context): Setting[Boolean] + def enablingOption(using Context): Setting[Boolean] } class FeatureWarning( msg: Message, pos: SourcePosition ) extends ConditionalWarning(msg, pos) { - def enablingOption(implicit ctx: Context): Setting[Boolean] = ctx.settings.feature + def enablingOption(using Context): Setting[Boolean] = ctx.settings.feature } class UncheckedWarning( msg: Message, pos: SourcePosition ) extends ConditionalWarning(msg, pos) { - def enablingOption(implicit ctx: Context): Setting[Boolean] = ctx.settings.unchecked + def enablingOption(using Context): Setting[Boolean] = ctx.settings.unchecked } class DeprecationWarning( msg: Message, pos: SourcePosition ) extends ConditionalWarning(msg, pos) { - def enablingOption(implicit ctx: Context): Setting[Boolean] = ctx.settings.deprecation + def enablingOption(using Context): Setting[Boolean] = ctx.settings.deprecation } class MigrationWarning( msg: Message, pos: SourcePosition ) extends Warning(msg, pos) { - def enablingOption(implicit ctx: Context): Setting[Boolean] = ctx.settings.migration + def enablingOption(using Context): Setting[Boolean] = ctx.settings.migration } class Diagnostic( diff --git a/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala b/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala index c44306ae2e9e..4225f00c1ba1 100644 --- a/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/HideNonSensicalMessages.scala @@ -11,7 +11,7 @@ trait HideNonSensicalMessages extends Reporter { /** Hides non-sensical messages, unless we haven't reported any error yet or * `-Yshow-suppressed-errors` is set. */ - override def isHidden(dia: Diagnostic)(implicit ctx: Context): Boolean = + override def isHidden(dia: Diagnostic)(using Context): Boolean = super.isHidden(dia) || { dia.msg.isNonSensical && hasErrors && // if there are no errors yet, report even if diagnostic is non-sensical diff --git a/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala b/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala index 74baa2383082..4e6260a1f4bb 100644 --- a/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala +++ b/compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala @@ -30,7 +30,7 @@ trait MessageRendering { * * @return a list of strings with inline locations */ - def outer(pos: SourcePosition, prefix: String)(implicit ctx: Context): List[String] = + def outer(pos: SourcePosition, prefix: String)(using Context): List[String] = if (pos.outer.exists) i"$prefix| This location contains code that was inlined from $pos" :: outer(pos.outer, prefix) @@ -41,7 +41,7 @@ trait MessageRendering { * * @return (lines before error, lines after error, line numbers offset) */ - def sourceLines(pos: SourcePosition, diagnosticLevel: String)(implicit ctx: Context): (List[String], List[String], Int) = { + def sourceLines(pos: SourcePosition, diagnosticLevel: String)(using Context): (List[String], List[String], Int) = { assert(pos.exists && pos.source.file.exists) var maxLen = Int.MinValue def render(offsetAndLine: (Int, String)): String = { @@ -78,7 +78,7 @@ trait MessageRendering { } /** The column markers aligned under the error */ - def columnMarker(pos: SourcePosition, offset: Int, diagnosticLevel: String)(implicit ctx: Context): String = { + def columnMarker(pos: SourcePosition, offset: Int, diagnosticLevel: String)(using Context): String = { val prefix = " " * (offset - 1) val padding = pos.startColumnPadding val carets = hl(diagnosticLevel) { @@ -93,7 +93,7 @@ trait MessageRendering { * * @return aligned error message */ - def errorMsg(pos: SourcePosition, msg: String, offset: Int)(implicit ctx: Context): String = { + def errorMsg(pos: SourcePosition, msg: String, offset: Int)(using Context): String = { val padding = msg.linesIterator.foldLeft(pos.startColumnPadding) { (pad, line) => val lineLength = stripColor(line).length val maxPad = math.max(0, ctx.settings.pageWidth.value - offset - lineLength) - offset @@ -111,7 +111,7 @@ trait MessageRendering { * * @return separator containing error location and kind */ - def posStr(pos: SourcePosition, diagnosticLevel: String, message: Message)(implicit ctx: Context): String = + def posStr(pos: SourcePosition, diagnosticLevel: String, message: Message)(using Context): String = if (pos.exists) hl(diagnosticLevel)({ val pos1 = pos.nonInlined val file = @@ -131,7 +131,7 @@ trait MessageRendering { }) else "" /** Explanation rendered under "Explanation" header */ - def explanation(m: Message)(implicit ctx: Context): String = { + def explanation(m: Message)(using Context): String = { val sb = new StringBuilder( s"""| |${Blue("Explanation").show} @@ -143,7 +143,7 @@ trait MessageRendering { } /** The whole message rendered from `msg` */ - def messageAndPos(msg: Message, pos: SourcePosition, diagnosticLevel: String)(implicit ctx: Context): String = { + def messageAndPos(msg: Message, pos: SourcePosition, diagnosticLevel: String)(using Context): String = { val sb = mutable.StringBuilder() val posString = posStr(pos, diagnosticLevel, msg) if (posString.nonEmpty) sb.append(posString).append(EOL) @@ -158,7 +158,7 @@ trait MessageRendering { sb.toString } - def hl(diagnosticLevel: String)(str: String)(implicit ctx: Context): String = diagnosticLevel match { + def hl(diagnosticLevel: String)(str: String)(using Context): String = diagnosticLevel match { case "Info" => Blue(str).show case "Error" => Red(str).show case _ => diff --git a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala index 331f19ef2c61..fbf2031adb97 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala @@ -26,7 +26,7 @@ object Reporter { /** Convert a SimpleReporter into a real Reporter */ def fromSimpleReporter(simple: interfaces.SimpleReporter): Reporter = new Reporter with UniqueMessagePositions with HideNonSensicalMessages { - override def doReport(dia: Diagnostic)(implicit ctx: Context): Unit = dia match { + override def doReport(dia: Diagnostic)(using Context): Unit = dia match { case dia: ConditionalWarning if !dia.enablingOption.value => case _ => simple.report(dia) @@ -35,14 +35,14 @@ object Reporter { /** A reporter that ignores reports, and doesn't record errors */ @sharable object NoReporter extends Reporter { - def doReport(dia: Diagnostic)(implicit ctx: Context): Unit = () - override def report(dia: Diagnostic)(implicit ctx: Context): Unit = () + def doReport(dia: Diagnostic)(using Context): Unit = () + override def report(dia: Diagnostic)(using Context): Unit = () } type ErrorHandler = (Diagnostic, Context) => Unit private val defaultIncompleteHandler: ErrorHandler = - (mc, ctx) => ctx.reporter.report(mc)(ctx) + (mc, ctx) => ctx.reporter.report(mc)(using ctx) /** Show prompt if `-Xprompt` is passed as a flag to the compiler */ def displayPrompt(reader: BufferedReader, writer: PrintWriter): Unit = { @@ -145,8 +145,8 @@ trait Reporting { thisCtx: Context => def restrictionError(msg: Message, pos: SourcePosition = NoSourcePosition): Unit = error(msg.mapMsg("Implementation restriction: " + _), pos) - def incompleteInputError(msg: Message, pos: SourcePosition = NoSourcePosition)(implicit ctx: Context): Unit = - reporter.incomplete(new Error(msg, pos))(ctx) + def incompleteInputError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + reporter.incomplete(new Error(msg, pos))(using ctx) /** Log msg if settings.log contains the current phase. * See [[config.CompilerCommand#explainAdvanced]] for the exact meaning of @@ -175,7 +175,7 @@ trait Reporting { thisCtx: Context => def debugwarn(msg: => String, pos: SourcePosition = NoSourcePosition): Unit = if (thisCtx.settings.Ydebug.value) warning(msg, pos) - private def addInlineds(pos: SourcePosition)(implicit ctx: Context) = { + 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 @@ -192,7 +192,7 @@ abstract class Reporter extends interfaces.ReporterResult { import Reporter._ /** Report a diagnostic */ - def doReport(dia: Diagnostic)(implicit ctx: Context): Unit + def doReport(dia: Diagnostic)(using Context): Unit /** Whether very long lines can be truncated. This exists so important * debugging information (like printing the classpath) is not rendered @@ -261,9 +261,9 @@ abstract class Reporter extends interfaces.ReporterResult { var unreportedWarnings: Map[String, Int] = Map.empty - def report(dia: Diagnostic)(implicit ctx: Context): Unit = + def report(dia: Diagnostic)(using Context): Unit = if (!isHidden(dia)) { - doReport(dia)(ctx.addMode(Mode.Printing)) + doReport(dia)(using ctx.addMode(Mode.Printing)) dia match { case dia: ConditionalWarning if !dia.enablingOption.value => val key = dia.enablingOption.name @@ -278,7 +278,7 @@ abstract class Reporter extends interfaces.ReporterResult { } } - def incomplete(dia: Diagnostic)(implicit ctx: Context): Unit = + def incomplete(dia: Diagnostic)(using Context): Unit = incompleteHandler(dia, ctx) /** Summary of warnings and errors */ @@ -294,7 +294,7 @@ abstract class Reporter extends interfaces.ReporterResult { } /** Print the summary of warnings and errors */ - def printSummary(implicit ctx: Context): Unit = { + def printSummary(using Context): Unit = { val s = summary if (s != "") ctx.echo(s) } @@ -307,7 +307,7 @@ abstract class Reporter extends interfaces.ReporterResult { } /** Should this diagnostic not be reported at all? */ - def isHidden(dia: Diagnostic)(implicit ctx: Context): Boolean = + def isHidden(dia: Diagnostic)(using Context): Boolean = ctx.mode.is(Mode.Printing) /** Does this reporter contain errors that have yet to be reported by its outer reporter ? @@ -316,10 +316,10 @@ abstract class Reporter extends interfaces.ReporterResult { def hasUnreportedErrors: Boolean = false /** If this reporter buffers messages, remove and return all buffered messages. */ - def removeBufferedMessages(implicit ctx: Context): List[Diagnostic] = Nil + def removeBufferedMessages(using Context): List[Diagnostic] = Nil /** Issue all error messages in this reporter to next outer one, or make sure they are written. */ - def flush()(implicit ctx: Context): Unit = + def flush()(using Context): Unit = removeBufferedMessages.foreach(ctx.reporter.report) /** If this reporter buffers messages, all buffered messages, otherwise Nil */ diff --git a/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala b/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala index cc214b17ddbd..38e803ec9ba6 100644 --- a/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/StoreReporter.scala @@ -21,7 +21,7 @@ class StoreReporter(outer: Reporter) extends Reporter { protected var infos: mutable.ListBuffer[Diagnostic] = null - def doReport(dia: Diagnostic)(implicit ctx: Context): Unit = { + def doReport(dia: Diagnostic)(using Context): Unit = { typr.println(s">>>> StoredError: ${dia.message}") // !!! DEBUG if (infos == null) infos = new mutable.ListBuffer infos += dia @@ -33,7 +33,7 @@ class StoreReporter(outer: Reporter) extends Reporter { override def hasStickyErrors: Boolean = infos != null && infos.exists(_.isInstanceOf[StickyError]) - override def removeBufferedMessages(implicit ctx: Context): List[Diagnostic] = + override def removeBufferedMessages(using Context): List[Diagnostic] = if (infos != null) try infos.toList finally infos = null else Nil diff --git a/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala b/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala index 520ab0ac5bd1..e3fb4aaccf3d 100644 --- a/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/ThrowingReporter.scala @@ -10,7 +10,7 @@ import Diagnostic.Error * info to the underlying reporter. */ class ThrowingReporter(reportInfo: Reporter) extends Reporter { - def doReport(dia: Diagnostic)(implicit ctx: Context): Unit = dia match { + def doReport(dia: Diagnostic)(using Context): Unit = dia match { case _: Error => throw dia case _ => reportInfo.doReport(dia) } diff --git a/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala b/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala index 73fae4b73b6d..e20dac2b31ad 100644 --- a/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala +++ b/compiler/src/dotty/tools/dotc/reporting/UniqueMessagePositions.scala @@ -15,7 +15,7 @@ trait UniqueMessagePositions extends Reporter { /** Logs a position and returns true if it was already logged. * @note Two positions are considered identical for logging if they have the same point. */ - override def isHidden(dia: Diagnostic)(implicit ctx: Context): Boolean = + override def isHidden(dia: Diagnostic)(using Context): Boolean = super.isHidden(dia) || { dia.pos.exists && !ctx.settings.YshowSuppressedErrors.value && { var shouldHide = false diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index 6250b0a55283..bace2cfd0c32 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -40,7 +40,7 @@ object messages { import ast.tpd /** Helper methods for messages */ - def implicitClassRestrictionsText(implicit ctx: Context): String = + 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")}""" @@ -76,7 +76,7 @@ object messages { abstract class ReferenceMsg(errorId: ErrorMessageID) extends Message(errorId): def kind = "Reference" - abstract class EmptyCatchOrFinallyBlock(tryBody: untpd.Tree, errNo: ErrorMessageID)(implicit ctx: Context) + abstract class EmptyCatchOrFinallyBlock(tryBody: untpd.Tree, errNo: ErrorMessageID)(using Context) extends SyntaxMsg(EmptyCatchOrFinallyBlockID) { def explain = { val tryString = tryBody match { @@ -112,21 +112,21 @@ object messages { } } - class EmptyCatchBlock(tryBody: untpd.Tree)(implicit ctx: Context) + class EmptyCatchBlock(tryBody: untpd.Tree)(using Context) extends EmptyCatchOrFinallyBlock(tryBody, EmptyCatchBlockID) { def msg = em"""|The ${hl("catch")} block does not contain a valid expression, try |adding a case like - ${hl("case e: Exception =>")} to the block""" } - class EmptyCatchAndFinallyBlock(tryBody: untpd.Tree)(implicit ctx: Context) + class EmptyCatchAndFinallyBlock(tryBody: untpd.Tree)(using Context) extends EmptyCatchOrFinallyBlock(tryBody, EmptyCatchAndFinallyBlockID) { def msg = em"""|A ${hl("try")} without ${hl("catch")} or ${hl("finally")} is equivalent to putting |its body in a block; no exceptions are handled.""" } - class DeprecatedWithOperator()(implicit ctx: Context) + class DeprecatedWithOperator()(using Context) extends SyntaxMsg(DeprecatedWithOperatorID) { def msg = em"""${hl("with")} as a type operator has been deprecated; use ${hl("&")} instead""" @@ -136,7 +136,7 @@ object messages { |semantics between intersection types and using ${hl("with")}.""" } - class CaseClassMissingParamList(cdef: untpd.TypeDef)(implicit ctx: Context) + class CaseClassMissingParamList(cdef: untpd.TypeDef)(using Context) extends SyntaxMsg(CaseClassMissingParamListID) { def msg = em"""|A ${hl("case class")} must have at least one parameter list""" @@ -151,7 +151,7 @@ object messages { args: List[untpd.Tree], tree: untpd.Function, pt: Type) - (implicit ctx: Context) + (using Context) extends TypeMsg(AnonymousFunctionMissingParamTypeID) { def msg = { val ofFun = @@ -172,7 +172,7 @@ object messages { def explain = "" } - class WildcardOnTypeArgumentNotAllowedOnNew()(implicit ctx: Context) + class WildcardOnTypeArgumentNotAllowedOnNew()(using Context) extends SyntaxMsg(WildcardOnTypeArgumentNotAllowedOnNewID) { def msg = "Type argument must be fully defined" def explain = @@ -204,7 +204,7 @@ object messages { // Type Errors ------------------------------------------------------------ // - class DuplicateBind(bind: untpd.Bind, tree: untpd.CaseDef)(implicit ctx: Context) + class DuplicateBind(bind: untpd.Bind, tree: untpd.CaseDef)(using Context) extends NamingMsg(DuplicateBindID) { def msg = em"duplicate pattern variable: ${bind.name}" @@ -230,7 +230,7 @@ object messages { } } - class MissingIdent(tree: untpd.Ident, treeKind: String, val name: Name)(implicit ctx: Context) + class MissingIdent(tree: untpd.Ident, treeKind: String, val name: Name)(using Context) extends NotFoundMsg(MissingIdentID) { def msg = em"Not found: $treeKind$name" def explain = { @@ -241,7 +241,7 @@ object messages { } } - class TypeMismatch(found: Type, expected: Type, addenda: => String*)(implicit ctx: Context) + class TypeMismatch(found: Type, expected: Type, addenda: => String*)(using Context) extends TypeMismatchMsg(TypeMismatchID): // replace constrained TypeParamRefs and their typevars by their bounds where possible @@ -288,7 +288,7 @@ object messages { def explain = "" end TypeMismatch - class NotAMember(site: Type, val name: Name, selected: String, addendum: => String = "")(implicit ctx: Context) + class NotAMember(site: Type, val name: Name, selected: String, addendum: => String = "")(using Context) extends NotFoundMsg(NotAMemberID) { //println(i"site = $site, decls = ${site.decls}, source = ${site.widen.typeSymbol.sourceFile}") //DEBUG @@ -347,7 +347,7 @@ object messages { def explain = "" } - class EarlyDefinitionsNotSupported()(implicit ctx: Context) + class EarlyDefinitionsNotSupported()(using Context) extends SyntaxMsg(EarlyDefinitionsNotSupportedID) { def msg = "Early definitions are not supported; use trait parameters instead" @@ -392,7 +392,7 @@ object messages { } } - class TopLevelImplicitClass(cdef: untpd.TypeDef)(implicit ctx: Context) + class TopLevelImplicitClass(cdef: untpd.TypeDef)(using Context) extends SyntaxMsg(TopLevelImplicitClassID) { def msg = em"""An ${hl("implicit class")} may not be top-level""" @@ -422,7 +422,7 @@ object messages { } } - class ImplicitCaseClass(cdef: untpd.TypeDef)(implicit ctx: Context) + class ImplicitCaseClass(cdef: untpd.TypeDef)(using Context) extends SyntaxMsg(ImplicitCaseClassID) { def msg = em"""A ${hl("case class")} may not be defined as ${hl("implicit")}""" @@ -434,7 +434,7 @@ object messages { |""" + implicitClassRestrictionsText } - class ImplicitClassPrimaryConstructorArity()(implicit ctx: Context) + class ImplicitClassPrimaryConstructorArity()(using Context) extends SyntaxMsg(ImplicitClassPrimaryConstructorArityID){ def msg = "Implicit classes must accept exactly one primary constructor parameter" def explain = { @@ -449,7 +449,7 @@ object messages { } } - class ObjectMayNotHaveSelfType(mdef: untpd.ModuleDef)(implicit ctx: Context) + class ObjectMayNotHaveSelfType(mdef: untpd.ModuleDef)(using Context) extends SyntaxMsg(ObjectMayNotHaveSelfTypeID) { def msg = em"""${hl("object")}s must not have a self ${hl("type")}""" @@ -539,7 +539,7 @@ object messages { |""" } - class IllegalStartSimpleExpr(illegalToken: String)(implicit ctx: Context) + class IllegalStartSimpleExpr(illegalToken: String)(using Context) extends SyntaxMsg(IllegalStartSimpleExprID) { def msg = em"expression expected but ${Red(illegalToken)} found" def explain = { @@ -558,7 +558,7 @@ object messages { |)}""" } - class MissingReturnTypeWithReturnStatement(method: Symbol)(implicit ctx: Context) + class MissingReturnTypeWithReturnStatement(method: Symbol)(using Context) extends SyntaxMsg(MissingReturnTypeWithReturnStatementID) { def msg = em"$method has a return statement; it needs a result type" def explain = @@ -568,7 +568,7 @@ object messages { |${hl("def good: Int /* explicit return type */ = return 1")}""" } - class YieldOrDoExpectedInForComprehension()(implicit ctx: Context) + class YieldOrDoExpectedInForComprehension()(using Context) extends SyntaxMsg(YieldOrDoExpectedInForComprehensionID) { def msg = em"${hl("yield")} or ${hl("do")} expected" @@ -600,7 +600,7 @@ object messages { |""" } - class ProperDefinitionNotFound()(implicit ctx: Context) + class ProperDefinitionNotFound()(using Context) extends Message(ProperDefinitionNotFoundID) { def kind: String = "Doc Comment" def msg = em"""Proper definition was not found in ${hl("@usecase")}""" @@ -639,7 +639,7 @@ object messages { } } - class ByNameParameterNotSupported(tpe: untpd.TypTree)(implicit ctx: Context) + class ByNameParameterNotSupported(tpe: untpd.TypTree)(using Context) extends SyntaxMsg(ByNameParameterNotSupportedID) { def msg = em"By-name parameter type ${tpe} not allowed here." @@ -662,7 +662,7 @@ object messages { |""" } - class WrongNumberOfTypeArgs(fntpe: Type, expectedArgs: List[ParamInfo], actual: List[untpd.Tree])(implicit ctx: Context) + class WrongNumberOfTypeArgs(fntpe: Type, expectedArgs: List[ParamInfo], actual: List[untpd.Tree])(using Context) extends SyntaxMsg(WrongNumberOfTypeArgsID) { private val expectedCount = expectedArgs.length @@ -703,7 +703,7 @@ object messages { } } - class IllegalVariableInPatternAlternative()(implicit ctx: Context) + class IllegalVariableInPatternAlternative()(using Context) extends SyntaxMsg(IllegalVariableInPatternAlternativeID) { def msg = "Variables are not allowed in alternative patterns" def explain = { @@ -731,7 +731,7 @@ object messages { } } - class IdentifierExpected(identifier: String)(implicit ctx: Context) + class IdentifierExpected(identifier: String)(using Context) extends SyntaxMsg(IdentifierExpectedID) { def msg = "identifier expected" def explain = { @@ -766,7 +766,7 @@ object messages { |""" } - class IncorrectRepeatedParameterSyntax()(implicit ctx: Context) + class IncorrectRepeatedParameterSyntax()(using Context) extends SyntaxMsg(IncorrectRepeatedParameterSyntaxID) { def msg = "'*' expected" def explain = @@ -792,7 +792,7 @@ object messages { |""".stripMargin } - class IllegalLiteral()(implicit ctx: Context) + class IllegalLiteral()(using Context) extends SyntaxMsg(IllegalLiteralID) { def msg = "Illegal literal" def explain = @@ -806,7 +806,7 @@ object messages { |""" } - class PatternMatchExhaustivity(uncoveredFn: => String)(implicit ctx: Context) + class PatternMatchExhaustivity(uncoveredFn: => String)(using Context) extends Message(PatternMatchExhaustivityID) { def kind = "Pattern Match Exhaustivity" lazy val uncovered = uncoveredFn @@ -824,7 +824,7 @@ object messages { |""" } - class UncheckedTypePattern(msgFn: => String)(implicit ctx: Context) + class UncheckedTypePattern(msgFn: => String)(using Context) extends PatternMatchMsg(UncheckedTypePatternID) { def msg = msgFn def explain = @@ -835,20 +835,20 @@ object messages { |""" } - class MatchCaseUnreachable()(implicit ctx: Context) + class MatchCaseUnreachable()(using Context) extends Message(MatchCaseUnreachableID) { def kind = "Match case Unreachable" def msg = "Unreachable case" def explain = "" } - class MatchCaseOnlyNullWarning()(implicit ctx: Context) + class MatchCaseOnlyNullWarning()(using Context) extends PatternMatchMsg(MatchCaseOnlyNullWarningID) { def msg = em"""Only ${hl("null")} is matched. Consider using ${hl("case null =>")} instead.""" def explain = "" } - class SeqWildcardPatternPos()(implicit ctx: Context) + class SeqWildcardPatternPos()(using Context) extends SyntaxMsg(SeqWildcardPatternPosID) { def msg = em"""${hl("_*")} can be used only for last argument""" def explain = { @@ -871,7 +871,7 @@ object messages { } } - class IllegalStartOfSimplePattern()(implicit ctx: Context) + class IllegalStartOfSimplePattern()(using Context) extends SyntaxMsg(IllegalStartOfSimplePatternID) { def msg = "pattern expected" def explain = { @@ -950,13 +950,13 @@ object messages { } } - class PkgDuplicateSymbol(existing: Symbol)(implicit ctx: Context) + class PkgDuplicateSymbol(existing: Symbol)(using Context) extends NamingMsg(PkgDuplicateSymbolID) { def msg = em"Trying to define package with same name as $existing" def explain = "" } - class ExistentialTypesNoLongerSupported()(implicit ctx: Context) + class ExistentialTypesNoLongerSupported()(using Context) extends SyntaxMsg(ExistentialTypesNoLongerSupportedID) { def msg = em"""|Existential types are no longer supported - @@ -978,7 +978,7 @@ object messages { |""" } - class UnboundWildcardType()(implicit ctx: Context) + class UnboundWildcardType()(using Context) extends SyntaxMsg(UnboundWildcardTypeID) { def msg = "Unbound wildcard type" def explain = @@ -1022,7 +1022,7 @@ object messages { |""" } - class DanglingThisInPath()(implicit ctx: Context) extends SyntaxMsg(DanglingThisInPathID) { + class DanglingThisInPath()(using Context) extends SyntaxMsg(DanglingThisInPathID) { def msg = em"""Expected an additional member selection after the keyword ${hl("this")}""" def explain = val contextCode: String = @@ -1053,7 +1053,7 @@ object messages { |""" } - class OverridesNothing(member: Symbol)(implicit ctx: Context) + class OverridesNothing(member: Symbol)(using Context) extends DeclarationMsg(OverridesNothingID) { def msg = em"""${member} overrides nothing""" @@ -1064,7 +1064,7 @@ object messages { |""" } - class OverridesNothingButNameExists(member: Symbol, existing: List[Denotations.SingleDenotation])(implicit ctx: Context) + class OverridesNothingButNameExists(member: Symbol, existing: List[Denotations.SingleDenotation])(using Context) extends DeclarationMsg(OverridesNothingButNameExistsID) { def msg = em"""${member} has a different signature than the overridden declaration""" def explain = @@ -1080,7 +1080,7 @@ object messages { |""" } - class ForwardReferenceExtendsOverDefinition(value: Symbol, definition: Symbol)(implicit ctx: Context) + class ForwardReferenceExtendsOverDefinition(value: Symbol, definition: Symbol)(using Context) extends ReferenceMsg(ForwardReferenceExtendsOverDefinitionID) { def msg = em"${definition.name} is a forward reference extending over the definition of ${value.name}" @@ -1098,7 +1098,7 @@ object messages { |""".stripMargin } - class ExpectedTokenButFound(expected: Token, found: Token)(implicit ctx: Context) + class ExpectedTokenButFound(expected: Token, found: Token)(using Context) extends SyntaxMsg(ExpectedTokenButFoundID) { private lazy val foundText = Tokens.showToken(found) @@ -1117,7 +1117,7 @@ object messages { "" } - class MixedLeftAndRightAssociativeOps(op1: Name, op2: Name, op2LeftAssoc: Boolean)(implicit ctx: Context) + class MixedLeftAndRightAssociativeOps(op1: Name, op2: Name, op2LeftAssoc: Boolean)(using Context) extends SyntaxMsg(MixedLeftAndRightAssociativeOpsID) { def msg = val op1Asso: String = if (op2LeftAssoc) "which is right-associative" else "which is left-associative" @@ -1151,7 +1151,7 @@ object messages { |""".stripMargin } - class CantInstantiateAbstractClassOrTrait(cls: Symbol, isTrait: Boolean)(implicit ctx: Context) + class CantInstantiateAbstractClassOrTrait(cls: Symbol, isTrait: Boolean)(using Context) extends TypeMsg(CantInstantiateAbstractClassOrTraitID) { private val traitOrAbstract = if (isTrait) "a trait" else "abstract" def msg = em"""${cls.name} is ${traitOrAbstract}; it cannot be instantiated""" @@ -1176,7 +1176,7 @@ object messages { |Such applications are equivalent to existential types, which are not |supported in Scala 3.""" - class OverloadedOrRecursiveMethodNeedsResultType(cycleSym: Symbol)(implicit ctx: Context) + class OverloadedOrRecursiveMethodNeedsResultType(cycleSym: Symbol)(using Context) extends CyclicMsg(OverloadedOrRecursiveMethodNeedsResultTypeID) { def msg = em"""Overloaded or recursive $cycleSym needs return type""" def explain = @@ -1190,7 +1190,7 @@ object messages { |""".stripMargin } - class RecursiveValueNeedsResultType(cycleSym: Symbol)(implicit ctx: Context) + class RecursiveValueNeedsResultType(cycleSym: Symbol)(using Context) extends CyclicMsg(RecursiveValueNeedsResultTypeID) { def msg = em"""Recursive $cycleSym needs type""" def explain = @@ -1198,7 +1198,7 @@ object messages { |""".stripMargin } - class CyclicReferenceInvolving(denot: SymDenotation)(implicit ctx: Context) + class CyclicReferenceInvolving(denot: SymDenotation)(using Context) extends CyclicMsg(CyclicReferenceInvolvingID) { def msg = val where = if denot.exists then s" involving $denot" else "" @@ -1210,7 +1210,7 @@ object messages { |""".stripMargin } - class CyclicReferenceInvolvingImplicit(cycleSym: Symbol)(implicit ctx: Context) + class CyclicReferenceInvolvingImplicit(cycleSym: Symbol)(using Context) extends CyclicMsg(CyclicReferenceInvolvingImplicitID) { def msg = em"""Cyclic reference involving implicit $cycleSym""" def explain = @@ -1221,7 +1221,7 @@ object messages { |""".stripMargin } - class SuperQualMustBeParent(qual: untpd.Ident, cls: ClassSymbol)(implicit ctx: Context) + class SuperQualMustBeParent(qual: untpd.Ident, cls: ClassSymbol)(using Context) extends ReferenceMsg(SuperQualMustBeParentID) { def msg = em"""|$qual does not name a parent of $cls""" def explain = @@ -1234,7 +1234,7 @@ object messages { |""".stripMargin } - class VarArgsParamMustComeLast()(implicit ctx: Context) + class VarArgsParamMustComeLast()(using Context) extends SyntaxMsg(IncorrectRepeatedParameterSyntaxID) { def msg = em"""${hl("varargs")} parameter must come last""" def explain = @@ -1245,7 +1245,7 @@ object messages { import typer.Typer.BindingPrec - class AmbiguousReference(name: Name, newPrec: BindingPrec, prevPrec: BindingPrec, prevCtx: Context)(implicit ctx: Context) + class AmbiguousReference(name: Name, newPrec: BindingPrec, prevPrec: BindingPrec, prevCtx: Context)(using Context) extends ReferenceMsg(AmbiguousReferenceID) { /** A string which explains how something was bound; Depending on `prec` this is either @@ -1286,7 +1286,7 @@ object messages { |""" } - class MethodDoesNotTakeParameters(tree: tpd.Tree)(implicit ctx: Context) + class MethodDoesNotTakeParameters(tree: tpd.Tree)(using Context) extends TypeMsg(MethodDoesNotTakeParametersId) { def methodSymbol: Symbol = tpd.methPart(tree).symbol @@ -1324,7 +1324,7 @@ object messages { |""" } - class ReassignmentToVal(name: Name)(implicit ctx: Context) + class ReassignmentToVal(name: Name)(using Context) extends TypeMsg(ReassignmentToValID) { def msg = em"""Reassignment to val $name""" def explain = @@ -1337,7 +1337,7 @@ object messages { |""".stripMargin } - class TypeDoesNotTakeParameters(tpe: Type, params: List[Trees.Tree[Trees.Untyped]])(implicit ctx: Context) + class TypeDoesNotTakeParameters(tpe: Type, params: List[Trees.Tree[Trees.Untyped]])(using Context) extends TypeMsg(TypeDoesNotTakeParametersID) { def msg = em"$tpe does not take type parameters" def explain = @@ -1349,7 +1349,7 @@ object messages { |""" } - class ParameterizedTypeLacksArguments(psym: Symbol)(implicit ctx: Context) + class ParameterizedTypeLacksArguments(psym: Symbol)(using Context) extends TypeMsg(ParameterizedTypeLacksArgumentsID) { def msg = em"Parameterized $psym lacks argument list" def explain = @@ -1358,7 +1358,7 @@ object messages { |""" } - class VarValParametersMayNotBeCallByName(name: TermName, mutable: Boolean)(implicit ctx: Context) + class VarValParametersMayNotBeCallByName(name: TermName, mutable: Boolean)(using Context) extends SyntaxMsg(VarValParametersMayNotBeCallByNameID) { def varOrVal = if (mutable) em"${hl("var")}" else em"${hl("val")}" def msg = s"$varOrVal parameters may not be call-by-name" @@ -1372,7 +1372,7 @@ object messages { |""" } - class MissingTypeParameterFor(tpe: Type)(implicit ctx: Context) + class MissingTypeParameterFor(tpe: Type)(using Context) extends SyntaxMsg(MissingTypeParameterForID) { def msg = if (tpe.derivesFrom(defn.AnyKindClass)) em"${tpe} cannot be used as a value type" @@ -1380,7 +1380,7 @@ object messages { def explain = "" } - class MissingTypeParameterInTypeApp(tpe: Type)(implicit ctx: Context) + class MissingTypeParameterInTypeApp(tpe: Type)(using Context) extends TypeMsg(MissingTypeParameterInTypeAppID) { def numParams = tpe.typeParams.length def parameters = if (numParams == 1) "parameter" else "parameters" @@ -1388,7 +1388,7 @@ object messages { def explain = em"A fully applied type is expected but $tpe takes $numParams $parameters" } - class DoesNotConformToBound(tpe: Type, which: String, bound: Type)(implicit ctx: Context) + class DoesNotConformToBound(tpe: Type, which: String, bound: Type)(using Context) extends TypeMismatchMsg(DoesNotConformToBoundID) { def msg = em"Type argument ${tpe} does not conform to $which bound $bound${err.whyNoMatchStr(tpe, bound)}" def explain = "" @@ -1435,7 +1435,7 @@ object messages { def explain = "" } - class TypesAndTraitsCantBeImplicit()(implicit ctx: Context) + class TypesAndTraitsCantBeImplicit()(using Context) extends SyntaxMsg(TypesAndTraitsCantBeImplicitID) { def msg = em"""${hl("implicit")} modifier cannot be used for types or traits""" def explain = "" @@ -1481,7 +1481,7 @@ object messages { def explain = s"$varNote" } - class CannotExtendAnyVal(sym: Symbol)(implicit ctx: Context) + class CannotExtendAnyVal(sym: Symbol)(using Context) extends SyntaxMsg(CannotExtendAnyValID) { def msg = em"""$sym cannot extend ${hl("AnyVal")}""" def explain = @@ -1491,7 +1491,7 @@ object messages { |""" } - class CannotHaveSameNameAs(sym: Symbol, cls: Symbol, reason: CannotHaveSameNameAs.Reason)(implicit ctx: Context) + class CannotHaveSameNameAs(sym: Symbol, cls: Symbol, reason: CannotHaveSameNameAs.Reason)(using Context) extends SyntaxMsg(CannotHaveSameNameAsID) { import CannotHaveSameNameAs._ def reasonMessage: String = reason match { @@ -1511,81 +1511,81 @@ object messages { case class DefinedInSelf(self: tpd.ValDef) extends Reason } - class ValueClassesMayNotDefineInner(valueClass: Symbol, inner: Symbol)(implicit ctx: Context) + class ValueClassesMayNotDefineInner(valueClass: Symbol, inner: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotDefineInnerID) { def msg = em"""Value classes may not define an inner class""" def explain = "" } - class ValueClassesMayNotDefineNonParameterField(valueClass: Symbol, field: Symbol)(implicit ctx: Context) + class ValueClassesMayNotDefineNonParameterField(valueClass: Symbol, field: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotDefineNonParameterFieldID) { def msg = em"""Value classes may not define non-parameter field""" def explain = "" } - class ValueClassesMayNotDefineASecondaryConstructor(valueClass: Symbol, constructor: Symbol)(implicit ctx: Context) + class ValueClassesMayNotDefineASecondaryConstructor(valueClass: Symbol, constructor: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotDefineASecondaryConstructorID) { def msg = em"""Value classes may not define a secondary constructor""" def explain = "" } - class ValueClassesMayNotContainInitalization(valueClass: Symbol)(implicit ctx: Context) + class ValueClassesMayNotContainInitalization(valueClass: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotContainInitalizationID) { def msg = em"""Value classes may not contain initialization statements""" def explain = "" } - class ValueClassesMayNotBeAbstract(valueClass: Symbol)(implicit ctx: Context) + class ValueClassesMayNotBeAbstract(valueClass: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotBeAbstractID) { def msg = em"""Value classes may not be ${hl("abstract")}""" def explain = "" } - class ValueClassesMayNotBeContainted(valueClass: Symbol)(implicit ctx: Context) + class ValueClassesMayNotBeContainted(valueClass: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotBeContaintedID) { private def localOrMember = if (valueClass.owner.isTerm) "local class" else "member of another class" def msg = s"""Value classes may not be a $localOrMember""" def explain = "" } - class ValueClassesMayNotWrapItself(valueClass: Symbol)(implicit ctx: Context) + class ValueClassesMayNotWrapItself(valueClass: Symbol)(using Context) extends SyntaxMsg(ValueClassesMayNotWrapItselfID) { def msg = """A value class may not wrap itself""" def explain = "" } - class ValueClassParameterMayNotBeAVar(valueClass: Symbol, param: Symbol)(implicit ctx: Context) + class ValueClassParameterMayNotBeAVar(valueClass: Symbol, param: Symbol)(using Context) extends SyntaxMsg(ValueClassParameterMayNotBeAVarID) { def msg = em"""A value class parameter may not be a ${hl("var")}""" def explain = em"""A value class must have exactly one ${hl("val")} parameter.""" } - class ValueClassNeedsOneValParam(valueClass: Symbol)(implicit ctx: Context) + class ValueClassNeedsOneValParam(valueClass: Symbol)(using Context) extends SyntaxMsg(ValueClassNeedsExactlyOneValParamID) { def msg = em"""Value class needs one ${hl("val")} parameter""" def explain = "" } - class ValueClassParameterMayNotBeCallByName(valueClass: Symbol, param: Symbol)(implicit ctx: Context) + class ValueClassParameterMayNotBeCallByName(valueClass: Symbol, param: Symbol)(using Context) extends SyntaxMsg(ValueClassParameterMayNotBeCallByNameID) { def msg = s"Value class parameter `${param.name}` may not be call-by-name" def explain = "" } - class OnlyCaseClassOrCaseObjectAllowed()(implicit ctx: Context) + class OnlyCaseClassOrCaseObjectAllowed()(using Context) extends SyntaxMsg(OnlyCaseClassOrCaseObjectAllowedID) { def msg = em"""Only ${hl("case class")} or ${hl("case object")} allowed""" def explain = "" } - class ExpectedToplevelDef()(implicit ctx: Context) + class ExpectedToplevelDef()(using Context) extends SyntaxMsg(ExpectedTopLevelDefID) { def msg = "Expected a toplevel definition" def explain = "" } - class SuperCallsNotAllowedInlineable(symbol: Symbol)(implicit ctx: Context) + class SuperCallsNotAllowedInlineable(symbol: Symbol)(using Context) extends SyntaxMsg(SuperCallsNotAllowedInlineableID) { def msg = em"Super call not allowed in inlineable $symbol" def explain = "Method inlining prohibits calling superclass methods, as it may lead to confusion about which super is being called." @@ -1599,27 +1599,27 @@ object messages { | - a reference to `this`, or | - a selection of an immutable path with an immutable value.""" - class WrongNumberOfParameters(expected: Int)(implicit ctx: Context) + class WrongNumberOfParameters(expected: Int)(using Context) extends SyntaxMsg(WrongNumberOfParametersID) { def msg = s"Wrong number of parameters, expected: $expected" def explain = "" } - class DuplicatePrivateProtectedQualifier()(implicit ctx: Context) + class DuplicatePrivateProtectedQualifier()(using Context) extends SyntaxMsg(DuplicatePrivateProtectedQualifierID) { def msg = "Duplicate private/protected qualifier" def explain = em"It is not allowed to combine `private` and `protected` modifiers even if they are qualified to different scopes" } - class ExpectedStartOfTopLevelDefinition()(implicit ctx: Context) + class ExpectedStartOfTopLevelDefinition()(using Context) extends SyntaxMsg(ExpectedStartOfTopLevelDefinitionID) { def msg = "Expected start of definition" def explain = em"You have to provide either ${hl("class")}, ${hl("trait")}, ${hl("object")}, or ${hl("enum")} definitions after qualifiers" } - class NoReturnFromInlineable(owner: Symbol)(implicit ctx: Context) + class NoReturnFromInlineable(owner: Symbol)(using Context) extends SyntaxMsg(NoReturnFromInlineableID) { def msg = em"No explicit ${hl("return")} allowed from inlineable $owner" def explain = @@ -1629,7 +1629,7 @@ object messages { |""" } - class ReturnOutsideMethodDefinition(owner: Symbol)(implicit ctx: Context) + class ReturnOutsideMethodDefinition(owner: Symbol)(using Context) extends SyntaxMsg(ReturnOutsideMethodDefinitionID) { def msg = em"${hl("return")} outside method definition" def explain = @@ -1638,14 +1638,14 @@ object messages { |""" } - class ExtendFinalClass(clazz:Symbol, finalClazz: Symbol)(implicit ctx: Context) + class ExtendFinalClass(clazz:Symbol, finalClazz: Symbol)(using Context) extends SyntaxMsg(ExtendFinalClassID) { def msg = em"$clazz cannot extend ${hl("final")} $finalClazz" def explain = em"""A class marked with the ${hl("final")} keyword cannot be extended""" } - class ExpectedTypeBoundOrEquals(found: Token)(implicit ctx: Context) + class ExpectedTypeBoundOrEquals(found: Token)(using Context) extends SyntaxMsg(ExpectedTypeBoundOrEqualsID) { def msg = em"${hl("=")}, ${hl(">:")}, or ${hl("<:")} expected, but ${Tokens.showToken(found)} found" @@ -1662,7 +1662,7 @@ object messages { |""" } - class ClassAndCompanionNameClash(cls: Symbol, other: Symbol)(implicit ctx: Context) + class ClassAndCompanionNameClash(cls: Symbol, other: Symbol)(using Context) extends NamingMsg(ClassAndCompanionNameClashID) { def msg = em"Name clash: both ${cls.owner} and its companion object defines ${cls.name.stripModuleClassSuffix}" def explain = @@ -1671,7 +1671,7 @@ object messages { | - ${other.owner} defines ${other}""" } - class TailrecNotApplicable(symbol: Symbol)(implicit ctx: Context) + class TailrecNotApplicable(symbol: Symbol)(using Context) extends SyntaxMsg(TailrecNotApplicableID) { def msg = { val reason = @@ -1685,7 +1685,7 @@ object messages { def explain = "" } - class FailureToEliminateExistential(tp: Type, tp1: Type, tp2: Type, boundSyms: List[Symbol])(implicit ctx: Context) + class FailureToEliminateExistential(tp: Type, tp1: Type, tp2: Type, boundSyms: List[Symbol])(using Context) extends Message(FailureToEliminateExistentialID) { def kind: String = "Compatibility" def msg = @@ -1704,7 +1704,7 @@ object messages { |are only approximated in a best-effort way.""" } - class OnlyFunctionsCanBeFollowedByUnderscore(tp: Type)(implicit ctx: Context) + class OnlyFunctionsCanBeFollowedByUnderscore(tp: Type)(using Context) extends SyntaxMsg(OnlyFunctionsCanBeFollowedByUnderscoreID) { def msg = em"Only function types can be followed by ${hl("_")} but the current expression has type $tp" def explain = @@ -1712,7 +1712,7 @@ object messages { |To convert to a function value, you need to explicitly write ${hl("() => x")}""" } - class MissingEmptyArgumentList(method: Symbol)(implicit ctx: Context) + class MissingEmptyArgumentList(method: Symbol)(using Context) extends SyntaxMsg(MissingEmptyArgumentListID) { def msg = em"$method must be called with ${hl("()")} argument" def explain = { @@ -1729,19 +1729,19 @@ object messages { } } - class DuplicateNamedTypeParameter(name: Name)(implicit ctx: Context) + class DuplicateNamedTypeParameter(name: Name)(using Context) extends SyntaxMsg(DuplicateNamedTypeParameterID) { def msg = em"Type parameter $name was defined multiple times." def explain = "" } - class UndefinedNamedTypeParameter(undefinedName: Name, definedNames: List[Name])(implicit ctx: Context) + class UndefinedNamedTypeParameter(undefinedName: Name, definedNames: List[Name])(using Context) extends SyntaxMsg(UndefinedNamedTypeParameterID) { def msg = em"Type parameter $undefinedName is undefined. Expected one of ${definedNames.map(_.show).mkString(", ")}." def explain = "" } - class IllegalStartOfStatement(isModifier: Boolean)(implicit ctx: Context) extends SyntaxMsg(IllegalStartOfStatementID) { + class IllegalStartOfStatement(isModifier: Boolean)(using Context) extends SyntaxMsg(IllegalStartOfStatementID) { def msg = { val addendum = if (isModifier) ": no modifiers allowed here" else "" "Illegal start of statement" + addendum @@ -1749,7 +1749,7 @@ object messages { def explain = "A statement is either an import, a definition or an expression." } - class TraitIsExpected(symbol: Symbol)(implicit ctx: Context) extends SyntaxMsg(TraitIsExpectedID) { + class TraitIsExpected(symbol: Symbol)(using Context) extends SyntaxMsg(TraitIsExpectedID) { def msg = em"$symbol is not a trait" def explain = { val errorCodeExample = @@ -1776,12 +1776,12 @@ object messages { } } - class TraitRedefinedFinalMethodFromAnyRef(method: Symbol)(implicit ctx: Context) extends SyntaxMsg(TraitRedefinedFinalMethodFromAnyRefID) { + class TraitRedefinedFinalMethodFromAnyRef(method: Symbol)(using Context) extends SyntaxMsg(TraitRedefinedFinalMethodFromAnyRefID) { def msg = em"Traits cannot redefine final $method from ${hl("class AnyRef")}." def explain = "" } - class PackageNameAlreadyDefined(pkg: Symbol)(implicit ctx: Context) extends NamingMsg(PackageNameAlreadyDefinedID) { + class PackageNameAlreadyDefined(pkg: Symbol)(using Context) extends NamingMsg(PackageNameAlreadyDefinedID) { lazy val (where, or) = if pkg.associatedFile == null then ("", "") else (s" in ${pkg.associatedFile}", " or delete the containing class file") @@ -1792,7 +1792,7 @@ object messages { |Rename either one of them$or.""" } - class UnapplyInvalidNumberOfArguments(qual: untpd.Tree, argTypes: List[Type])(implicit ctx: Context) + class UnapplyInvalidNumberOfArguments(qual: untpd.Tree, argTypes: List[Type])(using Context) extends SyntaxMsg(UnapplyInvalidNumberOfArgumentsID) { def msg = em"Wrong number of argument patterns for $qual; expected: ($argTypes%, %)" def explain = @@ -1804,7 +1804,7 @@ object messages { |""".stripMargin } - class UnapplyInvalidReturnType(unapplyResult: Type, unapplyName: Name)(implicit ctx: Context) + class UnapplyInvalidReturnType(unapplyResult: Type, unapplyName: Name)(using Context) extends DeclarationMsg(UnapplyInvalidReturnTypeID) { def msg = val addendum = @@ -1859,13 +1859,13 @@ object messages { """.stripMargin } - class StaticFieldsOnlyAllowedInObjects(member: Symbol)(implicit ctx: Context) extends SyntaxMsg(StaticFieldsOnlyAllowedInObjectsID) { + class StaticFieldsOnlyAllowedInObjects(member: Symbol)(using Context) extends SyntaxMsg(StaticFieldsOnlyAllowedInObjectsID) { def msg = em"${hl("@static")} $member in ${member.owner} must be defined inside an ${hl("object")}." def explain = em"${hl("@static")} members are only allowed inside objects." } - class StaticFieldsShouldPrecedeNonStatic(member: Symbol, defns: List[tpd.Tree])(implicit ctx: Context) extends SyntaxMsg(StaticFieldsShouldPrecedeNonStaticID) { + class StaticFieldsShouldPrecedeNonStatic(member: Symbol, defns: List[tpd.Tree])(using Context) extends SyntaxMsg(StaticFieldsShouldPrecedeNonStaticID) { def msg = em"${hl("@static")} $member in ${member.owner} must be defined before non-static fields." def explain = { val nonStatics = defns.takeWhile(_.symbol != member).take(3).filter(_.isInstanceOf[tpd.ValDef]) @@ -1885,7 +1885,7 @@ object messages { } } - class CyclicInheritance(symbol: Symbol, addendum: => String)(implicit ctx: Context) extends SyntaxMsg(CyclicInheritanceID) { + class CyclicInheritance(symbol: Symbol, addendum: => String)(using Context) extends SyntaxMsg(CyclicInheritanceID) { def msg = em"Cyclic inheritance: $symbol extends itself$addendum" def explain = { val codeExample = "class A extends A" @@ -1901,7 +1901,7 @@ object messages { } } - class BadSymbolicReference(denot: SymDenotation)(implicit ctx: Context) + class BadSymbolicReference(denot: SymDenotation)(using Context) extends ReferenceMsg(BadSymbolicReferenceID) { def msg = { val denotationOwner = denot.owner @@ -1920,12 +1920,12 @@ object messages { def explain = "" } - class UnableToExtendSealedClass(pclazz: Symbol)(implicit ctx: Context) extends SyntaxMsg(UnableToExtendSealedClassID) { + class UnableToExtendSealedClass(pclazz: Symbol)(using Context) extends SyntaxMsg(UnableToExtendSealedClassID) { def msg = em"Cannot extend ${hl("sealed")} $pclazz in a different source file" def explain = "A sealed class or trait can only be extended in the same file as its declaration" } - class SymbolHasUnparsableVersionNumber(symbol: Symbol, migrationMessage: => String)(implicit ctx: Context) + class SymbolHasUnparsableVersionNumber(symbol: Symbol, migrationMessage: => String)(using Context) extends SyntaxMsg(SymbolHasUnparsableVersionNumberID) { def msg = em"${symbol.showLocated} has an unparsable version number: $migrationMessage" def explain = @@ -1939,7 +1939,7 @@ object messages { class SymbolChangedSemanticsInVersion( symbol: Symbol, migrationVersion: ScalaVersion - )(implicit ctx: Context) extends SyntaxMsg(SymbolChangedSemanticsInVersionID) { + )(using Context) extends SyntaxMsg(SymbolChangedSemanticsInVersionID) { def msg = em"${symbol.showLocated} has changed semantics in version $migrationVersion" def explain = { em"""The ${symbol.showLocated} is marked with ${hl("@migration")} indicating it has changed semantics @@ -1948,7 +1948,7 @@ object messages { } } - class UnableToEmitSwitch(tooFewCases: Boolean)(implicit ctx: Context) + class UnableToEmitSwitch(tooFewCases: Boolean)(using Context) extends SyntaxMsg(UnableToEmitSwitchID) { def tooFewStr: String = if (tooFewCases) " since there are not enough cases" else "" def msg = em"Could not emit switch for ${hl("@switch")} annotated match$tooFewStr" @@ -1977,14 +1977,14 @@ object messages { } } - class MissingCompanionForStatic(member: Symbol)(implicit ctx: Context) + class MissingCompanionForStatic(member: Symbol)(using Context) extends SyntaxMsg(MissingCompanionForStaticID) { def msg = em"${member.owner} does not have a companion class" def explain = em"An object that contains ${hl("@static")} members must have a companion class." } - class PolymorphicMethodMissingTypeInParent(rsym: Symbol, parentSym: Symbol)(implicit ctx: Context) + class PolymorphicMethodMissingTypeInParent(rsym: Symbol, parentSym: Symbol)(using Context) extends SyntaxMsg(PolymorphicMethodMissingTypeInParentID) { def msg = em"Polymorphic refinement $rsym without matching type in parent $parentSym is no longer allowed" def explain = @@ -1993,13 +1993,13 @@ object messages { |polymorphic methods.""" } - class ParamsNoInline(owner: Symbol)(implicit ctx: Context) + class ParamsNoInline(owner: Symbol)(using Context) extends SyntaxMsg(ParamsNoInlineID) { def msg = em"""${hl("inline")} modifier can only be used for parameters of inline methods""" def explain = "" } - class JavaSymbolIsNotAValue(symbol: Symbol)(implicit ctx: Context) extends TypeMsg(JavaSymbolIsNotAValueID) { + class JavaSymbolIsNotAValue(symbol: Symbol)(using Context) extends TypeMsg(JavaSymbolIsNotAValueID) { def msg = { val kind = if (symbol is Package) em"$symbol" @@ -2010,10 +2010,10 @@ object messages { def explain = "" } - class DoubleDefinition(decl: Symbol, previousDecl: Symbol, base: Symbol)(implicit ctx: Context) extends NamingMsg(DoubleDefinitionID) { + class DoubleDefinition(decl: Symbol, previousDecl: Symbol, base: Symbol)(using Context) extends NamingMsg(DoubleDefinitionID) { def msg = { def nameAnd = if (decl.name != previousDecl.name) " name and" else "" - def details(implicit ctx: Context): String = + def details(using Context): String = if (decl.isRealMethod && previousDecl.isRealMethod) { import Signature.MatchDegree._ @@ -2024,7 +2024,7 @@ object messages { // they might match after erasure. val elimErasedCtx = ctx.withPhaseNoEarlier(ctx.elimErasedValueTypePhase.next) if (elimErasedCtx != ctx) - details(elimErasedCtx) + details(using elimErasedCtx) else "" // shouldn't be reachable case ParamMatch => @@ -2059,12 +2059,12 @@ object messages { def explain = "" } - class ImportRenamedTwice(ident: untpd.Ident)(implicit ctx: Context) extends SyntaxMsg(ImportRenamedTwiceID) { + class ImportRenamedTwice(ident: untpd.Ident)(using Context) extends SyntaxMsg(ImportRenamedTwiceID) { def msg = s"${ident.show} is renamed twice on the same import line." def explain = "" } - class TypeTestAlwaysSucceeds(scrutTp: Type, testTp: Type)(implicit ctx: Context) extends SyntaxMsg(TypeTestAlwaysSucceedsID) { + class TypeTestAlwaysSucceeds(scrutTp: Type, testTp: Type)(using Context) extends SyntaxMsg(TypeTestAlwaysSucceedsID) { def msg = { val addendum = if (scrutTp != testTp) s" is a subtype of ${testTp.show}" @@ -2075,7 +2075,7 @@ object messages { } // Relative of CyclicReferenceInvolvingImplicit and RecursiveValueNeedsResultType - class TermMemberNeedsResultTypeForImplicitSearch(cycleSym: Symbol)(implicit ctx: Context) + class TermMemberNeedsResultTypeForImplicitSearch(cycleSym: Symbol)(using Context) extends CyclicMsg(TermMemberNeedsNeedsResultTypeForImplicitSearchID) { def msg = em"""$cycleSym needs result type because its right-hand side attempts implicit search""" def explain = @@ -2084,12 +2084,12 @@ object messages { |""".stripMargin } - class ClassCannotExtendEnum(cls: Symbol, parent: Symbol)(implicit ctx: Context) extends SyntaxMsg(ClassCannotExtendEnumID) { + class ClassCannotExtendEnum(cls: Symbol, parent: Symbol)(using Context) extends SyntaxMsg(ClassCannotExtendEnumID) { def msg = em"""$cls in ${cls.owner} extends enum ${parent.name}, but extending enums is prohibited.""" def explain = "" } - class NotAnExtractor(tree: untpd.Tree)(implicit ctx: Context) extends SyntaxMsg(NotAnExtractorID) { + class NotAnExtractor(tree: untpd.Tree)(using Context) extends SyntaxMsg(NotAnExtractorID) { def msg = em"$tree cannot be used as an extractor in a pattern because it lacks an unapply or unapplySeq method" def explain = em"""|An ${hl("unapply")} method should be defined in an ${hl("object")} as follow: @@ -2108,7 +2108,7 @@ object messages { def explain = "" } - class PureExpressionInStatementPosition(stat: untpd.Tree, val exprOwner: Symbol)(implicit ctx: Context) + class PureExpressionInStatementPosition(stat: untpd.Tree, val exprOwner: Symbol)(using Context) extends Message(PureExpressionInStatementPositionID) { def kind = "Potential Issue" def msg = "A pure expression does nothing in statement position; you may be omitting necessary parentheses" @@ -2256,7 +2256,7 @@ object messages { def explain = "" } - class CaseClassMissingNonImplicitParamList(cdef: untpd.TypeDef)(implicit ctx: Context) + class CaseClassMissingNonImplicitParamList(cdef: untpd.TypeDef)(using Context) extends SyntaxMsg(CaseClassMissingNonImplicitParamListID) { def msg = em"""|A ${hl("case class")} must have at least one non-implicit parameter list""" @@ -2267,7 +2267,7 @@ object messages { | add an explicit ${hl("()")} as a parameter list to ${cdef.name}.""".stripMargin } - class EnumerationsShouldNotBeEmpty(cdef: untpd.TypeDef)(implicit ctx: Context) + class EnumerationsShouldNotBeEmpty(cdef: untpd.TypeDef)(using Context) extends SyntaxMsg(EnumerationsShouldNotBeEmptyID) { def msg = "Enumerations must contain at least one case" @@ -2280,7 +2280,7 @@ object messages { |""".stripMargin } - class AbstractCannotBeUsedForObjects(mdef: untpd.ModuleDef)(implicit ctx: Context) + class AbstractCannotBeUsedForObjects(mdef: untpd.ModuleDef)(using Context) extends SyntaxMsg(AbstractCannotBeUsedForObjectsID) { def msg = em"${hl("abstract")} modifier cannot be used for objects" @@ -2295,7 +2295,7 @@ object messages { |""".stripMargin } - class ModifierRedundantForObjects(mdef: untpd.ModuleDef, modifier: String)(implicit ctx: Context) + class ModifierRedundantForObjects(mdef: untpd.ModuleDef, modifier: String)(using Context) extends SyntaxMsg(ModifierRedundantForObjectsID) { def msg = em"${hl(modifier)} modifier is redundant for objects" @@ -2306,7 +2306,7 @@ object messages { |""".stripMargin } - class TypedCaseDoesNotExplicitlyExtendTypedEnum(enumDef: Symbol, caseDef: untpd.TypeDef)(implicit ctx: Context) + class TypedCaseDoesNotExplicitlyExtendTypedEnum(enumDef: Symbol, caseDef: untpd.TypeDef)(using Context) extends SyntaxMsg(TypedCaseDoesNotExplicitlyExtendTypedEnumID) { def msg = i"explicit extends clause needed because both enum case and enum class have type parameters" @@ -2320,7 +2320,7 @@ object messages { |""".stripMargin } - class IllegalRedefinitionOfStandardKind(kindType: String, name: Name)(implicit ctx: Context) + class IllegalRedefinitionOfStandardKind(kindType: String, name: Name)(using Context) extends SyntaxMsg(IllegalRedefinitionOfStandardKindID) { def msg = em"illegal redefinition of standard $kindType $name" def explain = @@ -2329,7 +2329,7 @@ object messages { |""".stripMargin } - class NoExtensionMethodAllowed(mdef: untpd.DefDef)(implicit ctx: Context) + class NoExtensionMethodAllowed(mdef: untpd.DefDef)(using Context) extends SyntaxMsg(NoExtensionMethodAllowedID) { def msg = em"No extension method allowed here, since collective parameters are given" def explain = @@ -2339,7 +2339,7 @@ object messages { |""".stripMargin } - class ExtensionMethodCannotHaveTypeParams(mdef: untpd.DefDef)(implicit ctx: Context) + class ExtensionMethodCannotHaveTypeParams(mdef: untpd.DefDef)(using Context) extends SyntaxMsg(ExtensionMethodCannotHaveTypeParamsID) { def msg = i"Extension method cannot have type parameters since some were already given previously" @@ -2351,7 +2351,7 @@ object messages { |""".stripMargin } - class ExtensionCanOnlyHaveDefs(mdef: untpd.Tree)(implicit ctx: Context) + class ExtensionCanOnlyHaveDefs(mdef: untpd.Tree)(using Context) extends SyntaxMsg(ExtensionCanOnlyHaveDefsID) { def msg = em"Only methods allowed here, since collective parameters are given" def explain = @@ -2360,7 +2360,7 @@ object messages { |""".stripMargin } - class UnexpectedPatternForSummonFrom(tree: Tree[_])(implicit ctx: Context) + class UnexpectedPatternForSummonFrom(tree: Tree[_])(using Context) extends SyntaxMsg(UnexpectedPatternForSummonFromID) { def msg = em"Unexpected pattern for summonFrom. Expected ${hl("`x: T`")} or ${hl("`_`")}" def explain = @@ -2379,7 +2379,7 @@ object messages { |""".stripMargin } - class AnonymousInstanceCannotBeEmpty(impl: untpd.Template)(implicit ctx: Context) + class AnonymousInstanceCannotBeEmpty(impl: untpd.Template)(using Context) extends SyntaxMsg(AnonymousInstanceCannotBeEmptyID) { def msg = i"anonymous instance must implement a type or have at least one extension method" def explain = @@ -2388,7 +2388,7 @@ object messages { |""".stripMargin } - class TypeSpliceInValPattern(expr: untpd.Tree)(implicit ctx: Context) + class TypeSpliceInValPattern(expr: untpd.Tree)(using Context) extends SyntaxMsg(TypeSpliceInValPatternID) { def msg = "Type splices cannot be used in val patterns. Consider using `match` instead." def explain = @@ -2397,7 +2397,7 @@ object messages { |""".stripMargin } - class ModifierNotAllowedForDefinition(flag: Flag)(implicit ctx: Context) + class ModifierNotAllowedForDefinition(flag: Flag)(using Context) extends SyntaxMsg(ModifierNotAllowedForDefinitionID) { 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 b9e047febf20..1f9b8f0503a5 100644 --- a/compiler/src/dotty/tools/dotc/reporting/trace.scala +++ b/compiler/src/dotty/tools/dotc/reporting/trace.scala @@ -25,40 +25,40 @@ object trace extends TraceSyntax { abstract class TraceSyntax { val isForced: Boolean - inline def onDebug[TD](inline question: String)(inline op: TD)(implicit ctx: Context): TD = + inline def onDebug[TD](inline question: String)(inline op: TD)(using Context): TD = conditionally(ctx.settings.YdebugTrace.value, question, false)(op) - inline def conditionally[TC](inline cond: Boolean, inline question: String, inline show: Boolean)(op: => TC)(implicit ctx: Context): TC = + inline def conditionally[TC](inline cond: Boolean, inline question: String, inline show: Boolean)(op: => TC)(using Context): TC = inline if (isForced || Config.tracingEnabled) { if (cond) apply[TC](question, Printers.default, show)(op) else op } else op - inline def apply[T](inline question: String, inline printer: Printers.Printer, inline showOp: Any => String)(op: => T)(implicit ctx: Context): T = + inline def apply[T](inline question: String, inline printer: Printers.Printer, inline showOp: Any => String)(op: => T)(using Context): T = inline if (isForced || Config.tracingEnabled) { if (!isForced && printer.eq(config.Printers.noPrinter)) op else doTrace[T](question, printer, showOp)(op) } else op - inline def apply[T](inline question: String, inline printer: Printers.Printer, inline show: Boolean)(op: => T)(implicit ctx: Context): T = + inline def apply[T](inline question: String, inline printer: Printers.Printer, inline show: Boolean)(op: => T)(using Context): T = inline if (isForced || Config.tracingEnabled) { if (!isForced && printer.eq(config.Printers.noPrinter)) op else doTrace[T](question, printer, if (show) showShowable(_) else alwaysToString)(op) } else op - inline def apply[T](inline question: String, inline printer: Printers.Printer)(inline op: T)(implicit ctx: Context): T = + inline def apply[T](inline question: String, inline printer: Printers.Printer)(inline op: T)(using Context): T = apply[T](question, printer, false)(op) - inline def apply[T](inline question: String, inline show: Boolean)(inline op: T)(implicit ctx: Context): T = + inline def apply[T](inline question: String, inline show: Boolean)(inline op: T)(using Context): T = apply[T](question, Printers.default, show)(op) - inline def apply[T](inline question: String)(inline op: T)(implicit ctx: Context): T = + inline def apply[T](inline question: String)(inline op: T)(using Context): T = apply[T](question, Printers.default, false)(op) - private def showShowable(x: Any)(implicit ctx: Context) = x match { + private def showShowable(x: Any)(using Context) = x match { case x: printing.Showable => x.show case _ => String.valueOf(x) } @@ -68,14 +68,14 @@ abstract class TraceSyntax { private def doTrace[T](question: => String, printer: Printers.Printer = Printers.default, showOp: Any => String = alwaysToString) - (op: => T)(implicit ctx: Context): T = { + (op: => T)(using Context): T = { // Avoid evaluating question multiple time, since each evaluation // may cause some extra logging output. lazy val q: String = question apply[T](s"==> $q?", (res: Any) => s"<== $q = ${showOp(res)}")(op) } - def apply[T](leading: => String, trailing: Any => String)(op: => T)(implicit ctx: Context): T = { + def apply[T](leading: => String, trailing: Any => String)(op: => T)(using Context): T = { val log: String => Unit = if (isForced) Console.println else { var logctx = ctx while (logctx.reporter.isInstanceOf[StoreReporter]) logctx = logctx.outer @@ -84,7 +84,7 @@ abstract class TraceSyntax { doApply(leading, trailing, log)(op) } - def doApply[T](leading: => String, trailing: Any => String, log: String => Unit)(op: => T)(implicit ctx: Context): T = + def doApply[T](leading: => String, trailing: Any => String, log: String => Unit)(op: => T)(using Context): T = if (ctx.mode.is(Mode.Printing)) op else { var finalized = false diff --git a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala index 158214e38f18..efd17996d818 100644 --- a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala +++ b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala @@ -37,7 +37,7 @@ object ErrorReporting { } def wrongNumberOfTypeArgs(fntpe: Type, expectedArgs: List[ParamInfo], actual: List[untpd.Tree], pos: SourcePosition)(using Context): ErrorType = - errorType(WrongNumberOfTypeArgs(fntpe, expectedArgs, actual)(ctx), pos) + errorType(WrongNumberOfTypeArgs(fntpe, expectedArgs, actual), pos) class Errors(using Context) { diff --git a/compiler/src/dotty/tools/repl/Rendering.scala b/compiler/src/dotty/tools/repl/Rendering.scala index 9b717ebdf944..283978458b51 100644 --- a/compiler/src/dotty/tools/repl/Rendering.scala +++ b/compiler/src/dotty/tools/repl/Rendering.scala @@ -97,7 +97,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { /** Formats errors using the `messageRenderer` */ def formatError(dia: Diagnostic)(implicit state: State): Diagnostic = new Diagnostic( - messageRenderer.messageAndPos(dia.msg, dia.pos, messageRenderer.diagnosticLevel(dia))(state.context), + messageRenderer.messageAndPos(dia.msg, dia.pos, messageRenderer.diagnosticLevel(dia))(using state.context), dia.pos, dia.level ) diff --git a/compiler/src/dotty/tools/repl/ReplCompiler.scala b/compiler/src/dotty/tools/repl/ReplCompiler.scala index 80f60f670de0..c4cbfaee2d65 100644 --- a/compiler/src/dotty/tools/repl/ReplCompiler.scala +++ b/compiler/src/dotty/tools/repl/ReplCompiler.scala @@ -153,7 +153,7 @@ class ReplCompiler extends Compiler { ctx.run.compileUnits(unit :: Nil) if (!ctx.reporter.hasErrors) (unit, state).result - else ctx.reporter.removeBufferedMessages(ctx).errors + else ctx.reporter.removeBufferedMessages(using ctx).errors } final def compile(parsed: Parsed)(implicit state: State): Result[(CompilationUnit, State)] = { diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index a64fe4181d8c..e7ff1526ea89 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -242,7 +242,7 @@ class ReplDriver(settings: Array[String], val newStateWithImports = newState.copy(imports = allImports) val warnings = newState.context.reporter - .removeBufferedMessages(newState.context) + .removeBufferedMessages(using newState.context) .map(rendering.formatError) inContext(newState.context) { diff --git a/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala b/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala index 8e2011f4b2d0..89b295d1cf49 100644 --- a/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala +++ b/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala @@ -17,7 +17,7 @@ object desugarPackage extends DeSugarTest { val buf = parsedTrees map desugarTree val ms2 = (System.nanoTime() - start)/1000000 println(s"$parsed files parsed in ${ms1}ms, ${nodes - startNodes} nodes desugared in ${ms2-ms1}ms, total trees created = ${Trees.ntrees - startNodes}") - ctx.reporter.printSummary(ctx) + ctx.reporter.printSummary(using ctx) } def main(args: Array[String]): Unit = { diff --git a/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala b/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala index c58cc673ccee..a99b22a7dfa8 100644 --- a/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala +++ b/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala @@ -70,7 +70,7 @@ object parsePackage extends ParserTest { val buf = parsedTrees map transformer.transform val ms2 = (System.nanoTime() - start)/1000000 println(s"$parsed files parsed in ${ms1}ms, $nodes nodes transformed in ${ms2-ms1}ms, total trees created = ${Trees.ntrees}") - ctx.reporter.printSummary(ctx) + ctx.reporter.printSummary(using ctx) } def main(args: Array[String]): Unit = { diff --git a/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTest.scala b/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTest.scala index 59b81ecf3a32..cc7d1eac2004 100644 --- a/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTest.scala +++ b/compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTest.scala @@ -36,7 +36,7 @@ trait ErrorMessagesTest extends DottyTest { if (!runCtx.reporter.hasErrors) new EmptyReport else { val rep = runCtx.reporter.asInstanceOf[StoreReporter] - val msgs = rep.removeBufferedMessages(runCtx).map(_.msg).reverse + val msgs = rep.removeBufferedMessages(using runCtx).map(_.msg).reverse new Report(msgs, runCtx) } } diff --git a/tests/pos-with-compiler/A.scala b/tests/pos-with-compiler/A.scala index 7de1bc1ef418..d5e8ad4e44e3 100644 --- a/tests/pos-with-compiler/A.scala +++ b/tests/pos-with-compiler/A.scala @@ -2,5 +2,5 @@ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.NameOps._ object Test { - "JFunction".toTermName.specializedFor(Nil, ???, Nil, Nil)(???) + "JFunction".toTermName.specializedFor(Nil, ???, Nil, Nil)(using ???) } From 1ae90ec6b09643b86a29af6def6cb44c306c0a94 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 16:54:07 +0200 Subject: [PATCH 21/41] Convert transform classes (1) --- .../dotty/tools/dotc/rewrites/Rewrites.scala | 6 +-- .../tools/dotc/transform/AccessProxies.scala | 24 +++++----- .../tools/dotc/transform/ArrayApply.scala | 6 +-- .../dotc/transform/ArrayConstructors.scala | 2 +- .../dotc/transform/AugmentScala2Traits.scala | 4 +- .../dotty/tools/dotc/transform/Bridges.scala | 12 ++--- .../tools/dotc/transform/ByNameClosures.scala | 2 +- .../dotc/transform/CacheAliasImplicits.scala | 2 +- .../tools/dotc/transform/CapturedVars.scala | 22 ++++----- .../tools/dotc/transform/CheckReentrant.scala | 8 ++-- .../tools/dotc/transform/CheckStatic.scala | 4 +- .../transform/CollectNullableFields.scala | 10 ++-- .../dotc/transform/CompleteJavaEnums.scala | 14 +++--- .../tools/dotc/transform/Constructors.scala | 22 ++++----- .../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 +- .../tools/dotc/transform/ElimByName.scala | 14 +++--- .../dotc/transform/ElimErasedValueType.scala | 24 +++++----- .../tools/dotc/transform/ElimOpaque.scala | 2 +- .../dotc/transform/ElimOuterSelect.scala | 2 +- .../dotc/transform/ElimPackagePrefixes.scala | 6 +-- .../dotc/transform/ElimPolyFunction.scala | 6 +-- .../tools/dotc/transform/ElimRepeated.scala | 30 ++++++------ .../tools/dotc/transform/ElimStaticThis.scala | 4 +- .../tools/dotc/transform/ExpandPrivate.scala | 12 ++--- .../tools/dotc/transform/ExpandSAMs.scala | 18 ++++---- .../tools/dotc/transform/ExplicitOuter.scala | 46 +++++++++---------- .../tools/dotc/transform/ExplicitSelf.scala | 4 +- .../dotc/transform/ExtensionMethods.scala | 14 +++--- .../tools/dotc/transform/FirstTransform.scala | 36 +++++++-------- .../dotty/tools/dotc/transform/Flatten.scala | 14 +++--- .../dotc/transform/FullParameterization.scala | 16 +++---- .../transform/FunctionXXLForwarders.scala | 2 +- .../dotc/transform/FunctionalInterfaces.scala | 2 +- 37 files changed, 200 insertions(+), 200 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala index a31fb96e471d..c3835ded4df7 100644 --- a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala +++ b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala @@ -63,7 +63,7 @@ object Rewrites { /** If -rewrite is set, record a patch that replaces the range * given by `span` in `source` by `replacement` */ - def patch(source: SourceFile, span: Span, replacement: String)(implicit ctx: Context): Unit = + def patch(source: SourceFile, span: Span, replacement: String)(using Context): Unit = if (ctx.reporter != Reporter.NoReporter) // NoReporter is used for syntax highlighting for (rewrites <- ctx.settings.rewrite.value) rewrites.patched @@ -71,7 +71,7 @@ object Rewrites { .addPatch(span, replacement) /** Patch position in `ctx.compilationUnit.source`. */ - def patch(span: Span, replacement: String)(implicit ctx: Context): Unit = + def patch(span: Span, replacement: String)(using Context): Unit = patch(ctx.compilationUnit.source, span, replacement) /** Does `span` overlap with a patch region of `source`? */ @@ -82,7 +82,7 @@ object Rewrites { /** If -rewrite is set, apply all patches and overwrite patched source files. */ - def writeBack()(implicit ctx: Context): Unit = + def writeBack()(using Context): Unit = for (rewrites <- ctx.settings.rewrite.value; source <- rewrites.patched.keys) { ctx.echo(s"[patched file ${source.file.path}]") rewrites.patched(source).writeBack() diff --git a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala index 8690acf3be03..6626ca5123a3 100644 --- a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala +++ b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala @@ -28,13 +28,13 @@ abstract class AccessProxies { /** Given the name of an accessor, is the receiver of the call to accessed obtained * as a parameterer? */ - protected def passReceiverAsArg(accessorName: Name)(implicit ctx: Context): Boolean = false + protected def passReceiverAsArg(accessorName: Name)(using Context): Boolean = false /** The accessor definitions that need to be added to class `cls` * As a side-effect, this method removes entries from the `accessedBy` map. * So a second call of the same method will yield the empty list. */ - private def accessorDefs(cls: Symbol)(implicit ctx: Context): Iterator[DefDef] = + private def accessorDefs(cls: Symbol)(using Context): Iterator[DefDef] = for (accessor <- cls.info.decls.iterator; accessed <- accessedBy.remove(accessor)) yield polyDefDef(accessor.asTerm, tps => argss => { def numTypeParams = accessed.info match { @@ -57,7 +57,7 @@ abstract class AccessProxies { }) /** Add all needed accessors to the `body` of class `cls` */ - def addAccessorDefs(cls: Symbol, body: List[Tree])(implicit ctx: Context): List[Tree] = { + def addAccessorDefs(cls: Symbol, body: List[Tree])(using Context): List[Tree] = { val accDefs = accessorDefs(cls) transforms.println(i"add accessors for $cls: $accDefs%, %") if (accDefs.isEmpty) body else body ++ accDefs @@ -67,22 +67,22 @@ abstract class AccessProxies { import ast.tpd._ def accessorNameKind: ClassifiedNameKind - def needsAccessor(sym: Symbol)(implicit ctx: Context): Boolean + def needsAccessor(sym: Symbol)(using Context): Boolean - def ifNoHost(reference: RefTree)(implicit ctx: Context): Tree = { + def ifNoHost(reference: RefTree)(using Context): Tree = { assert(false, "no host found for $reference with ${reference.symbol.showLocated} from ${ctx.owner}") reference } /** A fresh accessor symbol */ - private def newAccessorSymbol(owner: Symbol, name: TermName, info: Type, span: Span)(implicit ctx: Context): TermSymbol = { + 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 if (sym.allOverriddenSymbols.exists(!_.is(Deferred))) sym.setFlag(Override) sym } /** An accessor symbol, create a fresh one unless one exists already */ - protected def accessorSymbol(owner: Symbol, accessorName: TermName, accessorInfo: Type, accessed: Symbol)(implicit ctx: Context): Symbol = { + protected def accessorSymbol(owner: Symbol, accessorName: TermName, accessorInfo: Type, accessed: Symbol)(using Context): Symbol = { def refersToAccessed(sym: Symbol) = accessedBy.get(sym).contains(accessed) owner.info.decl(accessorName).suchThat(refersToAccessed).symbol.orElse { val acc = newAccessorSymbol(owner, accessorName, accessorInfo, accessed.span) @@ -92,7 +92,7 @@ abstract class AccessProxies { } /** Rewire reference to refer to `accessor` symbol */ - private def rewire(reference: RefTree, accessor: Symbol)(implicit ctx: Context): Tree = { + private def rewire(reference: RefTree, accessor: Symbol)(using Context): Tree = { reference match { case Select(qual, _) if qual.tpe.derivesFrom(accessor.owner) => qual.select(accessor) case _ => ref(accessor) @@ -100,7 +100,7 @@ abstract class AccessProxies { }.withSpan(reference.span) /** Given a reference to a getter accessor, the corresponding setter reference */ - def useSetter(getterRef: Tree)(implicit ctx: Context): Tree = getterRef match { + def useSetter(getterRef: Tree)(using Context): Tree = getterRef match { case getterRef: RefTree => val getter = getterRef.symbol.asTerm val accessed = accessedBy(getter) @@ -126,7 +126,7 @@ abstract class AccessProxies { * @param reference The original reference to the non-public symbol * @param onLHS The reference is on the left-hand side of an assignment */ - def useAccessor(reference: RefTree)(implicit ctx: Context): Tree = { + def useAccessor(reference: RefTree)(using Context): Tree = { val accessed = reference.symbol.asTerm var accessorClass = hostForAccessorOf(accessed: Symbol) if (accessorClass.exists) { @@ -142,7 +142,7 @@ abstract class AccessProxies { } /** Replace tree with a reference to an accessor if needed */ - def accessorIfNeeded(tree: Tree)(implicit ctx: Context): Tree = tree match { + 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) @@ -158,7 +158,7 @@ object AccessProxies { /** Where an accessor for the `accessed` symbol should be placed. * This is the closest enclosing class that has `accessed` as a member. */ - def hostForAccessorOf(accessed: Symbol)(implicit ctx: Context): Symbol = { + def hostForAccessorOf(accessed: Symbol)(using Context): Symbol = { def recur(cls: Symbol): Symbol = if (!cls.exists) NoSymbol else if cls.derivesFrom(accessed.owner) diff --git a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala index a8d72b17a98a..11283c0a869f 100644 --- a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala @@ -22,7 +22,7 @@ class ArrayApply extends MiniPhase { override def phaseName: String = "arrayApply" - override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = + override def transformApply(tree: tpd.Apply)(using Context): tpd.Tree = if (tree.symbol.name == nme.apply && tree.symbol.owner == defn.ArrayModule.moduleClass) // Is `Array.apply` tree.args match { case StripAscription(Apply(wrapRefArrayMeth, (seqLit: tpd.JavaSeqLiteral) :: Nil)) :: ct :: Nil @@ -44,7 +44,7 @@ class ArrayApply extends MiniPhase { * - `ClassTag.apply(java.lang.XYZ.Type)` for boxed primitives `XYZ`` * - `ClassTag.XYZ` for primitive types */ - private def elideClassTag(ct: Tree)(implicit ctx: Context): Boolean = ct match { + private def elideClassTag(ct: Tree)(using Context): Boolean = ct match { case Apply(_, rc :: Nil) if ct.symbol == defn.ClassTagModule_apply => rc match { case _: Literal => true // ClassTag.apply(classOf[XYZ]) @@ -60,7 +60,7 @@ class ArrayApply extends MiniPhase { } object StripAscription { - def unapply(tree: Tree)(implicit ctx: Context): Some[Tree] = tree match { + def unapply(tree: Tree)(using Context): Some[Tree] = tree match { case Typed(expr, _) => unapply(expr) case _ => Some(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala b/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala index 74044b06b96d..cbafbe3a206a 100644 --- a/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala +++ b/compiler/src/dotty/tools/dotc/transform/ArrayConstructors.scala @@ -24,7 +24,7 @@ class ArrayConstructors extends MiniPhase { override def phaseName: String = "arrayConstructors" - override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = { + override def transformApply(tree: tpd.Apply)(using Context): tpd.Tree = { def expand(elemType: Type, dims: List[Tree]) = tpd.newArray(elemType, tree.tpe, tree.span, JavaSeqLiteral(dims, TypeTree(defn.IntClass.typeRef))) diff --git a/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala b/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala index afeee713bd0e..82806fa1095d 100644 --- a/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala +++ b/compiler/src/dotty/tools/dotc/transform/AugmentScala2Traits.scala @@ -36,7 +36,7 @@ class AugmentScala2Traits extends MiniPhase with IdentityDenotTransformer { this override def phaseName: String = AugmentScala2Traits.name - override def transformTemplate(impl: Template)(implicit ctx: Context): Template = { + override def transformTemplate(impl: Template)(using Context): Template = { val cls = impl.symbol.owner.asClass for (mixin <- cls.mixins) { val erasedMixin = TypeErasure.normalizeClass(mixin) @@ -46,7 +46,7 @@ class AugmentScala2Traits extends MiniPhase with IdentityDenotTransformer { this impl } - private def augmentScala2Trait(mixin: ClassSymbol)(implicit ctx: Context): Unit = { + private def augmentScala2Trait(mixin: ClassSymbol)(using Context): Unit = { def traitSetter(getter: TermSymbol) = getter.copy( name = getter.ensureNotPrivate.name diff --git a/compiler/src/dotty/tools/dotc/transform/Bridges.scala b/compiler/src/dotty/tools/dotc/transform/Bridges.scala index dd95d301f73d..4a24344ed8d4 100644 --- a/compiler/src/dotty/tools/dotc/transform/Bridges.scala +++ b/compiler/src/dotty/tools/dotc/transform/Bridges.scala @@ -11,14 +11,14 @@ import util.Spans.Span import util.SourcePosition /** A helper class for generating bridge methods in class `root`. */ -class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(implicit ctx: Context) { +class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { import ast.tpd._ assert(ctx.phase == ctx.erasurePhase.next) private val preErasureCtx = ctx.withPhase(ctx.erasurePhase) private lazy val elimErasedCtx = ctx.withPhase(ctx.elimErasedValueTypePhase.next) - private class BridgesCursor(implicit ctx: Context) extends OverridingPairs.Cursor(root) { + private class BridgesCursor(using Context) extends OverridingPairs.Cursor(root) { /** Only use the superclass of `root` as a parent class. This means * overriding pairs that have a common implementation in a trait parent @@ -57,9 +57,9 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(implicit ctx: Cont def bridgeExists = bridgesScope.lookupAll(member.name).exists(bridge => bridgeTarget(bridge) == member && bridge.signature == other.signature) - def info(sym: Symbol)(implicit ctx: Context) = sym.info + def info(sym: Symbol)(using Context) = sym.info def desc(sym: Symbol)= { - val infoStr = info(sym)(preErasureCtx) match { + val infoStr = info(sym)(using preErasureCtx) match { case ExprType(info) => i": $info" case info => info.show } @@ -69,7 +69,7 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(implicit ctx: Cont if (!member.info.matches(other.info)) ctx.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)(elimErasedCtx)}."""", + |clashes with definition of the member itself; both have erased type ${info(member)(using elimErasedCtx)}."""", bridgePosFor(member)) } else if (!bridgeExists) @@ -112,7 +112,7 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(implicit ctx: Cont * time deferred methods in `stats` that are replaced by a bridge with the same signature. */ def add(stats: List[untpd.Tree]): List[untpd.Tree] = - val opc = new BridgesCursor()(preErasureCtx) + val opc = new BridgesCursor()(using preErasureCtx) val ectx = ctx.withPhase(thisPhase) while opc.hasNext do if !opc.overriding.is(Deferred) then diff --git a/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala b/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala index 8db79ba87430..81de144ecf00 100644 --- a/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala +++ b/compiler/src/dotty/tools/dotc/transform/ByNameClosures.scala @@ -25,7 +25,7 @@ class ByNameClosures extends TransformByNameApply with IdentityDenotTransformer override def phaseName: String = ByNameClosures.name - override def mkByNameClosure(arg: Tree, argType: Type)(implicit ctx: Context): Tree = { + override def mkByNameClosure(arg: Tree, argType: Type)(using Context): Tree = { val meth = ctx.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/CacheAliasImplicits.scala b/compiler/src/dotty/tools/dotc/transform/CacheAliasImplicits.scala index fcc5327e5080..c4cfe83ae4bb 100644 --- a/compiler/src/dotty/tools/dotc/transform/CacheAliasImplicits.scala +++ b/compiler/src/dotty/tools/dotc/transform/CacheAliasImplicits.scala @@ -46,7 +46,7 @@ class CacheAliasImplicits extends MiniPhase with IdentityDenotTransformer { this override def phaseName: String = CacheAliasImplicits.name - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(tree: DefDef)(using Context): Tree = { val sym = tree.symbol val isCached = !sym.is(Inline) && { sym.info match { diff --git a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala index 201f6c6b04df..01f770a19432 100644 --- a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala +++ b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala @@ -27,12 +27,12 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = // lifting tries changes what variables are considered to be captured private[this] var Captured: Store.Location[collection.Set[Symbol]] = _ - private def captured(implicit ctx: Context) = ctx.store(Captured) + private def captured(using Context) = ctx.store(Captured) override def initContext(ctx: FreshContext): Unit = Captured = ctx.addLocation(Set.empty) - private class RefInfo(implicit ctx: Context) { + private class RefInfo(using Context) { /** The classes for which a Ref type exists. */ val refClassKeys: collection.Set[Symbol] = defn.ScalaNumericValueClasses() `union` Set(defn.BooleanClass, defn.ObjectClass) @@ -48,14 +48,14 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = } private var myRefInfo: RefInfo = null - private def refInfo(implicit ctx: Context) = { + private def refInfo(using Context) = { if (myRefInfo == null) myRefInfo = new RefInfo() myRefInfo } private class CollectCaptured extends TreeTraverser { private val captured = mutable.HashSet[Symbol]() - def traverse(tree: Tree)(implicit ctx: Context) = tree match { + def traverse(tree: Tree)(using Context) = tree match { case id: Ident => val sym = id.symbol if (sym.is(Mutable, butNot = Method) && sym.owner.isTerm) { @@ -68,13 +68,13 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = case _ => traverseChildren(tree) } - def runOver(tree: Tree)(implicit ctx: Context): collection.Set[Symbol] = { + def runOver(tree: Tree)(using Context): collection.Set[Symbol] = { traverse(tree) captured } } - override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = { + override def prepareForUnit(tree: Tree)(using Context): Context = { val captured = (new CollectCaptured) .runOver(ctx.compilationUnit.tpdTree)(using ctx.withPhase(thisPhase)) ctx.fresh.updateStore(Captured, captured) @@ -83,14 +83,14 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = /** The {Volatile|}{Int|Double|...|Object}Ref class corresponding to the class `cls`, * depending on whether the reference should be @volatile */ - def refClass(cls: Symbol, isVolatile: Boolean)(implicit ctx: Context): Symbol = { + def refClass(cls: Symbol, isVolatile: Boolean)(using Context): Symbol = { val refMap = if (isVolatile) refInfo.volatileRefClass else refInfo.refClass if (cls.isClass) refMap.getOrElse(cls, refMap(defn.ObjectClass)) else refMap(defn.ObjectClass) } - override def prepareForValDef(vdef: ValDef)(implicit ctx: Context): Context = { + override def prepareForValDef(vdef: ValDef)(using Context): Context = { val sym = vdef.symbol(using ctx.withPhase(thisPhase)) if (captured contains sym) { val newd = sym.denot(using ctx.withPhase(thisPhase)).copySymDenotation( @@ -102,7 +102,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = ctx } - override def transformValDef(vdef: ValDef)(implicit ctx: Context): Tree = { + override def transformValDef(vdef: ValDef)(using Context): Tree = { val vble = vdef.symbol if (captured.contains(vble)) { def boxMethod(name: TermName): Tree = @@ -114,7 +114,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = else vdef } - override def transformIdent(id: Ident)(implicit ctx: Context): Tree = { + override def transformIdent(id: Ident)(using Context): Tree = { val vble = id.symbol if (captured.contains(vble)) id.select(nme.elem).ensureConforms(vble.denot(using ctx.withPhase(thisPhase)).info) @@ -137,7 +137,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = * Also: If the ref type lhs is followed by a cast (can be an artifact of nested translation), * drop the cast. */ - override def transformAssign(tree: Assign)(implicit ctx: Context): Tree = { + override def transformAssign(tree: Assign)(using Context): Tree = { def recur(lhs: Tree): Tree = lhs match { case TypeApply(Select(qual, nme.asInstanceOf_), _) => val Select(_, nme.elem) = qual diff --git a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala index 8f8158279639..ff2555aed00a 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckReentrant.scala @@ -44,7 +44,7 @@ class CheckReentrant extends MiniPhase { private val scalaJSIRPackageClass = new CtxLazy( summon[Context].getPackageClassIfDefined("org.scalajs.ir")) - def isIgnored(sym: Symbol)(implicit ctx: Context): Boolean = + def isIgnored(sym: Symbol)(using Context): Boolean = sym.hasAnnotation(sharableAnnot()) || sym.hasAnnotation(unsharedAnnot()) || sym.topLevelClass.owner == scalaJSIRPackageClass() || @@ -54,14 +54,14 @@ class CheckReentrant extends MiniPhase { // enum values are initialized eagerly before use // in the long run, we should make them vals - def scanning(sym: Symbol)(op: => Unit)(implicit ctx: Context): Unit = { + def scanning(sym: Symbol)(op: => Unit)(using Context): Unit = { ctx.log(i"${" " * indent}scanning $sym") indent += 1 try op finally indent -= 1 } - def addVars(cls: ClassSymbol)(implicit ctx: Context): Unit = + def addVars(cls: ClassSymbol)(using Context): Unit = if (!seen.contains(cls) && !isIgnored(cls)) { seen += cls scanning(cls) { @@ -82,7 +82,7 @@ class CheckReentrant extends MiniPhase { } } - override def transformTemplate(tree: Template)(implicit ctx: Context): Tree = { + override def transformTemplate(tree: Template)(using Context): Tree = { if (ctx.settings.YcheckReentrant.value && tree.symbol.owner.isStaticOwner) addVars(tree.symbol.owner.asClass) tree diff --git a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala index a5ac68e64f9d..570d7a8e9ec4 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala @@ -29,7 +29,7 @@ class CheckStatic extends MiniPhase { override def phaseName: String = CheckStatic.name - override def transformTemplate(tree: tpd.Template)(implicit ctx: Context): tpd.Tree = { + override def transformTemplate(tree: tpd.Template)(using Context): tpd.Tree = { val defns = tree.body.collect{case t: ValOrDefDef => t} var hadNonStaticField = false for (defn <- defns) @@ -59,7 +59,7 @@ class CheckStatic extends MiniPhase { tree } - override def transformSelect(tree: tpd.Select)(implicit ctx: Context): tpd.Tree = + override def transformSelect(tree: tpd.Select)(using Context): tpd.Tree = if (tree.symbol.hasAnnotation(defn.ScalaStaticAnnot)) { val symbolWhitelist = tree.symbol.ownersIterator.flatMap(x => if (x.is(Flags.Module)) List(x, x.companionModule) else List(x)).toSet def isSafeQual(t: Tree): Boolean = // follow the desugared paths created by typer diff --git a/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala b/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala index 4577f9665d3b..452020044ccb 100644 --- a/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala +++ b/compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala @@ -53,12 +53,12 @@ class CollectNullableFields extends MiniPhase { /** Whether or not a field is nullable */ private var nullability: IdentityHashMap[Symbol, FieldInfo] = _ - override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = { + override def prepareForUnit(tree: Tree)(using Context): Context = { if (nullability == null) nullability = new IdentityHashMap ctx } - private def recordUse(tree: Tree)(implicit ctx: Context): Tree = { + private def recordUse(tree: Tree)(using Context): Tree = { val sym = tree.symbol val isNullablePrivateField = sym.isField && @@ -90,14 +90,14 @@ class CollectNullableFields extends MiniPhase { tree } - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = recordUse(tree) - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = recordUse(tree) /** Map lazy values to the fields they should null after initialization. */ - def lazyValNullables(implicit ctx: Context): IdentityHashMap[Symbol, mutable.ListBuffer[Symbol]] = { + def lazyValNullables(using Context): IdentityHashMap[Symbol, mutable.ListBuffer[Symbol]] = { val result = new IdentityHashMap[Symbol, mutable.ListBuffer[Symbol]] nullability.forEach { diff --git a/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala b/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala index eb8796736ba7..26577ed2af99 100644 --- a/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala +++ b/compiler/src/dotty/tools/dotc/transform/CompleteJavaEnums.scala @@ -35,7 +35,7 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => override def relaxedTypingInGroup: Boolean = true // Because it adds additional parameters to some constructors - def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = + def transformInfo(tp: Type, sym: Symbol)(using Context): Type = if (sym.isConstructor && ( sym == defn.JavaEnumClass.primaryConstructor || sym.owner.derivesFromJavaEnum)) @@ -45,7 +45,7 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => /** Add constructor parameters `$name: String` and `$ordinal: Int` to the end of * the last parameter list of (method- or poly-) type `tp`. */ - private def addConstrParams(tp: Type)(implicit ctx: Context): Type = tp match { + private def addConstrParams(tp: Type)(using Context): Type = tp match { case tp: PolyType => tp.derivedLambdaType(resType = addConstrParams(tp.resType)) case tp: MethodType => @@ -62,7 +62,7 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => /** The list of parameter definitions `$name: String, $ordinal: Int`, in given `owner` * with given flags (either `Param` or `ParamAccessor`) */ - private def addedParams(owner: Symbol, flag: FlagSet)(implicit ctx: Context): List[ValDef] = { + 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) List(ValDef(nameParam), ValDef(ordinalParam)) @@ -71,14 +71,14 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => /** Add arguments `args` to the parent constructor application in `parents` that invokes * a constructor of `targetCls`, */ - private def addEnumConstrArgs(targetCls: Symbol, parents: List[Tree], args: List[Tree])(implicit ctx: Context): List[Tree] = + private def addEnumConstrArgs(targetCls: Symbol, parents: List[Tree], args: List[Tree])(using Context): List[Tree] = parents.map { case app @ Apply(fn, args0) if fn.symbol.owner == targetCls => cpy.Apply(app)(fn, args0 ++ args) case p => p } /** If this is a constructor of a enum class that extends, add $name and $ordinal parameters to it. */ - override def transformDefDef(tree: DefDef)(implicit ctx: Context): DefDef = { + override def transformDefDef(tree: DefDef)(using Context): DefDef = { val sym = tree.symbol if (sym.isConstructor && sym.owner.derivesFromJavaEnum) val tree1 = cpy.DefDef(tree)( @@ -91,7 +91,7 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => /** Return a list of forwarders for enum values defined in the companion object * for java interop. */ - private def addedEnumForwarders(clazz: Symbol)(implicit ctx: Context): List[ValDef] = { + private def addedEnumForwarders(clazz: Symbol)(using Context): List[ValDef] = { val moduleCls = clazz.companionClass val moduleRef = ref(clazz.companionModule) @@ -124,7 +124,7 @@ class CompleteJavaEnums extends MiniPhase with InfoTransformer { thisPhase => * "same as before" * } */ - override def transformTemplate(templ: Template)(implicit ctx: Context): Template = { + override def transformTemplate(templ: Template)(using Context): Template = { val cls = templ.symbol.owner if (cls.derivesFromJavaEnum) { val (params, rest) = decomposeTemplateBody(templ.body) diff --git a/compiler/src/dotty/tools/dotc/transform/Constructors.scala b/compiler/src/dotty/tools/dotc/transform/Constructors.scala index 88c7d4a486da..845f5cb45c4b 100644 --- a/compiler/src/dotty/tools/dotc/transform/Constructors.scala +++ b/compiler/src/dotty/tools/dotc/transform/Constructors.scala @@ -53,7 +53,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = // 3. It is accessed on an object other than `this` // 4. It is a mutable parameter accessor // 5. It is has a wildcard initializer `_` - private def markUsedPrivateSymbols(tree: RefTree)(implicit ctx: Context): Unit = { + private def markUsedPrivateSymbols(tree: RefTree)(using Context): Unit = { val sym = tree.symbol def retain() = retainedPrivateVals.add(sym) @@ -78,17 +78,17 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = } } - override def transformIdent(tree: tpd.Ident)(implicit ctx: Context): tpd.Tree = { + override def transformIdent(tree: tpd.Ident)(using Context): tpd.Tree = { markUsedPrivateSymbols(tree) tree } - override def transformSelect(tree: tpd.Select)(implicit ctx: Context): tpd.Tree = { + override def transformSelect(tree: tpd.Select)(using Context): tpd.Tree = { markUsedPrivateSymbols(tree) tree } - override def transformValDef(tree: tpd.ValDef)(implicit ctx: Context): tpd.Tree = { + override def transformValDef(tree: tpd.ValDef)(using Context): tpd.Tree = { if (mightBeDropped(tree.symbol)) seenPrivateVals += tree.symbol tree } @@ -97,7 +97,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = * All non-abstract methods should be implemented (this is assured for constructors * in this phase and for other methods in memoize). */ - override def checkPostCondition(tree: tpd.Tree)(implicit ctx: Context): Unit = { + override def checkPostCondition(tree: tpd.Tree)(using Context): Unit = { def emptyRhsOK(sym: Symbol) = sym.isOneOf(DeferredOrLazy) || sym.isConstructor && sym.owner.isAllOf(NoInitsTrait) tree match { @@ -112,18 +112,18 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = /** @return true if after ExplicitOuter, all references from this tree go via an * outer link, so no parameter accessors need to be rewired to parameters */ - private def noDirectRefsFrom(tree: Tree)(implicit ctx: Context) = + private def noDirectRefsFrom(tree: Tree)(using Context) = tree.isDef && tree.symbol.isClass /** Class members that can be eliminated if referenced only from their own * constructor. */ - private def mightBeDropped(sym: Symbol)(implicit ctx: Context) = + private def mightBeDropped(sym: Symbol)(using Context) = sym.is(Private, butNot = MethodOrLazy) && !sym.isAllOf(MutableParamAccessor) private final val MutableParamAccessor = Mutable | ParamAccessor - override def transformTemplate(tree: Template)(implicit ctx: Context): Tree = { + override def transformTemplate(tree: Template)(using Context): Tree = { val cls = ctx.owner.asClass val constr @ DefDef(nme.CONSTRUCTOR, Nil, vparams :: Nil, _, EmptyTree) = tree.constr @@ -145,7 +145,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = // (2) If the parameter accessor reference was to an alias getter, // drop the () when replacing by the parameter. object intoConstr extends TreeMap { - override def transform(tree: Tree)(implicit ctx: Context): Tree = tree match { + override def transform(tree: Tree)(using Context): Tree = tree match { case Ident(_) | Select(This(_), _) => var sym = tree.symbol if (sym.is(ParamAccessor, butNot = Mutable)) sym = sym.subst(accessors, paramSyms) @@ -159,7 +159,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = if (noDirectRefsFrom(tree)) tree else super.transform(tree) } - def apply(tree: Tree, prevOwner: Symbol)(implicit ctx: Context): Tree = + def apply(tree: Tree, prevOwner: Symbol)(using Context): Tree = transform(tree).changeOwnerAfter(prevOwner, constr.symbol, thisPhase) } @@ -170,7 +170,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = /** Map outer getters $outer and outer accessors $A$B$$$outer to the given outer parameter. */ def mapOuter(outerParam: Symbol) = new TreeMap { - override def transform(tree: Tree)(implicit ctx: Context) = tree match { + override def transform(tree: Tree)(using Context) = tree match { case Apply(fn, Nil) if (fn.symbol.is(OuterAccessor) || fn.symbol.isGetter && fn.symbol.name == nme.OUTER diff --git a/compiler/src/dotty/tools/dotc/transform/CookComments.scala b/compiler/src/dotty/tools/dotc/transform/CookComments.scala index b57b6f4ee657..c6d81f9d9edd 100644 --- a/compiler/src/dotty/tools/dotc/transform/CookComments.scala +++ b/compiler/src/dotty/tools/dotc/transform/CookComments.scala @@ -7,7 +7,7 @@ import dotty.tools.dotc.typer.Docstrings class CookComments extends MegaPhase.MiniPhase { override def phaseName: String = "cookComments" - override def transformTypeDef(tree: tpd.TypeDef)(implicit ctx: Context): tpd.Tree = { + override def transformTypeDef(tree: tpd.TypeDef)(using Context): tpd.Tree = { if (ctx.settings.YcookComments.value && tree.isClassDef) { val cls = tree.symbol val cookingCtx = ctx.localContext(tree, cls).setNewScope diff --git a/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala b/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala index 83b82dc92475..a4c9406cde30 100644 --- a/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala +++ b/compiler/src/dotty/tools/dotc/transform/CountOuterAccesses.scala @@ -46,7 +46,7 @@ class CountOuterAccesses extends MiniPhase: override def default(s: Symbol): Int = 0 } - private def markAccessed(tree: RefTree)(implicit ctx: Context): Tree = + private def markAccessed(tree: RefTree)(using Context): Tree = val sym = tree.symbol if CountOuterAccesses.mightBeDropped(sym) then outerAccessCount(sym) += 1 tree diff --git a/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala b/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala index 187b4ef90d61..0fc0da4b3e64 100644 --- a/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala +++ b/compiler/src/dotty/tools/dotc/transform/CrossCastAnd.scala @@ -18,7 +18,7 @@ class CrossCastAnd extends MiniPhase { override def phaseName: String = "crossCast" - override def transformSelect(tree: tpd.Select)(implicit ctx: Context): tpd.Tree = { + override def transformSelect(tree: tpd.Select)(using Context): tpd.Tree = { lazy val qtype = tree.qualifier.tpe.widen val sym = tree.symbol diff --git a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala index b49db2b61a8c..6b35ba2dedff 100644 --- a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala +++ b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala @@ -14,7 +14,7 @@ import core.Contexts.{Context, ctx} class CtxLazy[T](expr: Context ?=> T) { private var myValue: T = _ private var forced = false - def apply()(implicit ctx: Context): T = { + def apply()(using Context): T = { if (!forced) { myValue = expr(using ctx) forced = true diff --git a/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled b/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled index 6def243ab0ff..ce63ff87bde8 100644 --- a/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/DropEmptyCompanions.scala.disabled @@ -33,7 +33,7 @@ class DropEmptyCompanions extends MiniPhase { thisTransform => override def phaseName = "dropEmptyCompanions" override def runsAfter = Set(Flatten.name) - override def transformPackageDef(pdef: PackageDef)(implicit ctx: Context) = { + override def transformPackageDef(pdef: PackageDef)(using Context) = { /** Is `tree` an empty companion object? */ def isEmptyCompanion(tree: Tree) = tree match { diff --git a/compiler/src/dotty/tools/dotc/transform/ElimByName.scala b/compiler/src/dotty/tools/dotc/transform/ElimByName.scala index a3afecdf35a4..ddd8d3c6e162 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimByName.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimByName.scala @@ -39,20 +39,20 @@ class ElimByName extends TransformByNameApply with InfoTransformer { override def changesParents: Boolean = true // Only true for by-names /** Map `tree` to `tree.apply()` is `ftree` was of ExprType and becomes now a function */ - private def applyIfFunction(tree: Tree, ftree: Tree)(implicit ctx: Context) = + private def applyIfFunction(tree: Tree, ftree: Tree)(using Context) = if (isByNameRef(ftree)) { val tree0 = transformFollowing(tree) ctx.atPhase(next) { tree0.select(defn.Function0_apply).appliedToNone } } else tree - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = applyIfFunction(tree, tree) - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = applyIfFunction(tree, tree) - override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = tree match { + override def transformTypeApply(tree: TypeApply)(using Context): Tree = tree match { case TypeApply(Select(_, nme.asInstanceOf_), arg :: Nil) => // tree might be of form e.asInstanceOf[x.type] where x becomes a function. // See pos/t296.scala @@ -60,19 +60,19 @@ class ElimByName extends TransformByNameApply with InfoTransformer { case _ => tree } - override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = + override def transformValDef(tree: ValDef)(using Context): Tree = ctx.atPhase(next) { if (exprBecomesFunction(tree.symbol)) cpy.ValDef(tree)(tpt = tree.tpt.withType(tree.symbol.info)) else tree } - def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = tp match { + def transformInfo(tp: Type, sym: Symbol)(using Context): Type = tp match { case ExprType(rt) => defn.FunctionOf(Nil, rt) case _ => tp } - override def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = sym.isTerm && exprBecomesFunction(sym) + override def mayChange(sym: Symbol)(using Context): Boolean = sym.isTerm && exprBecomesFunction(sym) } object ElimByName { diff --git a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala index 200812946f06..6afe1fa8ee03 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala @@ -29,7 +29,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => override def runsAfter: Set[String] = Set(Erasure.name) - def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = sym match { + def transformInfo(tp: Type, sym: Symbol)(using Context): Type = sym match { case sym: ClassSymbol if sym.is(ModuleClass) => sym.companionClass match { case origClass: ClassSymbol if isDerivedValueClass(origClass) => @@ -47,7 +47,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => elimEVT(tp) } - def elimEVT(tp: Type)(implicit ctx: Context): Type = tp match { + def elimEVT(tp: Type)(using Context): Type = tp match { case ErasedValueType(_, underlying) => elimEVT(underlying) case tp: MethodType => @@ -58,10 +58,10 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => tp } - def transformTypeOfTree(tree: Tree)(implicit ctx: Context): Tree = + def transformTypeOfTree(tree: Tree)(using Context): Tree = tree.withType(elimEVT(tree.tpe)) - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = { + override def transformApply(tree: Apply)(using Context): Tree = { val Apply(fun, args) = tree // The casts to and from ErasedValueType are no longer needed once ErasedValueType @@ -77,7 +77,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => /** Check that we don't have pairs of methods that override each other after * this phase, yet do not have matching types before erasure. */ - private def checkNoClashes(root: Symbol)(implicit ctx: Context) = { + 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) @@ -85,7 +85,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => sym1.signature == sym2.signature } - def checkNoConflict(sym1: Symbol, sym2: Symbol, info: Type)(implicit ctx: Context): Unit = { + def checkNoConflict(sym1: Symbol, sym2: Symbol, info: Type)(using Context): Unit = { val site = root.thisType val info1 = site.memberInfo(sym1) val info2 = site.memberInfo(sym2) @@ -110,23 +110,23 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => // 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)(earlyCtx) + checkNoConflict(sym1, sym2, sym1.info)(using earlyCtx) opc.next() } } - override def prepareForTypeDef(tree: TypeDef)(implicit ctx: Context): Context = { + override def prepareForTypeDef(tree: TypeDef)(using Context): Context = { checkNoClashes(tree.symbol) ctx } - override def transformInlined(tree: Inlined)(implicit ctx: Context): Tree = + override def transformInlined(tree: Inlined)(using Context): Tree = transformTypeOfTree(tree) - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = transformTypeOfTree(tree) - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = transformTypeOfTree(tree) - override def transformTypeTree(tree: TypeTree)(implicit ctx: Context): Tree = + override def transformTypeTree(tree: TypeTree)(using Context): Tree = transformTypeOfTree(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala b/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala index 935d89c8949c..bb5c7fdc3454 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimOpaque.scala @@ -28,7 +28,7 @@ class ElimOpaque extends MiniPhase with DenotTransformer { // base types of opaque aliases change override def changesBaseTypes = true - def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = { + def transform(ref: SingleDenotation)(using Context): SingleDenotation = { val sym = ref.symbol ref match { case ref: SymDenotation if sym.isOpaqueAlias => diff --git a/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala b/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala index 7347216cc4dd..9d2a5ac9b2be 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimOuterSelect.scala @@ -22,7 +22,7 @@ class ElimOuterSelect extends MiniPhase { /** Convert a selection of the form `qual.n_` to an outer path from `qual` of * length `n`. */ - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = tree.name match { case OuterSelectName(_, nhops) => val SkolemType(tp) = tree.tpe diff --git a/compiler/src/dotty/tools/dotc/transform/ElimPackagePrefixes.scala b/compiler/src/dotty/tools/dotc/transform/ElimPackagePrefixes.scala index 9cd329fd96b9..9179fb6c2d2c 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimPackagePrefixes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimPackagePrefixes.scala @@ -14,17 +14,17 @@ class ElimPackagePrefixes extends MiniPhase { override def phaseName: String = "elimPackagePrefixes" - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = if (isPackageClassRef(tree)) Ident(tree.tpe.asInstanceOf[TypeRef]) else tree - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = tree match { + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case tree: Select => assert(!isPackageClassRef(tree), i"Unexpected reference to package in $tree") case _ => } /** Is the given tree a reference to a type in a package? */ - private def isPackageClassRef(tree: Select)(implicit ctx: Context): Boolean = tree.tpe match { + private def isPackageClassRef(tree: Select)(using Context): Boolean = tree.tpe match { case TypeRef(prefix, _) => prefix.termSymbol.is(Package) case _ => false } diff --git a/compiler/src/dotty/tools/dotc/transform/ElimPolyFunction.scala b/compiler/src/dotty/tools/dotc/transform/ElimPolyFunction.scala index 6ba6591abc05..c49e8ea651bc 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimPolyFunction.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimPolyFunction.scala @@ -28,7 +28,7 @@ class ElimPolyFunction extends MiniPhase with DenotTransformer { override def changesParents: Boolean = true // Replaces PolyFunction by FunctionN - override def transform(ref: SingleDenotation)(implicit ctx: Context) = ref match { + override def transform(ref: SingleDenotation)(using Context) = ref match { case ref: ClassDenotation if ref.symbol != defn.PolyFunctionClass && ref.derivesFrom(defn.PolyFunctionClass) => val cinfo = ref.classInfo val newParent = functionTypeOfPoly(cinfo) @@ -43,13 +43,13 @@ class ElimPolyFunction extends MiniPhase with DenotTransformer { ref } - def functionTypeOfPoly(cinfo: ClassInfo)(implicit ctx: Context): Type = { + def functionTypeOfPoly(cinfo: ClassInfo)(using Context): Type = { val applyMeth = cinfo.decls.lookup(nme.apply).info val arity = applyMeth.paramNamess.head.length defn.FunctionType(arity) } - override def transformTemplate(tree: Template)(implicit ctx: Context): Tree = { + override def transformTemplate(tree: Template)(using Context): Tree = { val newParents = tree.parents.mapconserve(parent => if (parent.tpe.typeSymbol == defn.PolyFunctionClass) { val cinfo = tree.symbol.owner.asClass.classInfo diff --git a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala index a2e2de4267f2..abbd2a271120 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala @@ -30,10 +30,10 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => override def changesMembers: Boolean = true // the phase adds vararg bridges - def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = + def transformInfo(tp: Type, sym: Symbol)(using Context): Type = elimRepeated(tp) - override def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = + override def transform(ref: SingleDenotation)(using Context): SingleDenotation = super.transform(ref) match { case ref1: SymDenotation if (ref1 ne ref) && overridesJava(ref1.symbol) => // This method won't override the corresponding Java method at the end of this phase, @@ -43,11 +43,11 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => ref1 } - override def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = sym.is(Method) + override def mayChange(sym: Symbol)(using Context): Boolean = sym.is(Method) - private def overridesJava(sym: Symbol)(implicit ctx: Context) = sym.allOverriddenSymbols.exists(_.is(JavaDefined)) + private def overridesJava(sym: Symbol)(using Context) = sym.allOverriddenSymbols.exists(_.is(JavaDefined)) - private def elimRepeated(tp: Type)(implicit ctx: Context): Type = tp.stripTypeVar match { + private def elimRepeated(tp: Type)(using Context): Type = tp.stripTypeVar match { case tp @ MethodTpe(paramNames, paramTypes, resultType) => val resultType1 = elimRepeated(resultType) val paramTypes1 = @@ -63,16 +63,16 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => tp } - def transformTypeOfTree(tree: Tree)(implicit ctx: Context): Tree = + def transformTypeOfTree(tree: Tree)(using Context): Tree = tree.withType(elimRepeated(tree.tpe)) - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = transformTypeOfTree(tree) - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = transformTypeOfTree(tree) - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = { + override def transformApply(tree: Apply)(using Context): Tree = { val args = tree.args.mapConserve { case arg: Typed if isWildcardStarArg(arg) => val isJavaDefined = tree.fun.symbol.is(JavaDefined) @@ -89,7 +89,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => } /** Convert sequence argument to Java array */ - private def seqToArray(tree: Tree)(implicit ctx: Context): Tree = tree match { + private def seqToArray(tree: Tree)(using Context): Tree = tree match { case SeqLiteral(elems, elemtpt) => JavaSeqLiteral(elems, elemtpt) case _ => @@ -103,16 +103,16 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => } /** Convert Java array argument to Scala Seq */ - private def arrayToSeq(tree: Tree)(implicit ctx: Context): Tree = + private def arrayToSeq(tree: Tree)(using Context): Tree = tpd.wrapArray(tree, tree.tpe.elemType) - override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = + override def transformTypeApply(tree: TypeApply)(using Context): Tree = transformTypeOfTree(tree) /** If method overrides a Java varargs method, add a varargs bridge. * Also transform trees inside method annotation */ - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = + override def transformDefDef(tree: DefDef)(using Context): Tree = ctx.atPhase(thisPhase) { if (tree.symbol.info.isVarArgsMethod && overridesJava(tree.symbol)) addVarArgsBridge(tree) @@ -134,7 +134,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => * The solution is to add a "bridge" method that converts its argument from `Array[? <: T]` to `Seq[T]` and * forwards it to `ddef`. */ - private def addVarArgsBridge(ddef: DefDef)(implicit ctx: Context): Tree = { + private def addVarArgsBridge(ddef: DefDef)(using Context): Tree = { val original = ddef.symbol.asTerm val bridge = original.copy( flags = ddef.symbol.flags &~ Private | Artifact, @@ -154,7 +154,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => } /** Convert type from Scala to Java varargs method */ - private def toJavaVarArgs(tp: Type)(implicit ctx: Context): Type = tp match { + private def toJavaVarArgs(tp: Type)(using Context): Type = tp match { case tp: PolyType => tp.derivedLambdaType(tp.paramNames, tp.paramInfos, toJavaVarArgs(tp.resultType)) case tp: MethodType => diff --git a/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala b/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala index f0de00316bcb..b0e13a7d56cf 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimStaticThis.scala @@ -15,14 +15,14 @@ class ElimStaticThis extends MiniPhase { import ast.tpd._ def phaseName: String = "elimStaticThis" - override def transformThis(tree: This)(implicit ctx: Context): Tree = + override def transformThis(tree: This)(using Context): Tree = if (!tree.symbol.is(Package) && ctx.owner.enclosingMethod.is(JavaStatic)) { assert(tree.symbol.is(ModuleClass)) ref(tree.symbol.sourceModule) } else tree - override def transformIdent(tree: tpd.Ident)(implicit ctx: Context): tpd.Tree = + override def transformIdent(tree: tpd.Ident)(using Context): tpd.Tree = if (ctx.owner.enclosingMethod.is(JavaStatic)) tree.tpe match { case TermRef(thiz: ThisType, _) if thiz.cls.is(ModuleClass, JavaDefined) => diff --git a/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala b/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala index 471b20a79e31..103869d41e9e 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExpandPrivate.scala @@ -39,7 +39,7 @@ class ExpandPrivate extends MiniPhase with IdentityDenotTransformer { thisPhase override def changesMembers: Boolean = true // the phase introduces new members with mangled names - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case t: DefDef => val sym = t.symbol @@ -54,7 +54,7 @@ class ExpandPrivate extends MiniPhase with IdentityDenotTransformer { thisPhase case _ => } - private def isVCPrivateParamAccessor(d: SymDenotation)(implicit ctx: Context) = + private def isVCPrivateParamAccessor(d: SymDenotation)(using Context) = d.isTerm && d.isAllOf(PrivateParamAccessor) && isDerivedValueClass(d.owner) /** Make private terms accessed from different classes non-private. @@ -62,7 +62,7 @@ class ExpandPrivate extends MiniPhase with IdentityDenotTransformer { thisPhase * If we change the scheme at one point to make static module class computations * static members of the companion class, we should tighten the condition below. */ - private def ensurePrivateAccessible(d: SymDenotation)(implicit ctx: Context) = + private def ensurePrivateAccessible(d: SymDenotation)(using Context) = if (isVCPrivateParamAccessor(d)) d.ensureNotPrivate.installAfter(thisPhase) else if (d.is(PrivateTerm) && !d.owner.is(Package) && d.owner != ctx.owner.lexicallyEnclosingClass) { @@ -88,17 +88,17 @@ class ExpandPrivate extends MiniPhase with IdentityDenotTransformer { thisPhase d.ensureNotPrivate.installAfter(thisPhase) } - override def transformIdent(tree: Ident)(implicit ctx: Context): Ident = { + override def transformIdent(tree: Ident)(using Context): Ident = { ensurePrivateAccessible(tree.symbol) tree } - override def transformSelect(tree: Select)(implicit ctx: Context): Select = { + override def transformSelect(tree: Select)(using Context): Select = { ensurePrivateAccessible(tree.symbol) tree } - override def transformDefDef(tree: DefDef)(implicit ctx: Context): DefDef = { + override def transformDefDef(tree: DefDef)(using Context): DefDef = { val sym = tree.symbol tree.rhs match { case Apply(sel @ Select(_: Super, _), _) diff --git a/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala b/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala index b053fde4eabc..34974e845452 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala @@ -28,10 +28,10 @@ class ExpandSAMs extends MiniPhase { import ast.tpd._ /** Is the SAMType `cls` also a SAM under the rules of the platform? */ - def isPlatformSam(cls: ClassSymbol)(implicit ctx: Context): Boolean = + def isPlatformSam(cls: ClassSymbol)(using Context): Boolean = ctx.platform.isSam(cls) - override def transformBlock(tree: Block)(implicit ctx: Context): Tree = tree match { + override def transformBlock(tree: Block)(using Context): Tree = tree match { case Block(stats @ (fn: DefDef) :: Nil, Closure(_, fnRef, tpt)) if fnRef.symbol == fn.symbol => tpt.tpe match { case NoType => @@ -93,7 +93,7 @@ class ExpandSAMs extends MiniPhase { * } * ``` */ - private def toPartialFunction(tree: Block, tpe: Type)(implicit ctx: Context): Tree = { + private def toPartialFunction(tree: Block, tpe: Type)(using Context): Tree = { /** An extractor for match, either contained in a block or standalone. */ object PartialFunctionRHS { def unapply(tree: Tree): Option[Match] = tree match { @@ -121,7 +121,7 @@ class ExpandSAMs extends MiniPhase { val isDefinedAtFn = overrideSym(defn.PartialFunction_isDefinedAt) val applyOrElseFn = overrideSym(defn.PartialFunction_applyOrElse) - def translateMatch(tree: Match, pfParam: Symbol, cases: List[CaseDef], defaultValue: Tree)(implicit ctx: Context) = { + 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) @@ -138,7 +138,7 @@ class ExpandSAMs extends MiniPhase { // And we need to update all references to 'param' } - def isDefinedAtRhs(paramRefss: List[List[Tree]])(implicit ctx: Context) = { + def isDefinedAtRhs(paramRefss: List[List[Tree]])(using Context) = { val tru = Literal(Constant(true)) def translateCase(cdef: CaseDef) = cpy.CaseDef(cdef)(body = tru).changeOwner(anonSym, isDefinedAtFn) @@ -147,7 +147,7 @@ class ExpandSAMs extends MiniPhase { translateMatch(pf, paramRef.symbol, pf.cases.map(translateCase), defaultValue) } - def applyOrElseRhs(paramRefss: List[List[Tree]])(implicit ctx: Context) = { + def applyOrElseRhs(paramRefss: List[List[Tree]])(using Context) = { val List(paramRef, defaultRef) = paramRefss.head def translateCase(cdef: CaseDef) = cdef.changeOwner(anonSym, applyOrElseFn) @@ -156,8 +156,8 @@ class ExpandSAMs extends MiniPhase { } val constr = ctx.newConstructor(pfSym, Synthetic, Nil, Nil).entered - val isDefinedAtDef = transformFollowingDeep(DefDef(isDefinedAtFn, isDefinedAtRhs(_)(ctx.withOwner(isDefinedAtFn)))) - val applyOrElseDef = transformFollowingDeep(DefDef(applyOrElseFn, applyOrElseRhs(_)(ctx.withOwner(applyOrElseFn)))) + 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)) cpy.Block(tree)(pfDef :: Nil, New(pfSym.typeRef, Nil)) @@ -168,7 +168,7 @@ class ExpandSAMs extends MiniPhase { } } - private def checkRefinements(tpe: Type, tree: Tree)(implicit ctx: Context): Type = tpe.dealias match { + 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) diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index 33c9004459a2..194175d0b7a6 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -47,7 +47,7 @@ class ExplicitOuter extends MiniPhase with InfoTransformer { thisPhase => override def changesMembers: Boolean = true // the phase adds outer accessors /** Add outer accessors if a class always needs an outer pointer */ - override def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = tp match { + override def transformInfo(tp: Type, sym: Symbol)(using Context): Type = tp match { case tp @ ClassInfo(_, cls, _, decls, _) if needsOuterAlways(cls) => val newDecls = decls.cloneScope newOuterAccessors(cls).foreach(newDecls.enter) @@ -56,7 +56,7 @@ class ExplicitOuter extends MiniPhase with InfoTransformer { thisPhase => tp } - override def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = sym.isClass && !sym.is(JavaDefined) + override def mayChange(sym: Symbol)(using Context): Boolean = sym.isClass && !sym.is(JavaDefined) /** First, add outer accessors if a class does not have them yet and it references an outer this. * If the class has outer accessors, implement them. @@ -69,7 +69,7 @@ class ExplicitOuter extends MiniPhase with InfoTransformer { thisPhase => * a separate phase which needs to run after erasure. However, we make sure here * that the super class constructor is indeed a New, and not just a type. */ - override def transformTemplate(impl: Template)(implicit ctx: Context): Tree = { + override def transformTemplate(impl: Template)(using Context): Tree = { val cls = ctx.owner.asClass val isTrait = cls.is(Trait) if (needsOuterIfReferenced(cls) && @@ -110,7 +110,7 @@ class ExplicitOuter extends MiniPhase with InfoTransformer { thisPhase => else impl } - override def transformClosure(tree: Closure)(implicit ctx: Context): tpd.Tree = { + override def transformClosure(tree: Closure)(using Context): tpd.Tree = { if (tree.tpt ne EmptyTree) { val cls = tree.tpt.asInstanceOf[TypeTree].tpe.classSymbol if (cls.exists && hasOuter(cls.asClass)) @@ -126,20 +126,20 @@ object ExplicitOuter { val name: String = "explicitOuter" /** Ensure that class `cls` has outer accessors */ - def ensureOuterAccessors(cls: ClassSymbol)(implicit ctx: Context): Unit = + def ensureOuterAccessors(cls: ClassSymbol)(using Context): Unit = ctx.atPhase(ctx.explicitOuterPhase.next) { if (!hasOuter(cls)) newOuterAccessors(cls).foreach(_.enteredAfter(ctx.explicitOuterPhase.asInstanceOf[DenotTransformer])) } /** The outer accessor and potentially outer param accessor needed for class `cls` */ - private def newOuterAccessors(cls: ClassSymbol)(implicit ctx: Context) = + private def newOuterAccessors(cls: ClassSymbol)(using Context) = newOuterAccessor(cls, cls) :: (if (cls.is(Trait)) Nil else newOuterParamAccessor(cls) :: Nil) /** Scala 2.x and Dotty don't always agree on what should be the type of the outer parameter, * so we replicate the old behavior when passing arguments to methods coming from Scala 2.x. */ - private def outerClass(cls: ClassSymbol)(implicit ctx: Context): Symbol = { + private def outerClass(cls: ClassSymbol)(using Context): Symbol = { val encl = cls.owner.enclosingClass if (cls.is(Scala2x)) encl.asClass.classInfo.selfInfo match { @@ -163,7 +163,7 @@ object ExplicitOuter { * base type of P.this wrt class O * - otherwise O[?, ..., ?] */ - private def newOuterSym(owner: ClassSymbol, cls: ClassSymbol, name: TermName, flags: FlagSet)(implicit ctx: Context) = { + private def newOuterSym(owner: ClassSymbol, cls: ClassSymbol, name: TermName, flags: FlagSet)(using Context) = { val outerThis = owner.owner.enclosingClass.thisType val outerCls = outerClass(cls) val target = @@ -178,22 +178,22 @@ object ExplicitOuter { } /** A new param accessor for the outer field in class `cls` */ - private def newOuterParamAccessor(cls: ClassSymbol)(implicit ctx: Context) = + private def newOuterParamAccessor(cls: ClassSymbol)(using Context) = newOuterSym(cls, cls, nme.OUTER, Private | Local | ParamAccessor) /** A new outer accessor for class `cls` which is a member of `owner` */ - private def newOuterAccessor(owner: ClassSymbol, cls: ClassSymbol)(implicit ctx: Context) = { + private def newOuterAccessor(owner: ClassSymbol, cls: ClassSymbol)(using Context) = { val deferredIfTrait = if (owner.is(Trait)) Deferred else EmptyFlags val outerAccIfOwn = if (owner == cls) OuterAccessor else EmptyFlags newOuterSym(owner, cls, outerAccName(cls), Final | Method | StableRealizable | outerAccIfOwn | deferredIfTrait) } - private def outerAccName(cls: ClassSymbol)(implicit ctx: Context): TermName = + private def outerAccName(cls: ClassSymbol)(using Context): TermName = nme.OUTER.expandedName(cls) /** Class needs an outer pointer, provided there is a reference to an outer this in it. */ - def needsOuterIfReferenced(cls: ClassSymbol)(implicit ctx: Context): Boolean = + def needsOuterIfReferenced(cls: ClassSymbol)(using Context): Boolean = !(cls.isStatic || cls.owner.enclosingClass.isStaticOwner || cls.is(PureInterface) @@ -204,7 +204,7 @@ object ExplicitOuter { * - we might not know at all instantiation sites whether outer is referenced or not * - we need to potentially pass along outer to a parent class or trait */ - private def needsOuterAlways(cls: ClassSymbol)(implicit ctx: Context): Boolean = + private def needsOuterAlways(cls: ClassSymbol)(using Context): Boolean = needsOuterIfReferenced(cls) && (!hasLocalInstantiation(cls) || // needs outer because we might not know whether outer is referenced or not cls.mixins.exists(needsOuterIfReferenced) || // needs outer for parent traits @@ -212,13 +212,13 @@ object ExplicitOuter { needsOuterIfReferenced(parent.classSymbol.asClass))) /** Class is always instantiated in the compilation unit where it is defined */ - private def hasLocalInstantiation(cls: ClassSymbol)(implicit ctx: Context): Boolean = + private def hasLocalInstantiation(cls: ClassSymbol)(using Context): Boolean = // scala2x modules always take an outer pointer(as of 2.11) // dotty modules are always locally instantiated cls.owner.isTerm || cls.is(Private) || cls.is(Module, butNot = Scala2x) /** The outer parameter accessor of cass `cls` */ - private def outerParamAccessor(cls: ClassSymbol)(implicit ctx: Context): TermSymbol = + private def outerParamAccessor(cls: ClassSymbol)(using Context): TermSymbol = cls.info.decl(nme.OUTER).symbol.asTerm /** The outer accessor of class `cls`. To find it is a bit tricky. The @@ -230,22 +230,22 @@ object ExplicitOuter { * result is phase dependent. In that case we use a backup strategy where we search all * definitions in the class to find the one with the OuterAccessor flag. */ - def outerAccessor(cls: ClassSymbol)(implicit ctx: Context): Symbol = + def outerAccessor(cls: ClassSymbol)(using Context): Symbol = if (cls.isStatic) NoSymbol // fast return to avoid scanning package decls else cls.info.member(outerAccName(cls)).suchThat(_.is(OuterAccessor)).symbol orElse cls.info.decls.find(_.is(OuterAccessor)) /** Class has an outer accessor. Can be called only after phase ExplicitOuter. */ - private def hasOuter(cls: ClassSymbol)(implicit ctx: Context): Boolean = + private def hasOuter(cls: ClassSymbol)(using Context): Boolean = needsOuterIfReferenced(cls) && outerAccessor(cls).exists /** Class constructor takes an outer argument. Can be called only after phase ExplicitOuter. */ - def hasOuterParam(cls: ClassSymbol)(implicit ctx: Context): Boolean = + def hasOuterParam(cls: ClassSymbol)(using Context): Boolean = !cls.is(Trait) && needsOuterIfReferenced(cls) && outerAccessor(cls).exists /** Tree references an outer class of `cls` which is not a static owner. */ - def referencesOuter(cls: Symbol, tree: Tree)(implicit ctx: Context): Boolean = { + def referencesOuter(cls: Symbol, tree: Tree)(using Context): Boolean = { def isOuterSym(sym: Symbol) = !sym.isStaticOwner && cls.isProperlyContainedIn(sym) def isOuterRef(ref: Type): Boolean = ref match { @@ -290,7 +290,7 @@ object ExplicitOuter { private final val HoistableFlags = Method | Lazy | Module /** The outer prefix implied by type `tpe` */ - private def outerPrefix(tpe: Type)(implicit ctx: Context): Type = tpe match { + private def outerPrefix(tpe: Type)(using Context): Type = tpe match { case tpe: TypeRef => tpe.symbol match { case cls: ClassSymbol => @@ -314,7 +314,7 @@ object ExplicitOuter { * in the first place. I was not yet able to find out how such references * arise and how to avoid them. */ - private def fixThis(tpe: Type)(implicit ctx: Context): Type = tpe match { + private def fixThis(tpe: Type)(using Context): Type = tpe match { case tpe: ThisType if tpe.cls.is(Module) && !ctx.owner.isContainedIn(tpe.cls) => fixThis(tpe.cls.owner.thisType.select(tpe.cls.sourceModule.asTerm)) case tpe: TermRef => @@ -326,7 +326,7 @@ object ExplicitOuter { def (sym: Symbol).isOuterParamAccessor(using Context): Boolean = sym.is(ParamAccessor) && sym.name == nme.OUTER - def outer(implicit ctx: Context): OuterOps = new OuterOps(ctx) + def outer(using Context): OuterOps = new OuterOps(ctx) /** The operations in this class * - add outer parameters @@ -396,7 +396,7 @@ object ExplicitOuter { @tailrec def loop(tree: Tree, count: Int): Tree = val treeCls = tree.tpe.widen.classSymbol val outerAccessorCtx = ctx.withPhaseNoLater(ctx.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)(outerAccessorCtx)} in $treeCls") + ctx.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 diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala index d749c14547c1..7d3aa1d45e4e 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitSelf.scala @@ -26,14 +26,14 @@ class ExplicitSelf extends MiniPhase { override def phaseName: String = "explicitSelf" - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = tree.tpe match { + override def transformIdent(tree: Ident)(using Context): Tree = tree.tpe match { case tp: ThisType => ctx.debuglog(s"owner = ${ctx.owner}, context = ${ctx}") This(tp.cls).withSpan(tree.span) case _ => tree } - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = tree match { + override def transformSelect(tree: Select)(using Context): Tree = tree match { case Select(thiz: This, name) if name.isTermName => val cls = thiz.symbol.asClass if (cls.givenSelfType.exists && !cls.derivesFrom(tree.symbol.owner)) diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index 71b3251eb4f7..eb056c77e81b 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -53,7 +53,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete override def changesMembers: Boolean = true // the phase adds extension methods - override def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = ref match { + override def transform(ref: SingleDenotation)(using Context): SingleDenotation = ref match { case moduleClassSym: ClassDenotation if moduleClassSym.is(ModuleClass) => moduleClassSym.linkedClass match { case valueClass: ClassSymbol if isDerivedValueClass(valueClass) => @@ -125,12 +125,12 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete } } - protected def rewiredTarget(target: Symbol, derived: Symbol)(implicit ctx: Context): Symbol = + protected def rewiredTarget(target: Symbol, derived: Symbol)(using Context): Symbol = if (isMethodWithExtension(target) && target.owner.linkedClass == derived.owner) extensionMethod(target) else NoSymbol - private def createExtensionMethod(imeth: Symbol, staticClass: Symbol)(implicit ctx: Context): TermSymbol = { + private def createExtensionMethod(imeth: Symbol, staticClass: Symbol)(using Context): TermSymbol = { val extensionMeth = ctx.newSymbol(staticClass, extensionName(imeth), (imeth.flags | Final) &~ (Override | Protected | AbsOverride), fullyParameterizedType(imeth.info, imeth.owner.asClass), @@ -144,7 +144,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete // TODO: this is state and should be per-run // todo: check that when transformation finished map is empty - override def transformTemplate(tree: tpd.Template)(implicit ctx: Context): tpd.Tree = + override def transformTemplate(tree: tpd.Template)(using Context): tpd.Tree = if (isDerivedValueClass(ctx.owner)) /* This is currently redundant since value classes may not wrap over other value classes anyway. @@ -160,7 +160,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete } else tree - override def transformDefDef(tree: tpd.DefDef)(implicit ctx: Context): tpd.Tree = + override def transformDefDef(tree: tpd.DefDef)(using Context): tpd.Tree = if (isMethodWithExtension(tree.symbol)) { val origMeth = tree.symbol val origClass = ctx.owner.asClass @@ -179,11 +179,11 @@ object ExtensionMethods { val name: String = "extmethods" /** Name of the extension method that corresponds to given instance method `meth`. */ - def extensionName(imeth: Symbol)(implicit ctx: Context): TermName = + def extensionName(imeth: Symbol)(using Context): TermName = ExtMethName(imeth.name.asTermName) /** Return the extension method that corresponds to given instance method `meth`. */ - def extensionMethod(imeth: Symbol)(implicit ctx: Context): TermSymbol = + def extensionMethod(imeth: Symbol)(using Context): TermSymbol = ctx.atPhase(ctx.extensionMethodsPhase.next) { // FIXME use toStatic instead? val companion = imeth.owner.companionModule diff --git a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala index fd32c22ae276..c1e82b2bbb57 100644 --- a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala @@ -39,16 +39,16 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => override def phaseName: String = FirstTransform.name /** eliminate self symbol in ClassInfo */ - override def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type = tp match { + override def transformInfo(tp: Type, sym: Symbol)(using Context): Type = tp match { case tp @ ClassInfo(_, _, _, _, self: Symbol) => tp.derivedClassInfo(selfInfo = self.info) case _ => tp } - override protected def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = sym.isClass + override protected def mayChange(sym: Symbol)(using Context): Boolean = sym.isClass - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case Select(qual, name) if !name.is(OuterSelectName) && tree.symbol.exists => val qualTpe = if (ctx.explicitNulls) { @@ -77,7 +77,7 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => } /** Reorder statements so that module classes always come after their companion classes */ - private def reorderAndComplete(stats: List[Tree])(implicit ctx: Context): List[Tree] = { + private def reorderAndComplete(stats: List[Tree])(using Context): List[Tree] = { val moduleClassDefs, singleClassDefs = mutable.Map[Name, Tree]() /* Returns the result of reordering stats and prepending revPrefix in reverse order to it. @@ -113,10 +113,10 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => } /** eliminate self in Template */ - override def transformTemplate(impl: Template)(implicit ctx: Context): Tree = + override def transformTemplate(impl: Template)(using Context): Tree = cpy.Template(impl)(self = EmptyValDef) - override def transformDefDef(ddef: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(ddef: DefDef)(using Context): Tree = { val meth = ddef.symbol.asTerm if (meth.hasAnnotation(defn.NativeAnnot)) { meth.resetFlag(Deferred) @@ -128,11 +128,11 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => else ddef } - override def transformStats(trees: List[Tree])(implicit ctx: Context): List[Tree] = + override def transformStats(trees: List[Tree])(using Context): List[Tree] = ast.Trees.flatten(reorderAndComplete(trees)(using ctx.withPhase(thisPhase.next))) private object collectBinders extends TreeAccumulator[List[Ident]] { - def apply(annots: List[Ident], t: Tree)(implicit ctx: Context): List[Ident] = t match { + def apply(annots: List[Ident], t: Tree)(using Context): List[Ident] = t match { case t @ Bind(_, body) => val annot = untpd.Ident(tpnme.BOUNDTYPE_ANNOT).withType(t.symbol.typeRef) apply(annot :: annots, body) @@ -145,19 +145,19 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => * nested Bind nodes in annotations. These are interpreted in TreeTypeMaps * so that bound symbols can be properly copied. */ - private def toTypeTree(tree: Tree)(implicit ctx: Context) = { + private def toTypeTree(tree: Tree)(using Context) = { val binders = collectBinders.apply(Nil, tree) val result: Tree = TypeTree(tree.tpe).withSpan(tree.span) binders.foldLeft(result)(Annotated(_, _)) } - override def transformOther(tree: Tree)(implicit ctx: Context): Tree = tree match { + override def transformOther(tree: Tree)(using Context): Tree = tree match { case tree: Import => EmptyTree case tree: NamedArg => transformAllDeep(tree.arg) case tree => if (tree.isType) toTypeTree(tree) else tree } - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = if (tree.isType) { toTypeTree(tree) } else if (tree.name != nme.WILDCARD) { @@ -169,24 +169,24 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => constToLiteral(tree) } else tree - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = if (tree.isType) toTypeTree(tree) else constToLiteral(tree) - override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = + override def transformTypeApply(tree: TypeApply)(using Context): Tree = constToLiteral(tree) - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = + override def transformApply(tree: Apply)(using Context): Tree = constToLiteral(foldCondition(tree)) - override def transformTyped(tree: Typed)(implicit ctx: Context): Tree = + override def transformTyped(tree: Typed)(using Context): Tree = // Singleton type cases (such as `case _: "a"`) are constant-foldable. // We avoid constant-folding those as doing so would change the meaning of the pattern (see transformIdent). if (!ctx.mode.is(Mode.Pattern)) constToLiteral(tree) else tree - override def transformBlock(tree: Block)(implicit ctx: Context): Tree = + override def transformBlock(tree: Block)(using Context): Tree = constToLiteral(tree) - override def transformIf(tree: If)(implicit ctx: Context): Tree = + override def transformIf(tree: If)(using Context): Tree = tree.cond.tpe match { case ConstantType(Constant(c: Boolean)) if isPureExpr(tree.cond) => if (c) tree.thenp else tree.elsep @@ -200,7 +200,7 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => * true || y ==> true * false || y ==> y */ - private def foldCondition(tree: Apply)(implicit ctx: Context) = tree.fun match { + private def foldCondition(tree: Apply)(using Context) = tree.fun match { case Select(x @ Literal(Constant(c: Boolean)), op) => tree.args match { case y :: Nil if y.tpe.widen.isRef(defn.BooleanClass) => diff --git a/compiler/src/dotty/tools/dotc/transform/Flatten.scala b/compiler/src/dotty/tools/dotc/transform/Flatten.scala index f2e86c30eff5..a43eb53bba4a 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, FreshContext} +import Contexts.{Context, ctx, FreshContext} import Flags._ import SymDenotations.SymDenotation import collection.mutable @@ -23,29 +23,29 @@ class Flatten extends MiniPhase with SymTransformer { override def changesMembers: Boolean = true // the phase removes inner classes private var LiftedDefs: Store.Location[mutable.ListBuffer[Tree]] = _ - private def liftedDefs(implicit ctx: Context) = ctx.store(LiftedDefs) + private def liftedDefs(using Context) = ctx.store(LiftedDefs) override def initContext(ctx: FreshContext): Unit = LiftedDefs = ctx.addLocation[mutable.ListBuffer[Tree]](null) - def transformSym(ref: SymDenotation)(implicit ctx: Context): SymDenotation = + def transformSym(ref: SymDenotation)(using Context): SymDenotation = if (ref.isClass && !ref.is(Package) && !ref.owner.is(Package)) ref.copySymDenotation( name = ref.flatName, owner = ref.enclosingPackageClass) else ref - override def prepareForPackageDef(tree: PackageDef)(implicit ctx: Context): FreshContext = + override def prepareForPackageDef(tree: PackageDef)(using Context): FreshContext = ctx.fresh.updateStore(LiftedDefs, new mutable.ListBuffer[Tree]) - private def liftIfNested(tree: Tree)(implicit ctx: Context) = + private def liftIfNested(tree: Tree)(using Context) = if (ctx.owner.is(Package)) tree else { transformFollowing(tree).foreachInThicket(liftedDefs += _) EmptyTree } - override def transformStats(stats: List[Tree])(implicit ctx: Context): List[Tree] = + override def transformStats(stats: List[Tree])(using Context): List[Tree] = if (ctx.owner.is(Package)) { val liftedStats = stats ++ liftedDefs liftedDefs.clear() @@ -53,6 +53,6 @@ class Flatten extends MiniPhase with SymTransformer { } else stats - override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree = + override def transformTypeDef(tree: TypeDef)(using Context): Tree = liftIfNested(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala b/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala index 46d3180e1b94..e9b0b228502f 100644 --- a/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala +++ b/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala @@ -57,7 +57,7 @@ trait FullParameterization { * `derived` should be rewired to some fully parameterized method, the rewiring target symbol, * otherwise NoSymbol. */ - protected def rewiredTarget(referenced: Symbol, derived: Symbol)(implicit ctx: Context): Symbol + protected def rewiredTarget(referenced: Symbol, derived: Symbol)(using Context): Symbol /** If references to some original symbol from given tree node within fully parameterized method * `derived` should be rewired to some fully parameterized method, the rewiring target symbol, @@ -67,7 +67,7 @@ trait FullParameterization { * * but can be overridden. */ - protected def rewiredTarget(tree: Tree, derived: Symbol)(implicit ctx: Context): Symbol = + protected def rewiredTarget(tree: Tree, derived: Symbol)(using Context): Symbol = rewiredTarget(tree.symbol, derived) /** Converts the type `info` of a member of class `clazz` to a method type that @@ -90,7 +90,7 @@ trait FullParameterization { * @param liftThisType if true, require created $this to be $this: (Foo[A] & Foo,this). * This is needed if created member stays inside scope of Foo(as in tailrec) */ - def fullyParameterizedType(info: Type, clazz: ClassSymbol, abstractOverClass: Boolean = true, liftThisType: Boolean = false)(implicit ctx: Context): Type = { + def fullyParameterizedType(info: Type, clazz: ClassSymbol, abstractOverClass: Boolean = true, liftThisType: Boolean = false)(using Context): Type = { val (mtparamCount, origResult) = info match { case info: PolyType => (info.paramNames.length, info.resultType) case info: ExprType => (0, info.resultType) @@ -134,7 +134,7 @@ trait FullParameterization { /** The type parameters (skolems) of the method definition `originalDef`, * followed by the class parameters of its enclosing class. */ - private def allInstanceTypeParams(originalDef: DefDef, abstractOverClass: Boolean)(implicit ctx: Context): List[Symbol] = + private def allInstanceTypeParams(originalDef: DefDef, abstractOverClass: Boolean)(using Context): List[Symbol] = if (abstractOverClass) originalDef.tparams.map(_.symbol) ::: originalDef.symbol.enclosingClass.typeParams else originalDef.tparams.map(_.symbol) @@ -146,7 +146,7 @@ trait FullParameterization { * `abstractOverClass` defines weather the DefDef should abstract over type parameters * of class that contained original defDef */ - def fullyParameterizedDef(derived: TermSymbol, originalDef: DefDef, abstractOverClass: Boolean = true)(implicit ctx: Context): Tree = + def fullyParameterizedDef(derived: TermSymbol, originalDef: DefDef, abstractOverClass: Boolean = true)(using Context): Tree = polyDefDef(derived, trefs => vrefss => { val origMeth = originalDef.symbol val origClass = origMeth.enclosingClass.asClass @@ -157,7 +157,7 @@ trait FullParameterization { /** If tree should be rewired, the rewired tree, otherwise EmptyTree. * @param targs Any type arguments passed to the rewired tree. */ - def rewireTree(tree: Tree, targs: List[Tree])(implicit ctx: Context): Tree = { + def rewireTree(tree: Tree, targs: List[Tree])(using Context): Tree = { def rewireCall(thisArg: Tree): Tree = { val rewired = rewiredTarget(tree, derived) if (rewired.exists) { @@ -220,7 +220,7 @@ trait FullParameterization { * - the `this` of the enclosing class, * - the value parameters of the original method `originalDef`. */ - def forwarder(derived: TermSymbol, originalDef: DefDef, abstractOverClass: Boolean = true, liftThisType: Boolean = false)(implicit ctx: Context): Tree = { + def forwarder(derived: TermSymbol, originalDef: DefDef, abstractOverClass: Boolean = true, liftThisType: Boolean = false)(using Context): Tree = { val fun = ref(derived.termRef) .appliedToTypes(allInstanceTypeParams(originalDef, abstractOverClass).map(_.typeRef)) @@ -257,7 +257,7 @@ object FullParameterization { * unpickled from Scala 2 (because Scala 2 extmeths phase happens before * pickling, which is maybe something we should change for 2.14). */ - def memberSignature(info: Type)(implicit ctx: Context): Signature = info match { + def memberSignature(info: Type)(using Context): Signature = info match { case info: PolyType => memberSignature(info.resultType) case MethodTpe(nme.SELF :: Nil, _, restpe) => diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala index d2bb92569586..4d1045c33d43 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionXXLForwarders.scala @@ -27,7 +27,7 @@ class FunctionXXLForwarders extends MiniPhase with IdentityDenotTransformer { override def phaseName: String = "functionXXLForwarders" - override def transformTemplate(impl: Template)(implicit ctx: Context): Template = { + override def transformTemplate(impl: Template)(using Context): Template = { def forwarderRhs(receiver: Tree, xsTree: Tree): Tree = { val argsApply = ref(xsTree.symbol).select(nme.apply) diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala index bd4d4f01468f..7dda4cf97d89 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala @@ -26,7 +26,7 @@ class FunctionalInterfaces extends MiniPhase { private val functionName = "JFunction".toTermName private val functionPackage = "dotty.runtime.function.".toTermName - override def transformClosure(tree: Closure)(implicit ctx: Context): Tree = { + override def transformClosure(tree: Closure)(using Context): Tree = { val cls = tree.tpe.widen.classSymbol.asClass val implType = tree.meth.tpe.widen From 7366f5c163a896a8792d0e5e134e7bb506de52b1 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 17:03:01 +0200 Subject: [PATCH 22/41] Convert transform classes (2) --- .../dotc/transform/GenericSignatures.scala | 22 +- .../dotty/tools/dotc/transform/Getters.scala | 6 +- .../tools/dotc/transform/HoistSuperArgs.scala | 4 +- .../dotc/transform/Instrumentation.scala | 10 +- .../dotc/transform/InterceptedMethods.scala | 10 +- .../IsInstanceOfEvaluator.scala.disabled | 2 +- .../tools/dotc/transform/LambdaLift.scala | 58 +- .../dotty/tools/dotc/transform/LazyVals.scala | 30 +- .../dotty/tools/dotc/transform/LiftTry.scala | 16 +- .../dotc/transform/LinkScala2Impls.scala | 8 +- .../dotc/transform/Literalize.scala.disabled | 14 +- .../tools/dotc/transform/MacroTransform.scala | 12 +- .../tools/dotc/transform/MegaPhase.scala | 526 +++++++++--------- .../dotty/tools/dotc/transform/Memoize.scala | 4 +- .../tools/dotc/transform/ReifyQuotes.scala | 2 +- .../dotty/tools/dotc/transform/Staging.scala | 2 +- 16 files changed, 363 insertions(+), 363 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala index 98a89287d829..640099529533 100644 --- a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala +++ b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala @@ -31,13 +31,13 @@ object GenericSignatures { * @param info The type of the symbol * @return The signature if it could be generated, `None` otherwise. */ - def javaSig(sym0: Symbol, info: Type)(implicit ctx: Context): Option[String] = + def javaSig(sym0: Symbol, info: Type)(using Context): Option[String] = // Avoid generating a signature for local symbols. if (sym0.isLocal) None else javaSig0(sym0, info)(using ctx.withPhase(ctx.erasurePhase)) @noinline - private final def javaSig0(sym0: Symbol, info: Type)(implicit ctx: Context): Option[String] = { + private final def javaSig0(sym0: Symbol, info: Type)(using Context): Option[String] = { val builder = new StringBuilder(64) val isTraitSignature = sym0.enclosingClass.is(Trait) @@ -247,7 +247,7 @@ object GenericSignatures { case mtpe: MethodType => // erased method parameters do not make it to the bytecode. - def effectiveParamInfoss(t: Type)(implicit ctx: Context): List[List[Type]] = t match { + def effectiveParamInfoss(t: Type)(using Context): List[List[Type]] = t match { case t: MethodType if t.isErasedMethod => effectiveParamInfoss(t.resType) case t: MethodType => t.paramInfos :: effectiveParamInfoss(t.resType) case _ => Nil @@ -319,7 +319,7 @@ object GenericSignatures { * not Object, the dominator is Tc. <--- @PP: "which is not Object" not in spec. * - Otherwise, the dominator is the first element of the span. */ - private def intersectionDominator(parents: List[Type])(implicit ctx: Context): Type = + private def intersectionDominator(parents: List[Type])(using Context): Type = if (parents.isEmpty) defn.ObjectType else { val psyms = parents map (_.typeSymbol) @@ -342,7 +342,7 @@ object GenericSignatures { /* Drop redundant types (ones which are implemented by some other parent) from the immediate parents. * This is important on Android because there is otherwise an interface explosion. */ - private def minimizeParents(cls: Symbol, parents: List[Type])(implicit ctx: Context): List[Type] = if (parents.isEmpty) parents else { + private def minimizeParents(cls: Symbol, parents: List[Type])(using Context): List[Type] = if (parents.isEmpty) parents else { // val requiredDirect: Symbol => Boolean = requiredDirectInterfaces.getOrElse(cls, Set.empty) var rest = parents.tail var leaves = collection.mutable.ListBuffer.empty[Type] += parents.head @@ -364,7 +364,7 @@ object GenericSignatures { leaves.toList } - private def hiBounds(bounds: TypeBounds)(implicit ctx: Context): List[Type] = bounds.hi.widenDealias match { + private def hiBounds(bounds: TypeBounds)(using Context): List[Type] = bounds.hi.widenDealias match { case AndType(tp1, tp2) => hiBounds(tp1.bounds) ::: hiBounds(tp2.bounds) case tp => tp :: Nil } @@ -374,7 +374,7 @@ object GenericSignatures { // * higher-order type parameters // * type parameters appearing in method parameters // * type members not visible in an enclosing template - private def isTypeParameterInSig(sym: Symbol, initialSymbol: Symbol)(implicit ctx: Context) = + private def isTypeParameterInSig(sym: Symbol, initialSymbol: Symbol)(using Context) = !sym.maybeOwner.isTypeParam && sym.isTypeParam && ( sym.isContainedIn(initialSymbol.topLevelClass) || @@ -390,13 +390,13 @@ object GenericSignatures { // included (use pre.baseType(cls.owner)). // // This requires that cls.isClass. - private def rebindInnerClass(pre: Type, cls: Symbol)(implicit ctx: Context): Type = { + private def rebindInnerClass(pre: Type, cls: Symbol)(using Context): Type = { val owner = cls.owner if (owner.is(PackageClass) || owner.isTerm) pre else cls.owner.info /* .tpe_* */ } private object RefOrAppliedType { - def unapply(tp: Type)(implicit ctx: Context): Option[(Symbol, Type, List[Type])] = tp match { + def unapply(tp: Type)(using Context): Option[(Symbol, Type, List[Type])] = tp match { case TypeParamRef(_, _) => Some((tp.typeSymbol, tp, Nil)) case TermParamRef(_, _) => @@ -411,12 +411,12 @@ object GenericSignatures { } } - private def needsJavaSig(tp: Type, throwsArgs: List[Type])(implicit ctx: Context): Boolean = !ctx.settings.YnoGenericSig.value && { + private def needsJavaSig(tp: Type, throwsArgs: List[Type])(using Context): Boolean = !ctx.settings.YnoGenericSig.value && { def needs(tp: Type) = (new NeedsSigCollector).apply(false, tp) needs(tp) || throwsArgs.exists(needs) } - private class NeedsSigCollector(implicit ctx: Context) extends TypeAccumulator[Boolean] { + private class NeedsSigCollector(using Context) extends TypeAccumulator[Boolean] { override def apply(x: Boolean, tp: Type): Boolean = if (!x) tp match { diff --git a/compiler/src/dotty/tools/dotc/transform/Getters.scala b/compiler/src/dotty/tools/dotc/transform/Getters.scala index 1e44d7e0ac66..a9d30a1f9330 100644 --- a/compiler/src/dotty/tools/dotc/transform/Getters.scala +++ b/compiler/src/dotty/tools/dotc/transform/Getters.scala @@ -62,7 +62,7 @@ class Getters extends MiniPhase with SymTransformer { thisPhase => override def phaseName: String = Getters.name - override def transformSym(d: SymDenotation)(implicit ctx: Context): SymDenotation = { + override def transformSym(d: SymDenotation)(using Context): SymDenotation = { def noGetterNeeded = d.isOneOf(NoGetterNeededFlags) || d.isAllOf(PrivateLocal) && !d.owner.is(Trait) && !isDerivedValueClass(d.owner) && !d.is(Lazy) || @@ -100,7 +100,7 @@ class Getters extends MiniPhase with SymTransformer { thisPhase => info = MethodType(sym.info.widenExpr :: Nil, defn.UnitType) ).enteredAfter(thisPhase) - override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = + override def transformValDef(tree: ValDef)(using Context): Tree = val sym = tree.symbol if !sym.is(Method) then return tree val getterDef = DefDef(sym.asTerm, tree.rhs).withSpan(tree.span) @@ -110,7 +110,7 @@ class Getters extends MiniPhase with SymTransformer { thisPhase => val setterDef = DefDef(sym.setter.asTerm, unitLiteral) Thicket(getterDef, setterDef) - override def transformAssign(tree: Assign)(implicit ctx: Context): Tree = + override def transformAssign(tree: Assign)(using Context): Tree = val lsym = tree.lhs.symbol.asTerm if (lsym.is(Method)) ensureSetter(lsym) diff --git a/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala b/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala index 7fd6c15375fe..8bf263ec538a 100644 --- a/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala +++ b/compiler/src/dotty/tools/dotc/transform/HoistSuperArgs.scala @@ -54,7 +54,7 @@ class HoistSuperArgs extends MiniPhase with IdentityDenotTransformer { thisPhase * parent super calls and constructor definitions. * Hoisted superarg methods are collected in `superArgDefs` */ - class Hoister(cls: Symbol)(implicit ctx: Context) { + class Hoister(cls: Symbol)(using Context) { val superArgDefs: mutable.ListBuffer[DefDef] = new mutable.ListBuffer /** If argument is complex, hoist it out into its own method and refer to the @@ -197,7 +197,7 @@ class HoistSuperArgs extends MiniPhase with IdentityDenotTransformer { thisPhase } } - override def transformTypeDef(tdef: TypeDef)(implicit ctx: Context): Tree = + override def transformTypeDef(tdef: TypeDef)(using Context): Tree = tdef.rhs match { case impl @ Template(cdef, superCall :: others, _, _) => val hoist = new Hoister(tdef.symbol) diff --git a/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala b/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala index c425fcb2bb1f..4d184397bb56 100644 --- a/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala +++ b/compiler/src/dotty/tools/dotc/transform/Instrumentation.scala @@ -24,25 +24,25 @@ class Instrumentation extends MiniPhase { thisPhase => override def phaseName: String = "instrumentation" - override def isEnabled(implicit ctx: Context) = + override def isEnabled(using Context) = ctx.settings.YinstrumentClosures.value || ctx.settings.YinstrumentAllocations.value private var consName: TermName = _ private var consEqName: TermName = _ - override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = { + override def prepareForUnit(tree: Tree)(using Context): Context = { consName = "::".toTermName consEqName = "+=".toTermName ctx } - private def record(category: String, tree: Tree)(implicit ctx: Context): Tree = { + private def record(category: String, tree: Tree)(using Context): Tree = { val key = Literal(Constant(s"$category${tree.sourcePos.show}")) ref(defn.Stats_doRecord).appliedTo(key, Literal(Constant(1))) } - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = tree.fun match { + override def transformApply(tree: Apply)(using Context): Tree = tree.fun match { case Select(nu: New, _) => cpy.Block(tree)(record(i"alloc/${nu.tpe}@", tree) :: Nil, tree) case Select(_, name) if name == consName || name == consEqName => @@ -51,7 +51,7 @@ class Instrumentation extends MiniPhase { thisPhase => tree } - override def transformBlock(tree: Block)(implicit ctx: Context): Block = tree.expr match { + override def transformBlock(tree: Block)(using Context): Block = tree.expr match { case _: Closure => cpy.Block(tree)(record("closure/", tree) :: tree.stats, tree.expr) case _ => diff --git a/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala b/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala index be456b9b8e27..5c9f6534c8fa 100644 --- a/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/InterceptedMethods.scala @@ -28,13 +28,13 @@ class InterceptedMethods extends MiniPhase { override def phaseName: String = InterceptedMethods.name // this should be removed if we have guarantee that ## will get Apply node - override def transformSelect(tree: tpd.Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: tpd.Select)(using Context): Tree = transformRefTree(tree) - override def transformIdent(tree: tpd.Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: tpd.Ident)(using Context): Tree = transformRefTree(tree) - private def transformRefTree(tree: RefTree)(implicit ctx: Context): Tree = + private def transformRefTree(tree: RefTree)(using Context): Tree = if (tree.symbol.isTerm && (defn.Any_## eq tree.symbol)) { val qual = tree match { case id: Ident => tpd.desugarIdentPrefix(id) @@ -47,7 +47,7 @@ class InterceptedMethods extends MiniPhase { else tree // TODO: add missing cases from scalac - private def poundPoundValue(tree: Tree)(implicit ctx: Context) = { + private def poundPoundValue(tree: Tree)(using Context) = { val s = tree.tpe.widen.typeSymbol def staticsCall(methodName: TermName): Tree = @@ -60,7 +60,7 @@ class InterceptedMethods extends MiniPhase { else staticsCall(nme.anyHash) } - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = { + override def transformApply(tree: Apply)(using Context): Tree = { lazy val qual = tree.fun match { case Select(qual, _) => qual case ident @ Ident(_) => diff --git a/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled b/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled index 8f247f064c58..abcbfbcf9cb6 100644 --- a/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala.disabled @@ -38,7 +38,7 @@ class IsInstanceOfEvaluator extends MiniPhase { /** Transforms a [TypeApply](dotty.tools.dotc.ast.Trees.TypeApply) in order to * evaluate an `isInstanceOf` check according to the rules defined above. */ - override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = { + override def transformTypeApply(tree: TypeApply)(using Context): Tree = { val defn = ctx.definitions /** Handles the four cases of statically known `isInstanceOf`s and gives diff --git a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala index 1e92b5a4dfdc..1e683547f5b5 100644 --- a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala +++ b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala @@ -26,7 +26,7 @@ object LambdaLift { val name: String = "lambdaLift" /** The core lambda lift functionality. */ - class Lifter(thisPhase: MiniPhase with DenotTransformer)(implicit ctx: Context) { + class Lifter(thisPhase: MiniPhase with DenotTransformer)(using Context) { private type SymSet = TreeSet[Symbol] @@ -84,7 +84,7 @@ object LambdaLift { /** A symbol is local if it is owned by a term or a local trait, * or if it is a constructor of a local symbol. */ - def isLocal(sym: Symbol)(implicit ctx: Context): Boolean = { + def isLocal(sym: Symbol)(using Context): Boolean = { val owner = sym.maybeOwner owner.isTerm || owner.is(Trait) && isLocal(owner) || @@ -94,7 +94,7 @@ object LambdaLift { /** Set `liftedOwner(sym)` to `owner` if `owner` is more deeply nested * than the previous value of `liftedowner(sym)`. */ - def narrowLiftedOwner(sym: Symbol, owner: Symbol)(implicit ctx: Context): Unit = + def narrowLiftedOwner(sym: Symbol, owner: Symbol)(using Context): Unit = if (sym.maybeOwner.isTerm && owner.isProperlyContainedIn(liftedOwner(sym)) && owner != sym) { @@ -147,7 +147,7 @@ object LambdaLift { * } * } */ - private def markFree(sym: Symbol, enclosure: Symbol)(implicit ctx: Context): Symbol = try { + private def markFree(sym: Symbol, enclosure: Symbol)(using Context): Symbol = try { if (!enclosure.exists) throw new NoPath if (enclosure == sym.enclosure) NoSymbol else { @@ -184,7 +184,7 @@ object LambdaLift { throw ex } - private def markCalled(callee: Symbol, caller: Symbol)(implicit ctx: Context): Unit = { + 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}") assert(isLocal(callee)) symSet(called, caller) += callee @@ -192,7 +192,7 @@ object LambdaLift { } private class CollectDependencies extends TreeTraverser { - def traverse(tree: Tree)(implicit ctx: Context) = try { //debug + def traverse(tree: Tree)(using Context) = try { //debug val sym = tree.symbol def enclosure = ctx.owner.enclosingMethod @@ -257,7 +257,7 @@ object LambdaLift { } /** Compute final free variables map `fvs by closing over caller dependencies. */ - private def computeFreeVars()(implicit ctx: Context): Unit = + private def computeFreeVars()(using Context): Unit = while ({ changedFreeVars = false for { @@ -272,7 +272,7 @@ object LambdaLift { () /** Compute final liftedOwner map by closing over caller dependencies */ - private def computeLiftedOwners()(implicit ctx: Context): Unit = + private def computeLiftedOwners()(using Context): Unit = while ({ changedLiftedOwner = false for { @@ -296,14 +296,14 @@ object LambdaLift { }) () - private def newName(sym: Symbol)(implicit ctx: Context): Name = + private def newName(sym: Symbol)(using Context): Name = if (sym.isAnonymousFunction && sym.owner.is(Method)) sym.name.replace { case name: SimpleName => ExpandPrefixName(sym.owner.name.asTermName, name) }.freshened else sym.name.freshened - private def generateProxies()(implicit ctx: Context): Unit = + 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}%, %") @@ -318,7 +318,7 @@ object LambdaLift { }.toMap } - private def liftedInfo(local: Symbol)(implicit ctx: Context): Type = local.info match { + private def liftedInfo(local: Symbol)(using Context): Type = local.info match { case MethodTpe(pnames, ptypes, restpe) => val ps = proxies(local) MethodType( @@ -328,7 +328,7 @@ object LambdaLift { case info => info } - private def liftLocals()(implicit ctx: Context): Unit = { + private def liftLocals()(using Context): Unit = { for ((local, lOwner) <- liftedOwner) { val (newOwner, maybeStatic) = if (lOwner is Package) { @@ -378,13 +378,13 @@ object LambdaLift { liftLocals()(using ctx.withPhase(thisPhase.next)) } - def currentEnclosure(implicit ctx: Context): Symbol = + def currentEnclosure(using Context): Symbol = ctx.owner.enclosingMethodOrClass - private def inCurrentOwner(sym: Symbol)(implicit ctx: Context) = + private def inCurrentOwner(sym: Symbol)(using Context) = sym.enclosure == currentEnclosure - private def proxy(sym: Symbol)(implicit ctx: Context): Symbol = { + private def proxy(sym: Symbol)(using Context): Symbol = { def liftedEnclosure(sym: Symbol) = liftedOwner.getOrElse(sym, sym.enclosure) def searchIn(enclosure: Symbol): Symbol = { if (!enclosure.exists) { @@ -406,7 +406,7 @@ object LambdaLift { if (inCurrentOwner(sym)) sym else searchIn(currentEnclosure) } - def memberRef(sym: Symbol)(implicit ctx: Context): Tree = { + def memberRef(sym: Symbol)(using Context): Tree = { val clazz = sym.enclosingClass val qual = if (clazz.isStaticOwner || ctx.owner.enclosingClass == clazz) @@ -420,18 +420,18 @@ object LambdaLift { thisPhase.transformFollowingDeep(qual.select(sym)) } - def proxyRef(sym: Symbol)(implicit ctx: Context): Tree = { + def proxyRef(sym: Symbol)(using Context): Tree = { val psym = proxy(sym)(using ctx.withPhase(thisPhase)) thisPhase.transformFollowingDeep(if (psym.owner.isTerm) ref(psym) else memberRef(psym)) } - def addFreeArgs(sym: Symbol, args: List[Tree])(implicit ctx: Context): List[Tree] = + def addFreeArgs(sym: Symbol, args: List[Tree])(using Context): List[Tree] = free get sym match { case Some(fvs) => fvs.toList.map(proxyRef(_)) ++ args case _ => args } - def addFreeParams(tree: Tree, proxies: List[Symbol])(implicit ctx: Context): Tree = proxies match { + def addFreeParams(tree: Tree, proxies: List[Symbol])(using Context): Tree = proxies match { case Nil => tree case proxies => val sym = tree.symbol @@ -461,7 +461,7 @@ object LambdaLift { } } - def liftDef(tree: MemberDef)(implicit ctx: Context): Tree = { + def liftDef(tree: MemberDef)(using Context): Tree = { val buf = liftedDefs(tree.symbol.owner) thisPhase.transformFollowing(rename(tree, tree.symbol.name)).foreachInThicket(buf += _) EmptyTree @@ -520,15 +520,15 @@ class LambdaLift extends MiniPhase with IdentityDenotTransformer { thisPhase => // this effect in scalac. private var Lifter: Store.Location[Lifter] = _ - private def lifter(implicit ctx: Context) = ctx.store(Lifter) + private def lifter(using Context) = ctx.store(Lifter) override def initContext(ctx: FreshContext): Unit = Lifter = ctx.addLocation[Lifter]() - override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = + override def prepareForUnit(tree: Tree)(using Context): Context = ctx.fresh.updateStore(Lifter, new Lifter(thisPhase)) - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = { + override def transformIdent(tree: Ident)(using Context): Tree = { val sym = tree.symbol tree.tpe match { case tpe @ TermRef(prefix, _) => @@ -547,13 +547,13 @@ class LambdaLift extends MiniPhase with IdentityDenotTransformer { thisPhase => } } - override def transformApply(tree: Apply)(implicit ctx: Context): Apply = + override def transformApply(tree: Apply)(using Context): Apply = cpy.Apply(tree)(tree.fun, lifter.addFreeArgs(tree.symbol, tree.args)).withSpan(tree.span) - override def transformClosure(tree: Closure)(implicit ctx: Context): Closure = + override def transformClosure(tree: Closure)(using Context): Closure = cpy.Closure(tree)(env = lifter.addFreeArgs(tree.meth.symbol, tree.env)) - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(tree: DefDef)(using Context): Tree = { val sym = tree.symbol val lft = lifter val paramsAdded = @@ -563,20 +563,20 @@ class LambdaLift extends MiniPhase with IdentityDenotTransformer { thisPhase => else paramsAdded } - override def transformReturn(tree: Return)(implicit ctx: Context): Tree = tree.expr match { + override def transformReturn(tree: Return)(using Context): Tree = tree.expr match { case Block(stats, value) => Block(stats, Return(value, tree.from)).withSpan(tree.span) case _ => tree } - override def transformTemplate(tree: Template)(implicit ctx: Context): Template = { + override def transformTemplate(tree: Template)(using Context): Template = { val cls = ctx.owner val lft = lifter val impl = lft.addFreeParams(tree, lft.proxies(cls)).asInstanceOf[Template] cpy.Template(impl)(body = impl.body ++ lft.liftedDefs.remove(cls).get) } - override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree = + override def transformTypeDef(tree: TypeDef)(using Context): Tree = if (lifter.needsLifting(tree.symbol)) lifter.liftDef(tree) else tree } diff --git a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala index 11ccd1ef5463..c11f80ae8d74 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -42,7 +42,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { /** A map of lazy values to the fields they should null after initialization. */ private var lazyValNullables: IdentityHashMap[Symbol, mutable.ListBuffer[Symbol]] = _ - private def nullableFor(sym: Symbol)(implicit ctx: Context) = { + private def nullableFor(sym: Symbol)(using Context) = { // optimisation: value only used once, we can remove the value from the map val nullables = lazyValNullables.remove(sym) if (nullables == null) Nil @@ -50,20 +50,20 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { } - override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = { + override def prepareForUnit(tree: Tree)(using Context): Context = { if (lazyValNullables == null) lazyValNullables = ctx.base.collectNullableFieldsPhase.asInstanceOf[CollectNullableFields].lazyValNullables ctx } - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = + override def transformDefDef(tree: DefDef)(using Context): Tree = transformLazyVal(tree) - override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = + override def transformValDef(tree: ValDef)(using Context): Tree = transformLazyVal(tree) - def transformLazyVal(tree: ValOrDefDef)(implicit ctx: Context): Tree = { + def transformLazyVal(tree: ValOrDefDef)(using Context): Tree = { val sym = tree.symbol if (!sym.is(Lazy) || sym.owner.is(Trait) || // val is accessor, lazy field will be implemented in subclass @@ -101,7 +101,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { /** Append offset fields to companion objects */ - override def transformTemplate(template: Template)(implicit ctx: Context): Tree = { + override def transformTemplate(template: Template)(using Context): Tree = { val cls = ctx.owner.asClass appendOffsetDefs.get(cls) match { @@ -122,7 +122,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { * Eager val ensures thread safety and has less code generated. * */ - def transformSyntheticModule(tree: ValOrDefDef)(implicit ctx: Context): Thicket = { + def transformSyntheticModule(tree: ValOrDefDef)(using Context): Thicket = { val sym = tree.symbol val holderSymbol = ctx.newSymbol(sym.owner, LazyLocalName.fresh(sym.asTerm.name), Synthetic, sym.info.widen.resultType).enteredAfter(this) @@ -147,7 +147,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { * def x(): Int = if (x$lzy.initialized()) x$lzy.value() else x$lzycompute() * ``` */ - def transformLocalDef(x: ValOrDefDef)(implicit ctx: Context): Thicket = { + def transformLocalDef(x: ValOrDefDef)(using Context): Thicket = { val xname = x.name.asTermName val tpe = x.tpe.widen.resultType.widen @@ -184,7 +184,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { } - override def transformStats(trees: List[tpd.Tree])(implicit ctx: Context): List[Tree] = { + override def transformStats(trees: List[tpd.Tree])(using Context): List[Tree] = { // backend requires field usage to be after field definition // need to bring containers to start of method val (holders, stats) = @@ -196,7 +196,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { holders:::stats } - private def nullOut(nullables: List[Symbol])(implicit ctx: Context): List[Tree] = + private def nullOut(nullables: List[Symbol])(using Context): List[Tree] = nullables.map { field => assert(field.isField) field.setFlag(Mutable) @@ -215,7 +215,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { * } * ``` */ - def mkThreadUnsafeDef(sym: Symbol, flag: Symbol, target: Symbol, rhs: Tree)(implicit ctx: Context): DefDef = { + def mkThreadUnsafeDef(sym: Symbol, flag: Symbol, target: Symbol, rhs: Tree)(using Context): DefDef = { val targetRef = ref(target) val flagRef = ref(flag) val stats = targetRef.becomes(rhs) :: flagRef.becomes(Literal(Constant(true))) :: nullOut(nullableFor(sym)) @@ -238,7 +238,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { * } * ``` */ - def mkDefThreadUnsafeNonNullable(sym: Symbol, target: Symbol, rhs: Tree)(implicit ctx: Context): DefDef = { + def mkDefThreadUnsafeNonNullable(sym: Symbol, target: Symbol, rhs: Tree)(using Context): DefDef = { val targetRef = ref(target) val stats = targetRef.becomes(rhs) :: nullOut(nullableFor(sym)) val init = If( @@ -249,7 +249,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { DefDef(sym.asTerm, Block(List(init), targetRef.ensureApplied)) } - def transformMemberDefThreadUnsafe(x: ValOrDefDef)(implicit ctx: Context): Thicket = { + def transformMemberDefThreadUnsafe(x: ValOrDefDef)(using Context): Thicket = { val claz = x.symbol.owner.asClass val tpe = x.tpe.widen.resultType.widen assert(!(x.symbol is Mutable)) @@ -313,7 +313,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { stateMask: Tree, casFlag: Tree, setFlagState: Tree, - waitOnLock: Tree)(implicit ctx: Context): DefDef = { + waitOnLock: Tree)(using Context): DefDef = { val initState = Literal(Constant(0)) val computeState = Literal(Constant(1)) val computedState = Literal(Constant(3)) @@ -371,7 +371,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { DefDef(methodSymbol, loop) } - def transformMemberDefThreadSafe(x: ValOrDefDef)(implicit ctx: Context): Thicket = { + def transformMemberDefThreadSafe(x: ValOrDefDef)(using Context): Thicket = { assert(!(x.symbol is Mutable)) val tpe = x.tpe.widen.resultType.widen diff --git a/compiler/src/dotty/tools/dotc/transform/LiftTry.scala b/compiler/src/dotty/tools/dotc/transform/LiftTry.scala index da789c32a685..34a1b482aa13 100644 --- a/compiler/src/dotty/tools/dotc/transform/LiftTry.scala +++ b/compiler/src/dotty/tools/dotc/transform/LiftTry.scala @@ -33,18 +33,18 @@ class LiftTry extends MiniPhase with IdentityDenotTransformer { thisPhase => val phaseName: String = LiftTry.name private var NeedLift: Store.Location[Boolean] = _ - private def needLift(implicit ctx: Context): Boolean = ctx.store(NeedLift) + private def needLift(using Context): Boolean = ctx.store(NeedLift) override def initContext(ctx: FreshContext): Unit = NeedLift = ctx.addLocation(false) - private def liftingCtx(p: Boolean)(implicit ctx: Context) = + private def liftingCtx(p: Boolean)(using Context) = if (needLift == p) ctx else ctx.fresh.updateStore(NeedLift, p) - override def prepareForApply(tree: Apply)(implicit ctx: Context): Context = + override def prepareForApply(tree: Apply)(using Context): Context = liftingCtx(true) - override def prepareForValDef(tree: ValDef)(implicit ctx: Context): Context = + override def prepareForValDef(tree: ValDef)(using Context): Context = if !tree.symbol.exists || tree.symbol.isSelfSym || tree.symbol.owner == ctx.owner.enclosingMethod @@ -56,18 +56,18 @@ class LiftTry extends MiniPhase with IdentityDenotTransformer { thisPhase => then ctx else liftingCtx(true) - override def prepareForAssign(tree: Assign)(implicit ctx: Context): Context = + override def prepareForAssign(tree: Assign)(using Context): Context = if (tree.lhs.symbol.maybeOwner == ctx.owner.enclosingMethod) ctx else liftingCtx(true) - override def prepareForReturn(tree: Return)(implicit ctx: Context): Context = + override def prepareForReturn(tree: Return)(using Context): Context = if (!isNonLocalReturn(tree)) ctx else liftingCtx(true) - override def prepareForTemplate(tree: Template)(implicit ctx: Context): Context = + override def prepareForTemplate(tree: Template)(using Context): Context = liftingCtx(false) - override def transformTry(tree: Try)(implicit ctx: Context): Tree = + 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( diff --git a/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala b/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala index 54d464079fb6..2f568140fc2f 100644 --- a/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala +++ b/compiler/src/dotty/tools/dotc/transform/LinkScala2Impls.scala @@ -34,7 +34,7 @@ class LinkScala2Impls extends MiniPhase with IdentityDenotTransformer { thisPhas // Adds as a side effect static members to traits which can confuse Mixin, // that's why it is runsAfterGroupOf - private def addStaticForwarders(mixin: ClassSymbol)(implicit ctx: Context): Unit = { + private def addStaticForwarders(mixin: ClassSymbol)(using Context): Unit = { val ops = new MixinOps(mixin, thisPhase) import ops._ @@ -63,14 +63,14 @@ class LinkScala2Impls extends MiniPhase with IdentityDenotTransformer { thisPhas mixin.resetFlag(Scala2xPartiallyAugmented) } - override def prepareForTemplate(impl: Template)(implicit ctx: Context): Context = { + override def prepareForTemplate(impl: Template)(using Context): Context = { val cls = impl.symbol.owner.asClass for (mixin <- cls.mixins if (mixin.is(Scala2xPartiallyAugmented))) addStaticForwarders(mixin) ctx } - override def transformApply(app: Apply)(implicit ctx: Context): Tree = { + override def transformApply(app: Apply)(using Context): Tree = { def currentClass = ctx.owner.enclosingClass.asClass app match { case Apply(sel @ Select(Super(_, _), _), args) @@ -84,7 +84,7 @@ class LinkScala2Impls extends MiniPhase with IdentityDenotTransformer { thisPhas } /** The 2.12 implementation method of a super call or implementation class target */ - private def implMethod(meth: Symbol)(implicit ctx: Context): Symbol = { + private def implMethod(meth: Symbol)(using Context): Symbol = { val implName = ImplMethName(meth.name.asTermName) val cls = meth.owner if (cls.isAllOf(Scala2xTrait)) diff --git a/compiler/src/dotty/tools/dotc/transform/Literalize.scala.disabled b/compiler/src/dotty/tools/dotc/transform/Literalize.scala.disabled index 8d2b06e24462..626cb9687df4 100644 --- a/compiler/src/dotty/tools/dotc/transform/Literalize.scala.disabled +++ b/compiler/src/dotty/tools/dotc/transform/Literalize.scala.disabled @@ -51,7 +51,7 @@ class Literalize extends MiniPhase { thisTransform => * Revisit this issue once we have implemented `inline`. Then we can demand * purity of the prefix unless the selection goes to an inline val. */ - def literalize(tree: Tree)(implicit ctx: Context): Tree = { + def literalize(tree: Tree)(using Context): Tree = { def recur(tp: Type): Tree = tp match { case ConstantType(value) if isIdempotentExpr(tree) => Literal(value) case tp: TermRef if tp.symbol.isStable => recur(tp.info.widenExpr) @@ -60,26 +60,26 @@ class Literalize extends MiniPhase { thisTransform => recur(tree.tpe) } - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = literalize(tree) - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = literalize(tree) - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = + override def transformApply(tree: Apply)(using Context): Tree = literalize(tree) - override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = + override def transformTypeApply(tree: TypeApply)(using Context): Tree = literalize(tree) - override def transformLiteral(tree: Literal)(implicit ctx: Context): Tree = tree.tpe match { + override def transformLiteral(tree: Literal)(using Context): Tree = tree.tpe match { case ConstantType(const) if tree.const.value != const.value || (tree.const.tag != const.tag) => Literal(const) case _ => tree } /** Check that all literals have types match underlying constants */ - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = { + override def checkPostCondition(tree: Tree)(using Context): Unit = { tree match { case Literal(c @ Constant(treeValue)) => tree.tpe match { diff --git a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala index f42f944169a7..76987308809d 100644 --- a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala @@ -16,28 +16,28 @@ abstract class MacroTransform extends Phase { import ast.tpd._ - override def run(implicit ctx: Context): Unit = { + override def run(using Context): Unit = { val unit = ctx.compilationUnit unit.tpdTree = newTransformer.transform(unit.tpdTree)(using ctx.withPhase(transformPhase)) } - protected def newTransformer(implicit ctx: Context): Transformer + protected def newTransformer(using Context): Transformer /** The phase in which the transformation should be run. * By default this is the phase given by the this macro transformer, * but it could be overridden to be the phase following that one. */ - protected def transformPhase(implicit ctx: Context): Phase = this + protected def transformPhase(using Context): Phase = this class Transformer extends TreeMap(cpy = cpyBetweenPhases) { - protected def localCtx(tree: Tree)(implicit ctx: Context): FreshContext = { + protected def localCtx(tree: Tree)(using Context): FreshContext = { val sym = tree.symbol val owner = if (sym.is(PackageVal)) sym.moduleClass else sym ctx.fresh.setTree(tree).setOwner(owner) } - def transformStats(trees: List[Tree], exprOwner: Symbol)(implicit ctx: Context): List[Tree] = { + def transformStats(trees: List[Tree], exprOwner: Symbol)(using Context): List[Tree] = { def transformStat(stat: Tree): Tree = stat match { case _: Import | _: DefTree => transform(stat) case _ => transform(stat)(using ctx.exprContext(stat, exprOwner)) @@ -68,7 +68,7 @@ abstract class MacroTransform extends Phase { tree } - def transformSelf(vd: ValDef)(implicit ctx: Context): ValDef = + def transformSelf(vd: ValDef)(using Context): ValDef = cpy.ValDef(vd)(tpt = transform(vd.tpt)) } } diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index 0c5ebffa99bd..6be02e43712d 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -46,89 +46,89 @@ object MegaPhase { val cpy: TypedTreeCopier = cpyBetweenPhases - def prepareForIdent(tree: Ident)(implicit ctx: Context): Context = ctx - def prepareForSelect(tree: Select)(implicit ctx: Context): Context = ctx - def prepareForThis(tree: This)(implicit ctx: Context): Context = ctx - def prepareForSuper(tree: Super)(implicit ctx: Context): Context = ctx - def prepareForApply(tree: Apply)(implicit ctx: Context): Context = ctx - def prepareForTypeApply(tree: TypeApply)(implicit ctx: Context): Context = ctx - def prepareForLiteral(tree: Literal)(implicit ctx: Context): Context = ctx - def prepareForNew(tree: New)(implicit ctx: Context): Context = ctx - def prepareForTyped(tree: Typed)(implicit ctx: Context): Context = ctx - def prepareForAssign(tree: Assign)(implicit ctx: Context): Context = ctx - def prepareForBlock(tree: Block)(implicit ctx: Context): Context = ctx - def prepareForIf(tree: If)(implicit ctx: Context): Context = ctx - def prepareForClosure(tree: Closure)(implicit ctx: Context): Context = ctx - def prepareForMatch(tree: Match)(implicit ctx: Context): Context = ctx - def prepareForCaseDef(tree: CaseDef)(implicit ctx: Context): Context = ctx - def prepareForLabeled(tree: Labeled)(implicit ctx: Context): Context = ctx - def prepareForReturn(tree: Return)(implicit ctx: Context): Context = ctx - def prepareForWhileDo(tree: WhileDo)(implicit ctx: Context): Context = ctx - def prepareForTry(tree: Try)(implicit ctx: Context): Context = ctx - def prepareForSeqLiteral(tree: SeqLiteral)(implicit ctx: Context): Context = ctx - def prepareForInlined(tree: Inlined)(implicit ctx: Context): Context = ctx - def prepareForTypeTree(tree: TypeTree)(implicit ctx: Context): Context = ctx - def prepareForBind(tree: Bind)(implicit ctx: Context): Context = ctx - def prepareForAlternative(tree: Alternative)(implicit ctx: Context): Context = ctx - def prepareForUnApply(tree: UnApply)(implicit ctx: Context): Context = ctx - def prepareForValDef(tree: ValDef)(implicit ctx: Context): Context = ctx - def prepareForDefDef(tree: DefDef)(implicit ctx: Context): Context = ctx - def prepareForTypeDef(tree: TypeDef)(implicit ctx: Context): Context = ctx - def prepareForTemplate(tree: Template)(implicit ctx: Context): Context = ctx - def prepareForPackageDef(tree: PackageDef)(implicit ctx: Context): Context = ctx - def prepareForStats(trees: List[Tree])(implicit ctx: Context): Context = ctx - def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = ctx - def prepareForOther(tree: Tree)(implicit ctx: Context): Context = ctx - - def transformIdent(tree: Ident)(implicit ctx: Context): Tree = tree - def transformSelect(tree: Select)(implicit ctx: Context): Tree = tree - def transformThis(tree: This)(implicit ctx: Context): Tree = tree - def transformSuper(tree: Super)(implicit ctx: Context): Tree = tree - def transformApply(tree: Apply)(implicit ctx: Context): Tree = tree - def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = tree - def transformLiteral(tree: Literal)(implicit ctx: Context): Tree = tree - def transformNew(tree: New)(implicit ctx: Context): Tree = tree - def transformTyped(tree: Typed)(implicit ctx: Context): Tree = tree - def transformAssign(tree: Assign)(implicit ctx: Context): Tree = tree - def transformBlock(tree: Block)(implicit ctx: Context): Tree = tree - def transformIf(tree: If)(implicit ctx: Context): Tree = tree - def transformClosure(tree: Closure)(implicit ctx: Context): Tree = tree - def transformMatch(tree: Match)(implicit ctx: Context): Tree = tree - def transformCaseDef(tree: CaseDef)(implicit ctx: Context): Tree = tree - def transformLabeled(tree: Labeled)(implicit ctx: Context): Tree = tree - def transformReturn(tree: Return)(implicit ctx: Context): Tree = tree - def transformWhileDo(tree: WhileDo)(implicit ctx: Context): Tree = tree - def transformTry(tree: Try)(implicit ctx: Context): Tree = tree - def transformSeqLiteral(tree: SeqLiteral)(implicit ctx: Context): Tree = tree - def transformInlined(tree: Inlined)(implicit ctx: Context): Tree = tree - def transformTypeTree(tree: TypeTree)(implicit ctx: Context): Tree = tree - def transformBind(tree: Bind)(implicit ctx: Context): Tree = tree - def transformAlternative(tree: Alternative)(implicit ctx: Context): Tree = tree - def transformUnApply(tree: UnApply)(implicit ctx: Context): Tree = tree - def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = tree - def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = tree - def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree = tree - def transformTemplate(tree: Template)(implicit ctx: Context): Tree = tree - def transformPackageDef(tree: PackageDef)(implicit ctx: Context): Tree = tree - def transformStats(trees: List[Tree])(implicit ctx: Context): List[Tree] = trees - def transformUnit(tree: Tree)(implicit ctx: Context): Tree = tree - def transformOther(tree: Tree)(implicit ctx: Context): Tree = tree + def prepareForIdent(tree: Ident)(using Context): Context = ctx + def prepareForSelect(tree: Select)(using Context): Context = ctx + def prepareForThis(tree: This)(using Context): Context = ctx + def prepareForSuper(tree: Super)(using Context): Context = ctx + def prepareForApply(tree: Apply)(using Context): Context = ctx + def prepareForTypeApply(tree: TypeApply)(using Context): Context = ctx + def prepareForLiteral(tree: Literal)(using Context): Context = ctx + def prepareForNew(tree: New)(using Context): Context = ctx + def prepareForTyped(tree: Typed)(using Context): Context = ctx + def prepareForAssign(tree: Assign)(using Context): Context = ctx + def prepareForBlock(tree: Block)(using Context): Context = ctx + def prepareForIf(tree: If)(using Context): Context = ctx + def prepareForClosure(tree: Closure)(using Context): Context = ctx + def prepareForMatch(tree: Match)(using Context): Context = ctx + def prepareForCaseDef(tree: CaseDef)(using Context): Context = ctx + def prepareForLabeled(tree: Labeled)(using Context): Context = ctx + def prepareForReturn(tree: Return)(using Context): Context = ctx + def prepareForWhileDo(tree: WhileDo)(using Context): Context = ctx + def prepareForTry(tree: Try)(using Context): Context = ctx + def prepareForSeqLiteral(tree: SeqLiteral)(using Context): Context = ctx + def prepareForInlined(tree: Inlined)(using Context): Context = ctx + def prepareForTypeTree(tree: TypeTree)(using Context): Context = ctx + def prepareForBind(tree: Bind)(using Context): Context = ctx + def prepareForAlternative(tree: Alternative)(using Context): Context = ctx + def prepareForUnApply(tree: UnApply)(using Context): Context = ctx + def prepareForValDef(tree: ValDef)(using Context): Context = ctx + def prepareForDefDef(tree: DefDef)(using Context): Context = ctx + def prepareForTypeDef(tree: TypeDef)(using Context): Context = ctx + def prepareForTemplate(tree: Template)(using Context): Context = ctx + def prepareForPackageDef(tree: PackageDef)(using Context): Context = ctx + def prepareForStats(trees: List[Tree])(using Context): Context = ctx + def prepareForUnit(tree: Tree)(using Context): Context = ctx + def prepareForOther(tree: Tree)(using Context): Context = ctx + + def transformIdent(tree: Ident)(using Context): Tree = tree + def transformSelect(tree: Select)(using Context): Tree = tree + def transformThis(tree: This)(using Context): Tree = tree + def transformSuper(tree: Super)(using Context): Tree = tree + def transformApply(tree: Apply)(using Context): Tree = tree + def transformTypeApply(tree: TypeApply)(using Context): Tree = tree + def transformLiteral(tree: Literal)(using Context): Tree = tree + def transformNew(tree: New)(using Context): Tree = tree + def transformTyped(tree: Typed)(using Context): Tree = tree + def transformAssign(tree: Assign)(using Context): Tree = tree + def transformBlock(tree: Block)(using Context): Tree = tree + def transformIf(tree: If)(using Context): Tree = tree + def transformClosure(tree: Closure)(using Context): Tree = tree + def transformMatch(tree: Match)(using Context): Tree = tree + def transformCaseDef(tree: CaseDef)(using Context): Tree = tree + def transformLabeled(tree: Labeled)(using Context): Tree = tree + def transformReturn(tree: Return)(using Context): Tree = tree + def transformWhileDo(tree: WhileDo)(using Context): Tree = tree + def transformTry(tree: Try)(using Context): Tree = tree + def transformSeqLiteral(tree: SeqLiteral)(using Context): Tree = tree + def transformInlined(tree: Inlined)(using Context): Tree = tree + def transformTypeTree(tree: TypeTree)(using Context): Tree = tree + def transformBind(tree: Bind)(using Context): Tree = tree + def transformAlternative(tree: Alternative)(using Context): Tree = tree + def transformUnApply(tree: UnApply)(using Context): Tree = tree + def transformValDef(tree: ValDef)(using Context): Tree = tree + def transformDefDef(tree: DefDef)(using Context): Tree = tree + def transformTypeDef(tree: TypeDef)(using Context): Tree = tree + def transformTemplate(tree: Template)(using Context): Tree = tree + def transformPackageDef(tree: PackageDef)(using Context): Tree = tree + def transformStats(trees: List[Tree])(using Context): List[Tree] = trees + def transformUnit(tree: Tree)(using Context): Tree = tree + def transformOther(tree: Tree)(using Context): Tree = tree /** Transform tree using all transforms of current group (including this one) */ - def transformAllDeep(tree: Tree)(implicit ctx: Context): Tree = + def transformAllDeep(tree: Tree)(using Context): Tree = superPhase.transformTree(tree, 0) /** Transform tree using all transforms following the current one in this group */ - def transformFollowingDeep(tree: Tree)(implicit ctx: Context): Tree = + def transformFollowingDeep(tree: Tree)(using Context): Tree = superPhase.transformTree(tree, idxInGroup + 1) /** Transform single node using all transforms following the current one in this group */ - def transformFollowing(tree: Tree)(implicit ctx: Context): Tree = + def transformFollowing(tree: Tree)(using Context): Tree = superPhase.transformNode(tree, idxInGroup + 1) protected def singletonGroup: MegaPhase = new MegaPhase(Array(this)) - override def run(implicit ctx: Context): Unit = + override def run(using Context): Unit = singletonGroup.run } } @@ -155,7 +155,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { private val cpy: TypedTreeCopier = cpyBetweenPhases /** Transform node using all phases in this group that have idxInGroup >= start */ - def transformNode(tree: Tree, start: Int)(implicit ctx: Context): Tree = { + def transformNode(tree: Tree, start: Int)(using Context): Tree = { def goNamed(tree: Tree, start: Int) = try tree match { @@ -212,8 +212,8 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } /** Transform full tree using all phases in this group that have idxInGroup >= start */ - def transformTree(tree: Tree, start: Int)(implicit ctx: Context): Tree = { - def localContext(implicit ctx: Context) = { + def transformTree(tree: Tree, start: Int)(using Context): Tree = { + def localContext(using Context) = { val sym = tree.symbol val owner = if (sym.is(PackageVal)) sym.moduleClass else sym ctx.fresh.setOwner(owner) @@ -221,208 +221,208 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def transformNamed(tree: Tree, start: Int, outerCtx: Context): Tree = tree match { case tree: Ident => - given Context = prepIdent(tree, start)(outerCtx) + given Context = prepIdent(tree, start)(using outerCtx) goIdent(tree, start) case tree: Select => - given Context = prepSelect(tree, start)(outerCtx) + given Context = prepSelect(tree, start)(using outerCtx) val qual = transformTree(tree.qualifier, start) goSelect(cpy.Select(tree)(qual, tree.name), start) case tree: ValDef => - given Context = prepValDef(tree, start)(outerCtx) - def mapValDef(implicit ctx: Context) = { + given Context = prepValDef(tree, start)(using outerCtx) + def mapValDef(using Context) = { val tpt = transformTree(tree.tpt, start) val rhs = transformTree(tree.rhs, start) cpy.ValDef(tree)(tree.name, tpt, rhs) } if (tree.isEmpty) tree - else goValDef(mapValDef(if (tree.symbol.exists) localContext else ctx), start) + else goValDef(mapValDef(using if (tree.symbol.exists) localContext else ctx), start) case tree: DefDef => - given Context = prepDefDef(tree, start)(outerCtx) - def mapDefDef(implicit ctx: Context) = { + given Context = prepDefDef(tree, start)(using outerCtx) + def mapDefDef(using Context) = { val tparams = transformSpecificTrees(tree.tparams, start) val vparamss = tree.vparamss.mapConserve(transformSpecificTrees(_, start)) val tpt = transformTree(tree.tpt, start) val rhs = transformTree(tree.rhs, start) cpy.DefDef(tree)(tree.name, tparams, vparamss, tpt, rhs) } - goDefDef(mapDefDef(localContext), start) + goDefDef(mapDefDef(using localContext), start) case tree: TypeDef => - given Context = prepTypeDef(tree, start)(outerCtx) - val rhs = transformTree(tree.rhs, start)(localContext) + given Context = prepTypeDef(tree, start)(using outerCtx) + val rhs = transformTree(tree.rhs, start)(using localContext) goTypeDef(cpy.TypeDef(tree)(tree.name, rhs), start) case tree: Labeled => - given Context = prepLabeled(tree, start)(outerCtx) + given Context = prepLabeled(tree, start)(using outerCtx) val bind = transformTree(tree.bind, start).asInstanceOf[Bind] val expr = transformTree(tree.expr, start) goLabeled(cpy.Labeled(tree)(bind, expr), start) case tree: Bind => - given Context = prepBind(tree, start)(outerCtx) + given Context = prepBind(tree, start)(using outerCtx) val body = transformTree(tree.body, start) goBind(cpy.Bind(tree)(tree.name, body), start) case _ => - given Context = prepOther(tree, start)(outerCtx) + given Context = prepOther(tree, start)(using outerCtx) goOther(tree, start) } def transformUnnamed(tree: Tree, start: Int, outerCtx: Context): Tree = tree match { case tree: Apply => - given Context = prepApply(tree, start)(outerCtx) + given Context = prepApply(tree, start)(using outerCtx) val fun = transformTree(tree.fun, start) val args = transformTrees(tree.args, start) goApply(cpy.Apply(tree)(fun, args), start) case tree: TypeTree => - given Context = prepTypeTree(tree, start)(outerCtx) + given Context = prepTypeTree(tree, start)(using outerCtx) goTypeTree(tree, start) case tree: Thicket => cpy.Thicket(tree)(transformTrees(tree.trees, start)) case tree: This => - given Context = prepThis(tree, start)(outerCtx) + given Context = prepThis(tree, start)(using outerCtx) goThis(tree, start) case tree: Literal => - given Context = prepLiteral(tree, start)(outerCtx) + given Context = prepLiteral(tree, start)(using outerCtx) goLiteral(tree, start) case tree: Block => - given Context = prepBlock(tree, start)(outerCtx) + given Context = prepBlock(tree, start)(using outerCtx) val stats = transformStats(tree.stats, ctx.owner, start) val expr = transformTree(tree.expr, start) goBlock(cpy.Block(tree)(stats, expr), start) case tree: TypeApply => - given Context = prepTypeApply(tree, start)(outerCtx) + given Context = prepTypeApply(tree, start)(using outerCtx) val fun = transformTree(tree.fun, start) val args = transformTrees(tree.args, start) goTypeApply(cpy.TypeApply(tree)(fun, args), start) case tree: If => - given Context = prepIf(tree, start)(outerCtx) + given Context = prepIf(tree, start)(using outerCtx) val cond = transformTree(tree.cond, start) val thenp = transformTree(tree.thenp, start) val elsep = transformTree(tree.elsep, start) goIf(cpy.If(tree)(cond, thenp, elsep), start) case tree: New => - given Context = prepNew(tree, start)(outerCtx) + given Context = prepNew(tree, start)(using outerCtx) val tpt = transformTree(tree.tpt, start) goNew(cpy.New(tree)(tpt), start) case tree: Typed => - given Context = prepTyped(tree, start)(outerCtx) + given Context = prepTyped(tree, start)(using outerCtx) val expr = transformTree(tree.expr, start) val tpt = transformTree(tree.tpt, start) goTyped(cpy.Typed(tree)(expr, tpt), start) case tree: CaseDef => - given Context = prepCaseDef(tree, start)(outerCtx) - val pat = transformTree(tree.pat, start)(ctx.addMode(Mode.Pattern)) + given Context = prepCaseDef(tree, start)(using outerCtx) + val pat = transformTree(tree.pat, start)(using ctx.addMode(Mode.Pattern)) val guard = transformTree(tree.guard, start) val body = transformTree(tree.body, start) goCaseDef(cpy.CaseDef(tree)(pat, guard, body), start) case tree: Closure => - given Context = prepClosure(tree, start)(outerCtx) + given Context = prepClosure(tree, start)(using outerCtx) val env = transformTrees(tree.env, start) val meth = transformTree(tree.meth, start) val tpt = transformTree(tree.tpt, start) goClosure(cpy.Closure(tree)(env, meth, tpt), start) case tree: Assign => - given Context = prepAssign(tree, start)(outerCtx) + given Context = prepAssign(tree, start)(using outerCtx) val lhs = transformTree(tree.lhs, start) val rhs = transformTree(tree.rhs, start) goAssign(cpy.Assign(tree)(lhs, rhs), start) case tree: SeqLiteral => - given Context = prepSeqLiteral(tree, start)(outerCtx) + given Context = prepSeqLiteral(tree, start)(using outerCtx) val elems = transformTrees(tree.elems, start) val elemtpt = transformTree(tree.elemtpt, start) goSeqLiteral(cpy.SeqLiteral(tree)(elems, elemtpt), start) case tree: Super => - given Context = prepSuper(tree, start)(outerCtx) + given Context = prepSuper(tree, start)(using outerCtx) goSuper(tree, start) case tree: Template => - given Context = prepTemplate(tree, start)(outerCtx) + given Context = prepTemplate(tree, start)(using outerCtx) val constr = transformSpecificTree(tree.constr, start) - val parents = transformTrees(tree.parents, start)(ctx.superCallContext) + val parents = transformTrees(tree.parents, start)(using ctx.superCallContext) val self = transformSpecificTree(tree.self, start) val body = transformStats(tree.body, tree.symbol, start) goTemplate(cpy.Template(tree)(constr, parents, Nil, self, body), start) case tree: Match => - given Context = prepMatch(tree, start)(outerCtx) + given Context = prepMatch(tree, start)(using outerCtx) val selector = transformTree(tree.selector, start) val cases = transformSpecificTrees(tree.cases, start) goMatch(cpy.Match(tree)(selector, cases), start) case tree: UnApply => - given Context = prepUnApply(tree, start)(outerCtx) + given Context = prepUnApply(tree, start)(using outerCtx) val fun = transformTree(tree.fun, start) val implicits = transformTrees(tree.implicits, start) val patterns = transformTrees(tree.patterns, start) goUnApply(cpy.UnApply(tree)(fun, implicits, patterns), start) case tree: PackageDef => - given Context = prepPackageDef(tree, start)(outerCtx) - def mapPackage(implicit ctx: Context) = { + given Context = prepPackageDef(tree, start)(using outerCtx) + def mapPackage(using Context) = { val pid = transformSpecificTree(tree.pid, start) val stats = transformStats(tree.stats, tree.symbol, start) cpy.PackageDef(tree)(pid, stats) } - goPackageDef(mapPackage(localContext), start) + goPackageDef(mapPackage(using localContext), start) case tree: Try => - given Context = prepTry(tree, start)(outerCtx) + given Context = prepTry(tree, start)(using outerCtx) val expr = transformTree(tree.expr, start) val cases = transformSpecificTrees(tree.cases, start) val finalizer = transformTree(tree.finalizer, start) goTry(cpy.Try(tree)(expr, cases, finalizer), start) case tree: Inlined => - given Context = prepInlined(tree, start)(outerCtx) + given Context = prepInlined(tree, start)(using outerCtx) val bindings = transformSpecificTrees(tree.bindings, start) - val expansion = transformTree(tree.expansion, start)(inlineContext(tree.call)) + val expansion = transformTree(tree.expansion, start)(using inlineContext(tree.call)) goInlined(cpy.Inlined(tree)(tree.call, bindings, expansion), start) case tree: Return => - given Context = prepReturn(tree, start)(outerCtx) + given Context = prepReturn(tree, start)(using outerCtx) val expr = transformTree(tree.expr, start) goReturn(cpy.Return(tree)(expr, tree.from), start) // don't transform `tree.from`, as this is not a normal ident, but // a pointer to the enclosing method. case tree: WhileDo => - given Context = prepWhileDo(tree, start)(outerCtx) + given Context = prepWhileDo(tree, start)(using outerCtx) val cond = transformTree(tree.cond, start) val body = transformTree(tree.body, start) goWhileDo(cpy.WhileDo(tree)(cond, body), start) case tree: Alternative => - given Context = prepAlternative(tree, start)(outerCtx) + given Context = prepAlternative(tree, start)(using outerCtx) val trees = transformTrees(tree.trees, start) goAlternative(cpy.Alternative(tree)(trees), start) case tree => - given Context = prepOther(tree, start)(outerCtx) + given Context = prepOther(tree, start)(using outerCtx) goOther(tree, start) } if (tree.source != ctx.source && tree.source.exists) - transformTree(tree, start)(ctx.withSource(tree.source)) + transformTree(tree, start)(using ctx.withSource(tree.source)) else if (tree.isInstanceOf[NameTree]) transformNamed(tree, start, ctx) else transformUnnamed(tree, start, ctx) } - def transformSpecificTree[T <: Tree](tree: T, start: Int)(implicit ctx: Context): T = + def transformSpecificTree[T <: Tree](tree: T, start: Int)(using Context): T = transformTree(tree, start).asInstanceOf[T] - def transformStats(trees: List[Tree], exprOwner: Symbol, start: Int)(implicit ctx: Context): List[Tree] = { - def transformStat(stat: Tree)(implicit ctx: Context): Tree = stat match { + def transformStats(trees: List[Tree], exprOwner: Symbol, start: Int)(using Context): List[Tree] = { + def transformStat(stat: Tree)(using Context): Tree = stat match { case _: Import | _: DefTree => transformTree(stat, start) case Thicket(stats) => cpy.Thicket(stat)(stats.mapConserve(transformStat)) - case _ => transformTree(stat, start)(ctx.exprContext(stat, exprOwner)) + case _ => transformTree(stat, start)(using ctx.exprContext(stat, exprOwner)) } - val nestedCtx = prepStats(trees, start)(ctx) - val trees1 = flatten(trees.mapConserve(transformStat(_)(nestedCtx))) - goStats(trees1, start)(nestedCtx) + val nestedCtx = prepStats(trees, start)(using ctx) + val trees1 = flatten(trees.mapConserve(transformStat(_)(using nestedCtx))) + goStats(trees1, start)(using nestedCtx) } - def transformUnit(tree: Tree)(implicit ctx: Context): Tree = { - val nestedCtx = prepUnit(tree, 0)(ctx) - val tree1 = transformTree(tree, 0)(nestedCtx) - goUnit(tree1, 0)(nestedCtx) + def transformUnit(tree: Tree)(using Context): Tree = { + val nestedCtx = prepUnit(tree, 0)(using ctx) + val tree1 = transformTree(tree, 0)(using nestedCtx) + goUnit(tree1, 0)(using nestedCtx) } - def transformTrees(trees: List[Tree], start: Int)(implicit ctx: Context): List[Tree] = + def transformTrees(trees: List[Tree], start: Int)(using Context): List[Tree] = flatten(trees.mapConserve(transformTree(_, start))) - def transformSpecificTrees[T <: Tree](trees: List[T], start: Int)(implicit ctx: Context): List[T] = + def transformSpecificTrees[T <: Tree](trees: List[T], start: Int)(using Context): List[T] = transformTrees(trees, start).asInstanceOf[List[T]] - override def run(implicit ctx: Context): Unit = + override def run(using Context): Unit = ctx.compilationUnit.tpdTree = transformUnit(ctx.compilationUnit.tpdTree)(using ctx.withPhase(miniPhases.last.next)) @@ -539,489 +539,489 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { // Boilerplate snippets - def prepIdent(tree: Ident, start: Int)(implicit ctx: Context): Context = { + def prepIdent(tree: Ident, start: Int)(using Context): Context = { val phase = nxIdentPrepPhase(start) if (phase == null) ctx - else prepIdent(tree, phase.idxInGroup + 1)(phase.prepareForIdent(tree)) + else prepIdent(tree, phase.idxInGroup + 1)(using phase.prepareForIdent(tree)) } - def goIdent(tree: Ident, start: Int)(implicit ctx: Context): Tree = { + def goIdent(tree: Ident, start: Int)(using Context): Tree = { val phase = nxIdentTransPhase(start) if (phase == null) tree - else phase.transformIdent(tree)(ctx) match { + else phase.transformIdent(tree)(using ctx) match { case tree1: Ident => goIdent(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepSelect(tree: Select, start: Int)(implicit ctx: Context): Context = { + def prepSelect(tree: Select, start: Int)(using Context): Context = { val phase = nxSelectPrepPhase(start) if (phase == null) ctx - else prepSelect(tree, phase.idxInGroup + 1)(phase.prepareForSelect(tree)) + else prepSelect(tree, phase.idxInGroup + 1)(using phase.prepareForSelect(tree)) } - def goSelect(tree: Select, start: Int)(implicit ctx: Context): Tree = { + def goSelect(tree: Select, start: Int)(using Context): Tree = { val phase = nxSelectTransPhase(start) if (phase == null) tree - else phase.transformSelect(tree)(ctx) match { + else phase.transformSelect(tree)(using ctx) match { case tree1: Select => goSelect(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepThis(tree: This, start: Int)(implicit ctx: Context): Context = { + def prepThis(tree: This, start: Int)(using Context): Context = { val phase = nxThisPrepPhase(start) if (phase == null) ctx - else prepThis(tree, phase.idxInGroup + 1)(phase.prepareForThis(tree)) + else prepThis(tree, phase.idxInGroup + 1)(using phase.prepareForThis(tree)) } - def goThis(tree: This, start: Int)(implicit ctx: Context): Tree = { + def goThis(tree: This, start: Int)(using Context): Tree = { val phase = nxThisTransPhase(start) if (phase == null) tree - else phase.transformThis(tree)(ctx) match { + else phase.transformThis(tree)(using ctx) match { case tree1: This => goThis(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepSuper(tree: Super, start: Int)(implicit ctx: Context): Context = { + def prepSuper(tree: Super, start: Int)(using Context): Context = { val phase = nxSuperPrepPhase(start) if (phase == null) ctx - else prepSuper(tree, phase.idxInGroup + 1)(phase.prepareForSuper(tree)) + else prepSuper(tree, phase.idxInGroup + 1)(using phase.prepareForSuper(tree)) } - def goSuper(tree: Super, start: Int)(implicit ctx: Context): Tree = { + def goSuper(tree: Super, start: Int)(using Context): Tree = { val phase = nxSuperTransPhase(start) if (phase == null) tree - else phase.transformSuper(tree)(ctx) match { + else phase.transformSuper(tree)(using ctx) match { case tree1: Super => goSuper(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepApply(tree: Apply, start: Int)(implicit ctx: Context): Context = { + def prepApply(tree: Apply, start: Int)(using Context): Context = { val phase = nxApplyPrepPhase(start) if (phase == null) ctx - else prepApply(tree, phase.idxInGroup + 1)(phase.prepareForApply(tree)) + else prepApply(tree, phase.idxInGroup + 1)(using phase.prepareForApply(tree)) } - def goApply(tree: Apply, start: Int)(implicit ctx: Context): Tree = { + def goApply(tree: Apply, start: Int)(using Context): Tree = { val phase = nxApplyTransPhase(start) if (phase == null) tree - else phase.transformApply(tree)(ctx) match { + else phase.transformApply(tree)(using ctx) match { case tree1: Apply => goApply(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepTypeApply(tree: TypeApply, start: Int)(implicit ctx: Context): Context = { + def prepTypeApply(tree: TypeApply, start: Int)(using Context): Context = { val phase = nxTypeApplyPrepPhase(start) if (phase == null) ctx - else prepTypeApply(tree, phase.idxInGroup + 1)(phase.prepareForTypeApply(tree)) + else prepTypeApply(tree, phase.idxInGroup + 1)(using phase.prepareForTypeApply(tree)) } - def goTypeApply(tree: TypeApply, start: Int)(implicit ctx: Context): Tree = { + def goTypeApply(tree: TypeApply, start: Int)(using Context): Tree = { val phase = nxTypeApplyTransPhase(start) if (phase == null) tree - else phase.transformTypeApply(tree)(ctx) match { + else phase.transformTypeApply(tree)(using ctx) match { case tree1: TypeApply => goTypeApply(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepLiteral(tree: Literal, start: Int)(implicit ctx: Context): Context = { + def prepLiteral(tree: Literal, start: Int)(using Context): Context = { val phase = nxLiteralPrepPhase(start) if (phase == null) ctx - else prepLiteral(tree, phase.idxInGroup + 1)(phase.prepareForLiteral(tree)) + else prepLiteral(tree, phase.idxInGroup + 1)(using phase.prepareForLiteral(tree)) } - def goLiteral(tree: Literal, start: Int)(implicit ctx: Context): Tree = { + def goLiteral(tree: Literal, start: Int)(using Context): Tree = { val phase = nxLiteralTransPhase(start) if (phase == null) tree - else phase.transformLiteral(tree)(ctx) match { + else phase.transformLiteral(tree)(using ctx) match { case tree1: Literal => goLiteral(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepNew(tree: New, start: Int)(implicit ctx: Context): Context = { + def prepNew(tree: New, start: Int)(using Context): Context = { val phase = nxNewPrepPhase(start) if (phase == null) ctx - else prepNew(tree, phase.idxInGroup + 1)(phase.prepareForNew(tree)) + else prepNew(tree, phase.idxInGroup + 1)(using phase.prepareForNew(tree)) } - def goNew(tree: New, start: Int)(implicit ctx: Context): Tree = { + def goNew(tree: New, start: Int)(using Context): Tree = { val phase = nxNewTransPhase(start) if (phase == null) tree - else phase.transformNew(tree)(ctx) match { + else phase.transformNew(tree)(using ctx) match { case tree1: New => goNew(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepTyped(tree: Typed, start: Int)(implicit ctx: Context): Context = { + def prepTyped(tree: Typed, start: Int)(using Context): Context = { val phase = nxTypedPrepPhase(start) if (phase == null) ctx - else prepTyped(tree, phase.idxInGroup + 1)(phase.prepareForTyped(tree)) + else prepTyped(tree, phase.idxInGroup + 1)(using phase.prepareForTyped(tree)) } - def goTyped(tree: Typed, start: Int)(implicit ctx: Context): Tree = { + def goTyped(tree: Typed, start: Int)(using Context): Tree = { val phase = nxTypedTransPhase(start) if (phase == null) tree - else phase.transformTyped(tree)(ctx) match { + else phase.transformTyped(tree)(using ctx) match { case tree1: Typed => goTyped(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepAssign(tree: Assign, start: Int)(implicit ctx: Context): Context = { + def prepAssign(tree: Assign, start: Int)(using Context): Context = { val phase = nxAssignPrepPhase(start) if (phase == null) ctx - else prepAssign(tree, phase.idxInGroup + 1)(phase.prepareForAssign(tree)) + else prepAssign(tree, phase.idxInGroup + 1)(using phase.prepareForAssign(tree)) } - def goAssign(tree: Assign, start: Int)(implicit ctx: Context): Tree = { + def goAssign(tree: Assign, start: Int)(using Context): Tree = { val phase = nxAssignTransPhase(start) if (phase == null) tree - else phase.transformAssign(tree)(ctx) match { + else phase.transformAssign(tree)(using ctx) match { case tree1: Assign => goAssign(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepBlock(tree: Block, start: Int)(implicit ctx: Context): Context = { + def prepBlock(tree: Block, start: Int)(using Context): Context = { val phase = nxBlockPrepPhase(start) if (phase == null) ctx - else prepBlock(tree, phase.idxInGroup + 1)(phase.prepareForBlock(tree)) + else prepBlock(tree, phase.idxInGroup + 1)(using phase.prepareForBlock(tree)) } - def goBlock(tree: Block, start: Int)(implicit ctx: Context): Tree = { + def goBlock(tree: Block, start: Int)(using Context): Tree = { val phase = nxBlockTransPhase(start) if (phase == null) tree - else phase.transformBlock(tree)(ctx) match { + else phase.transformBlock(tree)(using ctx) match { case tree1: Block => goBlock(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepIf(tree: If, start: Int)(implicit ctx: Context): Context = { + def prepIf(tree: If, start: Int)(using Context): Context = { val phase = nxIfPrepPhase(start) if (phase == null) ctx - else prepIf(tree, phase.idxInGroup + 1)(phase.prepareForIf(tree)) + else prepIf(tree, phase.idxInGroup + 1)(using phase.prepareForIf(tree)) } - def goIf(tree: If, start: Int)(implicit ctx: Context): Tree = { + def goIf(tree: If, start: Int)(using Context): Tree = { val phase = nxIfTransPhase(start) if (phase == null) tree - else phase.transformIf(tree)(ctx) match { + else phase.transformIf(tree)(using ctx) match { case tree1: If => goIf(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepClosure(tree: Closure, start: Int)(implicit ctx: Context): Context = { + def prepClosure(tree: Closure, start: Int)(using Context): Context = { val phase = nxClosurePrepPhase(start) if (phase == null) ctx - else prepClosure(tree, phase.idxInGroup + 1)(phase.prepareForClosure(tree)) + else prepClosure(tree, phase.idxInGroup + 1)(using phase.prepareForClosure(tree)) } - def goClosure(tree: Closure, start: Int)(implicit ctx: Context): Tree = { + def goClosure(tree: Closure, start: Int)(using Context): Tree = { val phase = nxClosureTransPhase(start) if (phase == null) tree - else phase.transformClosure(tree)(ctx) match { + else phase.transformClosure(tree)(using ctx) match { case tree1: Closure => goClosure(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepMatch(tree: Match, start: Int)(implicit ctx: Context): Context = { + def prepMatch(tree: Match, start: Int)(using Context): Context = { val phase = nxMatchPrepPhase(start) if (phase == null) ctx - else prepMatch(tree, phase.idxInGroup + 1)(phase.prepareForMatch(tree)) + else prepMatch(tree, phase.idxInGroup + 1)(using phase.prepareForMatch(tree)) } - def goMatch(tree: Match, start: Int)(implicit ctx: Context): Tree = { + def goMatch(tree: Match, start: Int)(using Context): Tree = { val phase = nxMatchTransPhase(start) if (phase == null) tree - else phase.transformMatch(tree)(ctx) match { + else phase.transformMatch(tree)(using ctx) match { case tree1: Match => goMatch(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepCaseDef(tree: CaseDef, start: Int)(implicit ctx: Context): Context = { + def prepCaseDef(tree: CaseDef, start: Int)(using Context): Context = { val phase = nxCaseDefPrepPhase(start) if (phase == null) ctx - else prepCaseDef(tree, phase.idxInGroup + 1)(phase.prepareForCaseDef(tree)) + else prepCaseDef(tree, phase.idxInGroup + 1)(using phase.prepareForCaseDef(tree)) } - def goCaseDef(tree: CaseDef, start: Int)(implicit ctx: Context): Tree = { + def goCaseDef(tree: CaseDef, start: Int)(using Context): Tree = { val phase = nxCaseDefTransPhase(start) if (phase == null) tree - else phase.transformCaseDef(tree)(ctx) match { + else phase.transformCaseDef(tree)(using ctx) match { case tree1: CaseDef => goCaseDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepLabeled(tree: Labeled, start: Int)(implicit ctx: Context): Context = { + def prepLabeled(tree: Labeled, start: Int)(using Context): Context = { val phase = nxLabeledPrepPhase(start) if (phase == null) ctx - else prepLabeled(tree, phase.idxInGroup + 1)(phase.prepareForLabeled(tree)) + else prepLabeled(tree, phase.idxInGroup + 1)(using phase.prepareForLabeled(tree)) } - def goLabeled(tree: Labeled, start: Int)(implicit ctx: Context): Tree = { + def goLabeled(tree: Labeled, start: Int)(using Context): Tree = { val phase = nxLabeledTransPhase(start) if (phase == null) tree - else phase.transformLabeled(tree)(ctx) match { + else phase.transformLabeled(tree)(using ctx) match { case tree1: Labeled => goLabeled(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepReturn(tree: Return, start: Int)(implicit ctx: Context): Context = { + def prepReturn(tree: Return, start: Int)(using Context): Context = { val phase = nxReturnPrepPhase(start) if (phase == null) ctx - else prepReturn(tree, phase.idxInGroup + 1)(phase.prepareForReturn(tree)) + else prepReturn(tree, phase.idxInGroup + 1)(using phase.prepareForReturn(tree)) } - def goReturn(tree: Return, start: Int)(implicit ctx: Context): Tree = { + def goReturn(tree: Return, start: Int)(using Context): Tree = { val phase = nxReturnTransPhase(start) if (phase == null) tree - else phase.transformReturn(tree)(ctx) match { + else phase.transformReturn(tree)(using ctx) match { case tree1: Return => goReturn(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepWhileDo(tree: WhileDo, start: Int)(implicit ctx: Context): Context = { + def prepWhileDo(tree: WhileDo, start: Int)(using Context): Context = { val phase = nxWhileDoPrepPhase(start) if (phase == null) ctx - else prepWhileDo(tree, phase.idxInGroup + 1)(phase.prepareForWhileDo(tree)) + else prepWhileDo(tree, phase.idxInGroup + 1)(using phase.prepareForWhileDo(tree)) } - def goWhileDo(tree: WhileDo, start: Int)(implicit ctx: Context): Tree = { + def goWhileDo(tree: WhileDo, start: Int)(using Context): Tree = { val phase = nxWhileDoTransPhase(start) if (phase == null) tree - else phase.transformWhileDo(tree)(ctx) match { + else phase.transformWhileDo(tree)(using ctx) match { case tree1: WhileDo => goWhileDo(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepTry(tree: Try, start: Int)(implicit ctx: Context): Context = { + def prepTry(tree: Try, start: Int)(using Context): Context = { val phase = nxTryPrepPhase(start) if (phase == null) ctx - else prepTry(tree, phase.idxInGroup + 1)(phase.prepareForTry(tree)) + else prepTry(tree, phase.idxInGroup + 1)(using phase.prepareForTry(tree)) } - def goTry(tree: Try, start: Int)(implicit ctx: Context): Tree = { + def goTry(tree: Try, start: Int)(using Context): Tree = { val phase = nxTryTransPhase(start) if (phase == null) tree - else phase.transformTry(tree)(ctx) match { + else phase.transformTry(tree)(using ctx) match { case tree1: Try => goTry(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepSeqLiteral(tree: SeqLiteral, start: Int)(implicit ctx: Context): Context = { + def prepSeqLiteral(tree: SeqLiteral, start: Int)(using Context): Context = { val phase = nxSeqLiteralPrepPhase(start) if (phase == null) ctx - else prepSeqLiteral(tree, phase.idxInGroup + 1)(phase.prepareForSeqLiteral(tree)) + else prepSeqLiteral(tree, phase.idxInGroup + 1)(using phase.prepareForSeqLiteral(tree)) } - def goSeqLiteral(tree: SeqLiteral, start: Int)(implicit ctx: Context): Tree = { + def goSeqLiteral(tree: SeqLiteral, start: Int)(using Context): Tree = { val phase = nxSeqLiteralTransPhase(start) if (phase == null) tree - else phase.transformSeqLiteral(tree)(ctx) match { + else phase.transformSeqLiteral(tree)(using ctx) match { case tree1: SeqLiteral => goSeqLiteral(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepInlined(tree: Inlined, start: Int)(implicit ctx: Context): Context = { + def prepInlined(tree: Inlined, start: Int)(using Context): Context = { val phase = nxInlinedPrepPhase(start) if (phase == null) ctx - else prepInlined(tree, phase.idxInGroup + 1)(phase.prepareForInlined(tree)) + else prepInlined(tree, phase.idxInGroup + 1)(using phase.prepareForInlined(tree)) } - def goInlined(tree: Inlined, start: Int)(implicit ctx: Context): Tree = { + def goInlined(tree: Inlined, start: Int)(using Context): Tree = { val phase = nxInlinedTransPhase(start) if (phase == null) tree - else phase.transformInlined(tree)(ctx) match { + else phase.transformInlined(tree)(using ctx) match { case tree1: Inlined => goInlined(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepTypeTree(tree: TypeTree, start: Int)(implicit ctx: Context): Context = { + def prepTypeTree(tree: TypeTree, start: Int)(using Context): Context = { val phase = nxTypeTreePrepPhase(start) if (phase == null) ctx - else prepTypeTree(tree, phase.idxInGroup + 1)(phase.prepareForTypeTree(tree)) + else prepTypeTree(tree, phase.idxInGroup + 1)(using phase.prepareForTypeTree(tree)) } - def goTypeTree(tree: TypeTree, start: Int)(implicit ctx: Context): Tree = { + def goTypeTree(tree: TypeTree, start: Int)(using Context): Tree = { val phase = nxTypeTreeTransPhase(start) if (phase == null) tree - else phase.transformTypeTree(tree)(ctx) match { + else phase.transformTypeTree(tree)(using ctx) match { case tree1: TypeTree => goTypeTree(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepBind(tree: Bind, start: Int)(implicit ctx: Context): Context = { + def prepBind(tree: Bind, start: Int)(using Context): Context = { val phase = nxBindPrepPhase(start) if (phase == null) ctx - else prepBind(tree, phase.idxInGroup + 1)(phase.prepareForBind(tree)) + else prepBind(tree, phase.idxInGroup + 1)(using phase.prepareForBind(tree)) } - def goBind(tree: Bind, start: Int)(implicit ctx: Context): Tree = { + def goBind(tree: Bind, start: Int)(using Context): Tree = { val phase = nxBindTransPhase(start) if (phase == null) tree - else phase.transformBind(tree)(ctx) match { + else phase.transformBind(tree)(using ctx) match { case tree1: Bind => goBind(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepAlternative(tree: Alternative, start: Int)(implicit ctx: Context): Context = { + def prepAlternative(tree: Alternative, start: Int)(using Context): Context = { val phase = nxAlternativePrepPhase(start) if (phase == null) ctx - else prepAlternative(tree, phase.idxInGroup + 1)(phase.prepareForAlternative(tree)) + else prepAlternative(tree, phase.idxInGroup + 1)(using phase.prepareForAlternative(tree)) } - def goAlternative(tree: Alternative, start: Int)(implicit ctx: Context): Tree = { + def goAlternative(tree: Alternative, start: Int)(using Context): Tree = { val phase = nxAlternativeTransPhase(start) if (phase == null) tree - else phase.transformAlternative(tree)(ctx) match { + else phase.transformAlternative(tree)(using ctx) match { case tree1: Alternative => goAlternative(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepUnApply(tree: UnApply, start: Int)(implicit ctx: Context): Context = { + def prepUnApply(tree: UnApply, start: Int)(using Context): Context = { val phase = nxUnApplyPrepPhase(start) if (phase == null) ctx - else prepUnApply(tree, phase.idxInGroup + 1)(phase.prepareForUnApply(tree)) + else prepUnApply(tree, phase.idxInGroup + 1)(using phase.prepareForUnApply(tree)) } - def goUnApply(tree: UnApply, start: Int)(implicit ctx: Context): Tree = { + def goUnApply(tree: UnApply, start: Int)(using Context): Tree = { val phase = nxUnApplyTransPhase(start) if (phase == null) tree - else phase.transformUnApply(tree)(ctx) match { + else phase.transformUnApply(tree)(using ctx) match { case tree1: UnApply => goUnApply(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepValDef(tree: ValDef, start: Int)(implicit ctx: Context): Context = { + def prepValDef(tree: ValDef, start: Int)(using Context): Context = { val phase = nxValDefPrepPhase(start) if (phase == null) ctx - else prepValDef(tree, phase.idxInGroup + 1)(phase.prepareForValDef(tree)) + else prepValDef(tree, phase.idxInGroup + 1)(using phase.prepareForValDef(tree)) } - def goValDef(tree: ValDef, start: Int)(implicit ctx: Context): Tree = { + def goValDef(tree: ValDef, start: Int)(using Context): Tree = { val phase = nxValDefTransPhase(start) if (phase == null) tree - else phase.transformValDef(tree)(ctx) match { + else phase.transformValDef(tree)(using ctx) match { case tree1: ValDef => goValDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepDefDef(tree: DefDef, start: Int)(implicit ctx: Context): Context = { + def prepDefDef(tree: DefDef, start: Int)(using Context): Context = { val phase = nxDefDefPrepPhase(start) if (phase == null) ctx - else prepDefDef(tree, phase.idxInGroup + 1)(phase.prepareForDefDef(tree)) + else prepDefDef(tree, phase.idxInGroup + 1)(using phase.prepareForDefDef(tree)) } - def goDefDef(tree: DefDef, start: Int)(implicit ctx: Context): Tree = { + def goDefDef(tree: DefDef, start: Int)(using Context): Tree = { val phase = nxDefDefTransPhase(start) if (phase == null) tree - else phase.transformDefDef(tree)(ctx) match { + else phase.transformDefDef(tree)(using ctx) match { case tree1: DefDef => goDefDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepTypeDef(tree: TypeDef, start: Int)(implicit ctx: Context): Context = { + def prepTypeDef(tree: TypeDef, start: Int)(using Context): Context = { val phase = nxTypeDefPrepPhase(start) if (phase == null) ctx - else prepTypeDef(tree, phase.idxInGroup + 1)(phase.prepareForTypeDef(tree)) + else prepTypeDef(tree, phase.idxInGroup + 1)(using phase.prepareForTypeDef(tree)) } - def goTypeDef(tree: TypeDef, start: Int)(implicit ctx: Context): Tree = { + def goTypeDef(tree: TypeDef, start: Int)(using Context): Tree = { val phase = nxTypeDefTransPhase(start) if (phase == null) tree - else phase.transformTypeDef(tree)(ctx) match { + else phase.transformTypeDef(tree)(using ctx) match { case tree1: TypeDef => goTypeDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepTemplate(tree: Template, start: Int)(implicit ctx: Context): Context = { + def prepTemplate(tree: Template, start: Int)(using Context): Context = { val phase = nxTemplatePrepPhase(start) if (phase == null) ctx - else prepTemplate(tree, phase.idxInGroup + 1)(phase.prepareForTemplate(tree)) + else prepTemplate(tree, phase.idxInGroup + 1)(using phase.prepareForTemplate(tree)) } - def goTemplate(tree: Template, start: Int)(implicit ctx: Context): Tree = { + def goTemplate(tree: Template, start: Int)(using Context): Tree = { val phase = nxTemplateTransPhase(start) if (phase == null) tree - else phase.transformTemplate(tree)(ctx) match { + else phase.transformTemplate(tree)(using ctx) match { case tree1: Template => goTemplate(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepPackageDef(tree: PackageDef, start: Int)(implicit ctx: Context): Context = { + def prepPackageDef(tree: PackageDef, start: Int)(using Context): Context = { val phase = nxPackageDefPrepPhase(start) if (phase == null) ctx - else prepPackageDef(tree, phase.idxInGroup + 1)(phase.prepareForPackageDef(tree)) + else prepPackageDef(tree, phase.idxInGroup + 1)(using phase.prepareForPackageDef(tree)) } - def goPackageDef(tree: PackageDef, start: Int)(implicit ctx: Context): Tree = { + def goPackageDef(tree: PackageDef, start: Int)(using Context): Tree = { val phase = nxPackageDefTransPhase(start) if (phase == null) tree - else phase.transformPackageDef(tree)(ctx) match { + else phase.transformPackageDef(tree)(using ctx) match { case tree1: PackageDef => goPackageDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } } - def prepStats(trees: List[Tree], start: Int)(implicit ctx: Context): Context = { + def prepStats(trees: List[Tree], start: Int)(using Context): Context = { val phase = nxStatsPrepPhase(start) if (phase == null) ctx - else prepStats(trees, phase.idxInGroup + 1)(phase.prepareForStats(trees)) + else prepStats(trees, phase.idxInGroup + 1)(using phase.prepareForStats(trees)) } - def goStats(trees: List[Tree], start: Int)(implicit ctx: Context): List[Tree] = { + def goStats(trees: List[Tree], start: Int)(using Context): List[Tree] = { val phase = nxStatsTransPhase(start) if (phase == null) trees - else goStats(phase.transformStats(trees)(ctx), phase.idxInGroup + 1) + else goStats(phase.transformStats(trees)(using ctx), phase.idxInGroup + 1) } - def prepUnit(tree: Tree, start: Int)(implicit ctx: Context): Context = { + def prepUnit(tree: Tree, start: Int)(using Context): Context = { val phase = nxUnitPrepPhase(start) if (phase == null) ctx - else prepUnit(tree, phase.idxInGroup + 1)(phase.prepareForUnit(tree)) + else prepUnit(tree, phase.idxInGroup + 1)(using phase.prepareForUnit(tree)) } - def goUnit(tree: Tree, start: Int)(implicit ctx: Context): Tree = { + def goUnit(tree: Tree, start: Int)(using Context): Tree = { val phase = nxUnitTransPhase(start) if (phase == null) tree - else goUnit(phase.transformUnit(tree)(ctx), phase.idxInGroup + 1) + else goUnit(phase.transformUnit(tree)(using ctx), phase.idxInGroup + 1) } - def prepOther(tree: Tree, start: Int)(implicit ctx: Context): Context = { + def prepOther(tree: Tree, start: Int)(using Context): Context = { val phase = nxOtherPrepPhase(start) if (phase == null) ctx - else prepOther(tree, phase.idxInGroup + 1)(phase.prepareForOther(tree)) + else prepOther(tree, phase.idxInGroup + 1)(using phase.prepareForOther(tree)) } - def goOther(tree: Tree, start: Int)(implicit ctx: Context): Tree = { + def goOther(tree: Tree, start: Int)(using Context): Tree = { val phase = nxOtherTransPhase(start) if (phase == null) tree - else goOther(phase.transformOther(tree)(ctx), phase.idxInGroup + 1) + else goOther(phase.transformOther(tree)(using ctx), phase.idxInGroup + 1) } } diff --git a/compiler/src/dotty/tools/dotc/transform/Memoize.scala b/compiler/src/dotty/tools/dotc/transform/Memoize.scala index 4e48c4fb9f1e..763362c01d35 100644 --- a/compiler/src/dotty/tools/dotc/transform/Memoize.scala +++ b/compiler/src/dotty/tools/dotc/transform/Memoize.scala @@ -132,7 +132,7 @@ class Memoize extends MiniPhase with IdentityDenotTransformer { thisPhase => val rhsClass = tree.tpt.tpe.widenDealias.classSymbol val getterRhs = if (isErasableBottomField(rhsClass)) erasedBottomTree(rhsClass) - else transformFollowingDeep(ref(field))(ctx.withOwner(sym)) + else transformFollowingDeep(ref(field))(using ctx.withOwner(sym)) val getterDef = cpy.DefDef(tree)(rhs = getterRhs) addAnnotations(fieldDef.denot) removeAnnotations(sym) @@ -144,7 +144,7 @@ class Memoize extends MiniPhase with IdentityDenotTransformer { thisPhase => val initializer = if (isErasableBottomField(tree.vparamss.head.head.tpt.tpe.classSymbol)) Literal(Constant(())) else Assign(ref(field), adaptToField(ref(tree.vparamss.head.head.symbol))) - val setterDef = cpy.DefDef(tree)(rhs = transformFollowingDeep(initializer)(ctx.withOwner(sym))) + val setterDef = cpy.DefDef(tree)(rhs = transformFollowingDeep(initializer)(using ctx.withOwner(sym))) removeAnnotations(sym) setterDef } diff --git a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala index 7edbeb81201b..c93d550379ec 100644 --- a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala @@ -86,7 +86,7 @@ class ReifyQuotes extends MacroTransform { } override def run(implicit ctx: Context): Unit = - if (ctx.compilationUnit.needsStaging) super.run(freshStagingContext) + if (ctx.compilationUnit.needsStaging) super.run(using freshStagingContext) protected def newTransformer(implicit ctx: Context): Transformer = new Transformer { override def transform(tree: tpd.Tree)(implicit ctx: Context): tpd.Tree = diff --git a/compiler/src/dotty/tools/dotc/transform/Staging.scala b/compiler/src/dotty/tools/dotc/transform/Staging.scala index 7f5547239b92..05b9c4902592 100644 --- a/compiler/src/dotty/tools/dotc/transform/Staging.scala +++ b/compiler/src/dotty/tools/dotc/transform/Staging.scala @@ -73,7 +73,7 @@ class Staging extends MacroTransform { } override def run(implicit ctx: Context): Unit = - if (ctx.compilationUnit.needsStaging) super.run(freshStagingContext) + if (ctx.compilationUnit.needsStaging) super.run(using freshStagingContext) protected def newTransformer(implicit ctx: Context): Transformer = new Transformer { override def transform(tree: tpd.Tree)(implicit ctx: Context): tpd.Tree = From 1798e29d5008bf45276c0ce8d28dce91f5354c2a Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 17:30:15 +0200 Subject: [PATCH 23/41] Convert transform classes (3) --- .../dotty/tools/dotc/transform/Memoize.scala | 4 +- .../dotty/tools/dotc/transform/Mixin.scala | 6 +- .../dotty/tools/dotc/transform/MixinOps.scala | 2 +- .../tools/dotc/transform/MoveStatics.scala | 4 +- .../dotc/transform/NonLocalReturns.scala | 16 ++--- .../dotc/transform/OverridingPairs.scala | 2 +- .../dotc/transform/PCPCheckAndHeal.scala | 14 ++-- .../tools/dotc/transform/PatternMatcher.scala | 16 ++--- .../dotty/tools/dotc/transform/Pickler.scala | 14 ++-- .../tools/dotc/transform/PostTyper.scala | 24 +++---- .../dotc/transform/ProtectedAccessors.scala | 18 +++--- .../dotc/transform/PruneErasedDefs.scala | 8 +-- .../tools/dotc/transform/PureStats.scala | 2 +- .../tools/dotc/transform/ReifyQuotes.scala | 50 +++++++-------- .../tools/dotc/transform/RenameLifted.scala | 6 +- .../tools/dotc/transform/ResolveSuper.scala | 6 +- .../tools/dotc/transform/RestoreScopes.scala | 4 +- .../tools/dotc/transform/SelectStatic.scala | 10 +-- .../tools/dotc/transform/SeqLiterals.scala | 4 +- .../tools/dotc/transform/SetRootTree.scala | 6 +- .../dotty/tools/dotc/transform/Splicer.scala | 12 ++-- .../dotty/tools/dotc/transform/Staging.scala | 10 +-- .../tools/dotc/transform/SuperAccessors.scala | 16 ++--- .../dotty/tools/dotc/transform/SymUtils.scala | 64 +++++++++---------- .../dotc/transform/SyntheticMembers.scala | 48 +++++++------- 25 files changed, 183 insertions(+), 183 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/transform/Memoize.scala b/compiler/src/dotty/tools/dotc/transform/Memoize.scala index 763362c01d35..2e955d85bb76 100644 --- a/compiler/src/dotty/tools/dotc/transform/Memoize.scala +++ b/compiler/src/dotty/tools/dotc/transform/Memoize.scala @@ -41,7 +41,7 @@ class Memoize extends MiniPhase with IdentityDenotTransformer { thisPhase => /* Makes sure that, after getters and constructors gen, there doesn't * exist non-deferred definitions that are not implemented. */ - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = { + 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 @@ -68,7 +68,7 @@ class Memoize extends MiniPhase with IdentityDenotTransformer { thisPhase => */ override def runsAfter: Set[String] = Set(Mixin.name) - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(tree: DefDef)(using Context): Tree = { val sym = tree.symbol def newField = { diff --git a/compiler/src/dotty/tools/dotc/transform/Mixin.scala b/compiler/src/dotty/tools/dotc/transform/Mixin.scala index 078f326647a9..0a35f48d86c6 100644 --- a/compiler/src/dotty/tools/dotc/transform/Mixin.scala +++ b/compiler/src/dotty/tools/dotc/transform/Mixin.scala @@ -120,7 +120,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => override def changesMembers: Boolean = true // the phase adds implementions of mixin accessors - override def transformSym(sym: SymDenotation)(implicit ctx: Context): SymDenotation = + override def transformSym(sym: SymDenotation)(using Context): SymDenotation = if (sym.is(Accessor, butNot = Deferred) && sym.owner.is(Trait)) { val sym1 = if (sym.is(Lazy)) sym @@ -134,7 +134,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => else sym - private def initializer(sym: Symbol)(implicit ctx: Context): TermSymbol = { + private def initializer(sym: Symbol)(using Context): TermSymbol = { if (sym.is(Lazy)) sym else { val initName = InitializerName(sym.name.asTermName) @@ -149,7 +149,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => } }.asTerm - override def transformTemplate(impl: Template)(implicit ctx: Context): Template = { + override def transformTemplate(impl: Template)(using Context): Template = { val cls = impl.symbol.owner.asClass val ops = new MixinOps(cls, thisPhase) import ops._ diff --git a/compiler/src/dotty/tools/dotc/transform/MixinOps.scala b/compiler/src/dotty/tools/dotc/transform/MixinOps.scala index 16a767cd1932..090ad4543e88 100644 --- a/compiler/src/dotty/tools/dotc/transform/MixinOps.scala +++ b/compiler/src/dotty/tools/dotc/transform/MixinOps.scala @@ -8,7 +8,7 @@ import SymUtils._ import StdNames._, NameOps._ import Decorators._ -class MixinOps(cls: ClassSymbol, thisPhase: DenotTransformer)(implicit ctx: Context) { +class MixinOps(cls: ClassSymbol, thisPhase: DenotTransformer)(using Context) { import ast.tpd._ val superCls: Symbol = cls.superClass diff --git a/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala b/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala index 574e45873c80..2b69b431017d 100644 --- a/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala +++ b/compiler/src/dotty/tools/dotc/transform/MoveStatics.scala @@ -23,7 +23,7 @@ class MoveStatics extends MiniPhase with SymTransformer { import tpd._ override def phaseName: String = MoveStatics.name - def transformSym(sym: SymDenotation)(implicit ctx: Context): SymDenotation = + def transformSym(sym: SymDenotation)(using Context): SymDenotation = if (sym.hasAnnotation(defn.ScalaStaticAnnot) && sym.owner.is(Flags.Module) && sym.owner.companionClass.exists && (sym.is(Flags.Method) || !(sym.is(Flags.Mutable) && sym.owner.companionClass.is(Flags.Trait)))) { sym.owner.asClass.delete(sym.symbol) @@ -32,7 +32,7 @@ class MoveStatics extends MiniPhase with SymTransformer { } else sym - override def transformStats(trees: List[Tree])(implicit ctx: Context): List[Tree] = + override def transformStats(trees: List[Tree])(using Context): List[Tree] = if (ctx.owner.is(Flags.Package)) { val (classes, others) = trees.partition(x => x.isInstanceOf[TypeDef] && x.symbol.isClass) val pairs = classes.groupBy(_.symbol.name.stripModuleClassSuffix).asInstanceOf[Map[Name, List[TypeDef]]] diff --git a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala index c50cb5c1f26b..14837ee8574b 100644 --- a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala +++ b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala @@ -10,7 +10,7 @@ import config.SourceVersion._ object NonLocalReturns { import ast.tpd._ - def isNonLocalReturn(ret: Return)(implicit ctx: Context): Boolean = + def isNonLocalReturn(ret: Return)(using Context): Boolean = !ret.from.symbol.is(Label) && (ret.from.symbol != ctx.owner.enclosingMethod || ctx.owner.is(Lazy)) } @@ -24,21 +24,21 @@ class NonLocalReturns extends MiniPhase { override def runsAfter: Set[String] = Set(ElimByName.name) - private def ensureConforms(tree: Tree, pt: Type)(implicit ctx: Context) = + private def ensureConforms(tree: Tree, pt: Type)(using Context) = if (tree.tpe <:< pt) tree else Erasure.Boxing.adaptToType(tree, pt) private def nonLocalReturnControl(using Context) = defn.NonLocalReturnControlClass.typeRef /** The type of a non-local return expression with given argument type */ - private def nonLocalReturnExceptionType(argtype: Type)(implicit ctx: Context) = + private def nonLocalReturnExceptionType(argtype: Type)(using Context) = nonLocalReturnControl.appliedTo(argtype) /** A hashmap from method symbols to non-local return keys */ private val nonLocalReturnKeys = newMutableSymbolMap[TermSymbol] /** Return non-local return key for given method */ - private def nonLocalReturnKey(meth: Symbol)(implicit ctx: Context) = + private def nonLocalReturnKey(meth: Symbol)(using Context) = nonLocalReturnKeys.getOrElseUpdate(meth, ctx.newSymbol( meth, NonLocalReturnKeyName.fresh(), Synthetic, defn.ObjectType, coord = meth.span)) @@ -50,7 +50,7 @@ class NonLocalReturns extends MiniPhase { * todo: maybe clone a pre-existing exception instead? * (but what to do about exceptions that miss their targets?) */ - private def nonLocalReturnThrow(expr: Tree, meth: Symbol)(implicit ctx: Context) = + private def nonLocalReturnThrow(expr: Tree, meth: Symbol)(using Context) = Throw( New( nonLocalReturnControl, @@ -69,7 +69,7 @@ class NonLocalReturns extends MiniPhase { * } * } */ - private def nonLocalReturnTry(body: Tree, key: TermSymbol, meth: Symbol)(implicit ctx: Context) = { + 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 pat = BindTyped(ex, nonLocalReturnControl) @@ -82,13 +82,13 @@ class NonLocalReturns extends MiniPhase { Block(keyDef :: Nil, tryCatch) } - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = + override def transformDefDef(tree: DefDef)(using Context): Tree = nonLocalReturnKeys.remove(tree.symbol) match { case Some(key) => cpy.DefDef(tree)(rhs = nonLocalReturnTry(tree.rhs, key, tree.symbol)) case _ => tree } - override def transformReturn(tree: Return)(implicit ctx: Context): Tree = + 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) diff --git a/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala b/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala index db25e1a75414..4e0df7fb6bbc 100644 --- a/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala +++ b/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala @@ -20,7 +20,7 @@ object OverridingPairs { /** The cursor class * @param base the base class that contains the overriding pairs */ - class Cursor(base: Symbol)(implicit ctx: Context) { + class Cursor(base: Symbol)(using Context) { private val self = base.thisType diff --git a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala index 23cfd3edbc69..7e101b652fdf 100644 --- a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala +++ b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala @@ -60,9 +60,9 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( private val InAnnotation = Property.Key[Unit]() - override def transform(tree: Tree)(implicit ctx: Context): Tree = + override def transform(tree: Tree)(using Context): Tree = if (tree.source != ctx.source && tree.source.exists) - transform(tree)(ctx.withSource(tree.source)) + transform(tree)(using ctx.withSource(tree.source)) else if !isInQuoteOrSplice then checkAnnotations(tree) super.transform(tree) @@ -100,7 +100,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( } /** Transform quoted trees while maintaining phase correctness */ - override protected def transformQuotation(body: Tree, quote: Tree)(implicit ctx: Context): Tree = { + override protected def transformQuotation(body: Tree, quote: Tree)(using Context): Tree = { val taggedTypes = new PCPCheckAndHeal.QuoteTypeTags(quote.span)(using ctx) if (ctx.property(InAnnotation).isDefined) @@ -109,7 +109,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( val contextWithQuote = if level == 0 then contextWithQuoteTypeTags(taggedTypes)(using quoteContext) else quoteContext - val body1 = transform(body)(contextWithQuote) + val body1 = transform(body)(using contextWithQuote) val body2 = taggedTypes.getTypeTags match case Nil => body1 @@ -123,8 +123,8 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( * - If inside inlined code, expand the macro code. * - If inside of a macro definition, check the validity of the macro. */ - protected def transformSplice(body: Tree, splice: Tree)(implicit ctx: Context): Tree = { - val body1 = transform(body)(spliceContext) + protected def transformSplice(body: Tree, splice: Tree)(using Context): Tree = { + val body1 = transform(body)(using spliceContext) splice match { case Apply(fun @ TypeApply(_, _ :: Nil), _) if splice.isTerm => // Type of the splice itsel must also be healed @@ -216,7 +216,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( * refercence to a type alias containing the equivalent of `${summon[quoted.Type[T]]}`. * Emits and error if `T` cannot be healed and returns `T`. */ - protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SourcePosition)(implicit ctx: Context): TypeRef = { + protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SourcePosition)(using Context): TypeRef = { val reqType = defn.QuotedTypeClass.typeRef.appliedTo(tp) val tag = ctx.typer.inferImplicitArg(reqType, pos.span) tag.tpe match diff --git a/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala b/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala index 361004d4e71e..750683a0419c 100644 --- a/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala +++ b/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala @@ -29,7 +29,7 @@ class PatternMatcher extends MiniPhase { override def phaseName: String = PatternMatcher.name override def runsAfter: Set[String] = Set(ElimRepeated.name) - override def transformMatch(tree: Match)(implicit ctx: Context): Tree = + override def transformMatch(tree: Match)(using Context): Tree = if (tree.isInstanceOf[InlineMatch]) tree else { // Widen termrefs with underlying `=> T` types. Otherwise ElimByName will produce @@ -62,7 +62,7 @@ object PatternMatcher { val TrustedTypeTestKey: Key[Unit] = new StickyKey[Unit] /** Was symbol generated by pattern matcher? */ - def isPatmatGenerated(sym: Symbol)(implicit ctx: Context): Boolean = + def isPatmatGenerated(sym: Symbol)(using Context): Boolean = sym.is(Synthetic) && sym.name.is(PatMatStdBinderName) /** The pattern matching translator. @@ -82,7 +82,7 @@ object PatternMatcher { * It's represented by its own data type. Plans are optimized by merging common * tests and eliminating dead code. */ - class Translator(resultType: Type, thisPhase: MiniPhase)(implicit ctx: Context) { + class Translator(resultType: Type, thisPhase: MiniPhase)(using Context) { // ------- Bindings for variables and labels --------------------- @@ -383,7 +383,7 @@ object PatternMatcher { assert(mt.isImplicitMethod || mt.isContextualMethod) val (args, rest) = implicits.splitAt(mt.paramNames.size) applyImplicits(acc.appliedToArgs(args), rest, mt.resultType) - case _ => + case _ => assert(implicits.isEmpty) acc } @@ -442,7 +442,7 @@ object PatternMatcher { /** A superclass for plan transforms */ class PlanTransform extends (Plan => Plan) { protected val treeMap: TreeMap = new TreeMap { - override def transform(tree: Tree)(implicit ctx: Context) = tree + override def transform(tree: Tree)(using Context) = tree } def apply(tree: Tree): Tree = treeMap.transform(tree) def apply(plan: TestPlan): Plan = { @@ -501,7 +501,7 @@ object PatternMatcher { private def varRefCount(plan: Plan): collection.Map[Symbol, Int] = { object refCounter extends RefCounter { override val treeMap = new TreeMap { - override def transform(tree: Tree)(implicit ctx: Context) = tree match { + override def transform(tree: Tree)(using Context) = tree match { case tree: Ident => if (isPatmatGenerated(tree.symbol)) count(tree.symbol) += 1 tree @@ -563,7 +563,7 @@ object PatternMatcher { def mergeTests(plan: Plan): Plan = { class SubstituteIdent(from: TermSymbol, to: TermSymbol) extends PlanTransform { override val treeMap = new TreeMap { - override def transform(tree: Tree)(implicit ctx: Context) = tree match { + override def transform(tree: Tree)(using Context) = tree match { case tree: Ident if tree.symbol == from => ref(to) case _ => super.transform(tree) } @@ -646,7 +646,7 @@ object PatternMatcher { object Inliner extends PlanTransform { override val treeMap = new TreeMap { - override def transform(tree: Tree)(implicit ctx: Context) = tree match { + override def transform(tree: Tree)(using Context) = tree match { case tree: Ident => val sym = tree.symbol if (toDrop(sym)) transform(initializer(sym)) diff --git a/compiler/src/dotty/tools/dotc/transform/Pickler.scala b/compiler/src/dotty/tools/dotc/transform/Pickler.scala index bdca26b52d2e..5d08b9d13f67 100644 --- a/compiler/src/dotty/tools/dotc/transform/Pickler.scala +++ b/compiler/src/dotty/tools/dotc/transform/Pickler.scala @@ -25,7 +25,7 @@ class Pickler extends Phase { override def phaseName: String = Pickler.name // No need to repickle trees coming from TASTY - override def isRunnable(implicit ctx: Context): Boolean = + override def isRunnable(using Context): Boolean = super.isRunnable && !ctx.settings.fromTasty.value private def output(name: String, msg: String) = { @@ -39,13 +39,13 @@ class Pickler extends Phase { private val picklers = new mutable.HashMap[ClassSymbol, TastyPickler] /** Drop any elements of this list that are linked module classes of other elements in the list */ - private def dropCompanionModuleClasses(clss: List[ClassSymbol])(implicit ctx: Context): List[ClassSymbol] = { + private def dropCompanionModuleClasses(clss: List[ClassSymbol])(using Context): List[ClassSymbol] = { val companionModuleClasses = clss.filterNot(_.is(Module)).map(_.linkedClass).filterNot(_.isAbsent()) clss.filterNot(companionModuleClasses.contains) } - override def run(implicit ctx: Context): Unit = { + override def run(using Context): Unit = { val unit = ctx.compilationUnit pickling.println(i"unpickling in run ${ctx.runId}") @@ -87,11 +87,11 @@ class Pickler extends Phase { } } - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { val result = super.runOn(units) if (ctx.settings.YtestPickler.value) testUnpickler( - ctx.fresh + using ctx.fresh .setPeriod(Period(ctx.runId + 1, FirstPhaseId)) .setReporter(new ThrowingReporter(ctx.reporter)) .addMode(Mode.ReadPositions) @@ -100,7 +100,7 @@ class Pickler extends Phase { result } - private def testUnpickler(implicit ctx: Context): Unit = { + private def testUnpickler(using Context): Unit = { pickling.println(i"testing unpickler at run ${ctx.runId}") ctx.initialize() val unpicklers = @@ -116,7 +116,7 @@ class Pickler extends Phase { } } - private def testSame(unpickled: String, previous: String, cls: ClassSymbol)(implicit ctx: Context) = + private def testSame(unpickled: String, previous: String, cls: ClassSymbol)(using Context) = if (previous != unpickled) { output("before-pickling.txt", previous) output("after-pickling.txt", unpickled) diff --git a/compiler/src/dotty/tools/dotc/transform/PostTyper.scala b/compiler/src/dotty/tools/dotc/transform/PostTyper.scala index d86aa086d917..ef21106f80c8 100644 --- a/compiler/src/dotty/tools/dotc/transform/PostTyper.scala +++ b/compiler/src/dotty/tools/dotc/transform/PostTyper.scala @@ -60,7 +60,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase /** the following two members override abstract members in Transform */ override def phaseName: String = PostTyper.name - override def checkPostCondition(tree: tpd.Tree)(implicit ctx: Context): Unit = tree match { + override def checkPostCondition(tree: tpd.Tree)(using Context): Unit = tree match { case tree: ValOrDefDef => assert(!tree.symbol.signature.isUnderDefined) case _ => @@ -68,9 +68,9 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase override def changesMembers: Boolean = true // the phase adds super accessors and synthetic members - override def transformPhase(implicit ctx: Context): Phase = thisPhase.next + override def transformPhase(using Context): Phase = thisPhase.next - protected def newTransformer(implicit ctx: Context): Transformer = + protected def newTransformer(using Context): Transformer = new PostTyperTransformer val superAcc: SuperAccessors = new SuperAccessors(thisPhase) @@ -81,7 +81,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase case _ => None } - private def checkValidJavaAnnotation(annot: Tree)(implicit ctx: Context): Unit = { + private def checkValidJavaAnnotation(annot: Tree)(using Context): Unit = { // TODO fill in } @@ -123,7 +123,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase case _ => case _ => - private def transformAnnot(annot: Tree)(implicit ctx: Context): Tree = { + private def transformAnnot(annot: Tree)(using Context): Tree = { val saved = inJavaAnnot inJavaAnnot = annot.symbol.is(JavaDefined) if (inJavaAnnot) checkValidJavaAnnotation(annot) @@ -131,10 +131,10 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase finally inJavaAnnot = saved } - private def transformAnnot(annot: Annotation)(implicit ctx: Context): Annotation = + private def transformAnnot(annot: Annotation)(using Context): Annotation = annot.derivedAnnotation(transformAnnot(annot.tree)) - private def processMemberDef(tree: Tree)(implicit ctx: Context): tree.type = { + private def processMemberDef(tree: Tree)(using Context): tree.type = { val sym = tree.symbol Checking.checkValidOperator(sym) sym.transformAnnotations(transformAnnot) @@ -164,7 +164,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase => Checking.checkAppliedTypesIn(tree) case _ => - private def transformSelect(tree: Select, targs: List[Tree])(implicit ctx: Context): Tree = { + private def transformSelect(tree: Select, targs: List[Tree])(using Context): Tree = { val qual = tree.qualifier qual.symbol.moduleClass.denot match { case pkg: PackageClassDenotation => @@ -180,7 +180,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase } } - private def normalizeTypeArgs(tree: TypeApply)(implicit ctx: Context): TypeApply = tree.tpe match { + private def normalizeTypeArgs(tree: TypeApply)(using Context): TypeApply = tree.tpe match { case pt: PolyType => // wait for more arguments coming tree case _ => @@ -216,7 +216,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase } private object dropInlines extends TreeMap { - override def transform(tree: Tree)(implicit ctx: Context): Tree = tree match { + override def transform(tree: Tree)(using Context): Tree = tree match { case Inlined(call, _, expansion) => val newExpansion = tree.tpe match case ConstantType(c) => Literal(c) @@ -226,7 +226,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase } } - override def transform(tree: Tree)(implicit ctx: Context): Tree = + override def transform(tree: Tree)(using Context): Tree = try tree match { case tree: Ident if !tree.isType => tree.tpe match { @@ -390,7 +390,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase /** Transforms the rhs tree into a its default tree if it is in an `erased` val/def. * Performed to shrink the tree that is known to be erased later. */ - private def normalizeErasedRhs(rhs: Tree, sym: Symbol)(implicit ctx: Context) = + private def normalizeErasedRhs(rhs: Tree, sym: Symbol)(using Context) = if (sym.isEffectivelyErased) dropInlines.transform(rhs) else rhs } } diff --git a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala index 2181f99d9432..e510847e8d6b 100644 --- a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala @@ -18,7 +18,7 @@ object ProtectedAccessors { val name: String = "protectedAccessors" /** Is the current context's owner inside the access boundary established by `sym`? */ - def insideBoundaryOf(sym: Symbol)(implicit ctx: Context): Boolean = + def insideBoundaryOf(sym: Symbol)(using Context): Boolean = if (sym.is(JavaDefined)) sym.is(JavaStatic) || // Java's static protected definitions are treated as public ctx.owner.enclosingPackageClass == sym.enclosingPackageClass @@ -33,13 +33,13 @@ object ProtectedAccessors { /** Do we need a protected accessor if the current context's owner * is not in a subclass or subtrait of `sym`? */ - def needsAccessorIfNotInSubclass(sym: Symbol)(implicit ctx: Context): Boolean = + def needsAccessorIfNotInSubclass(sym: Symbol)(using Context): Boolean = sym.isTerm && sym.is(Protected) && !sym.owner.is(Trait) && // trait methods need to be handled specially, are currently always public !insideBoundaryOf(sym) /** Do we need a protected accessor for accessing sym from the current context's owner? */ - def needsAccessor(sym: Symbol)(implicit ctx: Context): Boolean = + def needsAccessor(sym: Symbol)(using Context): Boolean = needsAccessorIfNotInSubclass(sym) && !ctx.owner.enclosingClass.derivesFrom(sym.owner) } @@ -52,9 +52,9 @@ class ProtectedAccessors extends MiniPhase { object Accessors extends AccessProxies { val insert: Insert = new Insert { def accessorNameKind = ProtectedAccessorName - def needsAccessor(sym: Symbol)(implicit ctx: Context) = ProtectedAccessors.needsAccessor(sym) + def needsAccessor(sym: Symbol)(using Context) = ProtectedAccessors.needsAccessor(sym) - override def ifNoHost(reference: RefTree)(implicit ctx: Context): Tree = { + 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", @@ -64,13 +64,13 @@ class ProtectedAccessors extends MiniPhase { } } - override def transformIdent(tree: Ident)(implicit ctx: Context): Tree = + override def transformIdent(tree: Ident)(using Context): Tree = Accessors.insert.accessorIfNeeded(tree) - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = Accessors.insert.accessorIfNeeded(tree) - override def transformAssign(tree: Assign)(implicit ctx: Context): Tree = + override def transformAssign(tree: Assign)(using Context): Tree = tree.lhs match { case lhs: RefTree if lhs.name.is(ProtectedAccessorName) => cpy.Apply(tree)(Accessors.insert.useSetter(lhs), tree.rhs :: Nil) @@ -78,6 +78,6 @@ class ProtectedAccessors extends MiniPhase { tree } - override def transformTemplate(tree: Template)(implicit ctx: Context): Tree = + override def transformTemplate(tree: Template)(using Context): Tree = cpy.Template(tree)(body = Accessors.addAccessorDefs(tree.symbol.owner, tree.body)) } diff --git a/compiler/src/dotty/tools/dotc/transform/PruneErasedDefs.scala b/compiler/src/dotty/tools/dotc/transform/PruneErasedDefs.scala index e03d1a91ff7e..4833421cb298 100644 --- a/compiler/src/dotty/tools/dotc/transform/PruneErasedDefs.scala +++ b/compiler/src/dotty/tools/dotc/transform/PruneErasedDefs.scala @@ -28,22 +28,22 @@ class PruneErasedDefs extends MiniPhase with SymTransformer { thisTransform => override def runsAfterGroupsOf: Set[String] = Set(RefChecks.name, ExplicitOuter.name) - override def transformSym(sym: SymDenotation)(implicit ctx: Context): SymDenotation = + override def transformSym(sym: SymDenotation)(using Context): SymDenotation = if (sym.isEffectivelyErased && !sym.is(Private) && sym.owner.isClass) sym.copySymDenotation(initFlags = sym.flags | Private) else sym - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = + override def transformApply(tree: Apply)(using Context): Tree = if (tree.fun.tpe.widen.isErasedMethod) cpy.Apply(tree)(tree.fun, tree.args.map(trivialErasedTree)) else tree - override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = + override def transformValDef(tree: ValDef)(using Context): Tree = if (tree.symbol.isEffectivelyErased && !tree.rhs.isEmpty) cpy.ValDef(tree)(rhs = trivialErasedTree(tree)) else tree - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = + override def transformDefDef(tree: DefDef)(using Context): Tree = if (tree.symbol.isEffectivelyErased && !tree.rhs.isEmpty) cpy.DefDef(tree)(rhs = trivialErasedTree(tree)) else tree diff --git a/compiler/src/dotty/tools/dotc/transform/PureStats.scala b/compiler/src/dotty/tools/dotc/transform/PureStats.scala index 82b495170576..fc9b3bd6543e 100644 --- a/compiler/src/dotty/tools/dotc/transform/PureStats.scala +++ b/compiler/src/dotty/tools/dotc/transform/PureStats.scala @@ -20,7 +20,7 @@ class PureStats extends MiniPhase { override def runsAfter: Set[String] = Set(Erasure.name) - override def transformBlock(tree: Block)(implicit ctx: Context): Tree = + override def transformBlock(tree: Block)(using Context): Tree = val stats = tree.stats.mapConserve { case Typed(Block(stats, expr), _) if isPureExpr(expr) => Thicket(stats) case stat if !stat.symbol.isConstructor && isPureExpr(stat) => EmptyTree diff --git a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala index c93d550379ec..e5efcee697ff 100644 --- a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala @@ -74,7 +74,7 @@ class ReifyQuotes extends MacroTransform { override def allowsImplicitSearch: Boolean = true - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case tree: RefTree if !Inliner.inInlineMethod => assert(!tree.symbol.isQuote) @@ -85,11 +85,11 @@ class ReifyQuotes extends MacroTransform { case _ => } - override def run(implicit ctx: Context): Unit = + override def run(using Context): Unit = if (ctx.compilationUnit.needsStaging) super.run(using freshStagingContext) - protected def newTransformer(implicit ctx: Context): Transformer = new Transformer { - override def transform(tree: tpd.Tree)(implicit ctx: Context): tpd.Tree = + protected def newTransformer(using Context): Transformer = new Transformer { + override def transform(tree: tpd.Tree)(using Context): tpd.Tree = new QuoteReifier(null, new mutable.HashMap[Symbol, Tree => Tree], new Embedded, ctx.owner)(ctx).transform(tree) } @@ -114,7 +114,7 @@ class ReifyQuotes extends MacroTransform { import StagingContext._ /** A nested reifier for a quote (if `isQuote = true`) or a splice (if not) */ - def nested(isQuote: Boolean)(implicit ctx: Context): QuoteReifier = { + def nested(isQuote: Boolean)(using Context): QuoteReifier = { val nestedEmbedded = if (level > 1 || (level == 1 && isQuote)) embedded else new Embedded new QuoteReifier(this, capturers, nestedEmbedded, ctx.owner)(ctx) } @@ -125,14 +125,14 @@ class ReifyQuotes extends MacroTransform { * `scala.quoted.Unpickler.unpickleExpr` that matches `tpe` with * core and splices as arguments. */ - override protected def transformQuotation(body: Tree, quote: Tree)(implicit ctx: Context): Tree = { + override protected def transformQuotation(body: Tree, quote: Tree)(using Context): Tree = { val isType = quote.symbol eq defn.InternalQuoted_typeQuote if (level > 0) { - val body1 = nested(isQuote = true).transform(body)(quoteContext) + val body1 = nested(isQuote = true).transform(body)(using quoteContext) super.transformQuotation(body1, quote) } else { - val (body1, splices) = nested(isQuote = true).splitQuote(body)(quoteContext) + val (body1, splices) = nested(isQuote = true).splitQuote(body)(using quoteContext) if (level == 0) { val body2 = if (body1.isType) body1 @@ -144,7 +144,7 @@ class ReifyQuotes extends MacroTransform { } } - private def pickledQuote(body: Tree, splices: List[Tree], originalTp: Type, isType: Boolean)(implicit ctx: Context) = { + private def pickledQuote(body: Tree, splices: List[Tree], originalTp: Type, isType: Boolean)(using Context) = { def pickleAsLiteral(lit: Literal) = { def liftedValue(lifter: Symbol) = ref(lifter).appliedToType(originalTp).select(nme.toExpr).appliedTo(lit) @@ -187,9 +187,9 @@ class ReifyQuotes extends MacroTransform { * and make a hole from these parts. Otherwise issue an error, unless we * are in the body of an inline method. */ - protected def transformSplice(body: Tree, splice: Tree)(implicit ctx: Context): Tree = + protected def transformSplice(body: Tree, splice: Tree)(using Context): Tree = if (level > 1) { - val body1 = nested(isQuote = false).transform(body)(spliceContext) + val body1 = nested(isQuote = false).transform(body)(using spliceContext) splice match { case splice: Apply => cpy.Apply(splice)(splice.fun, body1 :: Nil) case splice: Select => cpy.Select(splice)(body1, splice.name) @@ -197,7 +197,7 @@ class ReifyQuotes extends MacroTransform { } else { assert(level == 1, "unexpected top splice outside quote") - val (body1, quotes) = nested(isQuote = false).splitSplice(body)(spliceContext) + val (body1, quotes) = nested(isQuote = false).splitSplice(body)(using spliceContext) val tpe = outer.embedded.getHoleType(body, splice) val hole = makeHole(splice.isTerm, body1, quotes, tpe).withSpan(splice.span) // We do not place add the inline marker for trees that where lifted as they come from the same file as their @@ -234,8 +234,8 @@ class ReifyQuotes extends MacroTransform { * Hole(0 | x, y) * } */ - private def makeLambda(tree: Tree)(implicit ctx: Context): Tree = { - def body(arg: Tree)(implicit ctx: Context): Tree = { + private def makeLambda(tree: Tree)(using Context): Tree = { + def body(arg: Tree)(using Context): Tree = { var i = 0 transformWithCapturer(tree)( (captured: mutable.Map[Symbol, Tree]) => { @@ -270,10 +270,10 @@ class ReifyQuotes extends MacroTransform { 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) - Closure(meth, tss => body(tss.head.head)(ctx.withOwner(meth)).changeNonLocalOwners(meth)).withSpan(tree.span) + Closure(meth, tss => body(tss.head.head)(using ctx.withOwner(meth)).changeNonLocalOwners(meth)).withSpan(tree.span) } - private def transformWithCapturer(tree: Tree)(capturer: mutable.Map[Symbol, Tree] => Tree => Tree)(implicit ctx: Context): Tree = { + private def transformWithCapturer(tree: Tree)(capturer: mutable.Map[Symbol, Tree] => Tree => Tree)(using Context): Tree = { val captured = mutable.LinkedHashMap.empty[Symbol, Tree] val captured2 = capturer(captured) @@ -288,18 +288,18 @@ class ReifyQuotes extends MacroTransform { } /** Returns true if this tree will be captured by `makeLambda`. Checks phase consistency and presence of capturer. */ - private def isCaptured(sym: Symbol, level: Int)(implicit ctx: Context): Boolean = + private def isCaptured(sym: Symbol, level: Int)(using Context): Boolean = level == 1 && levelOf(sym) == 1 && capturers.contains(sym) /** Transform `tree` and return the resulting tree and all `embedded` quotes * or splices as a pair. */ - private def splitQuote(tree: Tree)(implicit ctx: Context): (Tree, List[Tree]) = { + private def splitQuote(tree: Tree)(using Context): (Tree, List[Tree]) = { val tree1 = stipTypeAnnotations(transform(tree)) (tree1, embedded.getTrees) } - private def splitSplice(tree: Tree)(implicit ctx: Context): (Tree, List[Tree]) = { + private def splitSplice(tree: Tree)(using Context): (Tree, List[Tree]) = { val tree1 = makeLambda(tree) (tree1, embedded.getTrees) } @@ -310,7 +310,7 @@ class ReifyQuotes extends MacroTransform { /** Register `body` as an `embedded` quote or splice * and return a hole with `splices` as arguments and the given type `tpe`. */ - private def makeHole(isTermHole: Boolean, body: Tree, splices: List[Tree], tpe: Type)(implicit ctx: Context): Hole = { + private def makeHole(isTermHole: Boolean, body: Tree, splices: List[Tree], tpe: Type)(using Context): Hole = { val idx = embedded.addTree(body, NoSymbol) /** Remove references to local types that will not be defined in this quote */ @@ -345,9 +345,9 @@ class ReifyQuotes extends MacroTransform { Hole(isTermHole, idx, splices).withType(holeType).asInstanceOf[Hole] } - override def transform(tree: Tree)(implicit ctx: Context): Tree = + override def transform(tree: Tree)(using Context): Tree = if (tree.source != ctx.source && tree.source.exists) - transform(tree)(ctx.withSource(tree.source)) + transform(tree)(using ctx.withSource(tree.source)) else reporting.trace(i"Reifier.transform $tree at $level", show = true) { tree match { case Apply(Select(TypeApply(fn, (body: RefTree) :: Nil), _), _) if fn.symbol == defn.InternalQuoted_typeQuote && isCaptured(body.symbol, level + 1) => @@ -380,7 +380,7 @@ class ReifyQuotes extends MacroTransform { } } - private def liftList(list: List[Tree], tpe: Type)(implicit ctx: Context): Tree = + private def liftList(list: List[Tree], tpe: Type)(using Context): Tree = list.foldRight[Tree](ref(defn.NilModule)) { (x, acc) => acc.select("::".toTermName).appliedToType(tpe).appliedTo(x) } @@ -410,13 +410,13 @@ object ReifyQuotes { } /** Type used for the hole that will replace this splice */ - def getHoleType(body: tpd.Tree, splice: tpd.Tree)(implicit ctx: Context): Type = + def getHoleType(body: tpd.Tree, splice: tpd.Tree)(using Context): Type = // For most expressions the splice.tpe but there are some types that are lost by lifting // that can be recoverd from the original tree. Currently the cases are: // * Method types: the splice represents a method reference map.get(body.symbol).map(_.tpe.widen).getOrElse(splice.tpe) - def isLiftedSymbol(sym: Symbol)(implicit ctx: Context): Boolean = map.contains(sym) + def isLiftedSymbol(sym: Symbol)(using Context): Boolean = map.contains(sym) /** Get the list of embedded trees */ def getTrees: List[tpd.Tree] = trees.toList diff --git a/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala b/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala index eeb9614c8a6e..137d4388d574 100644 --- a/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala +++ b/compiler/src/dotty/tools/dotc/transform/RenameLifted.scala @@ -18,7 +18,7 @@ class RenameLifted extends MiniPhase with SymTransformer { // Not clear why this should run after restoreScopes // override def runsAfterGroupsOf = Set(RestoreScopes.name) - def transformSym(ref: SymDenotation)(implicit ctx: Context): SymDenotation = + def transformSym(ref: SymDenotation)(using Context): SymDenotation = if (needsRefresh(ref.symbol)) ref.copySymDenotation(name = refreshedName(ref.symbol)) else ref @@ -26,11 +26,11 @@ class RenameLifted extends MiniPhase with SymTransformer { * - if it is a lifted class * - if it is a lifted method */ - private def needsRefresh(sym: Symbol)(implicit ctx: Context): Boolean = + private def needsRefresh(sym: Symbol)(using Context): Boolean = (sym.isClass || sym.isOneOf(Private | Method | JavaStatic)) && sym.name.is(UniqueName) /** Refreshes the number of the name based on the full name of the symbol */ - private def refreshedName(sym: Symbol)(implicit ctx: Context): Name = { + private def refreshedName(sym: Symbol)(using Context): Name = { def rewriteUnique: PartialFunction[Name, Name] = { case name: DerivedName if name.info.kind == UniqueName => val fullName = (sym.owner.fullName.toString + name.underlying).toTermName diff --git a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala index db7d0fd9e23b..f58359946b17 100644 --- a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala +++ b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala @@ -39,7 +39,7 @@ class ResolveSuper extends MiniPhase with IdentityDenotTransformer { thisPhase = override def changesMembers: Boolean = true // the phase adds super accessors - override def transformTemplate(impl: Template)(implicit ctx: Context): Template = { + override def transformTemplate(impl: Template)(using Context): Template = { val cls = impl.symbol.owner.asClass val ops = new MixinOps(cls, thisPhase) import ops._ @@ -56,7 +56,7 @@ class ResolveSuper extends MiniPhase with IdentityDenotTransformer { thisPhase = cpy.Template(impl)(body = overrides ::: impl.body) } - override def transformDefDef(ddef: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(ddef: DefDef)(using Context): Tree = { val meth = ddef.symbol.asTerm if (meth.isSuperAccessor && !meth.is(Deferred)) { assert(ddef.rhs.isEmpty) @@ -77,7 +77,7 @@ object ResolveSuper { * @param base The class in which everything is mixed together * @param acc The symbol statically referred to by the superaccessor in the trait */ - def rebindSuper(base: Symbol, acc: Symbol)(implicit ctx: Context): Symbol = { + def rebindSuper(base: Symbol, acc: Symbol)(using Context): Symbol = { var bcs = base.info.baseClasses.dropWhile(acc.owner != _).tail var sym: Symbol = NoSymbol val SuperAccessorName(memberName) = acc.name.unexpandedName diff --git a/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala b/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala index 67cd8e1b59bf..839d805a1fc3 100644 --- a/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala +++ b/compiler/src/dotty/tools/dotc/transform/RestoreScopes.scala @@ -25,12 +25,12 @@ class RestoreScopes extends MiniPhase with IdentityDenotTransformer { thisPhase * enclosing package definitions. So by the time RestoreScopes gets to * see a typedef or template, it still might be changed by DropEmptyConstructors. */ - override def transformPackageDef(pdef: PackageDef)(implicit ctx: Context): PackageDef = { + override def transformPackageDef(pdef: PackageDef)(using Context): PackageDef = { pdef.stats.foreach(restoreScope) pdef } - private def restoreScope(tree: Tree)(implicit ctx: Context) = tree match { + private def restoreScope(tree: Tree)(using Context) = tree match { case TypeDef(_, impl: Template) => val restoredDecls = newScope for (stat <- impl.constr :: impl.body) diff --git a/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala b/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala index b2671258554b..a3b6f0e6fbee 100644 --- a/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala @@ -21,7 +21,7 @@ class SelectStatic extends MiniPhase with IdentityDenotTransformer { override def phaseName: String = "selectStatic" - override def transformSelect(tree: tpd.Select)(implicit ctx: Context): tpd.Tree = { + override def transformSelect(tree: tpd.Select)(using Context): tpd.Tree = { val sym = tree.symbol def isStaticMember = (sym is Flags.Module) && sym.initial.maybeOwner.initial.isStaticOwner || @@ -36,7 +36,7 @@ class SelectStatic extends MiniPhase with IdentityDenotTransformer { normalize(tree1) } - private def normalize(t: Tree)(implicit ctx: Context) = t match { + private def normalize(t: Tree)(using Context) = t match { case Select(Block(stats, qual), nm) => Block(stats, cpy.Select(t)(qual, nm)) case Apply(Block(stats, qual), nm) => @@ -48,12 +48,12 @@ class SelectStatic extends MiniPhase with IdentityDenotTransformer { case _ => t } - override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = + override def transformApply(tree: tpd.Apply)(using Context): tpd.Tree = normalize(tree) - override def transformTypeApply(tree: tpd.TypeApply)(implicit ctx: Context): tpd.Tree = + override def transformTypeApply(tree: tpd.TypeApply)(using Context): tpd.Tree = normalize(tree) - override def transformClosure(tree: tpd.Closure)(implicit ctx: Context): tpd.Tree = + override def transformClosure(tree: tpd.Closure)(using Context): tpd.Tree = normalize(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala b/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala index f0930a162091..c28e5532eee2 100644 --- a/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala +++ b/compiler/src/dotty/tools/dotc/transform/SeqLiterals.scala @@ -20,12 +20,12 @@ class SeqLiterals extends MiniPhase { override def phaseName: String = "seqLiterals" override def runsAfter: Set[String] = Set(PatternMatcher.name) - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = tree match { + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case tpd: SeqLiteral => assert(tpd.isInstanceOf[JavaSeqLiteral]) case _ => } - override def transformSeqLiteral(tree: SeqLiteral)(implicit ctx: Context): Tree = tree match { + override def transformSeqLiteral(tree: SeqLiteral)(using Context): Tree = tree match { case tree: JavaSeqLiteral => tree case _ => val arr = JavaSeqLiteral(tree.elems, tree.elemtpt) diff --git a/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala b/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala index fa72cc90d1a3..dfd61315bdcc 100644 --- a/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala +++ b/compiler/src/dotty/tools/dotc/transform/SetRootTree.scala @@ -9,19 +9,19 @@ import dotty.tools.dotc.core.Phases.Phase class SetRootTree extends Phase { override val phaseName: String = SetRootTree.name - override def isRunnable(implicit ctx: Context) = + override def isRunnable(using Context) = super.isRunnable && ctx.settings.YretainTrees.value // Check no needed. Does not transform trees override def isCheckable: Boolean = false - override def run(implicit ctx: Context): Unit = { + override def run(using Context): Unit = { val tree = ctx.compilationUnit.tpdTree traverser.traverse(tree) } private def traverser = new tpd.TreeTraverser { - override def traverse(tree: tpd.Tree)(implicit ctx: Context): Unit = + override def traverse(tree: tpd.Tree)(using Context): Unit = tree match { case pkg: tpd.PackageDef => traverseChildren(pkg) diff --git a/compiler/src/dotty/tools/dotc/transform/Splicer.scala b/compiler/src/dotty/tools/dotc/transform/Splicer.scala index 386c63a08a1c..1efe4ec513b0 100644 --- a/compiler/src/dotty/tools/dotc/transform/Splicer.scala +++ b/compiler/src/dotty/tools/dotc/transform/Splicer.scala @@ -75,9 +75,9 @@ object Splicer { def checkEscapedVariables(tree: Tree, expansionOwner: Symbol)(using Context): tree.type = new TreeTraverser { private[this] var locals = Set.empty[Symbol] - private def markSymbol(sym: Symbol)(implicit ctx: Context): Unit = + private def markSymbol(sym: Symbol)(using Context): Unit = locals = locals + sym - private def markDef(tree: Tree)(implicit ctx: Context): Unit = tree match { + private def markDef(tree: Tree)(using Context): Unit = tree match { case tree: DefTree => markSymbol(tree.symbol) case _ => } @@ -117,7 +117,7 @@ object Splicer { * * See: `Staging` */ - def checkValidMacroBody(tree: Tree)(implicit ctx: Context): Unit = tree match { + def checkValidMacroBody(tree: Tree)(using Context): Unit = tree match { case Quoted(_) => // ok case _ => type Env = Set[Symbol] @@ -203,7 +203,7 @@ object Splicer { } /** Tree interpreter that evaluates the tree */ - private class Interpreter(pos: SourcePosition, classLoader: ClassLoader)(implicit ctx: Context) { + private class Interpreter(pos: SourcePosition, classLoader: ClassLoader)(using Context) { type Env = Map[Symbol, Object] @@ -490,11 +490,11 @@ object Splicer { /** Matches an expression that is either a field access or an application * It retruns a TermRef containing field accessed or a method reference and the arguments passed to it. */ - def unapply(arg: Tree)(implicit ctx: Context): Option[(RefTree, List[List[Tree]])] = + def unapply(arg: Tree)(using Context): Option[(RefTree, List[List[Tree]])] = Call0.unapply(arg).map((fn, args) => (fn, args.reverse)) private object Call0 { - def unapply(arg: Tree)(implicit ctx: Context): Option[(RefTree, List[List[Tree]])] = arg match { + def unapply(arg: Tree)(using Context): Option[(RefTree, List[List[Tree]])] = arg match { case Select(Call0(fn, args), nme.apply) if defn.isContextFunctionType(fn.tpe.widenDealias.finalResultType) => Some((fn, args)) case fn: Ident => Some((tpd.desugarIdent(fn).withSpan(fn.span), Nil)) diff --git a/compiler/src/dotty/tools/dotc/transform/Staging.scala b/compiler/src/dotty/tools/dotc/transform/Staging.scala index 05b9c4902592..09410c176a3c 100644 --- a/compiler/src/dotty/tools/dotc/transform/Staging.scala +++ b/compiler/src/dotty/tools/dotc/transform/Staging.scala @@ -37,13 +37,13 @@ class Staging extends MacroTransform { override def allowsImplicitSearch: Boolean = true - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = + override def checkPostCondition(tree: Tree)(using Context): Unit = if (ctx.phase <= ctx.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 => val checker = new PCPCheckAndHeal(freshStagingContext) { - override protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SourcePosition)(implicit ctx: Context): TypeRef = { + override protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SourcePosition)(using Context): TypeRef = { def symStr = if (sym.is(ModuleClass)) sym.sourceModule.show else i"${sym.name}.this" @@ -72,11 +72,11 @@ class Staging extends MacroTransform { } } - override def run(implicit ctx: Context): Unit = + override def run(using Context): Unit = if (ctx.compilationUnit.needsStaging) super.run(using freshStagingContext) - protected def newTransformer(implicit ctx: Context): Transformer = new Transformer { - override def transform(tree: tpd.Tree)(implicit ctx: Context): tpd.Tree = + protected def newTransformer(using Context): Transformer = new Transformer { + override def transform(tree: tpd.Tree)(using Context): tpd.Tree = new PCPCheckAndHeal(ctx).transform(tree) } } diff --git a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala index 619821f5d5ac..0dc2b33ddb80 100644 --- a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala @@ -48,21 +48,21 @@ class SuperAccessors(thisPhase: DenotTransformer) { */ private var invalidEnclClass: Symbol = NoSymbol - private def withInvalidCurrentClass[A](trans: => A)(implicit ctx: Context): A = { + private def withInvalidCurrentClass[A](trans: => A)(using Context): A = { val saved = invalidEnclClass invalidEnclClass = ctx.owner try trans finally invalidEnclClass = saved } - private def validCurrentClass(implicit ctx: Context): Boolean = + private def validCurrentClass(using Context): Boolean = ctx.owner.enclosingClass != invalidEnclClass /** List buffers for new accessor definitions, indexed by class */ private val accDefs = newMutableSymbolMap[mutable.ListBuffer[Tree]] /** A super accessor call corresponding to `sel` */ - private def superAccessorCall(sel: Select)(implicit ctx: Context) = { + private def superAccessorCall(sel: Select)(using Context) = { val Select(qual, name) = sel val sym = sel.symbol val clazz = qual.symbol.asClass @@ -94,7 +94,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { /** Check selection `super.f` for conforming to rules. If necessary, * replace by a super accessor call. */ - private def transformSuperSelect(sel: Select)(implicit ctx: Context): Tree = { + private def transformSuperSelect(sel: Select)(using Context): Tree = { val Select(sup @ Super(_, mix), name) = sel val sym = sel.symbol assert(sup.symbol.exists, s"missing symbol in $sel: ${sup.tpe}") @@ -154,14 +154,14 @@ class SuperAccessors(thisPhase: DenotTransformer) { /** Disallow some super.XX calls targeting Any methods which would * otherwise lead to either a compiler crash or runtime failure. */ - private def isDisallowed(sym: Symbol)(implicit ctx: Context) = + private def isDisallowed(sym: Symbol)(using Context) = sym.isTypeTestOrCast || (sym eq defn.Any_==) || (sym eq defn.Any_!=) || (sym eq defn.Any_##) /** Transform select node, adding super and protected accessors as needed */ - def transformSelect(tree: Tree, targs: List[Tree])(implicit ctx: Context): Tree = { + def transformSelect(tree: Tree, targs: List[Tree])(using Context): Tree = { val sel @ Select(qual, name) = tree val sym = sel.symbol @@ -194,7 +194,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { } /** Wrap template to template transform `op` with needed initialization and finalization */ - def wrapTemplate(tree: Template)(op: Template => Template)(implicit ctx: Context): Template = { + def wrapTemplate(tree: Template)(op: Template => Template)(using Context): Template = { accDefs(currentClass) = new mutable.ListBuffer[Tree] val impl = op(tree) val accessors = accDefs.remove(currentClass).get @@ -210,6 +210,6 @@ class SuperAccessors(thisPhase: DenotTransformer) { } /** Wrap `DefDef` producing operation `op`, potentially setting `invalidClass` info */ - def wrapDefDef(ddef: DefDef)(op: => DefDef)(implicit ctx: Context): DefDef = + def wrapDefDef(ddef: DefDef)(op: => DefDef)(using Context): DefDef = if (isMethodWithExtension(ddef.symbol)) withInvalidCurrentClass(op) else op } diff --git a/compiler/src/dotty/tools/dotc/transform/SymUtils.scala b/compiler/src/dotty/tools/dotc/transform/SymUtils.scala index 82b2b51f8bce..be1d76dc642d 100644 --- a/compiler/src/dotty/tools/dotc/transform/SymUtils.scala +++ b/compiler/src/dotty/tools/dotc/transform/SymUtils.scala @@ -30,7 +30,7 @@ class SymUtils(val self: Symbol) extends AnyVal { import SymUtils._ /** All traits implemented by a class or trait except for those inherited through the superclass. */ - def directlyInheritedTraits(implicit ctx: Context): List[ClassSymbol] = { + def directlyInheritedTraits(using Context): List[ClassSymbol] = { val superCls = self.asClass.superClass val baseClasses = self.asClass.baseClasses if (baseClasses.isEmpty) Nil @@ -40,33 +40,33 @@ class SymUtils(val self: Symbol) extends AnyVal { /** All traits implemented by a class, except for those inherited through the superclass. * The empty list if `self` is a trait. */ - def mixins(implicit ctx: Context): List[ClassSymbol] = + def mixins(using Context): List[ClassSymbol] = if (self.is(Trait)) Nil else directlyInheritedTraits - def isTypeTest(implicit ctx: Context): Boolean = + def isTypeTest(using Context): Boolean = self == defn.Any_isInstanceOf || self == defn.Any_typeTest - def isTypeCast(implicit ctx: Context): Boolean = + def isTypeCast(using Context): Boolean = self == defn.Any_asInstanceOf || self == defn.Any_typeCast - def isTypeTestOrCast(implicit ctx: Context): Boolean = + def isTypeTestOrCast(using Context): Boolean = isTypeCast || isTypeTest - def isThreadUnsafe(implicit ctx: Context): Boolean = self.hasAnnotation(defn.ThreadUnsafeAnnot) + def isThreadUnsafe(using Context): Boolean = self.hasAnnotation(defn.ThreadUnsafeAnnot) - def isVolatile(implicit ctx: Context): Boolean = self.hasAnnotation(defn.VolatileAnnot) + def isVolatile(using Context): Boolean = self.hasAnnotation(defn.VolatileAnnot) - def isAnyOverride(implicit ctx: Context): Boolean = self.is(Override) || self.is(AbsOverride) + def isAnyOverride(using Context): Boolean = self.is(Override) || self.is(AbsOverride) // careful: AbsOverride is a term only flag. combining with Override would catch only terms. - def isSuperAccessor(implicit ctx: Context): Boolean = self.name.is(SuperAccessorName) + def isSuperAccessor(using Context): Boolean = self.name.is(SuperAccessorName) /** Is this a type or term parameter or a term parameter accessor? */ - def isParamOrAccessor(implicit ctx: Context): Boolean = + def isParamOrAccessor(using Context): Boolean = self.is(Param) || self.is(ParamAccessor) - def derivesFromJavaEnum(implicit ctx: Context) = + def derivesFromJavaEnum(using Context) = self.is(Enum, butNot = Case) && self.info.parents.exists(p => p.typeSymbol == defn.JavaEnumClass) @@ -74,14 +74,14 @@ class SymUtils(val self: Symbol) extends AnyVal { * Excluded are value classes, abstract classes and case classes with more than one * parameter section. */ - def whyNotGenericProduct(implicit ctx: Context): String = + def whyNotGenericProduct(using Context): String = if (!self.is(CaseClass)) "it is not a case class" else if (self.is(Abstract)) "it is an abstract class" else if (self.primaryConstructor.info.paramInfoss.length != 1) "it takes more than one parameter list" else if (isDerivedValueClass(self)) "it is a value class" else "" - def isGenericProduct(implicit ctx: Context): Boolean = whyNotGenericProduct.isEmpty + def isGenericProduct(using Context): Boolean = whyNotGenericProduct.isEmpty /** Is this a sealed class or trait for which a sum mirror is generated? * It must satisfy the following conditions: @@ -90,7 +90,7 @@ class SymUtils(val self: Symbol) extends AnyVal { * - all of its children are addressable through a path from its companion object * - all of its children are generic products or singletons */ - def whyNotGenericSum(implicit ctx: Context): String = + def whyNotGenericSum(using Context): String = if (!self.is(Sealed)) s"it is not a sealed ${self.kindString}" else { @@ -114,18 +114,18 @@ class SymUtils(val self: Symbol) extends AnyVal { else children.map(problem).find(!_.isEmpty).getOrElse("") } - def isGenericSum(implicit ctx: Context): Boolean = whyNotGenericSum.isEmpty + def isGenericSum(using Context): Boolean = whyNotGenericSum.isEmpty /** If this is a constructor, its owner: otherwise this. */ - final def skipConstructor(implicit ctx: Context): Symbol = + final def skipConstructor(using Context): Symbol = if (self.isConstructor) self.owner else self /** The closest properly enclosing method or class of this symbol. */ - final def enclosure(implicit ctx: Context): Symbol = + final def enclosure(using Context): Symbol = self.owner.enclosingMethodOrClass /** The closest enclosing method or class of this symbol */ - @tailrec final def enclosingMethodOrClass(implicit ctx: Context): Symbol = + @tailrec final def enclosingMethodOrClass(using Context): Symbol = if (self.is(Method) || self.isClass) self else if (self.exists) self.owner.enclosingMethodOrClass else NoSymbol @@ -139,20 +139,20 @@ class SymUtils(val self: Symbol) extends AnyVal { loop(from, to) } - def accessorNamed(name: TermName)(implicit ctx: Context): Symbol = + def accessorNamed(name: TermName)(using Context): Symbol = self.owner.info.decl(name).suchThat(_.is(Accessor)).symbol - def caseAccessors(implicit ctx: Context): List[Symbol] = + def caseAccessors(using Context): List[Symbol] = self.info.decls.filter(_.is(CaseAccessor)) - def getter(implicit ctx: Context): Symbol = + def getter(using Context): Symbol = if (self.isGetter) self else accessorNamed(self.asTerm.name.getterName) - def setter(implicit ctx: Context): Symbol = + def setter(using Context): Symbol = if (self.isSetter) self else accessorNamed(self.asTerm.name.setterName) - def field(implicit ctx: Context): Symbol = { + def field(using Context): Symbol = { val thisName = self.name.asTermName val fieldName = if (self.hasAnnotation(defn.ScalaStaticAnnot)) thisName.getterName @@ -160,19 +160,19 @@ class SymUtils(val self: Symbol) extends AnyVal { self.owner.info.decl(fieldName).suchThat(!_.is(Method)).symbol } - def isField(implicit ctx: Context): Boolean = + def isField(using Context): Boolean = self.isTerm && !self.is(Method) - def annotationsCarrying(meta: ClassSymbol)(implicit ctx: Context): List[Annotation] = + def annotationsCarrying(meta: ClassSymbol)(using Context): List[Annotation] = self.annotations.filter(_.symbol.hasAnnotation(meta)) - def withAnnotationsCarrying(from: Symbol, meta: ClassSymbol)(implicit ctx: Context): self.type = { + def withAnnotationsCarrying(from: Symbol, meta: ClassSymbol)(using Context): self.type = { self.addAnnotations(from.annotationsCarrying(meta)) self } /** Does this symbol refer to anonymous classes synthesized by enum desugaring? */ - def isEnumAnonymClass(implicit ctx: Context): Boolean = + def isEnumAnonymClass(using Context): Boolean = self.isAnonymousClass && (self.owner.name.eq(nme.DOLLAR_NEW) || self.owner.is(CaseVal)) /** Is this symbol defined locally (i.e. at some level owned by a term) so that @@ -188,11 +188,11 @@ class SymUtils(val self: Symbol) extends AnyVal { || sym.isType && isAccessible(sym.owner, cls) !isAccessible(self.owner, cls) - def hasAnonymousChild(implicit ctx: Context): Boolean = + def hasAnonymousChild(using Context): Boolean = self.children.exists(_ `eq` self) /** Is symbol directly or indirectly owned by a term symbol? */ - @tailrec final def isLocal(implicit ctx: Context): Boolean = { + @tailrec final def isLocal(using Context): Boolean = { val owner = self.maybeOwner if (!owner.exists) false else if (owner.isTerm) true @@ -201,15 +201,15 @@ class SymUtils(val self: Symbol) extends AnyVal { } /** The typeRef with wildcard arguments for each type parameter */ - def rawTypeRef(implicit ctx: Context) = + def rawTypeRef(using Context) = self.typeRef.appliedTo(self.typeParams.map(_ => TypeBounds.emptyPolyKind)) /** Is symbol a quote operation? */ - def isQuote(implicit ctx: Context): Boolean = + def isQuote(using Context): Boolean = self == defn.InternalQuoted_exprQuote || self == defn.InternalQuoted_typeQuote /** Is symbol a splice operation? */ - def isSplice(implicit ctx: Context): Boolean = + def isSplice(using Context): Boolean = self == defn.InternalQuoted_exprSplice || self == defn.InternalQuoted_exprNestedSplice || self == defn.QuotedType_splice /** Is symbol an extension method? Accessors are excluded since diff --git a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala index acb731dfa293..de572716298b 100644 --- a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala +++ b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala @@ -59,7 +59,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { private var myCaseModuleSymbols: List[Symbol] = Nil private var myEnumCaseSymbols: List[Symbol] = Nil - private def initSymbols(implicit ctx: Context) = + private def initSymbols(using Context) = if (myValueSymbols.isEmpty) { myValueSymbols = List(defn.Any_hashCode, defn.Any_equals) myCaseSymbols = myValueSymbols ++ List(defn.Any_toString, defn.Product_canEqual, @@ -69,24 +69,24 @@ class SyntheticMembers(thisPhase: DenotTransformer) { myEnumCaseSymbols = List(defn.Enum_ordinal) } - def valueSymbols(implicit ctx: Context): List[Symbol] = { initSymbols; myValueSymbols } - def caseSymbols(implicit ctx: Context): List[Symbol] = { initSymbols; myCaseSymbols } - def caseModuleSymbols(implicit ctx: Context): List[Symbol] = { initSymbols; myCaseModuleSymbols } - def enumCaseSymbols(implicit ctx: Context): List[Symbol] = { initSymbols; myEnumCaseSymbols } + def valueSymbols(using Context): List[Symbol] = { initSymbols; myValueSymbols } + def caseSymbols(using Context): List[Symbol] = { initSymbols; myCaseSymbols } + def caseModuleSymbols(using Context): List[Symbol] = { initSymbols; myCaseModuleSymbols } + def enumCaseSymbols(using Context): List[Symbol] = { initSymbols; myEnumCaseSymbols } - private def existingDef(sym: Symbol, clazz: ClassSymbol)(implicit ctx: Context): Symbol = { + private def existingDef(sym: Symbol, clazz: ClassSymbol)(using Context): Symbol = { val existing = sym.matchingMember(clazz.thisType) if (existing != sym && !existing.is(Deferred)) existing else NoSymbol } - private def synthesizeDef(sym: TermSymbol, rhsFn: List[List[Tree]] => Context => Tree)(implicit ctx: Context): Tree = + 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) /** If this is a case or value class, return the appropriate additional methods, * otherwise return nothing. */ - def caseAndValueMethods(clazz: ClassSymbol)(implicit ctx: Context): List[Tree] = { + def caseAndValueMethods(clazz: ClassSymbol)(using Context): List[Tree] = { val clazzType = clazz.appliedRef lazy val accessors = if (isDerivedValueClass(clazz)) clazz.paramAccessors.take(1) // Tail parameters can only be `erased` @@ -118,7 +118,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { def ownName: Tree = Literal(Constant(clazz.name.stripModuleClassSuffix.toString)) - def syntheticRHS(vrefss: List[List[Tree]])(implicit ctx: Context): Tree = synthetic.name match { + def syntheticRHS(vrefss: List[List[Tree]])(using Context): Tree = synthetic.name match { case nme.hashCode_ if isDerivedValueClass(clazz) => valueHashCodeBody case nme.hashCode_ => chooseHashcode case nme.toString_ => if (clazz.is(ModuleClass)) ownName else forwardToRuntime(vrefss.head) @@ -131,7 +131,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { case nme.ordinal => Select(This(clazz), nme.ordinalDollar) } ctx.log(s"adding $synthetic to $clazz at ${ctx.phase}") - synthesizeDef(synthetic, treess => ctx => syntheticRHS(treess)(ctx)) + synthesizeDef(synthetic, treess => ctx => syntheticRHS(treess)(using ctx)) } /** The class @@ -150,7 +150,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * } * ``` */ - def productElementBody(arity: Int, index: Tree)(implicit ctx: Context): Tree = { + def productElementBody(arity: Int, index: Tree)(using Context): Tree = { // case N => _${N + 1} val cases = 0.until(arity).map { i => CaseDef(Literal(Constant(i)), EmptyTree, Select(This(clazz), nme.selectorName(i))) @@ -175,7 +175,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * } * ``` */ - def productElementNameBody(arity: Int, index: Tree)(implicit ctx: Context): Tree = { + def productElementNameBody(arity: Int, index: Tree)(using Context): Tree = { // case N => // name for case arg N val cases = 0.until(arity).map { i => CaseDef(Literal(Constant(i)), EmptyTree, Literal(Constant(accessors(i).name.toString))) @@ -223,7 +223,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * `@unchecked` is needed for parametric case classes. * */ - def equalsBody(that: Tree)(implicit ctx: Context): Tree = { + 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 def wildcardAscription(tp: Type) = Typed(Underscore(tp), TypeTree(tp)) val pattern = Bind(thatAsClazz, wildcardAscription(AnnotatedType(clazzType, Annotation(defn.UncheckedAnnot)))) // x$0 @ (_: C @unchecked) @@ -255,7 +255,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * def hashCode: Int = x.hashCode() * ``` */ - def valueHashCodeBody(implicit ctx: Context): Tree = { + def valueHashCodeBody(using Context): Tree = { assert(accessors.nonEmpty) ref(accessors.head).select(nme.hashCode_).ensureApplied } @@ -286,7 +286,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * * else if either `T` or `U` are primitive, gets the `hashCode` method implemented by [[caseHashCodeBody]] */ - def chooseHashcode(implicit ctx: Context) = + def chooseHashcode(using Context) = if (clazz.is(ModuleClass)) Literal(Constant(clazz.name.stripModuleClassSuffix.toString.hashCode)) else if (accessors.exists(_.info.finalResultType.classSymbol.isPrimitiveValueClass)) @@ -312,7 +312,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * } * ``` */ - def caseHashCodeBody(implicit ctx: Context): Tree = { + def caseHashCodeBody(using Context): Tree = { val acc = ctx.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), @@ -324,7 +324,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { } /** The `hashCode` implementation for given symbol `sym`. */ - def hashImpl(sym: Symbol)(implicit ctx: Context): Tree = + def hashImpl(sym: Symbol)(using Context): Tree = defn.scalaClassName(sym.info.finalResultType) match { case tpnme.Unit | tpnme.Null => Literal(Constant(0)) case tpnme.Boolean => If(ref(sym), Literal(Constant(1231)), Literal(Constant(1237))) @@ -362,7 +362,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * * unless an implementation already exists, otherwise do nothing. */ - def serializableObjectMethod(clazz: ClassSymbol)(implicit ctx: Context): List[Tree] = { + def serializableObjectMethod(clazz: ClassSymbol)(using Context): List[Tree] = { def hasWriteReplace: Boolean = clazz.membersNamed(nme.writeReplace) .filterWithPredicate(s => s.signature == Signature(defn.AnyRefType, isJava = false)) @@ -400,7 +400,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * type MirroredMonoType = C[?] * ``` */ - def fromProductBody(caseClass: Symbol, param: Tree)(implicit ctx: Context): Tree = { + def fromProductBody(caseClass: Symbol, param: Tree)(using Context): Tree = { val (classRef, methTpe) = caseClass.primaryConstructor.info match { case tl: PolyType => @@ -443,7 +443,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * a wildcard for each type parameter. The normalized type of an object * O is O.type. */ - def ordinalBody(cls: Symbol, param: Tree)(implicit ctx: Context): Tree = + def ordinalBody(cls: Symbol, param: Tree)(using Context): Tree = if (cls.is(Enum)) param.select(nme.ordinal).ensureApplied else { val cases = @@ -464,7 +464,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { * On this case the represented class or object is referred to in a pre-existing `MirroredMonoType` * member of the template. */ - def addMirrorSupport(impl: Template)(implicit ctx: Context): Template = { + def addMirrorSupport(impl: Template)(using Context): Template = { val clazz = ctx.owner.asClass var newBody = impl.body @@ -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(_, _)(_).ensureConforms(monoType.typeRef)) // t4758.scala or i3381.scala are examples where a cast is needed + fromProductBody(_, _)(using _).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(_, _)(_)) + ordinalBody(_, _)(using _)) } if (clazz.is(Module)) { @@ -525,7 +525,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { cpy.Template(impl)(parents = newParents, body = newBody) } - def addSyntheticMembers(impl: Template)(implicit ctx: Context): Template = { + def addSyntheticMembers(impl: Template)(using Context): Template = { val clazz = ctx.owner.asClass addMirrorSupport( cpy.Template(impl)(body = serializableObjectMethod(clazz) ::: caseAndValueMethods(clazz) ::: impl.body)) From ce9aa2d68922d6318f4f2ce04c69df66d1f1b342 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 17:39:43 +0200 Subject: [PATCH 24/41] Convert transform classes (4) --- .../dotty/tools/dotc/transform/TailRec.scala | 18 ++++++------ .../dotc/transform/TransformByNameApply.scala | 10 +++---- .../dotc/transform/TransformWildcards.scala | 4 +-- .../tools/dotc/transform/TreeExtractors.scala | 6 ++-- .../dotc/transform/TreeMapWithStages.scala | 14 +++++----- .../dotc/transform/TryCatchPatterns.scala | 8 +++--- .../dotc/transform/TupleOptimizations.scala | 20 ++++++------- .../tools/dotc/transform/TypeTestsCasts.scala | 6 ++-- .../tools/dotc/transform/TypeUtils.scala | 18 ++++++------ .../dotc/transform/VCElideAllocations.scala | 2 +- .../dotc/transform/VCInlineMethods.scala | 10 +++---- .../tools/dotc/transform/ValueClasses.scala | 16 +++++------ .../dotc/transform/YCheckPositions.scala | 12 ++++---- .../tools/dotc/transform/init/Checker.scala | 6 ++-- .../tools/dotc/transform/init/Checking.scala | 4 +-- .../tools/dotc/transform/init/Effects.scala | 10 +++---- .../tools/dotc/transform/init/Errors.scala | 28 +++++++++---------- .../dotc/transform/init/Potentials.scala | 22 +++++++-------- .../dotc/transform/init/SetDefTree.scala | 10 +++---- .../tools/dotc/transform/init/Summary.scala | 8 +++--- .../tools/dotc/transform/init/Util.scala | 10 +++---- .../localopt/StringInterpolatorOpt.scala | 12 ++++---- .../tools/dotc/transform/patmat/Space.scala | 22 +++++++-------- 23 files changed, 138 insertions(+), 138 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/transform/TailRec.scala b/compiler/src/dotty/tools/dotc/transform/TailRec.scala index 51bcd7a91e0f..c03b439861a7 100644 --- a/compiler/src/dotty/tools/dotc/transform/TailRec.scala +++ b/compiler/src/dotty/tools/dotc/transform/TailRec.scala @@ -114,7 +114,7 @@ class TailRec extends MiniPhase { override def runsAfter: Set[String] = Set(Erasure.name) // tailrec assumes erased types - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = { + override def transformDefDef(tree: DefDef)(using Context): Tree = { val method = tree.symbol val mandatory = method.hasAnnotation(defn.TailrecAnnot) def noTailTransform(failureReported: Boolean) = { @@ -222,7 +222,7 @@ class TailRec extends MiniPhase { /** The `tailLabelN` label symbol, used to encode a `continue` from the infinite `while` loop. */ private var myContinueLabel: Symbol = _ - def continueLabel(implicit ctx: Context): Symbol = { + def continueLabel(using Context): Symbol = { if (myContinueLabel == null) myContinueLabel = ctx.newSymbol(method, TailLabelName.fresh(), Label, defn.UnitType) myContinueLabel @@ -235,7 +235,7 @@ class TailRec extends MiniPhase { /** The replacement `var`s for the params in `rewrittenParamSyms`. */ var varsForRewrittenParamSyms: List[Symbol] = Nil - private def getVarForRewrittenThis()(implicit ctx: Context): Symbol = + private def getVarForRewrittenThis()(using Context): Symbol = varForRewrittenThis match { case Some(sym) => sym case none => @@ -247,7 +247,7 @@ class TailRec extends MiniPhase { sym } - private def getVarForRewrittenParam(param: Symbol)(implicit ctx: Context): Symbol = + 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) @@ -263,7 +263,7 @@ class TailRec extends MiniPhase { private var inTailPosition = true /** Rewrite this tree to contain no tail recursive calls */ - def transform(tree: Tree, tailPosition: Boolean)(implicit ctx: Context): Tree = + def transform(tree: Tree, tailPosition: Boolean)(using Context): Tree = if (inTailPosition == tailPosition) transform(tree) else { val saved = inTailPosition @@ -272,7 +272,7 @@ class TailRec extends MiniPhase { finally inTailPosition = saved } - def yesTailTransform(tree: Tree)(implicit ctx: Context): Tree = + def yesTailTransform(tree: Tree)(using Context): Tree = transform(tree, tailPosition = true) /** If not in tail position a tree traversal may not be needed. @@ -285,15 +285,15 @@ class TailRec extends MiniPhase { private def isTraversalNeeded = isMandatory || tailPositionLabeledSyms.nonEmpty - def noTailTransform(tree: Tree)(implicit ctx: Context): Tree = + def noTailTransform(tree: Tree)(using Context): Tree = if (isTraversalNeeded) transform(tree, tailPosition = false) else tree - def noTailTransforms[Tr <: Tree](trees: List[Tr])(implicit ctx: Context): List[Tr] = + def noTailTransforms[Tr <: Tree](trees: List[Tr])(using Context): List[Tr] = if (isTraversalNeeded) trees.mapConserve(noTailTransform).asInstanceOf[List[Tr]] else trees - override def transform(tree: Tree)(implicit ctx: Context): Tree = { + override def transform(tree: Tree)(using Context): Tree = { /* Rewrite an Apply to be considered for tail call transformation. */ def rewriteApply(tree: Apply): Tree = { val arguments = noTailTransforms(tree.args) diff --git a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala index d96a9fe49a2d..a9bcfe44bbaa 100644 --- a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala @@ -22,21 +22,21 @@ abstract class TransformByNameApply extends MiniPhase { thisPhase: DenotTransfor import ast.tpd._ /** The info of the tree's symbol before it is potentially transformed in this phase */ - private def originalDenotation(tree: Tree)(implicit ctx: Context) = + private def originalDenotation(tree: Tree)(using Context) = tree.symbol.denot(using ctx.withPhase(thisPhase)) /** If denotation had an ExprType before, it now gets a function type */ - protected def exprBecomesFunction(symd: SymDenotation)(implicit ctx: Context): Boolean = + protected def exprBecomesFunction(symd: SymDenotation)(using Context): Boolean = symd.is(Param) || symd.is(ParamAccessor, butNot = Method) - protected def isByNameRef(tree: Tree)(implicit ctx: Context): Boolean = { + protected def isByNameRef(tree: Tree)(using Context): Boolean = { val origDenot = originalDenotation(tree) origDenot.info.isInstanceOf[ExprType] && exprBecomesFunction(origDenot) } - def mkByNameClosure(arg: Tree, argType: Type)(implicit ctx: Context): Tree = unsupported(i"mkClosure($arg)") + def mkByNameClosure(arg: Tree, argType: Type)(using Context): Tree = unsupported(i"mkClosure($arg)") - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = + override def transformApply(tree: Apply)(using Context): Tree = trace(s"transforming ${tree.show} at phase ${ctx.phase}", show = true) { def transformArg(arg: Tree, formal: Type): Tree = formal.dealias match { diff --git a/compiler/src/dotty/tools/dotc/transform/TransformWildcards.scala b/compiler/src/dotty/tools/dotc/transform/TransformWildcards.scala index 3bffd8fb75a4..eac7ef11b7de 100644 --- a/compiler/src/dotty/tools/dotc/transform/TransformWildcards.scala +++ b/compiler/src/dotty/tools/dotc/transform/TransformWildcards.scala @@ -16,13 +16,13 @@ class TransformWildcards extends MiniPhase with IdentityDenotTransformer { override def phaseName: String = "transformWildcards" - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case vDef: ValDef => assert(!tpd.isWildcardArg(vDef.rhs)) case _ => } - override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = + override def transformValDef(tree: ValDef)(using Context): Tree = if (ctx.owner.isClass) tree else cpy.ValDef(tree)(rhs = tree.rhs.wildcardToDefault) } diff --git a/compiler/src/dotty/tools/dotc/transform/TreeExtractors.scala b/compiler/src/dotty/tools/dotc/transform/TreeExtractors.scala index 37570fd3d182..d02fa330cdf8 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeExtractors.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeExtractors.scala @@ -11,7 +11,7 @@ object TreeExtractors { /** Match arg1.op(arg2) and extract (arg1, op.symbol, arg2) */ object BinaryOp { - def unapply(t: Tree)(implicit ctx: Context): Option[(Tree, Symbol, Tree)] = t match { + def unapply(t: Tree)(using Context): Option[(Tree, Symbol, Tree)] = t match { case Apply(sel @ Select(arg1, _), List(arg2)) => Some((arg1, sel.symbol, arg2)) case _ => @@ -21,7 +21,7 @@ object TreeExtractors { /** Match new C(args) and extract (C, args) */ object NewWithArgs { - def unapply(t: Tree)(implicit ctx: Context): Option[(Type, List[Tree])] = t match { + def unapply(t: Tree)(using Context): Option[(Type, List[Tree])] = t match { case Apply(Select(New(_), nme.CONSTRUCTOR), args) => Some((t.tpe, args)) case _ => @@ -34,7 +34,7 @@ object TreeExtractors { * Match v.underlying() and extract v */ object ValueClassUnbox { - def unapply(t: Tree)(implicit ctx: Context): Option[Tree] = t match { + def unapply(t: Tree)(using Context): Option[Tree] = t match { case Apply(sel @ Select(ref, _), Nil) => val sym = ref.tpe.widenDealias.typeSymbol if (isDerivedValueClass(sym) && (sel.symbol eq valueClassUnbox(sym.asClass))) diff --git a/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala b/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala index 699140ff2da4..823c6b290a16 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala @@ -53,30 +53,30 @@ abstract class TreeMapWithStages(@constructorOnly ictx: Context) extends TreeMap protected def isInQuoteOrSplice: Boolean = inQuoteOrSplice /** Enter staging level of symbol defined by `tree` */ - private def markSymbol(sym: Symbol)(implicit ctx: Context): Unit = + private def markSymbol(sym: Symbol)(using Context): Unit = if level != 0 && !levelOfMap.contains(sym) then levelOfMap(sym) = level enteredSyms = sym :: enteredSyms /** Enter staging level of symbol defined by `tree`, if applicable. */ - private def markDef(tree: Tree)(implicit ctx: Context): Unit = tree match { + private def markDef(tree: Tree)(using Context): Unit = tree match { case tree: DefTree => markSymbol(tree.symbol) case _ => } /** Transform the quote `quote` which contains the quoted `body`. */ - protected def transformQuotation(body: Tree, quote: Tree)(implicit ctx: Context): Tree = + protected def transformQuotation(body: Tree, quote: Tree)(using Context): Tree = quote match { case quote: Apply => cpy.Apply(quote)(quote.fun, body :: Nil) case quote: TypeApply => cpy.TypeApply(quote)(quote.fun, body :: Nil) } /** Transform the splice `splice` which contains the spliced `body`. */ - protected def transformSplice(body: Tree, splice: Tree)(implicit ctx: Context): Tree + protected def transformSplice(body: Tree, splice: Tree)(using Context): Tree - override def transform(tree: Tree)(implicit ctx: Context): Tree = + override def transform(tree: Tree)(using Context): Tree = if (tree.source != ctx.source && tree.source.exists) - transform(tree)(ctx.withSource(tree.source)) + transform(tree)(using ctx.withSource(tree.source)) else reporting.trace(i"StagingTransformer.transform $tree at $level", staging, show = true) { def mapOverTree(lastEntered: List[Symbol]) = try super.transform(tree) @@ -149,7 +149,7 @@ object TreeMapWithStages { private val LevelOfKey = new Property.Key[mutable.HashMap[Symbol, Int]] /** Initial context for a StagingTransformer transformation. */ - def freshStagingContext(implicit ctx: Context): Context = + def freshStagingContext(using Context): Context = ctx.fresh.setProperty(LevelOfKey, new mutable.HashMap[Symbol, Int]) } \ No newline at end of file diff --git a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala index 41f72d838477..ad3bc57cb779 100644 --- a/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala +++ b/compiler/src/dotty/tools/dotc/transform/TryCatchPatterns.scala @@ -46,7 +46,7 @@ class TryCatchPatterns extends MiniPhase { override def runsAfter: Set[String] = Set(ElimRepeated.name) - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = tree match { + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case Try(_, cases, _) => cases.foreach { case CaseDef(Typed(_, _), guard, _) => assert(guard.isEmpty, "Try case should not contain a guard.") @@ -57,20 +57,20 @@ class TryCatchPatterns extends MiniPhase { case _ => } - override def transformTry(tree: Try)(implicit ctx: Context): Tree = { + override def transformTry(tree: Try)(using Context): Tree = { val (tryCases, patternMatchCases) = tree.cases.span(isCatchCase) val fallbackCase = mkFallbackPatterMatchCase(patternMatchCases, tree.span) cpy.Try(tree)(cases = tryCases ++ fallbackCase) } /** Is this pattern node a catch-all or type-test pattern? */ - private def isCatchCase(cdef: CaseDef)(implicit ctx: Context): Boolean = cdef match { + private def isCatchCase(cdef: CaseDef)(using Context): Boolean = cdef match { case CaseDef(Typed(Ident(nme.WILDCARD), tpt), EmptyTree, _) => isSimpleThrowable(tpt.tpe) case CaseDef(Bind(_, Typed(Ident(nme.WILDCARD), tpt)), EmptyTree, _) => isSimpleThrowable(tpt.tpe) case _ => isDefaultCase(cdef) } - private def isSimpleThrowable(tp: Type)(implicit ctx: Context): Boolean = tp.stripAnnots match { + private def isSimpleThrowable(tp: Type)(using Context): Boolean = tp.stripAnnots match { case tp @ TypeRef(pre, _) => (pre == NoPrefix || pre.widen.typeSymbol.isStatic) && // Does not require outer class check !tp.symbol.is(Flags.Trait) && // Traits not supported by JVM diff --git a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala index 6e63bd16298e..a15d68b60e2c 100644 --- a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala +++ b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala @@ -23,7 +23,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { def phaseName: String = "genericTuples" - override def transformApply(tree: tpd.Apply)(implicit ctx: Context): tpd.Tree = + override def transformApply(tree: tpd.Apply)(using Context): tpd.Tree = if (!tree.symbol.exists || tree.symbol.owner != defn.RuntimeTupleModuleClass) tree else if (tree.symbol == defn.RuntimeTuple_cons) transformTupleCons(tree) else if (tree.symbol == defn.RuntimeTuple_tail) transformTupleTail(tree) @@ -33,7 +33,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { else if (tree.symbol == defn.RuntimeTuple_toArray) transformTupleToArray(tree) else tree - private def transformTupleCons(tree: tpd.Apply)(implicit ctx: Context): Tree = { + private def transformTupleCons(tree: tpd.Apply)(using Context): Tree = { val head :: tail :: Nil = tree.args defn.tupleTypes(tree.tpe.widenTermRefExpr.dealias) match { case Some(tpes) => @@ -61,7 +61,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { } } - private def transformTupleTail(tree: tpd.Apply)(implicit ctx: Context): Tree = { + private def transformTupleTail(tree: tpd.Apply)(using Context): Tree = { val Apply(_, tup :: Nil) = tree defn.tupleTypes(tup.tpe.widenTermRefExpr.dealias, MaxTupleArity + 1) match { case Some(tpes) => @@ -98,13 +98,13 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { } } - private def transformTupleSize(tree: tpd.Apply)(implicit ctx: Context): Tree = + private def transformTupleSize(tree: tpd.Apply)(using Context): Tree = tree.tpe.tryNormalize match { case tp: ConstantType => Literal(tp.value) case _ => tree } - private def transformTupleConcat(tree: tpd.Apply)(implicit ctx: Context): Tree = { + private def transformTupleConcat(tree: tpd.Apply)(using Context): Tree = { val Apply(_, self :: that :: Nil) = tree (defn.tupleTypes(self.tpe.widenTermRefExpr.dealias), defn.tupleTypes(that.tpe.widenTermRefExpr.dealias)) match { case (Some(tpes1), Some(tpes2)) => @@ -139,7 +139,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { } } - private def transformTupleApply(tree: tpd.Apply)(implicit ctx: Context): Tree = { + private def transformTupleApply(tree: tpd.Apply)(using Context): Tree = { val Apply(_, tup :: nTree :: Nil) = tree (defn.tupleTypes(tup.tpe.widenTermRefExpr.dealias), nTree.tpe) match { case (Some(tpes), nTpe: ConstantType) => @@ -166,7 +166,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { } } - private def transformTupleToArray(tree: tpd.Apply)(implicit ctx: Context): Tree = { + private def transformTupleToArray(tree: tpd.Apply)(using Context): Tree = { val Apply(_, tup :: Nil) = tree defn.tupleTypes(tup.tpe.widen, MaxTupleArity) match { case Some(tpes) => @@ -188,14 +188,14 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { } /** Create a TupleN (1 <= N < 23) from the elements */ - private def knownTupleFromElements(tpes: List[Type], elements: List[Tree])(implicit ctx: Context) = { + private def knownTupleFromElements(tpes: List[Type], elements: List[Tree])(using Context) = { val size = elements.size assert(0 < size && size <= MaxTupleArity) val tupleModule = defn.TupleType(size).classSymbol.companionModule ref(tupleModule).select(nme.apply).appliedToTypes(tpes).appliedToArgs(elements) } - private def knownTupleFromIterator(size: Int, it: Tree)(implicit ctx: Context): Tree = + private def knownTupleFromIterator(size: Int, it: Tree)(using Context): Tree = if (size == 0) // EmptyTuple for empty tuple ref(defn.EmptyTupleModule.termRef) // TODO should this code be here? Or assert(size > specializedSize) @@ -214,7 +214,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { // TupleXXL.fromIterator(it) ref(defn.TupleXXL_fromIterator).appliedTo(it) - private def tupleSelectors(tup: Tree, size: Int)(implicit ctx: Context): List[Tree] = + private def tupleSelectors(tup: Tree, size: Int)(using Context): List[Tree] = (0 until size).map(i => tup.select(nme.selectorName(i))).toList } diff --git a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala index ebb1a20c8430..2bf2565b92bd 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala @@ -56,7 +56,7 @@ object TypeTestsCasts { def checkable(X: Type, P: Type, span: Span)(using Context): Boolean = { def isAbstract(P: Type) = !P.dealias.typeSymbol.isClass - def replaceP(tp: Type)(implicit ctx: Context) = new TypeMap { + def replaceP(tp: Type)(using Context) = new TypeMap { def apply(tp: Type) = tp match { case tref: TypeRef if tref.typeSymbol.isPatternBound => WildcardType @@ -66,7 +66,7 @@ object TypeTestsCasts { } }.apply(tp) - def replaceX(tp: Type)(implicit ctx: Context) = new TypeMap { + def replaceX(tp: Type)(using Context) = new TypeMap { def apply(tp: Type) = tp match { case tref: TypeRef if tref.typeSymbol.isPatternBound => if (variance == 1) tref.info.hiBound @@ -77,7 +77,7 @@ object TypeTestsCasts { }.apply(tp) /** Approximate type parameters depending on variance */ - def stripTypeParam(tp: Type)(implicit ctx: Context) = new ApproximatingTypeMap { + def stripTypeParam(tp: Type)(using Context) = new ApproximatingTypeMap { def apply(tp: Type): Type = tp match { case _: MatchType => tp // break cycles diff --git a/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala b/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala index 83648154af2c..d3cec855eafe 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeUtils.scala @@ -15,18 +15,18 @@ object TypeUtils { */ implicit class TypeUtilsOps(val self: Type) extends AnyVal { - def isErasedValueType(implicit ctx: Context): Boolean = + def isErasedValueType(using Context): Boolean = self.isInstanceOf[ErasedValueType] - def isPrimitiveValueType(implicit ctx: Context): Boolean = + def isPrimitiveValueType(using Context): Boolean = self.classSymbol.isPrimitiveValueClass - def ensureMethodic(implicit ctx: Context): Type = self match { + def ensureMethodic(using Context): Type = self match { case self: MethodicType => self case _ => if (ctx.erasedTypes) MethodType(Nil, self) else ExprType(self) } - def widenToParents(implicit ctx: Context): Type = self.parents match { + def widenToParents(using Context): Type = self.parents match { case Nil => self case ps => ps.reduceLeft(AndType(_, _)) } @@ -34,7 +34,7 @@ object TypeUtils { /** The arity of this tuple type, which can be made up of EmptyTuple, TupleX and `*:` pairs, * or -1 if this is not a tuple type. */ - def tupleArity(implicit ctx: Context): Int = self match { + def tupleArity(using Context): Int = self match { case AppliedType(tycon, _ :: tl :: Nil) if tycon.isRef(defn.PairClass) => val arity = tl.tupleArity if (arity < 0) arity else arity + 1 @@ -47,7 +47,7 @@ object TypeUtils { } /** The element types of this tuple type, which can be made up of EmptyTuple, TupleX and `*:` pairs */ - def tupleElementTypes(implicit ctx: Context): List[Type] = self match { + def tupleElementTypes(using Context): List[Type] = self match { case AppliedType(tycon, hd :: tl :: Nil) if tycon.isRef(defn.PairClass) => hd :: tl.tupleElementTypes case self: TermRef if self.symbol == defn.EmptyTupleModule => @@ -59,15 +59,15 @@ object TypeUtils { } /** The `*:` equivalent of an instance of a Tuple class */ - def toNestedPairs(implicit ctx: Context): Type = + def toNestedPairs(using Context): Type = TypeOps.nestedPairs(tupleElementTypes) - def refinedWith(name: Name, info: Type)(implicit ctx: Context) = RefinedType(self, name, info) + def refinedWith(name: Name, info: Type)(using Context) = RefinedType(self, name, info) /** The TermRef referring to the companion of the underlying class reference * of this type, while keeping the same prefix. */ - def companionRef(implicit ctx: Context): TermRef = self match { + def companionRef(using Context): TermRef = self match { case self @ TypeRef(prefix, _) if self.symbol.isClass => prefix.select(self.symbol.companionModule).asInstanceOf[TermRef] case self: TypeProxy => diff --git a/compiler/src/dotty/tools/dotc/transform/VCElideAllocations.scala b/compiler/src/dotty/tools/dotc/transform/VCElideAllocations.scala index 711c24aa7c06..caa387b9e937 100644 --- a/compiler/src/dotty/tools/dotc/transform/VCElideAllocations.scala +++ b/compiler/src/dotty/tools/dotc/transform/VCElideAllocations.scala @@ -22,7 +22,7 @@ class VCElideAllocations extends MiniPhase with IdentityDenotTransformer { override def runsAfter: Set[String] = Set(ElimErasedValueType.name) - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = + override def transformApply(tree: Apply)(using Context): Tree = tree match { // new V(u1) == new V(u2) => u1 == u2 // (We don't handle != because it has been eliminated by InterceptedMethods) diff --git a/compiler/src/dotty/tools/dotc/transform/VCInlineMethods.scala b/compiler/src/dotty/tools/dotc/transform/VCInlineMethods.scala index a37649b24188..a777a570da27 100644 --- a/compiler/src/dotty/tools/dotc/transform/VCInlineMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/VCInlineMethods.scala @@ -55,7 +55,7 @@ class VCInlineMethods extends MiniPhase with IdentityDenotTransformer { * @return A tree for the extension method call */ private def rewire(tree: Tree, mtArgs: List[Tree] = Nil, mArgss: List[List[Tree]] = Nil) - (implicit ctx: Context): Tree = + (using Context): Tree = tree match { case Apply(qual, mArgs) => rewire(qual, mtArgs, mArgs :: mArgss) @@ -88,7 +88,7 @@ class VCInlineMethods extends MiniPhase with IdentityDenotTransformer { /** If this tree corresponds to a fully-applied value class method call, replace it * by a call to the corresponding extension method, otherwise return it as is. */ - private def rewireIfNeeded(tree: Tree)(implicit ctx: Context) = tree.tpe.widen match { + private def rewireIfNeeded(tree: Tree)(using Context) = tree.tpe.widen match { case tp: LambdaType => tree // The rewiring will be handled by a fully-applied parent node case _ => @@ -98,10 +98,10 @@ class VCInlineMethods extends MiniPhase with IdentityDenotTransformer { tree } - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = + override def transformSelect(tree: Select)(using Context): Tree = rewireIfNeeded(tree) - override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree = + override def transformTypeApply(tree: TypeApply)(using Context): Tree = rewireIfNeeded(tree) - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = + override def transformApply(tree: Apply)(using Context): Tree = rewireIfNeeded(tree) } diff --git a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala index ae91791060ed..1653cf9bc36a 100644 --- a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala +++ b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala @@ -12,7 +12,7 @@ import SymUtils._ /** Methods that apply to user-defined value classes */ object ValueClasses { - def isDerivedValueClass(sym: Symbol)(implicit ctx: Context): Boolean = { + def isDerivedValueClass(sym: Symbol)(using Context): Boolean = { val d = sym.denot !ctx.settings.XnoValueClasses.value && !d.isRefinementClass && @@ -21,7 +21,7 @@ object ValueClasses { !d.isPrimitiveValueClass } - def isMethodWithExtension(sym: Symbol)(implicit ctx: Context): Boolean = + def isMethodWithExtension(sym: Symbol)(using Context): Boolean = ctx.atPhaseNotLaterThan(ctx.extensionMethodsPhase) { val d = sym.denot d.validFor.containsPhaseId(summon[Context].phaseId) && @@ -33,7 +33,7 @@ object ValueClasses { } /** The member of a derived value class that unboxes it. */ - def valueClassUnbox(cls: ClassSymbol)(implicit ctx: Context): Symbol = + def valueClassUnbox(cls: ClassSymbol)(using Context): Symbol = // (info.decl(nme.unbox)).orElse(...) uncomment once we accept unbox methods cls.classInfo.decls.find(_.is(ParamAccessor)) @@ -41,23 +41,23 @@ object ValueClasses { * ErasedValueType defined in the companion module. This method is added to the module * and further described in [[ExtensionMethods]]. */ - def u2evt(cls: ClassSymbol)(implicit ctx: Context): Symbol = + def u2evt(cls: ClassSymbol)(using Context): Symbol = cls.linkedClass.info.decl(nme.U2EVT).symbol /** For a value class `d`, this returns the synthetic cast from ErasedValueType to the * underlying type defined in the companion module. This method is added to the module * and further described in [[ExtensionMethods]]. */ - def evt2u(cls: ClassSymbol)(implicit ctx: Context): Symbol = + def evt2u(cls: ClassSymbol)(using Context): Symbol = cls.linkedClass.info.decl(nme.EVT2U).symbol /** The unboxed type that underlies a derived value class */ - def underlyingOfValueClass(sym: ClassSymbol)(implicit ctx: Context): Type = + def underlyingOfValueClass(sym: ClassSymbol)(using Context): Type = valueClassUnbox(sym).info.resultType /** Whether a value class wraps itself */ - def isCyclic(cls: ClassSymbol)(implicit ctx: Context): Boolean = { - def recur(seen: Set[Symbol], clazz: ClassSymbol)(implicit ctx: Context): Boolean = + def isCyclic(cls: ClassSymbol)(using Context): Boolean = { + def recur(seen: Set[Symbol], clazz: ClassSymbol)(using Context): Boolean = (seen contains clazz) || { val unboxed = underlyingOfValueClass(clazz).typeSymbol (isDerivedValueClass(unboxed)) && recur(seen + clazz, unboxed.asClass) diff --git a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala index d7136b3653eb..30238309a826 100644 --- a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala +++ b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala @@ -16,14 +16,14 @@ class YCheckPositions extends Phases.Phase { def phaseName: String = "inlinedPositions" - override def run(implicit ctx: Context): Unit = () // YCheck only + override def run(using Context): Unit = () // YCheck only - override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = + override def checkPostCondition(tree: Tree)(using Context): Unit = tree match { case PackageDef(pid, _) if tree.symbol.owner == defn.RootClass => new TreeTraverser { private var sources: List[SourceFile] = ctx.source :: Nil - def traverse(tree: tpd.Tree)(implicit ctx: Context): Unit = { + def traverse(tree: tpd.Tree)(using Context): Unit = { // Check current context is correct assert(ctx.source == sources.head) @@ -39,13 +39,13 @@ class YCheckPositions extends Phases.Phase { assert(bindings.isEmpty) val old = sources sources = old.tail - traverse(expansion)(inlineContext(EmptyTree).withSource(sources.head)) + traverse(expansion)(using inlineContext(EmptyTree).withSource(sources.head)) sources = old case Inlined(call, bindings, expansion) => bindings.foreach(traverse(_)) sources = call.symbol.topLevelClass.source :: sources if (!isMacro(call)) // FIXME macro implementations can drop Inlined nodes. We should reinsert them after macro expansion based on the positions of the trees - traverse(expansion)(inlineContext(call).withSource(sources.head)) + traverse(expansion)(using inlineContext(call).withSource(sources.head)) sources = sources.tail case _ => traverseChildren(tree) } @@ -54,7 +54,7 @@ class YCheckPositions extends Phases.Phase { case _ => } - private def isMacro(call: Tree)(implicit ctx: Context) = + private def isMacro(call: Tree)(using Context) = if (ctx.phase <= ctx.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/Checker.scala b/compiler/src/dotty/tools/dotc/transform/init/Checker.scala index f88faf5c1fb4..f8e36e66f8d6 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Checker.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Checker.scala @@ -27,10 +27,10 @@ class Checker extends MiniPhase { override val runsAfter = Set(Pickler.name) - override def isEnabled(implicit ctx: Context): Boolean = + override def isEnabled(using Context): Boolean = super.isEnabled && ctx.settings.YcheckInit.value - override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): tpd.Tree = { + override def transformTypeDef(tree: TypeDef)(using Context): tpd.Tree = { if (!tree.isClassDef) return tree val cls = tree.symbol.asClass @@ -46,7 +46,7 @@ class Checker extends MiniPhase { // A concrete class may not be instantiated if the self type is not satisfied if (instantiable) { - implicit val state = Checking.State( + implicit val state: Checking.State = Checking.State( visited = mutable.Set.empty, path = Vector.empty, thisClass = cls, diff --git a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala index 4ac57714b814..56886e75cb98 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala @@ -58,7 +58,7 @@ object Checking { // mark current class as initialized, required for linearization state.parentsInited += cls - def checkClassBodyStat(tree: Tree)(implicit ctx: Context): Unit = traceOp("checking " + tree.show, init) { + def checkClassBodyStat(tree: Tree)(using Context): Unit = traceOp("checking " + tree.show, init) { tree match { case vdef : ValDef => val (pots, effs) = Summarization.analyze(vdef.rhs)(theEnv.withOwner(vdef.symbol)) @@ -79,7 +79,7 @@ object Checking { // see spec 5.1 about "Template Evaluation". // https://www.scala-lang.org/files/archive/spec/2.13/05-classes-and-objects.html - def checkCtor(ctor: Symbol, tp: Type, source: Tree)(implicit ctx: Context): Unit = { + def checkCtor(ctor: Symbol, tp: Type, source: Tree)(using Context): Unit = { val cls = ctor.owner val classDef = cls.defTree if (!classDef.isEmpty) { diff --git a/compiler/src/dotty/tools/dotc/transform/init/Effects.scala b/compiler/src/dotty/tools/dotc/transform/init/Effects.scala index fecaee620148..6340f5286a85 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Effects.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Effects.scala @@ -15,13 +15,13 @@ object Effects { type Effects = Set[Effect] val empty: Effects = Set.empty - def show(effs: Effects)(implicit ctx: Context): String = + def show(effs: Effects)(using Context): String = effs.map(_.show).mkString(", ") /** Effects that are related to safe initialization */ sealed trait Effect { def size: Int - def show(implicit ctx: Context): String + def show(using Context): String def source: Tree } @@ -38,7 +38,7 @@ object Effects { */ case class Promote(potential: Potential)(val source: Tree) extends Effect { def size: Int = potential.size - def show(implicit ctx: Context): String = + def show(using Context): String = potential.show + "↑" } @@ -47,7 +47,7 @@ object Effects { assert(field != NoSymbol) def size: Int = potential.size - def show(implicit ctx: Context): String = + def show(using Context): String = potential.show + "." + field.name.show + "!" } @@ -56,7 +56,7 @@ object Effects { assert(method != NoSymbol) def size: Int = potential.size - def show(implicit ctx: Context): String = potential.show + "." + method.name.show + "!" + def show(using Context): String = potential.show + "." + method.name.show + "!" } // ------------------ operations on effects ------------------ diff --git a/compiler/src/dotty/tools/dotc/transform/init/Errors.scala b/compiler/src/dotty/tools/dotc/transform/init/Errors.scala index edca011f42b0..89300ce3adc1 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Errors.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Errors.scala @@ -15,20 +15,20 @@ object Errors { type Errors = Set[Error] val empty: Errors = Set.empty - def show(errs: Errors)(implicit ctx: Context): String = + def show(errs: Errors)(using Context): String = errs.map(_.show).mkString(", ") sealed trait Error { def source: Tree def trace: Vector[Tree] - def show(implicit ctx: Context): String + def show(using Context): String - def report(implicit ctx: Context): Unit = + def report(using Context): Unit = ctx.warning(show + stacktrace, source.sourcePos) def toErrors: Errors = Set(this) - def stacktrace(implicit ctx: Context): String = if (trace.isEmpty) "" else " Calling trace:\n" + { + def stacktrace(using Context): String = if (trace.isEmpty) "" else " Calling trace:\n" + { var indentCount = 0 var last: String = "" val sb = new StringBuilder @@ -62,41 +62,41 @@ object Errors { /** Access non-initialized field */ case class AccessNonInit(field: Symbol, trace: Vector[Tree]) extends Error { def source: Tree = trace.last - def show(implicit ctx: Context): String = + def show(using Context): String = "Access non-initialized field " + field.name.show + "." - override def report(implicit ctx: Context): Unit = ctx.error(show + stacktrace, field.sourcePos) + override def report(using Context): Unit = ctx.error(show + stacktrace, field.sourcePos) } /** Promote `this` under initialization to fully-initialized */ case class PromoteThis(pot: ThisRef, source: Tree, trace: Vector[Tree]) extends Error { - def show(implicit ctx: Context): String = "Promote the value under initialization to fully-initialized." + def show(using Context): String = "Promote the value under initialization to fully-initialized." } /** Promote `this` under initialization to fully-initialized */ case class PromoteWarm(pot: Warm, source: Tree, trace: Vector[Tree]) extends Error { - def show(implicit ctx: Context): String = + def show(using Context): String = "Promoting the value under initialization to fully-initialized." } /** Promote a cold value under initialization to fully-initialized */ case class PromoteCold(source: Tree, trace: Vector[Tree]) extends Error { - def show(implicit ctx: Context): String = + def show(using Context): String = "Promoting the value " + source.show + " to fully-initialized while it is under initialization" + "." } case class AccessCold(field: Symbol, source: Tree, trace: Vector[Tree]) extends Error { - def show(implicit ctx: Context): String = + def show(using Context): String = "Access field " + source.show + " on a value with an unknown initialization status" + "." } case class CallCold(meth: Symbol, source: Tree, trace: Vector[Tree]) extends Error { - def show(implicit ctx: Context): String = + def show(using Context): String = "Call method " + source.show + " on a value with an unknown initialization" + "." } case class CallUnknown(meth: Symbol, source: Tree, trace: Vector[Tree]) extends Error { - def show(implicit ctx: Context): String = + def show(using Context): String = "Calling the external method " + meth.show + " may cause initialization errors" + "." } @@ -104,9 +104,9 @@ object Errors { case class UnsafePromotion(pot: Potential, source: Tree, trace: Vector[Tree], errors: Errors) extends Error { assert(errors.nonEmpty) - override def report(implicit ctx: Context): Unit = ctx.warning(show, source.sourcePos) + override def report(using Context): Unit = ctx.warning(show, source.sourcePos) - def show(implicit ctx: Context): String = { + def show(using Context): String = { var index = 0 "Promoting the value to fully-initialized is unsafe.\n" + stacktrace + "\nThe unsafe promotion may cause the following problem(s):\n" + diff --git a/compiler/src/dotty/tools/dotc/transform/init/Potentials.scala b/compiler/src/dotty/tools/dotc/transform/init/Potentials.scala index 9098a0d2574d..777969929d39 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Potentials.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Potentials.scala @@ -17,20 +17,20 @@ object Potentials { type Potentials = Set[Potential] val empty: Potentials = Set.empty - def show(pots: Potentials)(implicit ctx: Context): String = + def show(pots: Potentials)(using Context): String = pots.map(_.show).mkString(", ") /** A potential represents an aliasing of a value that is possibly under initialization */ sealed trait Potential { def size: Int - def show(implicit ctx: Context): String + def show(using Context): String def source: Tree } /** The object pointed by `C.this` */ case class ThisRef(classSymbol: ClassSymbol)(val source: Tree) extends Potential { val size: Int = 1 - def show(implicit ctx: Context): String = classSymbol.name.show + ".this" + def show(using Context): String = classSymbol.name.show + ".this" /** Effects of a method call or a lazy val access * @@ -55,7 +55,7 @@ object Potentials { /** The object pointed by `C.super.this`, mainly used for override resolution */ case class SuperRef(pot: Potential, supercls: ClassSymbol)(val source: Tree) extends Potential { val size: Int = 1 - def show(implicit ctx: Context): String = pot.show + ".super[" + supercls.name.show + "]" + def show(using Context): String = pot.show + ".super[" + supercls.name.show + "]" } /** A warm potential represents an object of which all fields are initialized, but it may contain @@ -66,7 +66,7 @@ object Potentials { */ case class Warm(classSymbol: ClassSymbol, outer: Potential)(val source: Tree) extends Potential { def size: Int = 1 - def show(implicit ctx: Context): String = "Warm[" + classSymbol.show + ", outer = " + outer.show + "]" + def show(using Context): String = "Warm[" + classSymbol.show + ", outer = " + outer.show + "]" /** Effects of a method call or a lazy val access * @@ -113,7 +113,7 @@ object Potentials { */ case class Outer(pot: Potential, classSymbol: ClassSymbol)(val source: Tree) extends Potential { def size: Int = 1 - def show(implicit ctx: Context): String = "Outer[" + pot.show + ", " + classSymbol.show + "]" + def show(using Context): String = "Outer[" + pot.show + ", " + classSymbol.show + "]" } /** The object pointed by `this.f` */ @@ -121,7 +121,7 @@ object Potentials { assert(field != NoSymbol) def size: Int = potential.size + 1 - def show(implicit ctx: Context): String = potential.show + "." + field.name.show + def show(using Context): String = potential.show + "." + field.name.show } /** The object returned by `this.m()` */ @@ -129,19 +129,19 @@ object Potentials { assert(method != NoSymbol) def size: Int = potential.size + 1 - def show(implicit ctx: Context): String = potential.show + "." + method.name.show + def show(using Context): String = potential.show + "." + method.name.show } /** The object whose initialization status is unknown */ case class Cold()(val source: Tree) extends Potential { def size: Int = 1 - def show(implicit ctx: Context): String = "Cold" + def show(using Context): String = "Cold" } /** A function when called will produce the `effects` and return the `potentials` */ case class Fun(potentials: Potentials, effects: Effects)(val source: Tree) extends Potential { def size: Int = 1 - def show(implicit ctx: Context): String = + def show(using Context): String = "Fun[pots = " + potentials.map(_.show).mkString(";") + ", effs = " + effects.map(_.show).mkString(";") + "]" } @@ -149,7 +149,7 @@ object Potentials { def (pot: Potential) toPots: Potentials = Potentials.empty + pot - def (ps: Potentials) select (symbol: Symbol, source: Tree)(implicit ctx: Context): Summary = + def (ps: Potentials) select (symbol: Symbol, source: Tree)(using Context): Summary = ps.foldLeft(Summary.empty) { case ((pots, effs), pot) => // max potential length // TODO: it can be specified on a project basis via compiler options diff --git a/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala b/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala index cbe9c12064d1..379f4c5f976d 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/SetDefTree.scala @@ -13,19 +13,19 @@ class SetDefTree extends MiniPhase { override val phaseName: String = SetDefTree.name override val runsAfter = Set(Pickler.name) - override def isEnabled(implicit ctx: Context): Boolean = + override def isEnabled(using Context): Boolean = super.isEnabled && ctx.settings.YcheckInit.value - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { val ctx2 = ctx.fresh.setSetting(ctx.settings.YretainTrees, true) super.runOn(units)(using ctx2) } - override def transformValDef(tree: ValDef)(implicit ctx: Context): Tree = tree.setDefTree + override def transformValDef(tree: ValDef)(using Context): Tree = tree.setDefTree - override def transformDefDef(tree: DefDef)(implicit ctx: Context): Tree = tree.setDefTree + override def transformDefDef(tree: DefDef)(using Context): Tree = tree.setDefTree - override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree = tree.setDefTree + override def transformTypeDef(tree: TypeDef)(using Context): Tree = tree.setDefTree } object SetDefTree { diff --git a/compiler/src/dotty/tools/dotc/transform/init/Summary.scala b/compiler/src/dotty/tools/dotc/transform/init/Summary.scala index c90f90b489cf..9e626547710c 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Summary.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Summary.scala @@ -23,7 +23,7 @@ object Summary { case class ClassSummary(currentClass: ClassSymbol, parentOuter: Map[ClassSymbol, Potentials]) { private val summaryCache: mutable.Map[Symbol, Summary] = mutable.Map.empty - def cacheFor(member: Symbol, summary: Summary)(implicit ctx: Context): Unit = { + def cacheFor(member: Symbol, summary: Summary)(using Context): Unit = { traceIndented("cache for " + member.show + ", summary = " + Summary.show(summary), init) assert(member.owner == currentClass, "owner = " + member.owner.show + ", current = " + currentClass.show) summaryCache(member) = summary @@ -47,7 +47,7 @@ object Summary { def effectsOf(member: Symbol)(implicit env: Env): Effects = summaryOf(member)._2 def potentialsOf(member: Symbol)(implicit env: Env): Potentials = summaryOf(member)._1 - def show(implicit ctx: Context): String = + def show(using Context): String = "ClassSummary(" + currentClass.name.show + ", parents = " + parentOuter.map { case (k, v) => k.show + "->" + "[" + Potentials.show(v) + "]" } } @@ -75,12 +75,12 @@ object Summary { case None => ??? // impossible } - def show(implicit ctx: Context): String = + def show(using Context): String = "ObjectPart(this = " + thisValue.show + "," + currentClass.name.show + ", outer = " + Potentials.show(currentOuter) + "parents = " + parentOuter.map { case (k, v) => k.show + "->" + "[" + Potentials.show(v) + "]" } } - def show(summary: Summary)(implicit ctx: Context): String = { + def show(summary: Summary)(using Context): String = { val pots = Potentials.show(summary._1) val effs = Effects.show(summary._2) s"([$pots], [$effs])" diff --git a/compiler/src/dotty/tools/dotc/transform/init/Util.scala b/compiler/src/dotty/tools/dotc/transform/init/Util.scala index 7488bbcfebaa..58d05d63f573 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Util.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Util.scala @@ -10,23 +10,23 @@ import config.Printers.Printer import annotation.tailrec object Util { - def traceIndented(msg: String, printer: Printer)(implicit ctx: Context): Unit = + def traceIndented(msg: String, printer: Printer)(using Context): Unit = printer.println(s"${ctx.base.indentTab * ctx.base.indent} $msg") - def traceOp(msg: String, printer: Printer)(op: => Unit)(implicit ctx: Context): Unit = { + def traceOp(msg: String, printer: Printer)(op: => Unit)(using Context): Unit = { traceIndented(s"==> ${msg}", printer) op traceIndented(s"<== ${msg}", printer) } - def (symbol: Symbol) isInternal(implicit ctx: Context): Boolean = + def (symbol: Symbol) isInternal(using Context): Boolean = !symbol.defTree.isEmpty - def resolve(cls: ClassSymbol, sym: Symbol)(implicit ctx: Context): Symbol = + def resolve(cls: ClassSymbol, sym: Symbol)(using Context): Symbol = if (sym.isEffectivelyFinal || sym.isConstructor) sym else sym.matchingMember(cls.appliedRef) - def resolveSuper(cls: ClassSymbol, superCls: ClassSymbol, sym: Symbol)(implicit ctx: Context): Symbol = { + def resolveSuper(cls: ClassSymbol, superCls: ClassSymbol, sym: Symbol)(using Context): Symbol = { // println(s"bases of $cls: " + cls.info.baseClasses) @tailrec def loop(bcs: List[ClassSymbol]): Symbol = bcs match { case bc :: bcs1 => diff --git a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala index f7d7db553306..13f28ac95602 100644 --- a/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala +++ b/compiler/src/dotty/tools/dotc/transform/localopt/StringInterpolatorOpt.scala @@ -23,7 +23,7 @@ class StringInterpolatorOpt extends MiniPhase { override def phaseName: String = "stringInterpolatorOpt" - override def checkPostCondition(tree: tpd.Tree)(implicit ctx: Context): Unit = { + override def checkPostCondition(tree: tpd.Tree)(using Context): Unit = { tree match { case tree: RefTree => val sym = tree.symbol @@ -35,7 +35,7 @@ class StringInterpolatorOpt extends MiniPhase { /** Matches a list of constant literals */ private object Literals { - def unapply(tree: SeqLiteral)(implicit ctx: Context): Option[List[Literal]] = { + def unapply(tree: SeqLiteral)(using Context): Option[List[Literal]] = { tree.elems match { case literals if literals.forall(_.isInstanceOf[Literal]) => Some(literals.map(_.asInstanceOf[Literal])) @@ -45,7 +45,7 @@ class StringInterpolatorOpt extends MiniPhase { } private object StringContextApply { - def unapply(tree: Select)(implicit ctx: Context): Boolean = { + def unapply(tree: Select)(using Context): Boolean = { tree.symbol.eq(defn.StringContextModule_apply) && tree.qualifier.symbol.eq(defn.StringContextModule) } @@ -53,7 +53,7 @@ class StringInterpolatorOpt extends MiniPhase { /** Matches an s or raw string interpolator */ private object SOrRawInterpolator { - def unapply(tree: Tree)(implicit ctx: Context): Option[(List[Literal], List[Tree])] = { + def unapply(tree: Tree)(using Context): Option[(List[Literal], List[Tree])] = { tree match { case Apply(Select(Apply(StringContextApply(), List(Literals(strs))), _), List(SeqLiteral(elems, _))) if elems.length == strs.length - 1 => @@ -83,7 +83,7 @@ class StringInterpolatorOpt extends MiniPhase { * the variable references. */ private object StringContextIntrinsic { - def unapply(tree: Apply)(implicit ctx: Context): Option[(List[Literal], List[Tree])] = { + def unapply(tree: Apply)(using Context): Option[(List[Literal], List[Tree])] = { tree match { case SOrRawInterpolator(strs, elems) => if (tree.symbol == defn.StringContext_raw) Some(strs, elems) @@ -111,7 +111,7 @@ class StringInterpolatorOpt extends MiniPhase { } } - override def transformApply(tree: Apply)(implicit ctx: Context): Tree = { + override def transformApply(tree: Apply)(using Context): Tree = { val sym = tree.symbol val isInterpolatedMethod = // Test names first to avoid loading scala.StringContext if not used (sym.name == nme.raw_ && sym.eq(defn.StringContext_raw)) || diff --git a/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala b/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala index e57aefac3efa..737609ac644d 100644 --- a/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala +++ b/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala @@ -117,7 +117,7 @@ trait SpaceLogic { * * This reduces noise in counterexamples. */ - def simplify(space: Space, aggressive: Boolean = false)(implicit ctx: Context): Space = trace(s"simplify ${show(space)}, aggressive = $aggressive --> ", debug, x => show(x.asInstanceOf[Space]))(space match { + def simplify(space: Space, aggressive: Boolean = false)(using Context): Space = trace(s"simplify ${show(space)}, aggressive = $aggressive --> ", debug, x => show(x.asInstanceOf[Space]))(space match { case Prod(tp, fun, spaces, full) => val sp = Prod(tp, fun, spaces.map(simplify(_)), full) if (sp.params.contains(Empty)) Empty @@ -147,7 +147,7 @@ trait SpaceLogic { }) /** Flatten space to get rid of `Or` for pretty print */ - def flatten(space: Space)(implicit ctx: Context): List[Space] = space match { + def flatten(space: Space)(using Context): List[Space] = space match { case Prod(tp, fun, spaces, full) => spaces.map(flatten) match { case Nil => Prod(tp, fun, Nil, full) :: Nil @@ -163,7 +163,7 @@ trait SpaceLogic { } /** Is `a` a subspace of `b`? Equivalent to `a - b == Empty`, but faster */ - def isSubspace(a: Space, b: Space)(implicit ctx: Context): Boolean = trace(s"${show(a)} < ${show(b)}", debug) { + def isSubspace(a: Space, b: Space)(using Context): Boolean = trace(s"${show(a)} < ${show(b)}", debug) { def tryDecompose1(tp: Type) = canDecompose(tp) && isSubspace(Or(decompose(tp)), b) def tryDecompose2(tp: Type) = canDecompose(tp) && isSubspace(a, Or(decompose(tp))) @@ -189,7 +189,7 @@ trait SpaceLogic { } /** Intersection of two spaces */ - def intersect(a: Space, b: Space)(implicit ctx: Context): Space = trace(s"${show(a)} & ${show(b)}", debug, x => show(x.asInstanceOf[Space])) { + def intersect(a: Space, b: Space)(using Context): Space = trace(s"${show(a)} & ${show(b)}", debug, x => show(x.asInstanceOf[Space])) { def tryDecompose1(tp: Type) = intersect(Or(decompose(tp)), b) def tryDecompose2(tp: Type) = intersect(a, Or(decompose(tp))) @@ -229,7 +229,7 @@ trait SpaceLogic { } /** The space of a not covered by b */ - def minus(a: Space, b: Space)(implicit ctx: Context): Space = trace(s"${show(a)} - ${show(b)}", debug, x => show(x.asInstanceOf[Space])) { + def minus(a: Space, b: Space)(using Context): Space = trace(s"${show(a)} - ${show(b)}", debug, x => show(x.asInstanceOf[Space])) { def tryDecompose1(tp: Type) = minus(Or(decompose(tp)), b) def tryDecompose2(tp: Type) = minus(a, Or(decompose(tp))) @@ -286,7 +286,7 @@ object SpaceEngine { /** Is the unapply irrefutable? * @param unapp The unapply function reference */ - def isIrrefutableUnapply(unapp: tpd.Tree, patSize: Int)(implicit ctx: Context): Boolean = { + def isIrrefutableUnapply(unapp: tpd.Tree, patSize: Int)(using Context): Boolean = { val unappResult = unapp.tpe.widen.finalResultType unappResult.isRef(defn.SomeClass) || unappResult <:< ConstantType(Constant(true)) || @@ -300,7 +300,7 @@ object SpaceEngine { /** Is the unapplySeq irrefutable? * @param unapp The unapplySeq function reference */ - def isIrrefutableUnapplySeq(unapp: tpd.Tree, patSize: Int)(implicit ctx: Context): Boolean = { + def isIrrefutableUnapplySeq(unapp: tpd.Tree, patSize: Int)(using Context): Boolean = { val unappResult = unapp.tpe.widen.finalResultType unappResult.isRef(defn.SomeClass) || (unapp.symbol.is(Synthetic) && unapp.symbol.owner.linkedClass.is(Case)) || // scala2 compatibility @@ -314,7 +314,7 @@ object SpaceEngine { } /** Scala implementation of space logic */ -class SpaceEngine(implicit ctx: Context) extends SpaceLogic { +class SpaceEngine(using Context) extends SpaceLogic { import tpd._ import SpaceEngine._ @@ -422,7 +422,7 @@ class SpaceEngine(implicit ctx: Context) extends SpaceLogic { case tp => Typ(tp, decomposed = true) } - private def unapplySeqInfo(resTp: Type, pos: SourcePosition)(implicit ctx: Context): (Int, Type, Type) = { + private def unapplySeqInfo(resTp: Type, pos: SourcePosition)(using Context): (Int, Type, Type) = { var resultTp = resTp var elemTp = unapplySeqTypeElemTp(resultTp) var arity = productArity(resultTp, pos) @@ -716,7 +716,7 @@ class SpaceEngine(implicit ctx: Context) extends SpaceLogic { case _ => impossible } - def checkConstraint(constrs: List[(Type, Type)])(implicit ctx: Context): Boolean = { + def checkConstraint(constrs: List[(Type, Type)])(using Context): Boolean = { val tvarMap = collection.mutable.Map.empty[Symbol, TypeVar] val typeParamMap = new TypeMap() { override def apply(tp: Type): Type = tp match { @@ -729,7 +729,7 @@ class SpaceEngine(implicit ctx: Context) extends SpaceLogic { constrs.forall { case (tp1, tp2) => typeParamMap(tp1) <:< typeParamMap(tp2) } } - checkConstraint(genConstraint(sp))(ctx.fresh.setNewTyperState()) + checkConstraint(genConstraint(sp))(using ctx.fresh.setNewTyperState()) } def show(ss: Seq[Space]): String = ss.map(show).mkString(", ") From edb4869df72b26ef9d3cc80bec06f27034c384bc Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 17:50:07 +0200 Subject: [PATCH 25/41] Convert other dotc classes (1) --- .../backend/sjs/JUnitBootstrappers.scala | 4 +-- compiler/src/dotty/tools/dotc/Bench.scala | 2 +- .../dotty/tools/dotc/CompilationUnit.scala | 8 ++--- compiler/src/dotty/tools/dotc/Compiler.scala | 4 +-- compiler/src/dotty/tools/dotc/Driver.scala | 6 ++-- compiler/src/dotty/tools/dotc/Resident.scala | 2 +- compiler/src/dotty/tools/dotc/Run.scala | 22 +++++++------- .../dotc/classpath/ClassPathFactory.scala | 18 +++++------ .../ZipAndJarFileLookupFactory.scala | 2 +- .../decompiler/DecompilationPrinter.scala | 4 +-- .../dotc/decompiler/IDEDecompilerDriver.scala | 2 +- .../dotty/tools/dotc/decompiler/Main.scala | 2 +- .../tools/dotc/fromtasty/ReadTasty.scala | 10 +++---- .../tools/dotc/fromtasty/TASTYCompiler.scala | 2 +- .../dotc/interactive/InteractiveDriver.scala | 4 +-- .../src/dotty/tools/dotc/plugins/Plugin.scala | 2 +- .../dotty/tools/dotc/plugins/Plugins.scala | 10 +++---- .../tools/dotc/printing/Formatting.scala | 30 +++++++++---------- .../tools/dotc/printing/Highlighting.scala | 10 +++---- .../dotty/tools/dotc/printing/Showable.scala | 2 +- .../dotc/printing/SyntaxHighlighting.scala | 9 +++--- .../tools/dotc/profile/AsyncHelper.scala | 8 ++--- .../dotty/tools/dotc/profile/Profiler.scala | 4 +-- .../dotty/tools/dotc/reporting/messages.scala | 2 +- .../src/dotty/tools/dotc/sbt/APIUtils.scala | 4 +-- .../dotty/tools/dotc/util/ParsedComment.scala | 2 +- .../src/dotty/tools/repl/ReplDriver.scala | 6 ++-- 27 files changed, 91 insertions(+), 90 deletions(-) diff --git a/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala b/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala index f192b33d830b..7846aa70a2da 100644 --- a/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala +++ b/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala @@ -235,8 +235,8 @@ class JUnitBootstrappers extends MiniPhase { if timeoutName.toString == "timeout" => Some(timeoutLiteral) case other => { val shownName = other match { - case NamedArg(name, _) => name.show(ctx) - case other => other.show(ctx) + 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) None diff --git a/compiler/src/dotty/tools/dotc/Bench.scala b/compiler/src/dotty/tools/dotc/Bench.scala index 97c00108fc84..568503e4d783 100644 --- a/compiler/src/dotty/tools/dotc/Bench.scala +++ b/compiler/src/dotty/tools/dotc/Bench.scala @@ -17,7 +17,7 @@ object Bench extends Driver { private def ntimes(n: Int)(op: => Reporter): Reporter = (0 until n).foldLeft(emptyReporter)((_, _) => op) - override def doCompile(compiler: Compiler, fileNames: List[String])(implicit ctx: Context): Reporter = + override def doCompile(compiler: Compiler, fileNames: List[String])(using Context): Reporter = ntimes(numRuns) { val start = System.nanoTime() val r = super.doCompile(compiler, fileNames) diff --git a/compiler/src/dotty/tools/dotc/CompilationUnit.scala b/compiler/src/dotty/tools/dotc/CompilationUnit.scala index 2ffb201609b1..99dd16c24f30 100644 --- a/compiler/src/dotty/tools/dotc/CompilationUnit.scala +++ b/compiler/src/dotty/tools/dotc/CompilationUnit.scala @@ -79,11 +79,11 @@ object CompilationUnit { class SuspendException extends Exception /** Make a compilation unit for top class `clsd` with the contents of the `unpickled` tree */ - def apply(clsd: ClassDenotation, unpickled: Tree, forceTrees: Boolean)(implicit ctx: Context): CompilationUnit = + def apply(clsd: ClassDenotation, unpickled: Tree, forceTrees: Boolean)(using Context): CompilationUnit = apply(new SourceFile(clsd.symbol.associatedFile, Array.empty[Char]), unpickled, forceTrees) /** Make a compilation unit, given picked bytes and unpickled tree */ - def apply(source: SourceFile, unpickled: Tree, forceTrees: Boolean)(implicit ctx: Context): CompilationUnit = { + def apply(source: SourceFile, unpickled: Tree, forceTrees: Boolean)(using Context): CompilationUnit = { assert(!unpickled.isEmpty, unpickled) val unit1 = new CompilationUnit(source) unit1.tpdTree = unpickled @@ -98,7 +98,7 @@ object CompilationUnit { /** Create a compilation unit corresponding to `source`. * If `mustExist` is true, this will fail if `source` does not exist. */ - def apply(source: SourceFile, mustExist: Boolean = true)(implicit ctx: Context): CompilationUnit = { + def apply(source: SourceFile, mustExist: Boolean = true)(using Context): CompilationUnit = { val src = if (!mustExist) source @@ -117,7 +117,7 @@ object CompilationUnit { /** Force the tree to be loaded */ private class Force extends TreeTraverser { var needsStaging = false - def traverse(tree: Tree)(implicit ctx: Context): Unit = { + def traverse(tree: Tree)(using Context): Unit = { if (tree.symbol.isQuote) needsStaging = true traverseChildren(tree) diff --git a/compiler/src/dotty/tools/dotc/Compiler.scala b/compiler/src/dotty/tools/dotc/Compiler.scala index 40d3a74cbe39..c55fa34d2ebc 100644 --- a/compiler/src/dotty/tools/dotc/Compiler.scala +++ b/compiler/src/dotty/tools/dotc/Compiler.scala @@ -138,12 +138,12 @@ class Compiler { runId += 1; runId } - def reset()(implicit ctx: Context): Unit = { + def reset()(using Context): Unit = { ctx.base.reset() if (ctx.run != null) ctx.run.reset() } - def newRun(implicit ctx: Context): Run = { + def newRun(using Context): Run = { reset() val rctx = if ctx.settings.Ysemanticdb.value diff --git a/compiler/src/dotty/tools/dotc/Driver.scala b/compiler/src/dotty/tools/dotc/Driver.scala index c50029ca96ad..6271581d7526 100644 --- a/compiler/src/dotty/tools/dotc/Driver.scala +++ b/compiler/src/dotty/tools/dotc/Driver.scala @@ -25,13 +25,13 @@ import fromtasty.{TASTYCompiler, TastyFileUtil} */ class Driver { - protected def newCompiler(implicit ctx: Context): Compiler = + protected def newCompiler(using Context): Compiler = if (ctx.settings.fromTasty.value) new TASTYCompiler else new Compiler protected def emptyReporter: Reporter = new StoreReporter(null) - protected def doCompile(compiler: Compiler, fileNames: List[String])(implicit ctx: Context): Reporter = + protected def doCompile(compiler: Compiler, fileNames: List[String])(using Context): Reporter = if (fileNames.nonEmpty) try val run = compiler.newRun @@ -191,7 +191,7 @@ class Driver { */ def process(args: Array[String], rootCtx: Context): Reporter = { val (fileNames, compileCtx) = setup(args, rootCtx) - doCompile(newCompiler(compileCtx), fileNames)(compileCtx) + doCompile(newCompiler(using compileCtx), fileNames)(using compileCtx) } def main(args: Array[String]): Unit = { diff --git a/compiler/src/dotty/tools/dotc/Resident.scala b/compiler/src/dotty/tools/dotc/Resident.scala index 7ddae4ab9787..3a2df21b151d 100644 --- a/compiler/src/dotty/tools/dotc/Resident.scala +++ b/compiler/src/dotty/tools/dotc/Resident.scala @@ -41,7 +41,7 @@ class Resident extends Driver { final override def process(args: Array[String], rootCtx: Context): Reporter = { @tailrec def loop(args: Array[String], prevCtx: Context): Reporter = { var (fileNames, ctx) = setup(args, prevCtx) - doCompile(residentCompiler, fileNames)(ctx) + doCompile(residentCompiler, fileNames)(using ctx) var nextCtx = ctx var line = getLine() while (line == reset) { diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 95af51ad12f3..1fc18c64a4bf 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -59,7 +59,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint * for type checking. * imports For each element of RootImports, an import context */ - protected def rootContext(implicit ctx: Context): Context = { + protected def rootContext(using Context): Context = { ctx.initialize() ctx.base.setPhasePlan(comp.phases) val rootScope = new MutableScope @@ -80,7 +80,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint private var compiling = false - private var myCtx = rootContext(ictx) + private var myCtx = rootContext(using ictx) /** The context created for this run */ given runContext[Dummy_so_its_a_def] as Context = myCtx @@ -152,7 +152,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint compileUnits()(using ctx) } - private def compileUnits()(implicit ctx: Context) = Stats.maybeMonitored { + private def compileUnits()(using Context) = Stats.maybeMonitored { if (!ctx.mode.is(Mode.Interactive)) // IDEs might have multi-threaded access, accesses are synchronized ctx.base.checkSingleThreaded() @@ -168,7 +168,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint ctx.settings.Yskip.value, ctx.settings.YstopBefore.value, stopAfter, ctx.settings.Ycheck.value) ctx.base.usePhases(phases) - def runPhases(implicit ctx: Context) = { + def runPhases(using Context) = { var lastPrintedTree: PrintedTree = NoPrintedTree val profiler = ctx.profiler @@ -182,7 +182,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint if (ctx.settings.Xprint.value.containsPhase(phase)) for (unit <- units) lastPrintedTree = - printTree(lastPrintedTree)(ctx.fresh.setPhase(phase.next).setCompilationUnit(unit)) + printTree(lastPrintedTree)(using ctx.fresh.setPhase(phase.next).setCompilationUnit(unit)) ctx.informTime(s"$phase ", start) Stats.record(s"total trees at end of $phase", ast.Trees.ntrees) for (unit <- units) @@ -195,7 +195,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint val runCtx = ctx.fresh runCtx.setProfiler(Profiler()) ctx.phases.foreach(_.initContext(runCtx)) - runPhases(runCtx) + runPhases(using runCtx) if (!ctx.reporter.hasErrors) Rewrites.writeBack() while (finalizeActions.nonEmpty) { val action = finalizeActions.remove(0) @@ -209,11 +209,11 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint * If `typeCheck = true`, also run typer on the compilation unit, and set * `rootTreeOrProvider`. */ - def lateCompile(file: AbstractFile, typeCheck: Boolean)(implicit ctx: Context): Unit = + def lateCompile(file: AbstractFile, typeCheck: Boolean)(using Context): Unit = if (!files.contains(file) && !lateFiles.contains(file)) { lateFiles += file val unit = CompilationUnit(ctx.getSource(file.path)) - def process()(implicit ctx: Context) = { + def process()(using Context) = { unit.untpdTree = if (unit.isJava) new JavaParser(unit.source).parse() else new Parser(unit.source).parse() @@ -226,18 +226,18 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint if (typeCheck) if (compiling) finalizeActions += (() => processUnit()) else processUnit() } - process()(runContext.fresh.setCompilationUnit(unit)) + process()(using runContext.fresh.setCompilationUnit(unit)) } private sealed trait PrintedTree private /*final*/ case class SomePrintedTree(phase: String, tree: String) extends PrintedTree private object NoPrintedTree extends PrintedTree - private def printTree(last: PrintedTree)(implicit ctx: Context): PrintedTree = { + 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 treeString = unit.tpdTree.show(ctx.withProperty(XprintMode, Some(()))) + val treeString = unit.tpdTree.show(using ctx.withProperty(XprintMode, Some(()))) ctx.echo(s"result of $unit after $squashedPhase:") diff --git a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala index f3625d7eb7ef..81cd18657da2 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala @@ -16,12 +16,12 @@ class ClassPathFactory { /** * Create a new classpath based on the abstract file. */ - def newClassPath(file: AbstractFile)(implicit ctx: Context): ClassPath = ClassPathFactory.newClassPath(file) + def newClassPath(file: AbstractFile)(using Context): ClassPath = ClassPathFactory.newClassPath(file) /** * Creators for sub classpaths which preserve this context. */ - def sourcesInPath(path: String)(implicit ctx: Context): List[ClassPath] = + def sourcesInPath(path: String)(using Context): List[ClassPath] = for { file <- expandPath(path, expandStar = false) dir <- Option(AbstractFile getDirectory file) @@ -33,7 +33,7 @@ class ClassPathFactory { def expandDir(extdir: String): List[String] = dotty.tools.io.ClassPath.expandDir(extdir) - def contentsOfDirsInPath(path: String)(implicit ctx: Context): List[ClassPath] = + def contentsOfDirsInPath(path: String)(using Context): List[ClassPath] = for { dir <- expandPath(path, expandStar = false) name <- expandDir(dir) @@ -41,17 +41,17 @@ class ClassPathFactory { } yield newClassPath(entry) - def classesInExpandedPath(path: String)(implicit ctx: Context): IndexedSeq[ClassPath] = + def classesInExpandedPath(path: String)(using Context): IndexedSeq[ClassPath] = classesInPathImpl(path, expand = true).toIndexedSeq - def classesInPath(path: String)(implicit ctx: Context): List[ClassPath] = classesInPathImpl(path, expand = false) + def classesInPath(path: String)(using Context): List[ClassPath] = classesInPathImpl(path, expand = false) - def classesInManifest(useManifestClassPath: Boolean)(implicit ctx: Context): List[ClassPath] = + def classesInManifest(useManifestClassPath: Boolean)(using Context): List[ClassPath] = if (useManifestClassPath) dotty.tools.io.ClassPath.manifests.map(url => newClassPath(AbstractFile getResources url)) else Nil // Internal - protected def classesInPathImpl(path: String, expand: Boolean)(implicit ctx: Context): List[ClassPath] = + protected def classesInPathImpl(path: String, expand: Boolean)(using Context): List[ClassPath] = for { file <- expandPath(path, expand) dir <- { @@ -61,7 +61,7 @@ class ClassPathFactory { } yield newClassPath(dir) - private def createSourcePath(file: AbstractFile)(implicit ctx: Context): ClassPath = + private def createSourcePath(file: AbstractFile)(using Context): ClassPath = if (file.isJarOrZip) ZipAndJarSourcePathFactory.create(file) else if (file.isDirectory) @@ -71,7 +71,7 @@ class ClassPathFactory { } object ClassPathFactory { - def newClassPath(file: AbstractFile)(implicit ctx: Context): ClassPath = file match { + def newClassPath(file: AbstractFile)(using Context): ClassPath = file match { case vd: VirtualDirectory => VirtualDirectoryClassPath(vd) case _ => if (file.isJarOrZip) diff --git a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala index 73c3353518d1..75dcdf3c1979 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala @@ -21,7 +21,7 @@ import FileUtils._ sealed trait ZipAndJarFileLookupFactory { private val cache = new FileBasedCache[ClassPath] - def create(zipFile: AbstractFile)(implicit ctx: Context): ClassPath = + def create(zipFile: AbstractFile)(using Context): ClassPath = if (ctx.settings.YdisableFlatCpCaching.value || zipFile.file == null) createForZipFile(zipFile) else createUsingCache(zipFile) diff --git a/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala b/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala index c83990509372..5e17b655bda2 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala @@ -19,7 +19,7 @@ class DecompilationPrinter extends Phase { override def phaseName: String = "decompilationPrinter" - override def run(implicit ctx: Context): Unit = + override def run(using Context): Unit = if (ctx.settings.outputDir.isDefault) printToOutput(System.out) else { val outputDir = ctx.settings.outputDir.value @@ -36,7 +36,7 @@ class DecompilationPrinter extends Phase { } } - private def printToOutput(out: PrintStream)(implicit ctx: Context): Unit = { + private def printToOutput(out: PrintStream)(using Context): Unit = { val unit = ctx.compilationUnit if (ctx.settings.printTasty.value) println(new TastyPrinter(unit.pickled.head._2).printContents()) diff --git a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala index e97e0c4ddfb2..0a8f950b97bc 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/IDEDecompilerDriver.scala @@ -27,7 +27,7 @@ class IDEDecompilerDriver(val settings: List[String]) extends dotc.Driver { def run(className: String): (String, String) = { val reporter = new StoreReporter(null) with HideNonSensicalMessages - val run = decompiler.newRun(myInitCtx.fresh.setReporter(reporter)) + val run = decompiler.newRun(using myInitCtx.fresh.setReporter(reporter)) inContext(run.runContext) { run.compile(List(className)) diff --git a/compiler/src/dotty/tools/dotc/decompiler/Main.scala b/compiler/src/dotty/tools/dotc/decompiler/Main.scala index dd7cd8d00b15..e78dcb9d6def 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/Main.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/Main.scala @@ -10,7 +10,7 @@ import dotty.tools.dotc.core.Contexts._ * @author Nicolas Stucki */ object Main extends dotc.Driver { - override protected def newCompiler(implicit ctx: Context): dotc.Compiler = { + override protected def newCompiler(using Context): dotc.Compiler = { assert(ctx.settings.fromTasty.value) if (!ctx.settings.outputDir.isDefault) Files.deleteIfExists(ctx.settings.outputDir.value.fileNamed("decompiled.scala").jpath) diff --git a/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala b/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala index cd0eec7f5b8e..ad398a0036c9 100644 --- a/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala +++ b/compiler/src/dotty/tools/dotc/fromtasty/ReadTasty.scala @@ -17,13 +17,13 @@ class ReadTasty extends Phase { def phaseName: String = "readTasty" - override def isRunnable(implicit ctx: Context): Boolean = + override def isRunnable(using Context): Boolean = ctx.settings.fromTasty.value - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = - units.flatMap(readTASTY(_)(ctx.addMode(Mode.ReadPositions))) + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = + units.flatMap(readTASTY(_)(using ctx.addMode(Mode.ReadPositions))) - def readTASTY(unit: CompilationUnit)(implicit ctx: Context): Option[CompilationUnit] = unit match { + def readTASTY(unit: CompilationUnit)(using Context): Option[CompilationUnit] = unit match { case unit: TASTYCompilationUnit => val className = unit.className.toTypeName @@ -75,5 +75,5 @@ class ReadTasty extends Phase { Some(unit) } - def run(implicit ctx: Context): Unit = unsupported("run") + def run(using Context): Unit = unsupported("run") } diff --git a/compiler/src/dotty/tools/dotc/fromtasty/TASTYCompiler.scala b/compiler/src/dotty/tools/dotc/fromtasty/TASTYCompiler.scala index 649580dcf772..59f8444eb06a 100644 --- a/compiler/src/dotty/tools/dotc/fromtasty/TASTYCompiler.scala +++ b/compiler/src/dotty/tools/dotc/fromtasty/TASTYCompiler.scala @@ -12,7 +12,7 @@ class TASTYCompiler extends Compiler { override protected def frontendPhases: List[List[Phase]] = List(new ReadTasty) :: Nil - override def newRun(implicit ctx: Context): Run = { + override def newRun(using Context): Run = { reset() new TASTYRun(this, ctx.addMode(Mode.ReadPositions)) } diff --git a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala index d2c8fd8b0892..869147e9feb4 100644 --- a/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala +++ b/compiler/src/dotty/tools/dotc/interactive/InteractiveDriver.scala @@ -146,7 +146,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { val reporter = new StoreReporter(null) with UniqueMessagePositions with HideNonSensicalMessages - val run = compiler.newRun(myInitCtx.fresh.setReporter(reporter)) + val run = compiler.newRun(using myInitCtx.fresh.setReporter(reporter)) myCtx = run.runContext given Context = myCtx @@ -312,7 +312,7 @@ class InteractiveDriver(val settings: List[String]) extends Driver { * late-compilation is needed). */ private def initialize(): Unit = { - val run = compiler.newRun(myInitCtx.fresh) + val run = compiler.newRun(using myInitCtx.fresh) myCtx = run.runContext run.compileUnits(Nil, myCtx) } diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugin.scala b/compiler/src/dotty/tools/dotc/plugins/Plugin.scala index 35ee4138133f..cb4a6d9e99af 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugin.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugin.scala @@ -60,7 +60,7 @@ trait ResearchPlugin extends Plugin { * @param plan: the given phase plan * @return the new phase plan */ - def init(options: List[String], plan: List[List[Phase]])(implicit ctx: Context): List[List[Phase]] + def init(options: List[String], plan: List[List[Phase]])(using Context): List[List[Phase]] } object Plugin { diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala index 72c2b3bec543..653d593b66eb 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala @@ -23,7 +23,7 @@ trait Plugins { * test for same-named phases or other problems that are * filtered from the final list of plugins. */ - protected def loadRoughPluginsList(implicit ctx: Context): List[Plugin] = { + protected def loadRoughPluginsList(using Context): List[Plugin] = { def asPath(p: String) = ClassPath split p val paths = ctx.settings.plugin.value filter (_ != "") map (s => asPath(s) map Path.apply) val dirs = { @@ -43,7 +43,7 @@ trait Plugins { } private var _roughPluginsList: List[Plugin] = _ - protected def roughPluginsList(implicit ctx: Context): List[Plugin] = + protected def roughPluginsList(using Context): List[Plugin] = if (_roughPluginsList == null) { _roughPluginsList = loadRoughPluginsList _roughPluginsList @@ -54,7 +54,7 @@ trait Plugins { * either have the same name as another one, or which * define a phase name that another one does. */ - protected def loadPlugins(implicit ctx: Context): List[Plugin] = { + protected def loadPlugins(using Context): List[Plugin] = { // remove any with conflicting names or subcomponent names def pick( plugins: List[Plugin], @@ -95,7 +95,7 @@ trait Plugins { } private var _plugins: List[Plugin] = _ - def plugins(implicit ctx: Context): List[Plugin] = + def plugins(using Context): List[Plugin] = if (_plugins == null) { _plugins = loadPlugins _plugins @@ -113,7 +113,7 @@ trait Plugins { }).mkString /** Add plugin phases to phase plan */ - def addPluginPhases(plan: List[List[Phase]])(implicit ctx: Context): List[List[Phase]] = { + def addPluginPhases(plan: List[List[Phase]])(using Context): List[List[Phase]] = { // plugin-specific options. // The user writes `-P:plugname:opt1,opt2`, but the plugin sees `List(opt1, opt2)`. def options(plugin: Plugin): List[String] = { diff --git a/compiler/src/dotty/tools/dotc/printing/Formatting.scala b/compiler/src/dotty/tools/dotc/printing/Formatting.scala index c3686474bc68..b4a2af039b5c 100644 --- a/compiler/src/dotty/tools/dotc/printing/Formatting.scala +++ b/compiler/src/dotty/tools/dotc/printing/Formatting.scala @@ -23,7 +23,7 @@ object Formatting { * against accidentally treating an interpolated value as a margin. */ class StringFormatter(protected val sc: StringContext) { - protected def showArg(arg: Any)(implicit ctx: Context): String = arg match { + protected def showArg(arg: Any)(using Context): String = arg match { case arg: Showable => try arg.show catch { @@ -39,7 +39,7 @@ object Formatting { case _ => arg.toString } - private def treatArg(arg: Any, suffix: String)(implicit ctx: Context): (Any, String) = arg match { + private def treatArg(arg: Any, suffix: String)(using Context): (Any, String) = arg match { case arg: Seq[?] if suffix.nonEmpty && suffix.head == '%' => val (rawsep, rest) = suffix.tail.span(_ != '%') val sep = StringContext.processEscapes(rawsep) @@ -49,7 +49,7 @@ object Formatting { (showArg(arg), suffix) } - def assemble(args: Seq[Any])(implicit ctx: Context): String = { + def assemble(args: Seq[Any])(using Context): String = { def isLineBreak(c: Char) = c == '\n' || c == '\f' // compatible with StringLike#isLineBreak def stripTrailingPart(s: String) = { val (pre, post) = s.span(c => !isLineBreak(c)) @@ -72,11 +72,11 @@ object Formatting { * message composition methods, this is crucial. */ class ErrorMessageFormatter(sc: StringContext) extends StringFormatter(sc): - override protected def showArg(arg: Any)(implicit ctx: Context): String = + override protected def showArg(arg: Any)(using Context): String = wrapNonSensical(arg, super.showArg(arg)(using errorMessageCtx)) class SyntaxFormatter(sc: StringContext) extends StringFormatter(sc) { - override protected def showArg(arg: Any)(implicit ctx: Context): String = + override protected def showArg(arg: Any)(using Context): String = arg match { case hl: Highlight => hl.show @@ -87,7 +87,7 @@ object Formatting { } } - private def wrapNonSensical(arg: Any, str: String)(implicit ctx: Context): String = { + private def wrapNonSensical(arg: Any, str: String)(using Context): String = { import Message._ def isSensical(arg: Any): Boolean = arg match { case tpe: Type => @@ -111,7 +111,7 @@ object Formatting { override def default(key: SeenKey) = Nil - def record(str: String, isType: Boolean, entry: Recorded)(implicit ctx: Context): String = { + def record(str: String, isType: Boolean, entry: Recorded)(using Context): String = { /** If `e1` is an alias of another class of the same name, return the other * class symbol instead. This normalization avoids recording e.g. scala.List @@ -177,7 +177,7 @@ object Formatting { } /** Create explanation for single `Recorded` type or symbol */ - def explanation(entry: AnyRef)(implicit ctx: Context): String = { + def explanation(entry: AnyRef)(using Context): String = { def boundStr(bound: Type, default: ClassSymbol, cmp: String) = if (bound.isRef(default)) "" else i"$cmp $bound" @@ -219,7 +219,7 @@ object Formatting { * * @return string disambiguating types */ - private def explanations(seen: Seen)(implicit ctx: Context): String = { + private def explanations(seen: Seen)(using Context): String = { def needsExplanation(entry: Recorded) = entry match { case param: TypeParamRef => ctx.typerState.constraint.contains(param) case param: ParamRef => false @@ -261,7 +261,7 @@ object Formatting { case _ => ctx.fresh.setProperty(MessageLimiter, ErrorMessageLimiter()) /** Context with correct printer set for explanations */ - private def explainCtx(seen: Seen)(implicit ctx: Context): Context = + private def explainCtx(seen: Seen)(using Context): Context = val ectx = errorMessageCtx ectx.printer match case dp: ExplainingPrinter => @@ -275,7 +275,7 @@ object Formatting { * ex"disambiguate $tpe1 and $tpe2" * ``` */ - def explained(op: Context ?=> String)(implicit ctx: Context): String = { + def explained(op: Context ?=> String)(using Context): String = { val seen = new Seen val msg = op(using explainCtx(seen)) val addendum = explanations(seen) @@ -294,10 +294,10 @@ object Formatting { * @return the `where` section as well as the printing context for the * placeholders - `("T is a...", printCtx)` */ - def disambiguateTypes(args: Type*)(implicit ctx: Context): (String, Context) = { + def disambiguateTypes(args: Type*)(using Context): (String, Context) = { val seen = new Seen val printCtx = explainCtx(seen) - args.foreach(_.show(printCtx)) // showing each member will put it into `seen` + args.foreach(_.show(using printCtx)) // showing each member will put it into `seen` (explanations(seen), printCtx) } @@ -312,7 +312,7 @@ object Formatting { * @return the (found, expected, changePercentage) with coloring to * highlight the difference */ - def typeDiff(found: Type, expected: Type)(implicit ctx: Context): (String, String) = { + def typeDiff(found: Type, expected: Type)(using Context): (String, String) = { val fnd = wrapNonSensical(found, found.show) val exp = wrapNonSensical(expected, expected.show) @@ -324,6 +324,6 @@ object Formatting { } /** Explicit syntax highlighting */ - def hl(s: String)(implicit ctx: Context): String = + def hl(s: String)(using Context): String = SyntaxHighlighting.highlight(s) } diff --git a/compiler/src/dotty/tools/dotc/printing/Highlighting.scala b/compiler/src/dotty/tools/dotc/printing/Highlighting.scala index 59c8cccc3571..1678e8efd2f5 100644 --- a/compiler/src/dotty/tools/dotc/printing/Highlighting.scala +++ b/compiler/src/dotty/tools/dotc/printing/Highlighting.scala @@ -10,27 +10,27 @@ object Highlighting { abstract class Highlight(private val highlight: String) { def text: String - def show(implicit ctx: Context): String = + def show(using Context): String = if (ctx.settings.color.value == "never") text else highlight + text + Console.RESET override def toString: String = highlight + text + Console.RESET - def +(other: Highlight)(implicit ctx: Context): HighlightBuffer = + def +(other: Highlight)(using Context): HighlightBuffer = new HighlightBuffer(this) + other - def +(other: String)(implicit ctx: Context): HighlightBuffer = + def +(other: String)(using Context): HighlightBuffer = new HighlightBuffer(this) + other } abstract class Modifier(private val mod: String, text: String) extends Highlight(Console.RESET) { - override def show(implicit ctx: Context): String = + override def show(using Context): String = if (ctx.settings.color.value == "never") "" else mod + super.show } - case class HighlightBuffer(hl: Highlight)(implicit ctx: Context) { + case class HighlightBuffer(hl: Highlight)(using Context) { private val buffer = new mutable.ListBuffer[String] buffer += hl.show diff --git a/compiler/src/dotty/tools/dotc/printing/Showable.scala b/compiler/src/dotty/tools/dotc/printing/Showable.scala index 0e60ee526b6e..7b9496f7586f 100644 --- a/compiler/src/dotty/tools/dotc/printing/Showable.scala +++ b/compiler/src/dotty/tools/dotc/printing/Showable.scala @@ -20,7 +20,7 @@ trait Showable extends Any { def fallbackToText(printer: Printer): Text = toString /** The string representation of this showable element. */ - def show(implicit ctx: Context): String = toText(ctx.printer).show + def show(using Context): String = toText(ctx.printer).show /** The string representation with each line after the first one indented * by the given given margin (in spaces). diff --git a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala index 87935b558255..62da8a6a1d0d 100644 --- a/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala +++ b/compiler/src/dotty/tools/dotc/printing/SyntaxHighlighting.scala @@ -29,13 +29,14 @@ object SyntaxHighlighting { val TypeColor: String = Console.MAGENTA val AnnotationColor: String = Console.MAGENTA - def highlight(in: String)(implicit ctx: Context): String = { + def highlight(in: String)(using Context): String = { def freshCtx = ctx.fresh.setReporter(Reporter.NoReporter) if (in.isEmpty || ctx.settings.color.value == "never") in else { val source = SourceFile.virtual("", in) - given Context = freshCtx.setCompilationUnit(CompilationUnit(source, mustExist = false)(freshCtx)) + given Context = freshCtx + .setCompilationUnit(CompilationUnit(source, mustExist = false)(using freshCtx)) val colorAt = Array.fill(in.length)(NoColor) @@ -96,10 +97,10 @@ object SyntaxHighlighting { for (annotation <- tree.rawMods.annotations) highlightPosition(annotation.span, AnnotationColor) - def highlight(trees: List[Tree])(implicit ctx: Context): Unit = + def highlight(trees: List[Tree])(using Context): Unit = trees.foreach(traverse) - def traverse(tree: Tree)(implicit ctx: Context): Unit = { + def traverse(tree: Tree)(using Context): Unit = { tree match { case tree: NameTree if ignored(tree) => () diff --git a/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala b/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala index 72c16580c3d8..a9278430940a 100644 --- a/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala +++ b/compiler/src/dotty/tools/dotc/profile/AsyncHelper.scala @@ -19,12 +19,12 @@ sealed trait AsyncHelper { object AsyncHelper { - def apply(phase: Phase)(implicit ctx: Context): AsyncHelper = ctx.profiler match { + def apply(phase: Phase)(using Context): AsyncHelper = ctx.profiler match { case NoOpProfiler => new BasicAsyncHelper(phase) case r: RealProfiler => new ProfilingAsyncHelper(phase, r) } - private abstract class BaseAsyncHelper(phase: Phase)(implicit ctx: Context) extends AsyncHelper { + private abstract class BaseAsyncHelper(phase: Phase)(using Context) extends AsyncHelper { val baseGroup = new ThreadGroup(s"dotc-${phase.phaseName}") private def childGroup(name: String) = new ThreadGroup(baseGroup, name) @@ -47,7 +47,7 @@ object AsyncHelper { } } - private final class BasicAsyncHelper(phase: Phase)(implicit ctx: Context) extends BaseAsyncHelper(phase) { + private final class BasicAsyncHelper(phase: Phase)(using Context) extends BaseAsyncHelper(phase) { override def newUnboundedQueueFixedThreadPool(nThreads: Int, shortId: String, priority: Int): ThreadPoolExecutor = { val threadFactory = new CommonThreadFactory(shortId, priority = priority) @@ -64,7 +64,7 @@ object AsyncHelper { override protected def wrapRunnable(r: Runnable, shortId:String): Runnable = r } - private class ProfilingAsyncHelper(phase: Phase, private val profiler: RealProfiler)(implicit ctx: Context) extends BaseAsyncHelper(phase) { + private class ProfilingAsyncHelper(phase: Phase, private val profiler: RealProfiler)(using Context) extends BaseAsyncHelper(phase) { override def newUnboundedQueueFixedThreadPool(nThreads: Int, shortId: String, priority: Int): ThreadPoolExecutor = { val threadFactory = new CommonThreadFactory(shortId, priority = priority) diff --git a/compiler/src/dotty/tools/dotc/profile/Profiler.scala b/compiler/src/dotty/tools/dotc/profile/Profiler.scala index ffaba732ee5d..ff99c7646a87 100644 --- a/compiler/src/dotty/tools/dotc/profile/Profiler.scala +++ b/compiler/src/dotty/tools/dotc/profile/Profiler.scala @@ -12,7 +12,7 @@ import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.io.AbstractFile object Profiler { - def apply()(implicit ctx: Context): Profiler = + def apply()(using Context): Profiler = if (!ctx.settings.YprofileEnabled.value) NoOpProfiler else { val reporter = if (ctx.settings.YprofileDestination.value != "") @@ -90,7 +90,7 @@ private [profile] object RealProfiler { private val idGen = new AtomicInteger() } -private [profile] class RealProfiler(reporter : ProfileReporter)(implicit ctx: Context) extends Profiler with NotificationListener { +private [profile] class RealProfiler(reporter : ProfileReporter)(using Context) extends Profiler with NotificationListener { def completeBackground(threadRange: ProfileRange): Unit = reporter.reportBackground(this, threadRange) diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index bace2cfd0c32..44e194759276 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -280,7 +280,7 @@ object messages { else ctx.typer.importSuggestionAddendum(ViewProto(found.widen, expected)) val (where, printCtx) = Formatting.disambiguateTypes(found2, expected2) val whereSuffix = if (where.isEmpty) where else s"\n\n$where" - val (foundStr, expectedStr) = Formatting.typeDiff(found2, expected2)(printCtx) + val (foundStr, expectedStr) = Formatting.typeDiff(found2, expected2)(using printCtx) s"""|Found: $foundStr |Required: $expectedStr""".stripMargin + whereSuffix + err.whyNoMatchStr(found, expected) + postScript diff --git a/compiler/src/dotty/tools/dotc/sbt/APIUtils.scala b/compiler/src/dotty/tools/dotc/sbt/APIUtils.scala index 94077da72fca..d61718799b20 100644 --- a/compiler/src/dotty/tools/dotc/sbt/APIUtils.scala +++ b/compiler/src/dotty/tools/dotc/sbt/APIUtils.scala @@ -37,7 +37,7 @@ object APIUtils { * to be constructed, but if the class is never accessed by Scala source code, * a dummy empty class can be registered instead, using this method. */ - def registerDummyClass(classSym: ClassSymbol)(implicit ctx: Context): Unit = { + def registerDummyClass(classSym: ClassSymbol)(using Context): Unit = { if (ctx.sbtCallback != null) { val classLike = emptyClassLike(classSym) ctx.sbtCallback.api(ctx.compilationUnit.source.file.file, classLike) @@ -45,7 +45,7 @@ object APIUtils { } // See APIUtils.emptyClassLike - private def emptyClassLike(classSym: ClassSymbol)(implicit ctx: Context): api.ClassLike = { + private def emptyClassLike(classSym: ClassSymbol)(using Context): api.ClassLike = { val name = classSym.fullName.stripModuleClassSuffix.toString val definitionType = if (classSym.is(Trait)) api.DefinitionType.Trait diff --git a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala index af219681d942..9e7debc26e40 100644 --- a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala +++ b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala @@ -177,7 +177,7 @@ object ParsedComment { */ private def toCodeFence(language: String)(ctx: Context, snippet: String): String = if (colorEnabled(ctx)) - SyntaxHighlighting.highlight(snippet)(ctx) + SyntaxHighlighting.highlight(snippet)(using ctx) else s"""```$language |$snippet diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index e7ff1526ea89..cd924b1867e0 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -179,7 +179,7 @@ class ReplDriver(settings: Array[String], .typeCheck(expr, errorsAllowed = true) .map { tree => val file = SourceFile.virtual("", expr, maybeIncomplete = true) - val unit = CompilationUnit(file)(state.context) + val unit = CompilationUnit(file)(using state.context) unit.tpdTree = tree given Context = state.context.fresh.setCompilationUnit(unit) val srcPos = SourcePosition(file, Span(cursor)) @@ -360,7 +360,7 @@ class ReplDriver(settings: Array[String], for { objectIndex <- 1 to state.objectIndex imp <- state.imports.getOrElse(objectIndex, Nil) - } out.println(imp.show(state.context)) + } out.println(imp.show(using state.context)) state case Load(path) => @@ -377,7 +377,7 @@ class ReplDriver(settings: Array[String], case TypeOf(expr) => compiler.typeOf(expr)(newRun(state)).fold( displayErrors, - res => out.println(SyntaxHighlighting.highlight(res)(state.context)) + res => out.println(SyntaxHighlighting.highlight(res)(using state.context)) ) state From 68e1fea41b5e229f19bd8744294194df8a913056 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Thu, 9 Jul 2020 17:59:54 +0200 Subject: [PATCH 26/41] Convert other dotc classes (2) --- .../src/dotty/tools/dotc/sbt/ExtractAPI.scala | 6 +-- .../tools/dotc/sbt/ExtractDependencies.scala | 32 +++++++------- .../dotc/semanticdb/ExtractSemanticDB.scala | 4 +- .../tools/dotc/tastyreflect/FromSymbol.scala | 16 +++---- .../dotc/tastyreflect/MacroExpansion.scala | 4 +- .../tools/dotc/tastyreflect/package.scala | 2 +- .../dotty/tools/dotc/typer/ConstFold.scala | 6 +-- .../src/dotty/tools/dotc/typer/Deriving.scala | 9 ++-- .../dotty/tools/dotc/typer/Docstrings.scala | 2 +- .../dotty/tools/dotc/typer/Inferencing.scala | 6 +-- .../src/dotty/tools/dotc/typer/Inliner.scala | 2 +- .../src/dotty/tools/dotc/typer/Namer.scala | 44 +++++++++---------- .../dotty/tools/dotc/typer/RefChecks.scala | 8 ++-- .../src/dotty/tools/dotc/typer/Typer.scala | 4 +- .../dotty/tools/dotc/util/ParsedComment.scala | 14 +++--- .../dotty/tools/dotc/util/Signatures.scala | 8 ++-- .../dotty/tools/dotc/util/SourceFile.scala | 2 +- .../src/dotty/tools/dotc/util/Stats.scala | 2 +- 18 files changed, 86 insertions(+), 85 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala index 2c90fdb5ef0d..544df262407e 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala @@ -41,7 +41,7 @@ import scala.collection.mutable class ExtractAPI extends Phase { override def phaseName: String = "sbt-api" - override def isRunnable(implicit ctx: Context): Boolean = { + override def isRunnable(using Context): Boolean = { def forceRun = ctx.settings.YdumpSbtInc.value || ctx.settings.YforceSbtPhases.value super.isRunnable && (ctx.sbtCallback != null || forceRun) } @@ -56,7 +56,7 @@ class ExtractAPI extends Phase { // definitions, and `PostTyper` does not change definitions). override def runsAfter: Set[String] = Set(transform.PostTyper.name) - override def run(implicit ctx: Context): Unit = { + override def run(using Context): Unit = { val unit = ctx.compilationUnit val sourceFile = unit.source.file if (ctx.sbtCallback != null) @@ -124,7 +124,7 @@ class ExtractAPI extends Phase { * without going through an intermediate representation, see * http://www.scala-sbt.org/0.13/docs/Understanding-Recompilation.html#Hashing+an+API+representation */ -private class ExtractAPICollector(implicit ctx: Context) extends ThunkHolder { +private class ExtractAPICollector(using Context) extends ThunkHolder { import tpd._ import xsbti.api diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala index afc077753b47..9044a7e9f71a 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala @@ -49,7 +49,7 @@ class ExtractDependencies extends Phase { override def phaseName: String = "sbt-deps" - override def isRunnable(implicit ctx: Context): Boolean = { + override def isRunnable(using Context): Boolean = { def forceRun = ctx.settings.YdumpSbtInc.value || ctx.settings.YforceSbtPhases.value super.isRunnable && (ctx.sbtCallback != null || forceRun) } @@ -62,7 +62,7 @@ class ExtractDependencies extends Phase { // See the scripted test `constants` for an example where this matters. // TODO: Add a `Phase#runsBefore` method ? - override def run(implicit ctx: Context): Unit = { + override def run(using Context): Unit = { val unit = ctx.compilationUnit val collector = new ExtractDependenciesCollector collector.traverse(unit.tpdTree) @@ -105,7 +105,7 @@ class ExtractDependencies extends Phase { * that is coming from either source code (not necessarily compiled in this compilation * run) or from class file and calls respective callback method. */ - def recordDependency(dep: ClassDependency)(implicit ctx: Context): Unit = { + def recordDependency(dep: ClassDependency)(using Context): Unit = { val fromClassName = classNameAsString(dep.from) val sourceFile = ctx.compilationUnit.source.file.file @@ -161,7 +161,7 @@ class ExtractDependencies extends Phase { } object ExtractDependencies { - def classNameAsString(sym: Symbol)(implicit ctx: Context): String = + def classNameAsString(sym: Symbol)(using Context): String = sym.fullName.stripModuleClassSuffix.toString } @@ -217,10 +217,10 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT * class/trait/object declared in the compilation unit. If none exists, issue warning. */ private var _responsibleForImports: Symbol = _ - private def responsibleForImports(implicit ctx: Context) = { + private def responsibleForImports(using Context) = { def firstClassOrModule(tree: Tree) = { val acc = new TreeAccumulator[Symbol] { - def apply(x: Symbol, t: Tree)(implicit ctx: Context) = + def apply(x: Symbol, t: Tree)(using Context) = t match { case typeDef: TypeDef => typeDef.symbol @@ -250,7 +250,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT * Resolves dependency source (that is, the closest non-local enclosing * class from a given `ctx.owner` */ - private def resolveDependencySource(implicit ctx: Context): Symbol = { + private def resolveDependencySource(using Context): Symbol = { def nonLocalEnclosingClass = { var clazz = ctx.owner.enclosingClass var owner = clazz @@ -280,7 +280,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT usedName.update(name, scope) } - private def addUsedName(name: Name, scope: UseScope)(implicit ctx: Context): Unit = { + private def addUsedName(name: Name, scope: UseScope)(using Context): Unit = { val fromClass = resolveDependencySource if (fromClass.exists) { // can happen when visiting imports assert(fromClass.isClass) @@ -289,14 +289,14 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT } /** Mangle a JVM symbol name in a format better suited for internal uses by sbt. */ - private def mangledName(sym: Symbol)(implicit ctx: Context): Name = { + private def mangledName(sym: Symbol)(using Context): Name = { def constructorName = sym.owner.fullName ++ ";init;" if (sym.isConstructor) constructorName else sym.name.stripModuleClassSuffix } - private def addMemberRefDependency(sym: Symbol)(implicit ctx: Context): Unit = + private def addMemberRefDependency(sym: Symbol)(using Context): Unit = if (!ignoreDependency(sym)) { val enclOrModuleClass = if (sym.is(ModuleVal)) sym.moduleClass else sym.enclosingClass assert(enclOrModuleClass.isClass, s"$enclOrModuleClass, $sym") @@ -313,7 +313,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT } } - private def addInheritanceDependencies(tree: Template)(implicit ctx: Context): Unit = + private def addInheritanceDependencies(tree: Template)(using Context): Unit = if (tree.parents.nonEmpty) { val depContext = if (tree.symbol.owner.isLocal) LocalDependencyByInheritance @@ -324,7 +324,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT } } - private def ignoreDependency(sym: Symbol)(implicit ctx: Context) = + private def ignoreDependency(sym: Symbol)(using Context) = !sym.exists || sym.isAbsent(canForce = false) || // ignore dependencies that have a symbol but do not exist. // e.g. java.lang.Object companion object @@ -335,7 +335,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT /** Traverse the tree of a source file and record the dependencies and used names which * can be retrieved using `dependencies` and`usedNames`. */ - override def traverse(tree: Tree)(implicit ctx: Context): Unit = try { + override def traverse(tree: Tree)(using Context): Unit = try { tree match { case Match(selector, _) => addPatMatDependency(selector.tpe) @@ -415,7 +415,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT * The tests in sbt `types-in-used-names-a`, `types-in-used-names-b`, * `as-seen-from-a` and `as-seen-from-b` rely on this. */ - private abstract class TypeDependencyTraverser(implicit ctx: Context) extends TypeTraverser()(using ctx) { + private abstract class TypeDependencyTraverser(using Context) extends TypeTraverser()(using ctx) { protected def addDependency(symbol: Symbol): Unit val seen = new mutable.HashSet[Type] @@ -442,14 +442,14 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT } } - def addTypeDependency(tpe: Type)(implicit ctx: Context): Unit = { + def addTypeDependency(tpe: Type)(using Context): Unit = { val traverser = new TypeDependencyTraverser { def addDependency(symbol: Symbol) = addMemberRefDependency(symbol) } traverser.traverse(tpe) } - def addPatMatDependency(tpe: Type)(implicit ctx: Context): Unit = { + def addPatMatDependency(tpe: Type)(using Context): Unit = { val traverser = new TypeDependencyTraverser { def addDependency(symbol: Symbol) = if (!ignoreDependency(symbol) && symbol.is(Sealed)) { diff --git a/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala b/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala index 7f69903b8db2..79bd6a661bb9 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala @@ -35,13 +35,13 @@ class ExtractSemanticDB extends Phase: override val phaseName: String = ExtractSemanticDB.name - override def isRunnable(implicit ctx: Context) = + override def isRunnable(using Context) = super.isRunnable && ctx.settings.Ysemanticdb.value // Check not needed since it does not transform trees override def isCheckable: Boolean = false - override def run(implicit ctx: Context): Unit = + override def run(using Context): Unit = val unit = ctx.compilationUnit val extract = Extractor() extract.traverse(unit.tpdTree) diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala b/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala index 5132b3fa1743..248b35c309aa 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/FromSymbol.scala @@ -10,7 +10,7 @@ import dotty.tools.dotc.core.Types._ object FromSymbol { - def definitionFromSym(sym: Symbol)(implicit ctx: Context): tpd.Tree = { + def definitionFromSym(sym: Symbol)(using Context): tpd.Tree = { assert(sym.exists) if (sym.is(Package)) packageDefFromSym(sym) else if (sym.isClass) classDef(sym.asClass) @@ -21,9 +21,9 @@ object FromSymbol { else valDefFromSym(sym.asTerm) } - def packageDefFromSym(sym: Symbol)(implicit ctx: Context): PackageDefinition = PackageDefinitionImpl(sym) + def packageDefFromSym(sym: Symbol)(using Context): PackageDefinition = PackageDefinitionImpl(sym) - def classDef(cls: ClassSymbol)(implicit ctx: Context): tpd.TypeDef = cls.defTree match { + def classDef(cls: ClassSymbol)(using Context): tpd.TypeDef = cls.defTree match { case tree: tpd.TypeDef => tree case tpd.EmptyTree => val constrSym = cls.unforcedDecls.find(_.isPrimaryConstructor).orElse( @@ -36,27 +36,27 @@ object FromSymbol { tpd.ClassDefWithParents(cls, constr, parents, body) } - def typeDefFromSym(sym: TypeSymbol)(implicit ctx: Context): tpd.TypeDef = sym.defTree match { + def typeDefFromSym(sym: TypeSymbol)(using Context): tpd.TypeDef = sym.defTree match { case tree: tpd.TypeDef => tree case tpd.EmptyTree => tpd.TypeDef(sym) } - def defDefFromSym(sym: TermSymbol)(implicit ctx: Context): tpd.DefDef = sym.defTree match { + def defDefFromSym(sym: TermSymbol)(using Context): tpd.DefDef = sym.defTree match { case tree: tpd.DefDef => tree case tpd.EmptyTree => tpd.DefDef(sym) } - def valDefFromSym(sym: TermSymbol)(implicit ctx: Context): tpd.ValDef = sym.defTree match { + def valDefFromSym(sym: TermSymbol)(using Context): tpd.ValDef = sym.defTree match { case tree: tpd.ValDef => tree case tpd.EmptyTree => tpd.ValDef(sym) } - def bindFromSym(sym: TermSymbol)(implicit ctx: Context): tpd.Bind = sym.defTree match { + def bindFromSym(sym: TermSymbol)(using Context): tpd.Bind = sym.defTree match { case tree: tpd.Bind => tree case tpd.EmptyTree => tpd.Bind(sym, untpd.Ident(nme.WILDCARD).withType(sym.typeRef)) } - def typeBindFromSym(sym: TypeSymbol)(implicit ctx: Context): tpd.Bind = sym.defTree match { + def typeBindFromSym(sym: TypeSymbol)(using Context): tpd.Bind = sym.defTree match { case tree: tpd.Bind => tree case tpd.EmptyTree => tpd.Bind(sym, untpd.Ident(nme.WILDCARD).withType(sym.typeRef)) } diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/MacroExpansion.scala b/compiler/src/dotty/tools/dotc/tastyreflect/MacroExpansion.scala index a44cb3d522aa..7bc925a03146 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/MacroExpansion.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/MacroExpansion.scala @@ -10,10 +10,10 @@ object MacroExpansion { private val MacroExpansionPosition = new Property.Key[SourcePosition] - def position(implicit ctx: Context): Option[SourcePosition] = + def position(using Context): Option[SourcePosition] = ctx.property(MacroExpansionPosition) - def context(inlinedFrom: tpd.Tree)(implicit ctx: Context): Context = + def context(inlinedFrom: tpd.Tree)(using Context): Context = ctx.fresh.setProperty(MacroExpansionPosition, SourcePosition(inlinedFrom.source, inlinedFrom.span)).setTypeAssigner(new Typer).withSource(inlinedFrom.source) } diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/package.scala b/compiler/src/dotty/tools/dotc/tastyreflect/package.scala index 2ad86a9fa984..3db7a3e6b680 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/package.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/package.scala @@ -16,7 +16,7 @@ package object tastyreflect { case class PackageDefinitionImpl[-T >: Untyped] private[tastyreflect] (sym: Symbol)(implicit @constructorOnly src: SourceFile) extends Tree[T] { type ThisTree[-T >: Untyped] = PackageDefinitionImpl[T] - override def denot(implicit ctx: Context): SymDenotation = sym.denot + override def denot(using Context): SymDenotation = sym.denot } } diff --git a/compiler/src/dotty/tools/dotc/typer/ConstFold.scala b/compiler/src/dotty/tools/dotc/typer/ConstFold.scala index eb9a548488e3..804a062c9801 100644 --- a/compiler/src/dotty/tools/dotc/typer/ConstFold.scala +++ b/compiler/src/dotty/tools/dotc/typer/ConstFold.scala @@ -19,7 +19,7 @@ object ConstFold { import tpd._ /** If tree is a constant operation, replace with result. */ - def apply[T <: Tree](tree: T)(implicit ctx: Context): T = finish(tree) { + def apply[T <: Tree](tree: T)(using Context): T = finish(tree) { tree match { case Apply(Select(xt, op), yt :: Nil) => xt.tpe.widenTermRefExpr.normalized match @@ -45,7 +45,7 @@ object ConstFold { /** If tree is a constant value that can be converted to type `pt`, perform * the conversion. */ - def apply[T <: Tree](tree: T, pt: Type)(implicit ctx: Context): T = + def apply[T <: Tree](tree: T, pt: Type)(using Context): T = finish(apply(tree)) { tree.tpe.widenTermRefExpr.normalized match { case ConstantType(x) => x convertTo pt @@ -53,7 +53,7 @@ object ConstFold { } } - inline private def finish[T <: Tree](tree: T)(compX: => Constant)(implicit ctx: Context): T = + inline private def finish[T <: Tree](tree: T)(compX: => Constant)(using Context): T = try { val x = compX if (x ne null) tree.withType(ConstantType(x)).asInstanceOf[T] diff --git a/compiler/src/dotty/tools/dotc/typer/Deriving.scala b/compiler/src/dotty/tools/dotc/typer/Deriving.scala index 42099edbdb1d..cbe7f980815a 100644 --- a/compiler/src/dotty/tools/dotc/typer/Deriving.scala +++ b/compiler/src/dotty/tools/dotc/typer/Deriving.scala @@ -28,7 +28,7 @@ trait Deriving { * synthesized infrastructure code that is not connected with a * `derives` instance. */ - class Deriver(cls: ClassSymbol, codePos: SourcePosition)(implicit ctx: Context) { + class Deriver(cls: ClassSymbol, codePos: SourcePosition)(using Context) { /** A buffer for synthesized symbols for type class instances */ private var synthetics = new mutable.ListBuffer[Symbol] @@ -268,7 +268,7 @@ trait Deriving { import tpd._ /** The type class instance definition with symbol `sym` */ - def typeclassInstance(sym: Symbol)(implicit ctx: Context): List[Type] => (List[List[tpd.Tree]] => tpd.Tree) = { + def typeclassInstance(sym: Symbol)(using Context): List[Type] => (List[List[tpd.Tree]] => tpd.Tree) = { (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) @@ -291,8 +291,9 @@ trait Deriving { typed(rhs, resultType) } - def syntheticDef(sym: Symbol): Tree = - tpd.polyDefDef(sym.asTerm, typeclassInstance(sym)(ctx.fresh.setOwner(sym).setNewScope)) + def syntheticDef(sym: Symbol): Tree = inContext(ctx.fresh.setOwner(sym).setNewScope) { + tpd.polyDefDef(sym.asTerm, typeclassInstance(sym)) + } synthetics.map(syntheticDef).toList } diff --git a/compiler/src/dotty/tools/dotc/typer/Docstrings.scala b/compiler/src/dotty/tools/dotc/typer/Docstrings.scala index f25931022dd6..8b69a1a357ca 100644 --- a/compiler/src/dotty/tools/dotc/typer/Docstrings.scala +++ b/compiler/src/dotty/tools/dotc/typer/Docstrings.scala @@ -56,7 +56,7 @@ object Docstrings { newComment } - private def expandComment(sym: Symbol)(implicit ctx: Context, docCtx: ContextDocstrings): Option[Comment] = + private def expandComment(sym: Symbol)(using Context)(using docCtx: ContextDocstrings): Option[Comment] = if (sym eq NoSymbol) None else for { diff --git a/compiler/src/dotty/tools/dotc/typer/Inferencing.scala b/compiler/src/dotty/tools/dotc/typer/Inferencing.scala index 401d44d40480..d21d61bb427c 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inferencing.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inferencing.scala @@ -164,7 +164,7 @@ object Inferencing { ) } - def approximateGADT(tp: Type)(implicit ctx: Context): Type = { + def approximateGADT(tp: Type)(using Context): Type = { val map = new ApproximateGadtAccumulator val res = map(tp) assert(!map.failed) @@ -174,7 +174,7 @@ object Inferencing { /** This class is mostly based on IsFullyDefinedAccumulator. * It tries to approximate the given type based on the available GADT constraints. */ - private class ApproximateGadtAccumulator(implicit ctx: Context) extends TypeMap { + private class ApproximateGadtAccumulator(using Context) extends TypeMap { var failed = false @@ -184,7 +184,7 @@ object Inferencing { inst } - private def instDirection2(sym: Symbol)(implicit ctx: Context): Int = { + private def instDirection2(sym: Symbol)(using Context): Int = { val constrained = ctx.gadt.fullBounds(sym) val original = sym.info.bounds val cmp = ctx.typeComparer diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index 2f0be5d202b3..77d652c7d663 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -502,7 +502,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { * of a containing object so they are merely idempotent. */ object isElideableExpr { - def isStatElideable(tree: Tree)(implicit ctx: Context): Boolean = unsplice(tree) match { + def isStatElideable(tree: Tree)(using Context): Boolean = unsplice(tree) match { case EmptyTree | TypeDef(_, _) | Import(_, _) diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index 3802209dca9a..45029a954c90 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -818,11 +818,11 @@ class Namer { typer: Typer => protected def typeSig(sym: Symbol): Type = original match { case original: ValDef => if (sym.is(Module)) moduleValSig(sym) - else valOrDefDefSig(original, sym, Nil, Nil, identity)(localContext(sym).setNewScope) + else valOrDefDefSig(original, sym, Nil, Nil, identity)(using localContext(sym).setNewScope) case original: DefDef => val typer1 = ctx.typer.newLikeThis nestedTyper(sym) = typer1 - typer1.defDefSig(original, sym)(localContext(sym).setTyper(typer1)) + typer1.defDefSig(original, sym)(using localContext(sym).setTyper(typer1)) case imp: Import => try { val expr1 = typedAheadExpr(imp.expr, AnySelectionProto) @@ -863,7 +863,7 @@ class Namer { typer: Typer => case original: untpd.MemberDef => lazy val annotCtx = annotContext(original, sym) for (annotTree <- original.mods.annotations) { - val cls = typedAheadAnnotationClass(annotTree)(annotCtx) + val cls = typedAheadAnnotationClass(annotTree)(using annotCtx) if (cls eq sym) ctx.error("An annotation class cannot be annotated with iself", annotTree.sourcePos) else { @@ -908,7 +908,7 @@ class Namer { typer: Typer => /** If completed symbol is an enum value or a named class, register it as a child * in all direct parent classes which are sealed. */ - def registerIfChild(denot: SymDenotation)(implicit ctx: Context): Unit = { + def registerIfChild(denot: SymDenotation)(using Context): Unit = { val sym = denot.symbol def register(child: Symbol, parentCls: ClassSymbol) = { @@ -952,7 +952,7 @@ class Namer { typer: Typer => private var nestedCtx: Context = null assert(!original.isClassDef) - override def completerTypeParams(sym: Symbol)(implicit ctx: Context): List[TypeSymbol] = + override def completerTypeParams(sym: Symbol)(using Context): List[TypeSymbol] = if myTypeParams == null then //println(i"completing type params of $sym in ${sym.owner}") nestedCtx = localContext(sym).setNewScope @@ -975,7 +975,7 @@ class Namer { typer: Typer => end completerTypeParams override final def typeSig(sym: Symbol): Type = - val tparamSyms = completerTypeParams(sym)(ictx) + val tparamSyms = completerTypeParams(sym)(using ictx) given ctx as Context = nestedCtx def abstracted(tp: TypeBounds): TypeBounds = @@ -1075,7 +1075,7 @@ class Namer { typer: Typer => def init(): Context = index(params) /** Add forwarders as required by the export statements in this class */ - private def processExports(implicit ctx: Context): Unit = { + private def processExports(using Context): Unit = { /** A string indicating that no forwarders for this kind of symbol are emitted */ val SKIP = "(skip)" @@ -1246,7 +1246,7 @@ class Namer { typer: Typer => /* The type of a parent constructor. Types constructor arguments * only if parent type contains uninstantiated type parameters. */ - def parentType(parent: untpd.Tree)(implicit ctx: Context): Type = + def parentType(parent: untpd.Tree)(using Context): Type = if (parent.isType) typedAheadType(parent, AnyTypeConstructorProto).tpe else { @@ -1276,7 +1276,7 @@ class Namer { typer: Typer => * (4) If the class is sealed, it is defined in the same compilation unit as the current class */ def checkedParentType(parent: untpd.Tree): Type = { - val ptype = parentType(parent)(completerCtx.superCallContext).dealiasKeepAnnots + val ptype = parentType(parent)(using completerCtx.superCallContext).dealiasKeepAnnots if (cls.isRefinementClass) ptype else { val pt = checkClassType(ptype, parent.sourcePos, @@ -1319,7 +1319,7 @@ class Namer { typer: Typer => case Some(pos) => (cls.companionClass.orElse(cls).asClass, pos) case None => (cls, impl.sourcePos.startPos) } - val deriver = new Deriver(derivingClass, derivePos)(localCtx) + val deriver = new Deriver(derivingClass, derivePos)(using localCtx) deriver.enterDerived(impl.derived) original.putAttachment(Deriver, deriver) } @@ -1333,19 +1333,19 @@ class Namer { typer: Typer => cls.baseClasses.foreach(_.invalidateBaseTypeCache()) // we might have looked before and found nothing cls.setNoInitsFlags(parentsKind(parents), untpd.bodyKind(rest)) if (cls.isNoInitsClass) cls.primaryConstructor.setFlag(StableRealizable) - processExports(localCtx) + processExports(using localCtx) } } class SuspendCompleter extends LazyType, SymbolLoaders.SecondCompleter { - final override def complete(denot: SymDenotation)(implicit ctx: Context): Unit = + final override def complete(denot: SymDenotation)(using Context): Unit = denot.resetFlag(Touched) // allow one more completion ctx.compilationUnit.suspend() } /** Typecheck `tree` during completion using `typed`, and remember result in TypedAhead map */ - def typedAhead(tree: Tree, typed: untpd.Tree => tpd.Tree)(implicit ctx: Context): tpd.Tree = { + def typedAhead(tree: Tree, typed: untpd.Tree => tpd.Tree)(using Context): tpd.Tree = { val xtree = expanded(tree) xtree.getAttachment(TypedAhead) match { case Some(ttree) => ttree @@ -1356,16 +1356,16 @@ class Namer { typer: Typer => } } - def typedAheadType(tree: Tree, pt: Type = WildcardType)(implicit ctx: Context): tpd.Tree = + def typedAheadType(tree: Tree, pt: Type = WildcardType)(using Context): tpd.Tree = typedAhead(tree, typer.typed(_, pt)(using ctx.retractMode(Mode.PatternOrTypeBits).addMode(Mode.Type))) - def typedAheadExpr(tree: Tree, pt: Type = WildcardType)(implicit ctx: Context): tpd.Tree = + def typedAheadExpr(tree: Tree, pt: Type = WildcardType)(using Context): tpd.Tree = typedAhead(tree, typer.typed(_, pt)(using ctx.retractMode(Mode.PatternOrTypeBits))) - def typedAheadAnnotation(tree: Tree)(implicit ctx: Context): tpd.Tree = + def typedAheadAnnotation(tree: Tree)(using Context): tpd.Tree = typedAheadExpr(tree, defn.AnnotationClass.typeRef) - def typedAheadAnnotationClass(tree: Tree)(implicit ctx: Context): Symbol = tree match { + def typedAheadAnnotationClass(tree: Tree)(using Context): Symbol = tree match { case Apply(fn, _) => typedAheadAnnotationClass(fn) case TypeApply(fn, _) => typedAheadAnnotationClass(fn) case Select(qual, nme.CONSTRUCTOR) => typedAheadAnnotationClass(qual) @@ -1373,7 +1373,7 @@ class Namer { typer: Typer => } /** Enter and typecheck parameter list */ - def completeParams(params: List[MemberDef])(implicit ctx: Context): Unit = { + def completeParams(params: List[MemberDef])(using Context): Unit = { index(params) for (param <- params) typedAheadExpr(param) } @@ -1383,7 +1383,7 @@ class Namer { typer: Typer => * without going through the defined type of the ValDef. This is necessary * to avoid cyclic references involving imports and module val defs. */ - def moduleValSig(sym: Symbol)(implicit ctx: Context): Type = { + 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) @@ -1396,7 +1396,7 @@ class Namer { typer: Typer => * @param paramFn A wrapping function that produces the type of the * defined symbol, given its final return type */ - def valOrDefDefSig(mdef: ValOrDefDef, sym: Symbol, typeParams: List[Symbol], paramss: List[List[Symbol]], paramFn: Type => Type)(implicit ctx: Context): Type = { + def valOrDefDefSig(mdef: ValOrDefDef, sym: Symbol, typeParams: List[Symbol], paramss: List[List[Symbol]], paramFn: Type => Type)(using Context): Type = { def inferredType = { /** A type for this definition that might be inherited from elsewhere: @@ -1492,7 +1492,7 @@ class Namer { typer: Typer => rhsCtx.setFreshGADTBounds rhsCtx.gadt.addToConstraint(typeParams) } - def rhsType = typedAheadExpr(mdef.rhs, (inherited orElse rhsProto).widenExpr)(rhsCtx).tpe + def rhsType = typedAheadExpr(mdef.rhs, (inherited orElse rhsProto).widenExpr)(using rhsCtx).tpe // Approximate a type `tp` with a type that does not contain skolem types. val deskolemize = new ApproximatingTypeMap { @@ -1563,7 +1563,7 @@ class Namer { typer: Typer => } /** The type signature of a DefDef with given symbol */ - def defDefSig(ddef: DefDef, sym: Symbol)(implicit ctx: Context): Type = { + def defDefSig(ddef: DefDef, sym: Symbol)(using Context): Type = { // Beware: ddef.name need not match sym.name if sym was freshened! val DefDef(_, tparams, vparamss, _, _) = ddef val isConstructor = sym.name == nme.CONSTRUCTOR diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index 5a834820c0fc..549268fab3b9 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -1257,7 +1257,7 @@ class RefChecks extends MiniPhase { thisPhase => } ) } - private def checkTypeRef(tp: Type, tree: Tree, skipBounds: Boolean)(implicit ctx: Context) = tp match { + private def checkTypeRef(tp: Type, tree: Tree, skipBounds: Boolean)(using Context) = tp match { case TypeRef(pre, sym, args) => tree match { case tt: TypeTree if tt.original == null => // SI-7783 don't warn about inferred types @@ -1292,7 +1292,7 @@ class RefChecks extends MiniPhase { thisPhase => } private def doTypeTraversal(tree: Tree)(f: Type => Unit) = if (!inPattern) tree.tpe foreach f - private def applyRefchecksToAnnotations(tree: Tree)(implicit ctx: Context): Unit = { + private def applyRefchecksToAnnotations(tree: Tree)(using Context): Unit = { def applyChecks(annots: List[Annotation]) = { checkAnnotations(annots map (_.atp), tree) transformTrees(annots flatMap (_.args)) @@ -1434,7 +1434,7 @@ class RefChecks extends MiniPhase { thisPhase => } /* Convert a reference to a case factory of type `tpe` to a new of the class it produces. */ - def toConstructor(pos: Position, tpe: Type)(implicit ctx: Context): Tree = { + def toConstructor(pos: Position, tpe: Type)(using Context): Tree = { val rtpe = tpe.finalResultType assert(rtpe.typeSymbol.is(Case), tpe) New(rtpe).withPos(pos).select(rtpe.typeSymbol.primaryConstructor) @@ -1532,7 +1532,7 @@ class RefChecks extends MiniPhase { thisPhase => case _ => } } - override def transform(tree: Tree)(implicit ctx: Context): Tree = { + override def transform(tree: Tree)(using Context): Tree = { //val savedLocalTyper = localTyper try { val sym = tree.symbol diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index b6eed1ca47a1..436ea76c912d 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -165,7 +165,7 @@ class Typer extends Namer * previous and new contexts do not have the same scope, we select * the previous (inner) definition. This models what scalac does. */ - def checkNewOrShadowed(found: Type, newPrec: BindingPrec, scala2pkg: Boolean = false)(implicit ctx: Context): Type = + def checkNewOrShadowed(found: Type, newPrec: BindingPrec, scala2pkg: Boolean = false)(using Context): Type = if !previous.exists || ctx.typeComparer.isSameRef(previous, found) then found else if (prevCtx.scope eq ctx.scope) @@ -1402,7 +1402,7 @@ class Typer extends Namer * typing of a match), instantiate that type lambda with the pattern * variables found in the pattern `pat`. */ - def instantiateMatchTypeProto(pat: Tree, pt: Type)(implicit ctx: Context) = pt match { + def instantiateMatchTypeProto(pat: Tree, pt: Type)(using Context) = pt match { case caseTp: HKTypeLambda => val bindingsSyms = tpd.patVars(pat).reverse val bindingsTps = bindingsSyms.collect { case sym if sym.isType => sym.typeRef } diff --git a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala index 9e7debc26e40..5609e0009a6c 100644 --- a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala +++ b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala @@ -52,7 +52,7 @@ class ParsedComment(val comment: Comment) { * * The different sections are formatted according to the mapping in `knownTags`. */ - def renderAsMarkdown(implicit ctx: Context): String = { + def renderAsMarkdown(using Context): String = { val buf = new StringBuilder buf.append(mainDoc + System.lineSeparator + System.lineSeparator) val groupedSections = CommentParsing.groupedSections(content, tagIndex) @@ -100,7 +100,7 @@ object ParsedComment { * @param symbol The symbol for which to retrieve the documentation * @return If it exists, the `ParsedComment` for `symbol`. */ - def docOf(symbol: Symbol)(implicit ctx: Context): Option[ParsedComment] = { + def docOf(symbol: Symbol)(using Context): Option[ParsedComment] = { val documentedSymbol = if (symbol.isPrimaryConstructor) symbol.owner else symbol for { docCtx <- ctx.docCtx @@ -138,7 +138,7 @@ object ParsedComment { private def toDescriptionList(ctx: Context, items: List[String]): String = { val formattedItems = items.map { p => val name :: rest = p.split(" ", 2).toList - s"${bold(name)(ctx)} ${rest.mkString("").trim}" + s"${bold(name)(using ctx)} ${rest.mkString("").trim}" } toMarkdownList(ctx, formattedItems) } @@ -176,7 +176,7 @@ object ParsedComment { * @return `snippet`, wrapped in a code fence. */ private def toCodeFence(language: String)(ctx: Context, snippet: String): String = - if (colorEnabled(ctx)) + if (colorEnabled(using ctx)) SyntaxHighlighting.highlight(snippet)(using ctx) else s"""```$language @@ -198,7 +198,7 @@ object ParsedComment { * @param items The items to format * @return If items is not empty, the items formatted using `fn`. */ - def apply(items: List[String])(implicit ctx: Context): Option[String] = items match { + def apply(items: List[String])(using Context): Option[String] = items match { case Nil => None case items => @@ -209,11 +209,11 @@ object ParsedComment { } /** Is the color enabled in the context? */ - private def colorEnabled(implicit ctx: Context): Boolean = + private def colorEnabled(using Context): Boolean = ctx.settings.color.value != "never" /** Show `str` in bold */ - private def bold(str: String)(implicit ctx: Context): String = + private def bold(str: String)(using Context): String = if (colorEnabled) s"$BOLD$str$RESET" else s"**$str**" } diff --git a/compiler/src/dotty/tools/dotc/util/Signatures.scala b/compiler/src/dotty/tools/dotc/util/Signatures.scala index db43c134f666..5365aa652634 100644 --- a/compiler/src/dotty/tools/dotc/util/Signatures.scala +++ b/compiler/src/dotty/tools/dotc/util/Signatures.scala @@ -48,7 +48,7 @@ object Signatures { * @return A triple containing the index of the parameter being edited, the index of the function * being called, the list of overloads of this function). */ - def callInfo(path: List[tpd.Tree], span: Span)(implicit ctx: Context): (Int, Int, List[SingleDenotation]) = + def callInfo(path: List[tpd.Tree], span: Span)(using Context): (Int, Int, List[SingleDenotation]) = path match { case Apply(fun, params) :: _ => val alreadyAppliedCount = Signatures.countParams(fun) @@ -75,12 +75,12 @@ object Signatures { (0, 0, Nil) } - def toSignature(denot: SingleDenotation)(implicit ctx: Context): Option[Signature] = { + def toSignature(denot: SingleDenotation)(using Context): Option[Signature] = { val symbol = denot.symbol val docComment = ParsedComment.docOf(symbol) val classTree = symbol.topLevelClass.asClass.rootTree - def toParamss(tp: MethodType)(implicit ctx: Context): List[List[Param]] = { + def toParamss(tp: MethodType)(using Context): List[List[Param]] = { val rest = tp.resType match { case res: MethodType => // Hide parameter lists consisting only of DummyImplicit, @@ -160,7 +160,7 @@ object Signatures { * @return A pair composed of the index of the best alternative (0 if no alternatives * were found), and the list of alternatives. */ - private def alternativesFromError(err: ErrorType, params: List[tpd.Tree])(implicit ctx: Context): (Int, List[SingleDenotation]) = { + 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 diff --git a/compiler/src/dotty/tools/dotc/util/SourceFile.scala b/compiler/src/dotty/tools/dotc/util/SourceFile.scala index ceab3ac42b96..3ad9bf07fb17 100644 --- a/compiler/src/dotty/tools/dotc/util/SourceFile.scala +++ b/compiler/src/dotty/tools/dotc/util/SourceFile.scala @@ -207,7 +207,7 @@ class SourceFile(val file: AbstractFile, computeContent: => Array[Char]) extends object SourceFile { implicit def eqSource: Eql[SourceFile, SourceFile] = Eql.derived - implicit def fromContext(implicit ctx: Context): SourceFile = ctx.source + implicit def fromContext(using Context): SourceFile = ctx.source def fromId(id: Int): SourceFile = sourceOfChunk(id >> ChunkSizeLog) diff --git a/compiler/src/dotty/tools/dotc/util/Stats.scala b/compiler/src/dotty/tools/dotc/util/Stats.scala index 943dad7decda..7967b41ddb18 100644 --- a/compiler/src/dotty/tools/dotc/util/Stats.scala +++ b/compiler/src/dotty/tools/dotc/util/Stats.scala @@ -50,7 +50,7 @@ import collection.mutable hits(s"Total $prefix") += hits(name) } - def maybeMonitored[T](op: => T)(implicit ctx: Context): T = + def maybeMonitored[T](op: => T)(using Context): T = if (ctx.settings.YdetailedStats.value) { monitored = true try op From 4dc0b9b8c53251431eaaa240b823a2020264f64d Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 11:51:03 +0200 Subject: [PATCH 27/41] Fixes --- compiler/test/dotty/tools/compilerSupport.scala | 4 ++-- .../dotty/tools/dotc/printing/SyntaxHighlightingTests.scala | 2 +- doc-tool/test/dotty/tools/dottydoc/DottyDocTest.scala | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/test/dotty/tools/compilerSupport.scala b/compiler/test/dotty/tools/compilerSupport.scala index 3a4fab6b452a..97c3c8c6fe46 100644 --- a/compiler/test/dotty/tools/compilerSupport.scala +++ b/compiler/test/dotty/tools/compilerSupport.scala @@ -20,10 +20,10 @@ import dotc.core.Comments.{ContextDoc, ContextDocstrings} def inCompilerContext[T](classpath: String, separateRun: Boolean = true, scalaSources: String*)(op: Context ?=> T): T = val compiler = Compiler() val rootCtx = initCtx(classpath) - val firstRun = compiler.newRun(rootCtx) + val firstRun = compiler.newRun(using rootCtx) firstRun.compileFromStrings(scalaSources.toList) val opRun = if separateRun - then compiler.newRun(rootCtx) + then compiler.newRun(using rootCtx) else firstRun op(using opRun.runContext) diff --git a/compiler/test/dotty/tools/dotc/printing/SyntaxHighlightingTests.scala b/compiler/test/dotty/tools/dotc/printing/SyntaxHighlightingTests.scala index 8ac639db732f..53a66f1d24fb 100644 --- a/compiler/test/dotty/tools/dotc/printing/SyntaxHighlightingTests.scala +++ b/compiler/test/dotty/tools/dotc/printing/SyntaxHighlightingTests.scala @@ -11,7 +11,7 @@ class SyntaxHighlightingTests extends DottyTest { private def test(source: String, expected: String): Unit = { val testCtx = ctx.fresh.setSetting(ctx.settings.color, "always") - val highlighted = SyntaxHighlighting.highlight(source)(testCtx) + val highlighted = SyntaxHighlighting.highlight(source)(using testCtx) .replace(NoColor, ">") .replace(CommentColor, " Date: Thu, 9 Jul 2020 18:11:19 +0200 Subject: [PATCH 28/41] Convert tools classes --- .../tools/backend/jvm/BCodeHelpers.scala | 4 +- .../tools/backend/jvm/CollectSuperCalls.scala | 6 +- .../dotty/tools/backend/jvm/GenBCode.scala | 6 +- .../dotty/tools/backend/sjs/GenSJSIR.scala | 4 +- .../dotty/tools/backend/sjs/JSCodeGen.scala | 8 +- .../tools/backend/sjs/JSDefinitions.scala | 150 +++++++++--------- .../dotty/tools/backend/sjs/JSEncoding.scala | 26 +-- .../dotty/tools/backend/sjs/JSInterop.scala | 18 +-- .../dotty/tools/backend/sjs/JSPositions.scala | 2 +- .../tools/backend/sjs/JSPrimitives.scala | 12 +- .../backend/sjs/JUnitBootstrappers.scala | 24 +-- 11 files changed, 130 insertions(+), 130 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index f98b78494278..a62829ae2476 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala @@ -844,7 +844,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { } } - private def getGenericSignatureHelper(sym: Symbol, owner: Symbol, memberTpe: Type)(implicit ctx: Context): Option[String] = { + private def getGenericSignatureHelper(sym: Symbol, owner: Symbol, memberTpe: Type)(using Context): Option[String] = { if (needsGenericSignature(sym)) { val erasedTypeSym = TypeErasure.fullErasure(sym.denot.info).typeSymbol if (erasedTypeSym.isPrimitiveValueClass) { @@ -864,7 +864,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { } } - private def verifySignature(sym: Symbol, sig: String)(implicit ctx: Context): Unit = { + private def verifySignature(sym: Symbol, sig: String)(using Context): Unit = { import scala.tools.asm.util.CheckClassAdapter def wrap(body: => Unit): Unit = { try body diff --git a/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala b/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala index 8e646b5b7d81..b190b38450ed 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 +import dotty.tools.dotc.core.Contexts.{Context, ctx} import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Flags.Trait import dotty.tools.dotc.transform.MegaPhase.MiniPhase @@ -21,7 +21,7 @@ class CollectSuperCalls extends MiniPhase { def phaseName: String = "collectSuperCalls" - override def transformSelect(tree: Select)(implicit ctx: Context): Tree = { + override def transformSelect(tree: Select)(using Context): Tree = { tree.qualifier match { case sup: Super => if (tree.symbol.owner.is(Trait)) @@ -31,7 +31,7 @@ class CollectSuperCalls extends MiniPhase { tree } - private def registerSuperCall(sym: ClassSymbol, calls: ClassSymbol)(implicit ctx: Context) = { + private def registerSuperCall(sym: ClassSymbol, calls: ClassSymbol)(using Context) = { ctx.genBCodePhase match { case genBCodePhase: GenBCode => genBCodePhase.registerSuperCall(sym, calls) diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index 694ce9bd8b56..ff32aa3733ff 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -40,18 +40,18 @@ class GenBCode extends Phase { private var myOutput: AbstractFile = _ - private def outputDir(implicit ctx: Context): AbstractFile = { + private def outputDir(using Context): AbstractFile = { if (myOutput eq null) myOutput = ctx.settings.outputDir.value myOutput } - def run(implicit ctx: Context): Unit = { + def run(using Context): Unit = { new GenBCodePipeline(new DottyBackendInterface( outputDir, superCallsMap.toMap)(using ctx))(using ctx).run(ctx.compilationUnit.tpdTree) } - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { try super.runOn(units) finally myOutput match { case jar: JarArchive => diff --git a/compiler/src/dotty/tools/backend/sjs/GenSJSIR.scala b/compiler/src/dotty/tools/backend/sjs/GenSJSIR.scala index 0659eb8d6f09..a5eb4f0d117a 100644 --- a/compiler/src/dotty/tools/backend/sjs/GenSJSIR.scala +++ b/compiler/src/dotty/tools/backend/sjs/GenSJSIR.scala @@ -8,9 +8,9 @@ import Phases._ class GenSJSIR extends Phase { def phaseName: String = "genSJSIR" - override def isRunnable(implicit ctx: Context): Boolean = + override def isRunnable(using Context): Boolean = super.isRunnable && ctx.settings.scalajs.value - def run(implicit ctx: Context): Unit = + def run(using Context): Unit = new JSCodeGen().run() } diff --git a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala index 7e6f9741d8d3..5dc4db30eade 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala @@ -55,14 +55,14 @@ import ScopedVar.withScopedVars * - `genMethod()` and similar methods generate the declarations of methods. * - `genStatOrExpr()` and everything else generate the bodies of methods. */ -class JSCodeGen()(implicit ctx: Context) { +class JSCodeGen()(using genCtx: Context) { import JSCodeGen._ import tpd._ private val jsdefn = JSDefinitions.jsdefn - private val primitives = new JSPrimitives(ctx) + private val primitives = new JSPrimitives(genCtx) - private val positionConversions = new JSPositions()(using ctx) + private val positionConversions = new JSPositions()(using genCtx) import positionConversions._ // Some state -------------------------------------------------------------- @@ -2732,7 +2732,7 @@ class JSCodeGen()(implicit ctx: Context) { private def genActualJSArgs(sym: Symbol, args: List[Tree])( implicit pos: Position): List[js.TreeOrJSSpread] = { - def paramNamesAndTypes(implicit ctx: Context): List[(Names.TermName, Type)] = + def paramNamesAndTypes(using Context): List[(Names.TermName, Type)] = sym.info.paramNamess.flatten.zip(sym.info.paramInfoss.flatten) val wereRepeated = ctx.atPhase(ctx.elimRepeatedPhase) { diff --git a/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala b/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala index 2e4cca9694e3..2b0531cf0a51 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSDefinitions.scala @@ -14,167 +14,167 @@ import dotty.tools.dotc.config.SJSPlatform object JSDefinitions { /** The Scala.js-specific definitions for the current context. */ - def jsdefn(implicit ctx: Context): JSDefinitions = + def jsdefn(using Context): JSDefinitions = ctx.platform.asInstanceOf[SJSPlatform].jsDefinitions } -final class JSDefinitions()(implicit ctx: Context) { +final class JSDefinitions()(using Context) { @threadUnsafe lazy val InlineAnnotType: TypeRef = ctx.requiredClassRef("scala.inline") - def InlineAnnot(implicit ctx: Context) = InlineAnnotType.symbol.asClass + def InlineAnnot(using Context) = InlineAnnotType.symbol.asClass @threadUnsafe lazy val NoinlineAnnotType: TypeRef = ctx.requiredClassRef("scala.noinline") - def NoinlineAnnot(implicit ctx: Context) = NoinlineAnnotType.symbol.asClass + def NoinlineAnnot(using Context) = NoinlineAnnotType.symbol.asClass @threadUnsafe lazy val JavaLangVoidType: TypeRef = ctx.requiredClassRef("java.lang.Void") - def JavaLangVoidClass(implicit ctx: Context) = JavaLangVoidType.symbol.asClass + def JavaLangVoidClass(using Context) = JavaLangVoidType.symbol.asClass @threadUnsafe lazy val ScalaJSJSPackageVal = ctx.requiredPackage("scala.scalajs.js") @threadUnsafe lazy val ScalaJSJSPackageClass = ScalaJSJSPackageVal.moduleClass.asClass @threadUnsafe lazy val JSPackage_typeOfR = ScalaJSJSPackageClass.requiredMethodRef("typeOf") - def JSPackage_typeOf(implicit ctx: Context) = JSPackage_typeOfR.symbol + def JSPackage_typeOf(using Context) = JSPackage_typeOfR.symbol @threadUnsafe lazy val JSPackage_constructorOfR = ScalaJSJSPackageClass.requiredMethodRef("constructorOf") - def JSPackage_constructorOf(implicit ctx: Context) = JSPackage_constructorOfR.symbol + def JSPackage_constructorOf(using Context) = JSPackage_constructorOfR.symbol @threadUnsafe lazy val JSPackage_nativeR = ScalaJSJSPackageClass.requiredMethodRef("native") - def JSPackage_native(implicit ctx: Context) = JSPackage_nativeR.symbol + def JSPackage_native(using Context) = JSPackage_nativeR.symbol @threadUnsafe lazy val JSNativeAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.native") - def JSNativeAnnot(implicit ctx: Context) = JSNativeAnnotType.symbol.asClass + def JSNativeAnnot(using Context) = JSNativeAnnotType.symbol.asClass @threadUnsafe lazy val JSAnyType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.Any") - def JSAnyClass(implicit ctx: Context) = JSAnyType.symbol.asClass + def JSAnyClass(using Context) = JSAnyType.symbol.asClass @threadUnsafe lazy val JSObjectType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.Object") - def JSObjectClass(implicit ctx: Context) = JSObjectType.symbol.asClass + def JSObjectClass(using Context) = JSObjectType.symbol.asClass @threadUnsafe lazy val JSBaseThisFunctionType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.ThisFunction") - def JSBaseThisFunctionClass(implicit ctx: Context) = JSBaseThisFunctionType.symbol.asClass + def JSBaseThisFunctionClass(using Context) = JSBaseThisFunctionType.symbol.asClass @threadUnsafe lazy val JSArrayType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.Array") - def JSArrayClass(implicit ctx: Context) = JSArrayType.symbol.asClass + def JSArrayClass(using Context) = JSArrayType.symbol.asClass @threadUnsafe lazy val JSFunctionType = (0 to 22).map(n => ctx.requiredClassRef("scala.scalajs.js.Function" + n)).toArray - def JSFunctionClass(n: Int)(implicit ctx: Context) = JSFunctionType(n).symbol.asClass + 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 - def JSThisFunctionClass(n: Int)(implicit ctx: Context) = JSThisFunctionType(n).symbol.asClass + def JSThisFunctionClass(n: Int)(using Context) = JSThisFunctionType(n).symbol.asClass @threadUnsafe lazy val RuntimeExceptionType: TypeRef = ctx.requiredClassRef("java.lang.RuntimeException") - def RuntimeExceptionClass(implicit ctx: Context) = RuntimeExceptionType.symbol.asClass + def RuntimeExceptionClass(using Context) = RuntimeExceptionType.symbol.asClass @threadUnsafe lazy val JavaScriptExceptionType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.JavaScriptException") - def JavaScriptExceptionClass(implicit ctx: Context) = JavaScriptExceptionType.symbol.asClass + def JavaScriptExceptionClass(using Context) = JavaScriptExceptionType.symbol.asClass @threadUnsafe lazy val JSGlobalScopeAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSGlobalScope") - def JSGlobalScopeAnnot(implicit ctx: Context) = JSGlobalScopeAnnotType.symbol.asClass + def JSGlobalScopeAnnot(using Context) = JSGlobalScopeAnnotType.symbol.asClass @threadUnsafe lazy val JSNameAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSName") - def JSNameAnnot(implicit ctx: Context) = JSNameAnnotType.symbol.asClass + def JSNameAnnot(using Context) = JSNameAnnotType.symbol.asClass @threadUnsafe lazy val JSFullNameAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSFullName") - def JSFullNameAnnot(implicit ctx: Context) = JSFullNameAnnotType.symbol.asClass + def JSFullNameAnnot(using Context) = JSFullNameAnnotType.symbol.asClass @threadUnsafe lazy val JSBracketAccessAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSBracketAccess") - def JSBracketAccessAnnot(implicit ctx: Context) = JSBracketAccessAnnotType.symbol.asClass + def JSBracketAccessAnnot(using Context) = JSBracketAccessAnnotType.symbol.asClass @threadUnsafe lazy val JSBracketCallAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSBracketCall") - def JSBracketCallAnnot(implicit ctx: Context) = JSBracketCallAnnotType.symbol.asClass + def JSBracketCallAnnot(using Context) = JSBracketCallAnnotType.symbol.asClass @threadUnsafe lazy val JSExportAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExport") - def JSExportAnnot(implicit ctx: Context) = JSExportAnnotType.symbol.asClass + def JSExportAnnot(using Context) = JSExportAnnotType.symbol.asClass @threadUnsafe lazy val JSExportDescendentObjectsAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportDescendentObjects") - def JSExportDescendentObjectsAnnot(implicit ctx: Context) = JSExportDescendentObjectsAnnotType.symbol.asClass + def JSExportDescendentObjectsAnnot(using Context) = JSExportDescendentObjectsAnnotType.symbol.asClass @threadUnsafe lazy val JSExportDescendentClassesAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportDescendentClasses") - def JSExportDescendentClassesAnnot(implicit ctx: Context) = JSExportDescendentClassesAnnotType.symbol.asClass + def JSExportDescendentClassesAnnot(using Context) = JSExportDescendentClassesAnnotType.symbol.asClass @threadUnsafe lazy val JSExportAllAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportAll") - def JSExportAllAnnot(implicit ctx: Context) = JSExportAllAnnotType.symbol.asClass + def JSExportAllAnnot(using Context) = JSExportAllAnnotType.symbol.asClass @threadUnsafe lazy val JSExportNamedAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.JSExportNamed") - def JSExportNamedAnnot(implicit ctx: Context) = JSExportNamedAnnotType.symbol.asClass + def JSExportNamedAnnot(using Context) = JSExportNamedAnnotType.symbol.asClass @threadUnsafe lazy val RawJSTypeAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.RawJSType") - def RawJSTypeAnnot(implicit ctx: Context) = RawJSTypeAnnotType.symbol.asClass + def RawJSTypeAnnot(using Context) = RawJSTypeAnnotType.symbol.asClass @threadUnsafe lazy val ExposedJSMemberAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.annotation.ExposedJSMember") - def ExposedJSMemberAnnot(implicit ctx: Context) = ExposedJSMemberAnnotType.symbol.asClass + def ExposedJSMemberAnnot(using Context) = ExposedJSMemberAnnotType.symbol.asClass @threadUnsafe lazy val JSAnyModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Any") - def JSAnyModule(implicit ctx: Context) = JSAnyModuleRef.symbol + 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)(implicit ctx: Context) = JSAny_fromFunctionR(n).symbol + def JSAny_fromFunction(n: Int)(using Context) = JSAny_fromFunctionR(n).symbol @threadUnsafe lazy val JSDynamicModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Dynamic") - def JSDynamicModule(implicit ctx: Context) = JSDynamicModuleRef.symbol + def JSDynamicModule(using Context) = JSDynamicModuleRef.symbol @threadUnsafe lazy val JSDynamic_globalR = JSDynamicModule.requiredMethodRef("global") - def JSDynamic_global(implicit ctx: Context) = JSDynamic_globalR.symbol + def JSDynamic_global(using Context) = JSDynamic_globalR.symbol @threadUnsafe lazy val JSDynamic_newInstanceR = JSDynamicModule.requiredMethodRef("newInstance") - def JSDynamic_newInstance(implicit ctx: Context) = JSDynamic_newInstanceR.symbol + def JSDynamic_newInstance(using Context) = JSDynamic_newInstanceR.symbol @threadUnsafe lazy val JSDynamicLiteralModuleRef = JSDynamicModule.moduleClass.requiredValueRef("literal") - def JSDynamicLiteralModule(implicit ctx: Context) = JSDynamicLiteralModuleRef.symbol + def JSDynamicLiteralModule(using Context) = JSDynamicLiteralModuleRef.symbol @threadUnsafe lazy val JSDynamicLiteral_applyDynamicNamedR = JSDynamicLiteralModule.requiredMethodRef("applyDynamicNamed") - def JSDynamicLiteral_applyDynamicNamed(implicit ctx: Context) = JSDynamicLiteral_applyDynamicNamedR.symbol + def JSDynamicLiteral_applyDynamicNamed(using Context) = JSDynamicLiteral_applyDynamicNamedR.symbol @threadUnsafe lazy val JSDynamicLiteral_applyDynamicR = JSDynamicLiteralModule.requiredMethodRef("applyDynamic") - def JSDynamicLiteral_applyDynamic(implicit ctx: Context) = JSDynamicLiteral_applyDynamicR.symbol + def JSDynamicLiteral_applyDynamic(using Context) = JSDynamicLiteral_applyDynamicR.symbol @threadUnsafe lazy val JSObjectModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Object") - def JSObjectModule(implicit ctx: Context) = JSObjectModuleRef.symbol + def JSObjectModule(using Context) = JSObjectModuleRef.symbol @threadUnsafe lazy val JSArrayModuleRef = ctx.requiredModuleRef("scala.scalajs.js.Array") - def JSArrayModule(implicit ctx: Context) = JSArrayModuleRef.symbol + def JSArrayModule(using Context) = JSArrayModuleRef.symbol @threadUnsafe lazy val JSArray_applyR = JSArrayModule.requiredMethodRef(nme.apply) - def JSArray_apply(implicit ctx: Context) = JSArray_applyR.symbol + def JSArray_apply(using Context) = JSArray_applyR.symbol @threadUnsafe lazy val JSThisFunctionModuleRef = ctx.requiredModuleRef("scala.scalajs.js.ThisFunction") - def JSThisFunctionModule(implicit ctx: Context) = JSThisFunctionModuleRef.symbol + 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)(implicit ctx: Context) = JSThisFunction_fromFunctionR(n - 1).symbol + def JSThisFunction_fromFunction(n: Int)(using Context) = JSThisFunction_fromFunctionR(n - 1).symbol @threadUnsafe lazy val JSConstructorTagModuleRef = ctx.requiredModuleRef("scala.scalajs.js.ConstructorTag") - def JSConstructorTagModule(implicit ctx: Context) = JSConstructorTagModuleRef.symbol + def JSConstructorTagModule(using Context) = JSConstructorTagModuleRef.symbol @threadUnsafe lazy val JSConstructorTag_materializeR = JSConstructorTagModule.requiredMethodRef("materialize") - def JSConstructorTag_materialize(implicit ctx: Context) = JSConstructorTag_materializeR.symbol + def JSConstructorTag_materialize(using Context) = JSConstructorTag_materializeR.symbol @threadUnsafe lazy val RuntimePackageVal = ctx.requiredPackage("scala.scalajs.runtime") @threadUnsafe lazy val RuntimePackageClass = RuntimePackageVal.moduleClass.asClass @threadUnsafe lazy val RuntimePackage_wrapJavaScriptExceptionR = RuntimePackageClass.requiredMethodRef("wrapJavaScriptException") - def Runtime_wrapJavaScriptException(implicit ctx: Context) = RuntimePackage_wrapJavaScriptExceptionR.symbol + def Runtime_wrapJavaScriptException(using Context) = RuntimePackage_wrapJavaScriptExceptionR.symbol @threadUnsafe lazy val Runtime_unwrapJavaScriptExceptionR = RuntimePackageClass.requiredMethodRef("unwrapJavaScriptException") - def Runtime_unwrapJavaScriptException(implicit ctx: Context) = Runtime_unwrapJavaScriptExceptionR.symbol + def Runtime_unwrapJavaScriptException(using Context) = Runtime_unwrapJavaScriptExceptionR.symbol @threadUnsafe lazy val Runtime_toScalaVarArgsR = RuntimePackageClass.requiredMethodRef("toScalaVarArgs") - def Runtime_toScalaVarArgs(implicit ctx: Context) = Runtime_toScalaVarArgsR.symbol + def Runtime_toScalaVarArgs(using Context) = Runtime_toScalaVarArgsR.symbol @threadUnsafe lazy val Runtime_toJSVarArgsR = RuntimePackageClass.requiredMethodRef("toJSVarArgs") - def Runtime_toJSVarArgs(implicit ctx: Context) = Runtime_toJSVarArgsR.symbol + def Runtime_toJSVarArgs(using Context) = Runtime_toJSVarArgsR.symbol @threadUnsafe lazy val Runtime_constructorOfR = RuntimePackageClass.requiredMethodRef("constructorOf") - def Runtime_constructorOf(implicit ctx: Context) = Runtime_constructorOfR.symbol + def Runtime_constructorOf(using Context) = Runtime_constructorOfR.symbol @threadUnsafe lazy val Runtime_newConstructorTagR = RuntimePackageClass.requiredMethodRef("newConstructorTag") - def Runtime_newConstructorTag(implicit ctx: Context) = Runtime_newConstructorTagR.symbol + def Runtime_newConstructorTag(using Context) = Runtime_newConstructorTagR.symbol @threadUnsafe lazy val Runtime_linkingInfoR = RuntimePackageClass.requiredMethodRef("linkingInfo") - def Runtime_linkingInfo(implicit ctx: Context) = Runtime_linkingInfoR.symbol + def Runtime_linkingInfo(using Context) = Runtime_linkingInfoR.symbol @threadUnsafe lazy val SpecialPackageVal = ctx.requiredPackage("scala.scalajs.js.special") @threadUnsafe lazy val SpecialPackageClass = SpecialPackageVal.moduleClass.asClass @threadUnsafe lazy val Special_debuggerR = SpecialPackageClass.requiredMethodRef("debugger") - def Special_debugger(implicit ctx: Context) = Special_debuggerR.symbol + def Special_debugger(using Context) = Special_debuggerR.symbol @threadUnsafe lazy val Special_deleteR = SpecialPackageClass.requiredMethodRef("delete") - def Special_delete(implicit ctx: Context) = Special_deleteR.symbol + def Special_delete(using Context) = Special_deleteR.symbol @threadUnsafe lazy val Special_forinR = SpecialPackageClass.requiredMethodRef("forin") - def Special_forin(implicit ctx: Context) = Special_forinR.symbol + def Special_forin(using Context) = Special_forinR.symbol @threadUnsafe lazy val Special_inR = SpecialPackageClass.requiredMethodRef("in") - def Special_in(implicit ctx: Context) = Special_inR.symbol + def Special_in(using Context) = Special_inR.symbol @threadUnsafe lazy val Special_instanceofR = SpecialPackageClass.requiredMethodRef("instanceof") - def Special_instanceof(implicit ctx: Context) = Special_instanceofR.symbol + def Special_instanceof(using Context) = Special_instanceofR.symbol @threadUnsafe lazy val WrappedArrayType: TypeRef = ctx.requiredClassRef("scala.scalajs.js.WrappedArray") - def WrappedArrayClass(implicit ctx: Context) = WrappedArrayType.symbol.asClass + def WrappedArrayClass(using Context) = WrappedArrayType.symbol.asClass @threadUnsafe lazy val ScalaRunTime_isArrayR = defn.ScalaRuntimeModule.requiredMethodRef("isArray", List(???, ???)) - def ScalaRunTime_isArray(implicit ctx: Context): Symbol = ScalaRunTime_isArrayR.symbol + def ScalaRunTime_isArray(using Context): Symbol = ScalaRunTime_isArrayR.symbol @threadUnsafe lazy val BoxesRunTime_boxToCharacterR = defn.BoxesRunTimeModule.requiredMethodRef("boxToCharacter") - def BoxesRunTime_boxToCharacter(implicit ctx: Context): Symbol = BoxesRunTime_boxToCharacterR.symbol + def BoxesRunTime_boxToCharacter(using Context): Symbol = BoxesRunTime_boxToCharacterR.symbol @threadUnsafe lazy val BoxesRunTime_unboxToCharR = defn.BoxesRunTimeModule.requiredMethodRef("unboxToChar") - def BoxesRunTime_unboxToChar(implicit ctx: Context): Symbol = BoxesRunTime_unboxToCharR.symbol + def BoxesRunTime_unboxToChar(using Context): Symbol = BoxesRunTime_unboxToCharR.symbol @threadUnsafe lazy val EnableReflectiveInstantiationAnnotType: TypeRef = ctx.requiredClassRef("scala.scalajs.reflect.annotation.EnableReflectiveInstantiation") - def EnableReflectiveInstantiationAnnot(implicit ctx: Context) = EnableReflectiveInstantiationAnnotType.symbol.asClass + def EnableReflectiveInstantiationAnnot(using Context) = EnableReflectiveInstantiationAnnotType.symbol.asClass @threadUnsafe lazy val ReflectModuleRef = ctx.requiredModuleRef("scala.scalajs.reflect.Reflect") - def ReflectModule(implicit ctx: Context) = ReflectModuleRef.symbol + def ReflectModule(using Context) = ReflectModuleRef.symbol @threadUnsafe lazy val Reflect_registerLoadableModuleClassR = ReflectModule.requiredMethodRef("registerLoadableModuleClass") - def Reflect_registerLoadableModuleClass(implicit ctx: Context) = Reflect_registerLoadableModuleClassR.symbol + def Reflect_registerLoadableModuleClass(using Context) = Reflect_registerLoadableModuleClassR.symbol @threadUnsafe lazy val Reflect_registerInstantiatableClassR = ReflectModule.requiredMethodRef("registerInstantiatableClass") - def Reflect_registerInstantiatableClass(implicit ctx: Context) = Reflect_registerInstantiatableClassR.symbol + def Reflect_registerInstantiatableClass(using Context) = Reflect_registerInstantiatableClassR.symbol private var allRefClassesCache: Set[Symbol] = _ - def allRefClasses(implicit ctx: Context): Set[Symbol] = { + def allRefClasses(using Context): Set[Symbol] = { if (allRefClassesCache == null) { val baseNames = List("Object", "Boolean", "Character", "Byte", "Short", "Int", "Long", "Float", "Double") @@ -187,7 +187,7 @@ final class JSDefinitions()(implicit ctx: Context) { } /** If `cls` is a class in the scala package, its name, otherwise EmptyTypeName */ - private def scalajsClassName(cls: Symbol)(implicit ctx: Context): TypeName = + private def scalajsClassName(cls: Symbol)(using Context): TypeName = if (cls.isClass && cls.owner == ScalaJSJSPackageClass) cls.asClass.name else EmptyTypeName @@ -210,22 +210,22 @@ final class JSDefinitions()(implicit ctx: Context) { /** Definitions related to the treatment of JUnit boostrappers. */ object junit { @threadUnsafe lazy val TestAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Test") - def TestAnnotClass(implicit ctx: Context): ClassSymbol = TestAnnotType.symbol.asClass + def TestAnnotClass(using Context): ClassSymbol = TestAnnotType.symbol.asClass @threadUnsafe lazy val BeforeAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Before") - def BeforeAnnotClass(implicit ctx: Context): ClassSymbol = BeforeAnnotType.symbol.asClass + def BeforeAnnotClass(using Context): ClassSymbol = BeforeAnnotType.symbol.asClass @threadUnsafe lazy val AfterAnnotType: TypeRef = ctx.requiredClassRef("org.junit.After") - def AfterAnnotClass(implicit ctx: Context): ClassSymbol = AfterAnnotType.symbol.asClass + def AfterAnnotClass(using Context): ClassSymbol = AfterAnnotType.symbol.asClass @threadUnsafe lazy val BeforeClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.BeforeClass") - def BeforeClassAnnotClass(implicit ctx: Context): ClassSymbol = BeforeClassAnnotType.symbol.asClass + def BeforeClassAnnotClass(using Context): ClassSymbol = BeforeClassAnnotType.symbol.asClass @threadUnsafe lazy val AfterClassAnnotType: TypeRef = ctx.requiredClassRef("org.junit.AfterClass") - def AfterClassAnnotClass(implicit ctx: Context): ClassSymbol = AfterClassAnnotType.symbol.asClass + def AfterClassAnnotClass(using Context): ClassSymbol = AfterClassAnnotType.symbol.asClass @threadUnsafe lazy val IgnoreAnnotType: TypeRef = ctx.requiredClassRef("org.junit.Ignore") - def IgnoreAnnotClass(implicit ctx: Context): ClassSymbol = IgnoreAnnotType.symbol.asClass + def IgnoreAnnotClass(using Context): ClassSymbol = IgnoreAnnotType.symbol.asClass @threadUnsafe lazy val BootstrapperType: TypeRef = ctx.requiredClassRef("org.scalajs.junit.Bootstrapper") @@ -234,13 +234,13 @@ final class JSDefinitions()(implicit ctx: Context) { @threadUnsafe lazy val NoSuchMethodExceptionType: TypeRef = ctx.requiredClassRef("java.lang.NoSuchMethodException") @threadUnsafe lazy val FutureType: TypeRef = ctx.requiredClassRef("scala.concurrent.Future") - def FutureClass(implicit ctx: Context): ClassSymbol = FutureType.symbol.asClass + def FutureClass(using Context): ClassSymbol = FutureType.symbol.asClass @threadUnsafe private lazy val FutureModule_successfulR = ctx.requiredModule("scala.concurrent.Future").requiredMethodRef("successful") - def FutureModule_successful(implicit ctx: Context): Symbol = FutureModule_successfulR.symbol + def FutureModule_successful(using Context): Symbol = FutureModule_successfulR.symbol @threadUnsafe private lazy val SuccessModule_applyR = ctx.requiredModule("scala.util.Success").requiredMethodRef(nme.apply) - def SuccessModule_apply(implicit ctx: Context): Symbol = SuccessModule_applyR.symbol + def SuccessModule_apply(using Context): Symbol = SuccessModule_applyR.symbol } } diff --git a/compiler/src/dotty/tools/backend/sjs/JSEncoding.scala b/compiler/src/dotty/tools/backend/sjs/JSEncoding.scala index aa96e9121226..a097c4ca5a8b 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSEncoding.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSEncoding.scala @@ -88,7 +88,7 @@ object JSEncoding { def freshLocalIdent(base: TermName)(implicit pos: ir.Position): js.LocalIdent = freshLocalIdent(base.mangledString) - def localSymbolName(sym: Symbol)(implicit ctx: Context): LocalName = { + def localSymbolName(sym: Symbol)(using Context): LocalName = { localSymbolNames.getOrElseUpdate(sym, { /* The emitter does not like local variables that start with a '$', * because it needs to encode them not to clash with emitter-generated @@ -120,7 +120,7 @@ object JSEncoding { def freshLabelIdent(base: String)(implicit pos: ir.Position): js.LabelIdent = js.LabelIdent(freshLabelName(base)) - def labelSymbolName(sym: Symbol)(implicit ctx: Context): LabelName = + def labelSymbolName(sym: Symbol)(using Context): LabelName = labelSymbolNames.getOrElseUpdate(sym, freshLabelName(sym.javaSimpleName)) def getEnclosingReturnLabel()(implicit pos: ir.Position): js.LabelIdent = { @@ -206,7 +206,7 @@ object JSEncoding { } /** Computes the type ref for a type, to be used in a method signature. */ - private def paramOrResultTypeRef(tpe: Type)(implicit ctx: Context): jstpe.TypeRef = { + private def paramOrResultTypeRef(tpe: Type)(using Context): jstpe.TypeRef = { toTypeRef(tpe) match { case jstpe.ClassRef(ScalaNullClassName) => jstpe.NullRef case jstpe.ClassRef(ScalaNothingClassName) => jstpe.NothingRef @@ -221,7 +221,7 @@ object JSEncoding { js.LocalIdent(localNames.localSymbolName(sym)) } - def encodeClassType(sym: Symbol)(implicit ctx: Context): jstpe.Type = { + def encodeClassType(sym: Symbol)(using Context): jstpe.Type = { if (sym == defn.ObjectClass) jstpe.AnyType else if (isJSType(sym)) jstpe.AnyType else { @@ -231,14 +231,14 @@ object JSEncoding { } } - def encodeClassRef(sym: Symbol)(implicit ctx: Context): jstpe.ClassRef = + def encodeClassRef(sym: Symbol)(using Context): jstpe.ClassRef = jstpe.ClassRef(encodeClassName(sym)) def encodeClassNameIdent(sym: Symbol)( implicit ctx: Context, pos: ir.Position): js.ClassIdent = js.ClassIdent(encodeClassName(sym)) - def encodeClassName(sym: Symbol)(implicit ctx: Context): ClassName = { + def encodeClassName(sym: Symbol)(using Context): ClassName = { val sym1 = if (sym.isAllOf(ModuleClass | JavaDefined)) sym.linkedClass else sym @@ -253,7 +253,7 @@ object JSEncoding { } } - def toIRType(tp: Type)(implicit ctx: Context): jstpe.Type = { + def toIRType(tp: Type)(using Context): jstpe.Type = { val typeRefInternal = toTypeRefInternal(tp) typeRefInternal._1 match { case jstpe.PrimRef(irTpe) => @@ -275,10 +275,10 @@ object JSEncoding { } } - def toTypeRef(tp: Type)(implicit ctx: Context): jstpe.TypeRef = + def toTypeRef(tp: Type)(using Context): jstpe.TypeRef = toTypeRefInternal(tp)._1 - private def toTypeRefInternal(tp: Type)(implicit ctx: Context): (jstpe.TypeRef, Symbol) = { + private def toTypeRefInternal(tp: Type)(using Context): (jstpe.TypeRef, Symbol) = { def primitiveOrClassToTypeRef(sym: Symbol): (jstpe.TypeRef, Symbol) = { assert(sym.isClass, sym) //assert(sym != defn.ArrayClass || isCompilingArray, sym) @@ -343,7 +343,7 @@ object JSEncoding { * This method returns `UnitType` for constructor methods, and otherwise * `sym.info.resultType`. */ - def patchedResultType(sym: Symbol)(implicit ctx: Context): Type = + def patchedResultType(sym: Symbol)(using Context): Type = if (sym.isConstructor) defn.UnitType else sym.info.resultType @@ -355,13 +355,13 @@ object JSEncoding { else OriginalName(originalName) } - def originalNameOfField(sym: Symbol)(implicit ctx: Context): OriginalName = + def originalNameOfField(sym: Symbol)(using Context): OriginalName = originalNameOf(sym.name) - def originalNameOfMethod(sym: Symbol)(implicit ctx: Context): OriginalName = + def originalNameOfMethod(sym: Symbol)(using Context): OriginalName = originalNameOf(sym.name) - def originalNameOfClass(sym: Symbol)(implicit ctx: Context): OriginalName = + def originalNameOfClass(sym: Symbol)(using Context): OriginalName = originalNameOf(sym.fullName) private def originalNameOf(name: Name): OriginalName = { diff --git a/compiler/src/dotty/tools/backend/sjs/JSInterop.scala b/compiler/src/dotty/tools/backend/sjs/JSInterop.scala index 664543ca599a..8fe20566fe47 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSInterop.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSInterop.scala @@ -14,7 +14,7 @@ import JSDefinitions._ object JSInterop { /** Is this symbol a JavaScript type? */ - def isJSType(sym: Symbol)(implicit ctx: Context): Boolean = { + def isJSType(sym: Symbol)(using Context): Boolean = { //sym.hasAnnotation(jsdefn.RawJSTypeAnnot) ctx.atPhase(ctx.erasurePhase) { sym.derivesFrom(jsdefn.JSAnyClass) @@ -22,7 +22,7 @@ object JSInterop { } /** Is this symbol a Scala.js-defined JS class, i.e., a non-native JS class? */ - def isScalaJSDefinedJSClass(sym: Symbol)(implicit ctx: Context): Boolean = + def isScalaJSDefinedJSClass(sym: Symbol)(using Context): Boolean = isJSType(sym) && !sym.hasAnnotation(jsdefn.JSNativeAnnot) /** Should this symbol be translated into a JS getter? @@ -31,7 +31,7 @@ object JSInterop { * Unlike `SymDenotations.isGetter`, it applies to user-defined methods as * much as *accessor* methods created for `val`s and `var`s. */ - def isJSGetter(sym: Symbol)(implicit ctx: Context): Boolean = { + def isJSGetter(sym: Symbol)(using Context): Boolean = { sym.info.firstParamTypes.isEmpty && ctx.atPhase(ctx.erasurePhase) { sym.info.isParameterless } @@ -43,21 +43,21 @@ object JSInterop { * Unlike `SymDenotations.isGetter`, it applies to user-defined methods as * much as *accessor* methods created for `var`s. */ - def isJSSetter(sym: Symbol)(implicit ctx: Context): Boolean = + def isJSSetter(sym: Symbol)(using Context): Boolean = sym.name.isSetterName && sym.is(Method) /** Should this symbol be translated into a JS bracket access? * * This is true for methods annotated with `@JSBracketAccess`. */ - def isJSBracketAccess(sym: Symbol)(implicit ctx: Context): Boolean = + def isJSBracketAccess(sym: Symbol)(using Context): Boolean = sym.hasAnnotation(jsdefn.JSBracketAccessAnnot) /** Should this symbol be translated into a JS bracket call? * * This is true for methods annotated with `@JSBracketCall`. */ - def isJSBracketCall(sym: Symbol)(implicit ctx: Context): Boolean = + def isJSBracketCall(sym: Symbol)(using Context): Boolean = sym.hasAnnotation(jsdefn.JSBracketCallAnnot) /** Is this symbol a default param accessor for a JS method? @@ -66,7 +66,7 @@ object JSInterop { * the companion *class* of the owner is a JS type; not whether the owner * is a JS type. */ - def isJSDefaultParam(sym: Symbol)(implicit ctx: Context): Boolean = { + def isJSDefaultParam(sym: Symbol)(using Context): Boolean = { sym.name.is(DefaultGetterName) && { val owner = sym.owner if (owner.is(ModuleClass)) { @@ -89,7 +89,7 @@ object JSInterop { * If it is not explicitly specified with an `@JSName` annotation, the * JS name is inferred from the Scala name. */ - def jsNameOf(sym: Symbol)(implicit ctx: Context): String = { + def jsNameOf(sym: Symbol)(using Context): String = { sym.getAnnotation(jsdefn.JSNameAnnot).flatMap(_.argumentConstant(0)).fold { val base = sym.name.unexpandedName.decode.toString.stripSuffix("_=") if (sym.is(ModuleClass)) base.stripSuffix("$") @@ -105,7 +105,7 @@ object JSInterop { * This is the JS name of the symbol qualified by the fully qualified JS * name of its original owner if the latter is a native JS object. */ - def fullJSNameOf(sym: Symbol)(implicit ctx: Context): String = { + def fullJSNameOf(sym: Symbol)(using Context): String = { assert(sym.isClass, s"fullJSNameOf called for non-class symbol $sym") sym.getAnnotation(jsdefn.JSFullNameAnnot).flatMap(_.argumentConstant(0)).fold { jsNameOf(sym) diff --git a/compiler/src/dotty/tools/backend/sjs/JSPositions.scala b/compiler/src/dotty/tools/backend/sjs/JSPositions.scala index 960fedebbafc..6ab6a6bb4238 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSPositions.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSPositions.scala @@ -9,7 +9,7 @@ import dotty.tools.dotc.util.Spans.Span import org.scalajs.ir /** Conversion utilities from dotty Positions to IR Positions. */ -class JSPositions()(implicit ctx: Context) { +class JSPositions()(using Context) { private def sourceAndSpan2irPos(source: SourceFile, span: Span): ir.Position = { if (!span.exists) ir.Position.NoPosition diff --git a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala index 214f617772f0..56959c1d214d 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala @@ -46,23 +46,23 @@ object JSPrimitives { } -class JSPrimitives(ctx: Context) extends DottyPrimitives(ctx) { +class JSPrimitives(ictx: Context) extends DottyPrimitives(ictx) { import JSPrimitives._ import dotty.tools.backend.ScalaPrimitivesOps._ - private lazy val jsPrimitives: Map[Symbol, Int] = initJSPrimitives(ctx) + private lazy val jsPrimitives: Map[Symbol, Int] = initJSPrimitives(using ictx) override def getPrimitive(sym: Symbol): Int = jsPrimitives.getOrElse(sym, super.getPrimitive(sym)) - override def getPrimitive(app: Apply, tpe: Type)(implicit ctx: Context): Int = + override def getPrimitive(app: Apply, tpe: Type)(using Context): Int = jsPrimitives.getOrElse(app.fun.symbol, super.getPrimitive(app, tpe)) override def isPrimitive(fun: Tree): Boolean = - jsPrimitives.contains(fun.symbol(using ctx)) || super.isPrimitive(fun) + jsPrimitives.contains(fun.symbol(using ictx)) || super.isPrimitive(fun) /** Initialize the primitive map */ - private def initJSPrimitives(implicit ctx: Context): Map[Symbol, Int] = { + private def initJSPrimitives(using Context): Map[Symbol, Int] = { val primitives = newMutableSymbolMap[Int] @@ -73,7 +73,7 @@ class JSPrimitives(ctx: Context) extends DottyPrimitives(ctx) { primitives(s) = code } - def addPrimitives(cls: Symbol, method: TermName, code: Int)(implicit ctx: Context): Unit = { + 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") diff --git a/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala b/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala index 7846aa70a2da..9f50aa97fda2 100644 --- a/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala +++ b/compiler/src/dotty/tools/backend/sjs/JUnitBootstrappers.scala @@ -112,12 +112,12 @@ class JUnitBootstrappers extends MiniPhase { def phaseName: String = "junitBootstrappers" - override def isEnabled(implicit ctx: Context): Boolean = + override def isEnabled(using Context): Boolean = super.isEnabled && ctx.settings.scalajs.value // The actual transform ------------------------------- - override def transformPackageDef(tree: PackageDef)(implicit ctx: Context): Tree = { + override def transformPackageDef(tree: PackageDef)(using Context): Tree = { val junitdefn = jsdefn.junit @tailrec @@ -141,7 +141,7 @@ class JUnitBootstrappers extends MiniPhase { else cpy.PackageDef(tree)(tree.pid, tree.stats ::: bootstrappers) } - private def genBootstrapper(testClass: ClassSymbol)(implicit ctx: Context): TypeDef = { + private def genBootstrapper(testClass: ClassSymbol)(using Context): TypeDef = { val junitdefn = jsdefn.junit /* The name of the boostrapper module. It is derived from the test class name by @@ -177,7 +177,7 @@ class JUnitBootstrappers extends MiniPhase { ClassDef(classSym, constr, defs) } - private def genConstructor(owner: ClassSymbol)(implicit ctx: Context): DefDef = { + private def genConstructor(owner: ClassSymbol)(using Context): DefDef = { val sym = ctx.newDefaultConstructor(owner).entered DefDef(sym, { Block( @@ -187,7 +187,7 @@ class JUnitBootstrappers extends MiniPhase { }) } - private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol)(implicit ctx: Context): DefDef = { + private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol)(using Context): DefDef = { val sym = ctx.newSymbol(owner, name, Synthetic | Method, MethodType(Nil, Nil, defn.UnitType)).entered @@ -202,7 +202,7 @@ class JUnitBootstrappers extends MiniPhase { }) } - private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: ClassSymbol, annot: Symbol)(implicit ctx: Context): DefDef = { + private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: ClassSymbol, annot: Symbol)(using Context): DefDef = { val sym = ctx.newSymbol(owner, name, Synthetic | Method, MethodType(junitNme.instance :: Nil, defn.ObjectType :: Nil, defn.UnitType)).entered @@ -214,7 +214,7 @@ class JUnitBootstrappers extends MiniPhase { }) } - private def genTests(owner: ClassSymbol, tests: List[Symbol])(implicit ctx: Context): DefDef = { + private def genTests(owner: ClassSymbol, tests: List[Symbol])(using Context): DefDef = { val junitdefn = jsdefn.junit val sym = ctx.newSymbol(owner, junitNme.tests, Synthetic | Method, @@ -250,7 +250,7 @@ class JUnitBootstrappers extends MiniPhase { }) } - private def genInvokeTest(owner: ClassSymbol, testClass: ClassSymbol, tests: List[Symbol])(implicit ctx: Context): DefDef = { + 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, @@ -273,7 +273,7 @@ class JUnitBootstrappers extends MiniPhase { }) } - private def genTestInvocation(testClass: ClassSymbol, testMethod: Symbol, instance: Tree)(implicit ctx: Context): Tree = { + private def genTestInvocation(testClass: ClassSymbol, testMethod: Symbol, instance: Tree)(using Context): Tree = { val junitdefn = jsdefn.junit val resultType = testMethod.info.resultType @@ -292,17 +292,17 @@ class JUnitBootstrappers extends MiniPhase { } } - private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol)(implicit ctx: Context): DefDef = { + private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol)(using Context): DefDef = { val sym = ctx.newSymbol(owner, junitNme.newInstance, Synthetic | Method, MethodType(Nil, defn.ObjectType)).entered DefDef(sym, New(testClass.typeRef, Nil)) } - private def castParam(param: Symbol, clazz: Symbol)(implicit ctx: Context): Tree = + private def castParam(param: Symbol, clazz: Symbol)(using Context): Tree = ref(param).cast(clazz.typeRef) - private def annotatedMethods(owner: ClassSymbol, annot: Symbol)(implicit ctx: Context): List[Symbol] = + private def annotatedMethods(owner: ClassSymbol, annot: Symbol)(using Context): List[Symbol] = owner.info.decls.filter(m => m.is(Method) && m.hasAnnotation(annot)) } From 682ef6a42f9a54ae4b32e2a28d1170a273d680bf Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 12:00:41 +0200 Subject: [PATCH 29/41] Convert repl classes --- .../dotc/tastyreflect/ReflectionImpl.scala | 2 +- .../tools/repl/CollectTopLevelImports.scala | 2 +- .../src/dotty/tools/repl/JLineTerminal.scala | 12 +++++------ .../src/dotty/tools/repl/ParseResult.scala | 10 +++++----- compiler/src/dotty/tools/repl/Rendering.scala | 20 +++++++++---------- .../src/dotty/tools/repl/ReplCompiler.scala | 18 ++++++++--------- .../src/dotty/tools/repl/ReplFrontEnd.scala | 4 ++-- .../src/dotty/tools/repl/ScriptEngine.scala | 2 +- 8 files changed, 35 insertions(+), 35 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala index 1a5ae33a627a..24af1dc67722 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala @@ -11,7 +11,7 @@ object ReflectionImpl { def apply(rootContext: Contexts.Context): scala.tasty.Reflection = new scala.tasty.Reflection(new ReflectionCompilerInterface(rootContext)) - def showTree(tree: tpd.Tree)(implicit ctx: Contexts.Context): String = { + def showTree(tree: tpd.Tree)(using Contexts.Context): String = { val refl = new scala.tasty.Reflection(new ReflectionCompilerInterface(MacroExpansion.context(tree))) val reflCtx = ctx.asInstanceOf[refl.Context] val reflTree = tree.asInstanceOf[refl.Tree] diff --git a/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala b/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala index 53b8ccead3ee..266d1f1528f4 100644 --- a/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala +++ b/compiler/src/dotty/tools/repl/CollectTopLevelImports.scala @@ -18,7 +18,7 @@ class CollectTopLevelImports extends Phase { private var myImports: List[Import] = _ def imports: List[Import] = myImports - def run(implicit ctx: Context): Unit = { + def run(using Context): Unit = { def topLevelImports(tree: Tree) = { val PackageDef(_, _ :: TypeDef(_, rhs: Template) :: _) = tree rhs.body.collect { case tree: Import => tree } diff --git a/compiler/src/dotty/tools/repl/JLineTerminal.scala b/compiler/src/dotty/tools/repl/JLineTerminal.scala index 44d423fa3c51..36ed0aa3ea38 100644 --- a/compiler/src/dotty/tools/repl/JLineTerminal.scala +++ b/compiler/src/dotty/tools/repl/JLineTerminal.scala @@ -24,11 +24,11 @@ final class JLineTerminal extends java.io.Closeable { .build() private val history = new DefaultHistory - private def blue(str: String)(implicit ctx: Context) = + private def blue(str: String)(using Context) = if (ctx.settings.color.value != "never") Console.BLUE + str + Console.RESET else str - private def prompt(implicit ctx: Context) = blue("scala> ") - private def newLinePrompt(implicit ctx: Context) = blue(" | ") + private def prompt(using Context) = blue("scala> ") + private def newLinePrompt(using Context) = blue(" | ") /** Blockingly read line from `System.in` * @@ -45,7 +45,7 @@ final class JLineTerminal extends java.io.Closeable { */ def readLine( completer: Completer // provide auto-completions - )(implicit ctx: Context): String = { + )(using Context): String = { import LineReader.Option._ import LineReader._ val userHome = System.getProperty("user.home") @@ -74,7 +74,7 @@ final class JLineTerminal extends java.io.Closeable { def close(): Unit = terminal.close() /** Provide syntax highlighting */ - private class Highlighter(implicit ctx: Context) extends reader.Highlighter { + private class Highlighter(using Context) extends reader.Highlighter { def highlight(reader: LineReader, buffer: String): AttributedString = { val highlighted = SyntaxHighlighting.highlight(buffer) AttributedString.fromAnsi(highlighted) @@ -84,7 +84,7 @@ final class JLineTerminal extends java.io.Closeable { } /** Provide multi-line editing support */ - private class Parser(implicit ctx: Context) extends reader.Parser { + private class Parser(using Context) extends reader.Parser { /** * @param cursor The cursor position within the line diff --git a/compiler/src/dotty/tools/repl/ParseResult.scala b/compiler/src/dotty/tools/repl/ParseResult.scala index a88a90f152cd..06ecd5c4d356 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, inContext} +import dotc.core.Contexts.{Context, ctx, inContext} import dotc.core.StdNames.str import dotc.parsing.Parsers.Parser import dotc.parsing.Tokens @@ -112,7 +112,7 @@ object ParseResult { @sharable private val CommandExtract = """(:[\S]+)\s*(.*)""".r - private def parseStats(implicit ctx: Context): List[untpd.Tree] = { + private def parseStats(using Context): List[untpd.Tree] = { val parser = new Parser(ctx.source) val stats = parser.blockStatSeq() parser.accept(Tokens.EOF) @@ -144,7 +144,7 @@ object ParseResult { case _ => inContext(state.context) { val reporter = newStoreReporter - val stats = parseStats(state.context.fresh.setReporter(reporter).withSource(source)) + val stats = parseStats(using state.context.fresh.setReporter(reporter).withSource(source)) if (reporter.hasErrors) SyntaxErrors( @@ -165,7 +165,7 @@ object ParseResult { * This can be used in order to check if a newline can be inserted without * having to evaluate the expression. */ - def isIncomplete(sourceCode: String)(implicit ctx: Context): Boolean = + def isIncomplete(sourceCode: String)(using Context): Boolean = sourceCode match { case CommandExtract(_) | "" => false case _ => { @@ -177,7 +177,7 @@ object ParseResult { .setReporter(reporter) var needsMore = false reporter.withIncompleteHandler((_, _) => needsMore = true) { - parseStats(localCtx) + parseStats(using localCtx) } !reporter.hasErrors && needsMore } diff --git a/compiler/src/dotty/tools/repl/Rendering.scala b/compiler/src/dotty/tools/repl/Rendering.scala index 283978458b51..0c5874480562 100644 --- a/compiler/src/dotty/tools/repl/Rendering.scala +++ b/compiler/src/dotty/tools/repl/Rendering.scala @@ -33,7 +33,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { /** A `MessageRenderer` for the REPL without file positions */ private val messageRenderer = new MessageRendering { - override def posStr(pos: SourcePosition, diagnosticLevel: String, message: Message)(implicit ctx: Context): String = "" + override def posStr(pos: SourcePosition, diagnosticLevel: String, message: Message)(using Context): String = "" } private var myClassLoader: ClassLoader = _ @@ -42,7 +42,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { /** Class loader used to load compiled code */ - private[repl] def classLoader()(implicit ctx: Context) = + private[repl] def classLoader()(using Context) = if (myClassLoader != null) myClassLoader else { val parent = parentClassLoader.getOrElse { @@ -65,7 +65,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { } /** Return a String representation of a value we got from `classLoader()`. */ - private[repl] def replStringOf(value: Object)(implicit ctx: Context): String = { + private[repl] def replStringOf(value: Object)(using Context): String = { assert(myReplStringOf != null, "replStringOf should only be called on values creating using `classLoader()`, but `classLoader()` has not been called so far") myReplStringOf(value) @@ -75,7 +75,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { * * Calling this method evaluates the expression using reflection */ - private def valueOf(sym: Symbol)(implicit ctx: Context): Option[String] = { + private def valueOf(sym: Symbol)(using Context): Option[String] = { val objectName = sym.owner.fullName.encode.toString.stripSuffix("$") val resObj: Class[?] = Class.forName(objectName, true, classLoader()) val value = @@ -102,18 +102,18 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { dia.level ) - def renderTypeDef(d: Denotation)(implicit ctx: Context): Diagnostic = + def renderTypeDef(d: Denotation)(using Context): Diagnostic = infoDiagnostic("// defined " ++ d.symbol.showUser, d) - def renderTypeAlias(d: Denotation)(implicit ctx: Context): Diagnostic = + def renderTypeAlias(d: Denotation)(using Context): Diagnostic = infoDiagnostic("// defined alias " ++ d.symbol.showUser, d) /** Render method definition result */ - def renderMethod(d: Denotation)(implicit ctx: Context): Diagnostic = + def renderMethod(d: Denotation)(using Context): Diagnostic = infoDiagnostic(d.symbol.showUser, d) /** Render value definition result */ - def renderVal(d: Denotation)(implicit ctx: Context): Option[Diagnostic] = { + def renderVal(d: Denotation)(using Context): Option[Diagnostic] = { val dcl = d.symbol.showUser try { @@ -135,7 +135,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { sw.toString } - private def infoDiagnostic(msg: String, d: Denotation)(implicit ctx: Context): Diagnostic = + private def infoDiagnostic(msg: String, d: Denotation)(using Context): Diagnostic = new Diagnostic.Info(msg, d.symbol.sourcePos) } @@ -143,7 +143,7 @@ private[repl] class Rendering(parentClassLoader: Option[ClassLoader] = None) { object Rendering { implicit class ShowUser(val s: Symbol) extends AnyVal { - def showUser(implicit ctx: Context): String = { + def showUser(using Context): String = { val printer = new ReplPrinter(ctx) val text = printer.dclText(s) text.mkString(ctx.settings.pageWidth.value, ctx.settings.printLines.value) diff --git a/compiler/src/dotty/tools/repl/ReplCompiler.scala b/compiler/src/dotty/tools/repl/ReplCompiler.scala index c4cbfaee2d65..960a0aec84bc 100644 --- a/compiler/src/dotty/tools/repl/ReplCompiler.scala +++ b/compiler/src/dotty/tools/repl/ReplCompiler.scala @@ -41,11 +41,11 @@ class ReplCompiler extends Compiler { def newRun(initCtx: Context, state: State): Run = new Run(this, initCtx) { /** Import previous runs and user defined imports */ - override protected def rootContext(implicit ctx: Context): Context = { - def importContext(imp: tpd.Import)(implicit ctx: Context) = + override protected def rootContext(using Context): Context = { + def importContext(imp: tpd.Import)(using Context) = ctx.importContext(imp, imp.symbol) - def importPreviousRun(id: Int)(implicit ctx: Context) = { + def importPreviousRun(id: Int)(using Context) = { // we first import the wrapper object id val path = nme.EMPTY_PACKAGE ++ "." ++ objectNames(id) def importWrapper(c: Context, importGiven: Boolean) = { @@ -59,11 +59,11 @@ class ReplCompiler extends Compiler { val imports = state.imports.getOrElse(id, Nil) if (imports.isEmpty) ctx0 else imports.foldLeft(ctx0.fresh.setNewScope)((ctx, imp) => - importContext(imp)(ctx)) + importContext(imp)(using ctx)) } (1 to state.objectIndex).foldLeft(super.rootContext)((ctx, id) => - importPreviousRun(id)(ctx)) + importPreviousRun(id)(using ctx)) } } @@ -136,7 +136,7 @@ class ReplCompiler extends Compiler { PackageDef(Ident(nme.EMPTY_PACKAGE), List(module)) } - private def createUnit(defs: Definitions, span: Span)(implicit ctx: Context): CompilationUnit = { + private def createUnit(defs: Definitions, span: Span)(using Context): CompilationUnit = { val objectName = ctx.source.file.toString assert(objectName.startsWith(str.REPL_SESSION_LINE)) assert(objectName.endsWith(defs.state.objectIndex.toString)) @@ -159,7 +159,7 @@ class ReplCompiler extends Compiler { final def compile(parsed: Parsed)(implicit state: State): Result[(CompilationUnit, State)] = { assert(!parsed.trees.isEmpty) val defs = definitions(parsed.trees, state) - val unit = createUnit(defs, Span(0, parsed.trees.last.span.end))(state.context) + val unit = createUnit(defs, Span(0, parsed.trees.last.span.end))(using state.context) runCompilationUnit(unit, defs.state) } @@ -225,7 +225,7 @@ class ReplCompiler extends Compiler { final def typeCheck(expr: String, errorsAllowed: Boolean = false)(implicit state: State): Result[tpd.ValDef] = { - def wrapped(expr: String, sourceFile: SourceFile, state: State)(implicit ctx: Context): Result[untpd.PackageDef] = { + def wrapped(expr: String, sourceFile: SourceFile, state: State)(using Context): Result[untpd.PackageDef] = { def wrap(trees: List[untpd.Tree]): untpd.PackageDef = { import untpd._ @@ -252,7 +252,7 @@ class ReplCompiler extends Compiler { } } - def unwrapped(tree: tpd.Tree, sourceFile: SourceFile)(implicit ctx: Context): Result[tpd.ValDef] = { + def unwrapped(tree: tpd.Tree, sourceFile: SourceFile)(using Context): Result[tpd.ValDef] = { def error: Result[tpd.ValDef] = List(new Diagnostic.Error(s"Invalid scala expression", sourceFile.atSpan(Span(0, sourceFile.content.length)))).errors diff --git a/compiler/src/dotty/tools/repl/ReplFrontEnd.scala b/compiler/src/dotty/tools/repl/ReplFrontEnd.scala index 5c73a676baec..dd4fbc2a6ee7 100644 --- a/compiler/src/dotty/tools/repl/ReplFrontEnd.scala +++ b/compiler/src/dotty/tools/repl/ReplFrontEnd.scala @@ -13,9 +13,9 @@ import dotc.core.Contexts.{Context, ctx} */ private[repl] class REPLFrontEnd extends FrontEnd { - override def isRunnable(implicit ctx: Context): Boolean = true + override def isRunnable(using Context): Boolean = true - override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { assert(units.size == 1) // REPl runs one compilation unit at a time val unitContext = ctx.fresh.setCompilationUnit(units.head) diff --git a/compiler/src/dotty/tools/repl/ScriptEngine.scala b/compiler/src/dotty/tools/repl/ScriptEngine.scala index ac10be7f4574..8a1d3e7c2148 100644 --- a/compiler/src/dotty/tools/repl/ScriptEngine.scala +++ b/compiler/src/dotty/tools/repl/ScriptEngine.scala @@ -37,7 +37,7 @@ class ScriptEngine extends AbstractScriptEngine { val vid = state.valIndex state = driver.run(script)(state) val oid = state.objectIndex - Class.forName(s"${str.REPL_SESSION_LINE}$oid", true, rendering.classLoader()(state.context)) + Class.forName(s"${str.REPL_SESSION_LINE}$oid", true, rendering.classLoader()(using state.context)) .getDeclaredMethods.find(_.getName == s"${str.REPL_RES_PREFIX}$vid") .map(_.invoke(null)) .getOrElse(null) From 6e54aed6a1fe5e53788411f453956f887f3fd368 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 12:07:15 +0200 Subject: [PATCH 30/41] Convert test classes (1) --- .../dotc/classpath/ZipAndJarFileLookupFactory.scala | 1 + compiler/test/dotty/tools/CheckTypesTests.scala | 5 +++-- compiler/test/dotty/tools/DottyTest.scala | 2 +- compiler/test/dotty/tools/DottyTypeStealer.scala | 2 +- .../dotty/tools/backend/jvm/DottyBytecodeTest.scala | 4 ++-- compiler/test/dotty/tools/dotc/ast/DesugarTests.scala | 4 ++-- compiler/test/dotty/tools/dotc/ast/TreeInfoTest.scala | 3 ++- .../classpath/ZipAndJarFileLookupFactoryTest.scala | 4 ++-- .../tools/dotc/parsing/ModifiersParsingTest.scala | 4 ++-- .../test/dotty/tools/dotc/printing/PrinterTests.scala | 6 ++++-- .../dotc/reporting/UserDefinedErrorMessages.scala | 10 +++++----- .../dotc/transform/CreateCompanionObjectsTest.scala | 8 ++++---- .../dotc/transform/PostTyperTransformerTest.scala | 10 +++++----- .../tools/dotc/transform/TreeTransformerTest.scala | 10 +++++----- .../dotty/tools/dotc/typer/DivergenceChecker.scala | 2 +- .../tools/dotc/typer/SubtypingInvariantTests.scala | 2 +- compiler/test/dotty/tools/repl/ReplCompilerTests.scala | 3 ++- 17 files changed, 43 insertions(+), 37 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala index 75dcdf3c1979..8d74503fdcd3 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala @@ -12,6 +12,7 @@ import scala.annotation.tailrec import dotty.tools.io.{AbstractFile, ClassPath, ClassRepresentation, FileZipArchive, ManifestResources} import dotty.tools.dotc.core.Contexts.{Context, ctx} import FileUtils._ +import dotty.tools.dotc.core.Contexts.{Context, ctx} /** * A trait providing an optional cache for classpath entries obtained from zip and jar files. diff --git a/compiler/test/dotty/tools/CheckTypesTests.scala b/compiler/test/dotty/tools/CheckTypesTests.scala index 3e3e5a7a86f6..7a59bc3e5f20 100644 --- a/compiler/test/dotty/tools/CheckTypesTests.scala +++ b/compiler/test/dotty/tools/CheckTypesTests.scala @@ -5,6 +5,7 @@ import org.junit.Assert.{ assertFalse, assertTrue, fail } import dotc.ast.Trees._ import dotc.core.Decorators._ +import dotc.core.Contexts.{Context, ctx} class CheckTypeTest extends DottyTest { @Test @@ -27,7 +28,7 @@ class CheckTypeTest extends DottyTest { checkTypes(source, types: _*) { case (List(a, b, lu, li, lr, ls, la, lb), context) => - implicit val ctx = context + given Context = context assertTrue ( b <:< a) assertTrue (li <:< lu) @@ -59,7 +60,7 @@ class CheckTypeTest extends DottyTest { checkTypes(source, List(typesA, typesB)) { case (List(sups, subs), context) => - implicit val ctx = context + given Context = context sups.lazyZip(subs).foreach { (sup, sub) => assertTrue(sub <:< sup) } diff --git a/compiler/test/dotty/tools/DottyTest.scala b/compiler/test/dotty/tools/DottyTest.scala index ecb1eae5449c..1411c1419dbe 100644 --- a/compiler/test/dotty/tools/DottyTest.scala +++ b/compiler/test/dotty/tools/DottyTest.scala @@ -80,7 +80,7 @@ trait DottyTest extends ContextEscapeDetection { val gatheredSource = s"${source}\nobject A$dummyName {$vals}" checkCompile("typer", gatheredSource) { (tree, context) => - implicit val ctx = context + given Context = context val findValDef: (List[tpd.ValDef], tpd.Tree) => List[tpd.ValDef] = (acc , tree) => { tree match { diff --git a/compiler/test/dotty/tools/DottyTypeStealer.scala b/compiler/test/dotty/tools/DottyTypeStealer.scala index 80026def0881..0a80205fbacf 100644 --- a/compiler/test/dotty/tools/DottyTypeStealer.scala +++ b/compiler/test/dotty/tools/DottyTypeStealer.scala @@ -16,7 +16,7 @@ object DottyTypeStealer extends DottyTest { var tp: List[Type] = null checkCompile("typer", gatheredSource) { (tree, context) => - implicit val ctx = context + given Context = context val findValDef: (List[ValDef], tpd.Tree) => List[ValDef] = (acc , tree) => tree match { case t: ValDef if t.name.startsWith(dummyName) => t :: acc diff --git a/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala b/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala index c7de4b775f9b..54e719808133 100644 --- a/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala +++ b/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala @@ -4,7 +4,7 @@ package backend.jvm import vulpix.TestConfiguration -import dotc.core.Contexts.{Context, ContextBase} +import dotc.core.Contexts.{Context, ContextBase, ctx} import dotc.core.Comments.{ContextDoc, ContextDocstrings} import dotc.core.Phases.Phase import dotc.Compiler @@ -58,7 +58,7 @@ trait DottyBytecodeTest { /** Checks source code from raw strings */ def checkBCode(scalaSources: List[String], javaSources: List[String] = Nil)(checkOutput: AbstractFile => Unit): Unit = { - implicit val ctx: Context = initCtx + given Context = initCtx val compiler = new Compiler val run = compiler.newRun diff --git a/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala b/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala index ce36bc5eec0e..5177f4dc603c 100644 --- a/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala +++ b/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala @@ -23,7 +23,7 @@ class DesugarTests extends DottyTest { @Test def caseClassHasCorrectMembers: Unit = checkCompile("typer", "case class Foo(x: Int, y: String)") { (tree, context) => - implicit val ctx = context + given Context = context val ccTree = tree.find(tree => tree.symbol.name == typeName("Foo")).get val List(_, foo) = defPath(ccTree.symbol, tree).map(_.symbol.info) @@ -38,7 +38,7 @@ class DesugarTests extends DottyTest { @Test def caseClassCompanionHasCorrectMembers: Unit = checkCompile("typer", "case class Foo(x: Int, y: String)") { (tree, context) => - implicit val ctx = context + given Context = context val ccTree = tree.find(tree => tree.symbol.name == termName("Foo")).get val List(_, foo) = defPath(ccTree.symbol, tree).map(_.symbol.info) diff --git a/compiler/test/dotty/tools/dotc/ast/TreeInfoTest.scala b/compiler/test/dotty/tools/dotc/ast/TreeInfoTest.scala index 2df74c1eed65..b8e011c8c8dd 100644 --- a/compiler/test/dotty/tools/dotc/ast/TreeInfoTest.scala +++ b/compiler/test/dotty/tools/dotc/ast/TreeInfoTest.scala @@ -8,6 +8,7 @@ import core.StdNames.nme import core.Types._ import core.Symbols._ import org.junit.Assert._ +import core.Contexts.{Context, ctx} class TreeInfoTest extends DottyTest { @@ -16,7 +17,7 @@ class TreeInfoTest extends DottyTest { @Test def testDefPath: Unit = checkCompile("typer", "class A { def bar = { val x = { val z = 0; 0} }} ") { (tree, context) => - implicit val ctx = context + given Context = context val xTree = tree.find(tree => tree.symbol.name == termName("x")).get val path = defPath(xTree.symbol, tree) assertEquals(List( diff --git a/compiler/test/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactoryTest.scala b/compiler/test/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactoryTest.scala index f929df085fe4..439f5ed6a019 100644 --- a/compiler/test/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactoryTest.scala +++ b/compiler/test/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactoryTest.scala @@ -4,7 +4,7 @@ import org.junit.Test import java.nio.file._ import java.nio.file.attribute.FileTime -import dotty.tools.dotc.core.Contexts.{Context, ContextBase} +import dotty.tools.dotc.core.Contexts.{Context, ContextBase, ctx} import dotty.tools.io.AbstractFile @@ -16,7 +16,7 @@ class ZipAndJarFileLookupFactoryTest { val f = Files.createTempFile("test-", ".jar") Files.delete(f) - implicit val ctx: Context = new ContextBase().initialCtx + given Context = new ContextBase().initialCtx assert(!ctx.settings.YdisableFlatCpCaching.value) // we're testing with our JAR metadata caching enabled. def createCp = ZipAndJarClassPathFactory.create(AbstractFile.getFile(f)) diff --git a/compiler/test/dotty/tools/dotc/parsing/ModifiersParsingTest.scala b/compiler/test/dotty/tools/dotc/parsing/ModifiersParsingTest.scala index ef7264033a04..edb29b855e65 100644 --- a/compiler/test/dotty/tools/dotc/parsing/ModifiersParsingTest.scala +++ b/compiler/test/dotty/tools/dotc/parsing/ModifiersParsingTest.scala @@ -14,7 +14,7 @@ import core.Contexts._ import core.Flags object ModifiersParsingTest { - implicit val ctx: Context = (new ContextBase).initialCtx + given Context = (new ContextBase).initialCtx def parse(code: String): Tree = { val (_, stats) = new Parser(SourceFile.virtual("", code)).templateStatSeq() @@ -74,7 +74,7 @@ object ModifiersParsingTest { class ModifiersParsingTest { - import ModifiersParsingTest._ + import ModifiersParsingTest.{_, given _} @Test def valDef = { diff --git a/compiler/test/dotty/tools/dotc/printing/PrinterTests.scala b/compiler/test/dotty/tools/dotc/printing/PrinterTests.scala index 4bbe5c3aae55..acf7610238a2 100644 --- a/compiler/test/dotty/tools/dotc/printing/PrinterTests.scala +++ b/compiler/test/dotty/tools/dotc/printing/PrinterTests.scala @@ -5,6 +5,8 @@ import dotty.tools.dotc.ast.{Trees,tpd} import dotty.tools.dotc.core.Names._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Decorators._ +import dotty.tools.dotc.core.Contexts.{Context, ctx} + import org.junit.Assert.assertEquals import org.junit.Test @@ -26,7 +28,7 @@ class PrinterTests extends DottyTest { """ checkCompile("typer", source) { (tree, context) => - implicit val ctx = context + given Context = context val bar = tree.find(tree => tree.symbol.name == termName("bar")).get assertEquals("package object foo", bar.symbol.owner.show) } @@ -43,7 +45,7 @@ class PrinterTests extends DottyTest { """.stripMargin checkCompile("typer", source) { (tree, context) => - implicit val ctx = context + given Context = context val bar @ Trees.DefDef(_, _, _, _, _) = tree.find(tree => tree.symbol.name == termName("bar2")).get assertEquals("Int & (Boolean | String)", bar.tpt.show) } diff --git a/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala b/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala index 51d31de5424d..5ce44bada89e 100644 --- a/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala +++ b/compiler/test/dotty/tools/dotc/reporting/UserDefinedErrorMessages.scala @@ -24,7 +24,7 @@ class UserDefinedErrorMessages extends ErrorMessagesTest { |} """.stripMargin }.expect { (itcx, messages) => - implicit val ctx: Context = itcx + given Context = itcx assertMessageCount(1, messages) val (m: NoExplanation) :: Nil = messages @@ -48,7 +48,7 @@ class UserDefinedErrorMessages extends ErrorMessagesTest { |} """.stripMargin }.expect { (itcx, messages) => - implicit val ctx: Context = itcx + given Context = itcx assertMessageCount(1, messages) val (m: NoExplanation) :: Nil = messages @@ -73,7 +73,7 @@ class UserDefinedErrorMessages extends ErrorMessagesTest { |} """.stripMargin }.expect { (itcx, messages) => - implicit val ctx: Context = itcx + given Context = itcx assertMessageCount(1, messages) val (m: NoExplanation) :: Nil = messages @@ -95,7 +95,7 @@ class UserDefinedErrorMessages extends ErrorMessagesTest { |} """.stripMargin }.expect { (itcx, messages) => - implicit val ctx: Context = itcx + given Context = itcx assertMessageCount(1, messages) val (m: NoExplanation) :: Nil = messages @@ -117,7 +117,7 @@ class UserDefinedErrorMessages extends ErrorMessagesTest { |} """.stripMargin }.expect { (itcx, messages) => - implicit val ctx: Context = itcx + given Context = itcx assertMessageCount(1, messages) val (m: NoExplanation) :: Nil = messages diff --git a/compiler/test/dotty/tools/dotc/transform/CreateCompanionObjectsTest.scala b/compiler/test/dotty/tools/dotc/transform/CreateCompanionObjectsTest.scala index a2095aec04f2..fa811ccbb9c7 100644 --- a/compiler/test/dotty/tools/dotc/transform/CreateCompanionObjectsTest.scala +++ b/compiler/test/dotty/tools/dotc/transform/CreateCompanionObjectsTest.scala @@ -25,7 +25,7 @@ class CreateCompanionObjectsTest extends DottyTest { @Test def shouldCreateNonExistingObjectsInPackage = checkCompile("typer", "class A{} ") { (tree, context) => - implicit val ctx = context + given Context = context val transformer = new PostTyperTransformer { override def transformations = Array(new CreateCompanionObjects { @@ -51,7 +51,7 @@ class CreateCompanionObjectsTest extends DottyTest { @Test def shouldCreateNonExistingObjectsInBlock = checkCompile("typer", "class D {def p = {class A{}; 1}} ") { (tree, context) => - implicit val ctx = context + given Context = context val transformer = new PostTyperTransformer { override def transformations = Array(new CreateCompanionObjects { @@ -76,7 +76,7 @@ class CreateCompanionObjectsTest extends DottyTest { @Test def shouldCreateNonExistingObjectsInTemplate = checkCompile("typer", "class D {class A{}; } ") { (tree, context) => - implicit val ctx = context + given Context = context val transformer = new PostTyperTransformer { override def transformations = Array(new CreateCompanionObjects { override def name: String = "create all companion modules" @@ -100,7 +100,7 @@ class CreateCompanionObjectsTest extends DottyTest { @Test def shouldCreateOnlyIfAskedFor = checkCompile("typer", "class DONT {class CREATE{}; } ") { (tree, context) => - implicit val ctx = context + given Context = context val transformer = new PostTyperTransformer { override def transformations = Array(new CreateCompanionObjects { override def name: String = "create all companion modules" diff --git a/compiler/test/dotty/tools/dotc/transform/PostTyperTransformerTest.scala b/compiler/test/dotty/tools/dotc/transform/PostTyperTransformerTest.scala index d2e7c02f1eca..1e6687617083 100644 --- a/compiler/test/dotty/tools/dotc/transform/PostTyperTransformerTest.scala +++ b/compiler/test/dotty/tools/dotc/transform/PostTyperTransformerTest.scala @@ -20,7 +20,7 @@ class PostTyperTransformerTest extends DottyTest { @Test def shouldStripImports = checkCompile("typer", "class A{ import scala.collection.mutable._; val d = 1}") { (tree, context) => - implicit val ctx = context + given Context = context class EmptyTransform extends TreeTransform { override def name: String = "empty" init(ctx, ctx.period.firstPhaseId, ctx.period.lastPhaseId) @@ -40,7 +40,7 @@ class PostTyperTransformerTest extends DottyTest { @Test def shouldStripNamedArgs = checkCompile("typer", "class A{ def p(x:Int, y:Int= 2) = 1; p(1, y = 2)}") { (tree, context) => - implicit val ctx = context + given Context = context class EmptyTransform extends TreeTransform { override def name: String = "empty" init(ctx, ctx.period.firstPhaseId, ctx.period.lastPhaseId) @@ -60,7 +60,7 @@ class PostTyperTransformerTest extends DottyTest { @Test def shouldReorderExistingObjectsInPackage = checkCompile("typer", "object A{}; class A{} ") { (tree, context) => - implicit val ctx = context + given Context = context class EmptyTransform extends TreeTransform { override def name: String = "empty" init(ctx, ctx.period.firstPhaseId, ctx.period.lastPhaseId) @@ -84,7 +84,7 @@ class PostTyperTransformerTest extends DottyTest { @Test def shouldReorderExistingObjectsInBlock = checkCompile("typer", "class D {def p = {object A{}; class A{}; 1}} ") { (tree, context) => - implicit val ctx = context + given Context = context class EmptyTransform extends TreeTransform { override def name: String = "empty" init(ctx, ctx.period.firstPhaseId, ctx.period.lastPhaseId) @@ -108,7 +108,7 @@ class PostTyperTransformerTest extends DottyTest { @Test def shouldReorderExistingObjectsInTemplate = checkCompile("typer", "class D {object A{}; class A{}; } ") { (tree, context) => - implicit val ctx = context + given Context = context class EmptyTransform extends TreeTransform { override def name: String = "empty" init(ctx, ctx.period.firstPhaseId, ctx.period.lastPhaseId) diff --git a/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala b/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala index f75bb70023cc..ba8d06aaa70f 100644 --- a/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala +++ b/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala @@ -13,7 +13,7 @@ class TreeTransformerTest extends DottyTest { @Test def shouldReturnSameTreeIfUnchanged: Unit = checkCompile("typer", "class A{ val d = 1}") { (tree, context) => - implicit val ctx = context + given Context = context class EmptyTransform extends MiniPhase { override def phaseName: String = "empty" init(ctx.base, ctx.period.firstPhaseId, ctx.period.lastPhaseId) @@ -29,7 +29,7 @@ class TreeTransformerTest extends DottyTest { // Disabled, awaiting resolution. @Test def canReplaceConstant: Unit = checkCompile("typer", "class A{ val d = 1}") { (tree, context) => - implicit val ctx = context + given Context = context class ConstantTransform extends MiniPhase { override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = tpd.Literal(Constant(2)) @@ -47,7 +47,7 @@ class TreeTransformerTest extends DottyTest { @Test def canOverwrite: Unit = checkCompile("typer", "class A{ val d = 1}") { (tree, context) => - implicit val ctx = context + given Context = context class Transformation extends MiniPhase { override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = tpd.Literal(Constant(-1)) @@ -73,7 +73,7 @@ class TreeTransformerTest extends DottyTest { @Test def transformationOrder: Unit = checkCompile("typer", "class A{ val d = 1}") { (tree, context) => - implicit val ctx = context + given Context = context class Transformation1 extends MiniPhase { override def phaseName: String = "transformationOrder1" @@ -115,7 +115,7 @@ class TreeTransformerTest extends DottyTest { @Test def invocationCount: Unit = checkCompile("typer", "class A{ val d = 1}") { (tree, context) => - implicit val ctx = context + given Context = context var transformed1 = 0 class Transformation1 extends MiniPhase { override def phaseName: String = "invocationCount1" diff --git a/compiler/test/dotty/tools/dotc/typer/DivergenceChecker.scala b/compiler/test/dotty/tools/dotc/typer/DivergenceChecker.scala index fc0fa7c3d734..228d24dd1df0 100644 --- a/compiler/test/dotty/tools/dotc/typer/DivergenceChecker.scala +++ b/compiler/test/dotty/tools/dotc/typer/DivergenceChecker.scala @@ -33,7 +33,7 @@ class DivergenceCheckerTests extends DottyTest { checkTypes(source, List(types, elements)) { case (List(tpes, elements0), context) => - implicit val ctx = context + given Context = context val List(a, b, n, o, s, t2, i, l) = elements0.map(_.typeConstructor) val expectedCoveringSets = List( diff --git a/compiler/test/dotty/tools/dotc/typer/SubtypingInvariantTests.scala b/compiler/test/dotty/tools/dotc/typer/SubtypingInvariantTests.scala index af27154d8c66..eb9ccf5f0619 100644 --- a/compiler/test/dotty/tools/dotc/typer/SubtypingInvariantTests.scala +++ b/compiler/test/dotty/tools/dotc/typer/SubtypingInvariantTests.scala @@ -11,7 +11,7 @@ class SubtypingInvariantTests extends DottyTest { @Test def typeVarInvariant(): Unit = { checkCompile("typer", "class A") { (_, ctx0) => - implicit val ctx: Context = ctx0 + given Context = ctx0 val a = newTypeVar(TypeBounds.empty) val b = newTypeVar(TypeBounds.empty) assert(a <:< b) diff --git a/compiler/test/dotty/tools/repl/ReplCompilerTests.scala b/compiler/test/dotty/tools/repl/ReplCompilerTests.scala index 5b3835666d2a..681ce83d22a2 100644 --- a/compiler/test/dotty/tools/repl/ReplCompilerTests.scala +++ b/compiler/test/dotty/tools/repl/ReplCompilerTests.scala @@ -4,6 +4,7 @@ import java.util.regex.Pattern import org.junit.Assert.{assertTrue => assert, _} import org.junit.{Ignore, Test} +import dotty.tools.dotc.core.Contexts.Context class ReplCompilerTests extends ReplTest { import ReplCompilerTests._ @@ -189,7 +190,7 @@ class ReplCompilerTests extends ReplTest { } @Test def i7934: Unit = fromInitialState { state => - implicit val ctx = state.context + given Context = state.context assertFalse(ParseResult.isIncomplete("_ + 1")) // was: assertThrows[NullPointerException] } From f71a4b3b6653a73847c3beab31a11ae4078798c8 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 12:09:28 +0200 Subject: [PATCH 31/41] Convert test classes (2) --- compiler/test/dotty/tools/DottyTest.scala | 2 +- .../tools/dotc/EntryPointsTest.scala.disabled | 2 +- .../dotty/tools/dotc/ast/DesugarTests.scala | 2 +- .../tools/dotc/ast/UntypedTreeMapTest.scala | 2 +- .../tools/dotc/parsing/DeSugarTest.scala | 6 +++--- .../tools/dotc/parsing/parsePackage.scala | 2 +- .../dotc/reporting/TestMessageLaziness.scala | 6 +++--- .../tools/dotc/reporting/TestReporter.scala | 8 ++++---- .../dotc/transform/TreeTransformerTest.scala | 20 +++++++++---------- .../dotty/tools/vulpix/ParallelTesting.scala | 2 +- 10 files changed, 26 insertions(+), 26 deletions(-) diff --git a/compiler/test/dotty/tools/DottyTest.scala b/compiler/test/dotty/tools/DottyTest.scala index 1411c1419dbe..b3b5c2f2fca6 100644 --- a/compiler/test/dotty/tools/DottyTest.scala +++ b/compiler/test/dotty/tools/DottyTest.scala @@ -54,7 +54,7 @@ trait DottyTest extends ContextEscapeDetection { val lastGroup = allPhases.find(x => x.contains(targetPhase)).get.takeWhile(x => !(x eq targetPhase)) val checker = new Phase { def phaseName = "assertionChecker" - override def run(implicit ctx: Context): Unit = assertion(ctx.compilationUnit.tpdTree, ctx) + override def run(using ctx: Context): Unit = assertion(ctx.compilationUnit.tpdTree, ctx) } val lastGroupAppended = List(lastGroup ::: targetPhase :: Nil) diff --git a/compiler/test/dotty/tools/dotc/EntryPointsTest.scala.disabled b/compiler/test/dotty/tools/dotc/EntryPointsTest.scala.disabled index e759dd1b0b25..f5b5fbf1bcc9 100644 --- a/compiler/test/dotty/tools/dotc/EntryPointsTest.scala.disabled +++ b/compiler/test/dotty/tools/dotc/EntryPointsTest.scala.disabled @@ -50,7 +50,7 @@ class EntryPointsTest { private class CustomReporter extends Reporter with UniqueMessagePositions with HideNonSensicalMessages { - def doReport(m: Diagnostic)(implicit ctx: Context): Unit = { + def doReport(m: Diagnostic)(using Context): Unit = { } } diff --git a/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala b/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala index 5177f4dc603c..0242e730913d 100644 --- a/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala +++ b/compiler/test/dotty/tools/dotc/ast/DesugarTests.scala @@ -11,7 +11,7 @@ import org.junit.Assert._ class DesugarTests extends DottyTest { import tpd._ - private def validSym(sym: Symbol)(implicit ctx: Context): Unit = { + private def validSym(sym: Symbol)(using Context): Unit = { assert( // remaining symbols must be either synthetic: sym.is(Synthetic) || diff --git a/compiler/test/dotty/tools/dotc/ast/UntypedTreeMapTest.scala b/compiler/test/dotty/tools/dotc/ast/UntypedTreeMapTest.scala index 1633cfaa9b57..472e47d859f3 100644 --- a/compiler/test/dotty/tools/dotc/ast/UntypedTreeMapTest.scala +++ b/compiler/test/dotty/tools/dotc/ast/UntypedTreeMapTest.scala @@ -22,7 +22,7 @@ class UntpdTreeMapTest extends DottyTest { def testMapInterpolatedString = { val tree = parse(""" q"hello ${2017}!" """) val identity = new UntypedTreeMap { - override def transform(tree: Tree)(implicit ctx: Context): Tree = tree match { + override def transform(tree: Tree)(using Context): Tree = tree match { case _ => super.transform(tree) } } diff --git a/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala b/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala index 4dcc98868f07..b19c35244854 100644 --- a/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala +++ b/compiler/test/dotty/tools/dotc/parsing/DeSugarTest.scala @@ -31,10 +31,10 @@ class DeSugarTest extends ParserTest { finally curMode = saved } - def transform(tree: Tree, mode: Mode)(implicit ctx: Context): Tree = withMode(mode) { transform(tree) } - def transform(trees: List[Tree], mode: Mode)(implicit ctx: Context): List[Tree] = withMode(mode) { transform(trees) } + def transform(tree: Tree, mode: Mode)(using Context): Tree = withMode(mode) { transform(tree) } + def transform(trees: List[Tree], mode: Mode)(using Context): List[Tree] = withMode(mode) { transform(trees) } - override def transform(tree: Tree)(implicit ctx: Context): Tree = { + override def transform(tree: Tree)(using Context): Tree = { val tree1 = desugar(tree)(using ctx.withModeBits(curMode)) tree1 match { case TypedSplice(t) => diff --git a/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala b/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala index a99b22a7dfa8..f55da0d9a7d0 100644 --- a/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala +++ b/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala @@ -14,7 +14,7 @@ object parsePackage extends ParserTest { var nodes = 0 val transformer = new UntypedTreeMap { - override def transform(tree: Tree)(implicit ctx: Context): Tree = { + override def transform(tree: Tree)(using Context): Tree = { nodes += 1 tree match { case Ident(name) => diff --git a/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala b/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala index bd90ef6075ba..e0db4a77c9d2 100644 --- a/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala +++ b/compiler/test/dotty/tools/dotc/reporting/TestMessageLaziness.scala @@ -9,11 +9,11 @@ import core.Contexts._ class TestMessageLaziness extends DottyTest { ctx = ctx.fresh.setReporter(new NonchalantReporter) - class NonchalantReporter(implicit ctx: Context) extends Reporter + class NonchalantReporter(using Context) extends Reporter with UniqueMessagePositions with HideNonSensicalMessages { - def doReport(dia: Diagnostic)(implicit ctx: Context) = ??? + def doReport(dia: Diagnostic)(using Context) = ??? - override def report(dia: Diagnostic)(implicit ctx: Context) = () + override def report(dia: Diagnostic)(using Context) = () } case class LazyError() extends Message(ErrorMessageID.LazyErrorId) { diff --git a/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala b/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala index c935b579b234..6dbdebd33208 100644 --- a/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala +++ b/compiler/test/dotty/tools/dotc/reporting/TestReporter.scala @@ -33,7 +33,7 @@ extends Reporter with UniqueMessagePositions with HideNonSensicalMessages with M private var _didCrash = false final def compilerCrashed: Boolean = _didCrash - protected final def inlineInfo(pos: SourcePosition)(implicit ctx: Context): String = + protected final def inlineInfo(pos: SourcePosition)(using Context): String = if (pos.exists) { if (pos.outer.exists) i"\ninlined at ${pos.outer}:\n" + inlineInfo(pos.outer) @@ -53,7 +53,7 @@ extends Reporter with UniqueMessagePositions with HideNonSensicalMessages with M } /** Prints the message with the given position indication. */ - def printMessageAndPos(dia: Diagnostic, extra: String)(implicit ctx: Context): Unit = { + def printMessageAndPos(dia: Diagnostic, extra: String)(using Context): Unit = { val msg = messageAndPos(dia.msg, dia.pos, diagnosticLevel(dia)) val extraInfo = inlineInfo(dia.pos) @@ -66,7 +66,7 @@ extends Reporter with UniqueMessagePositions with HideNonSensicalMessages with M if (extraInfo.nonEmpty) _messageBuf.append(extraInfo) } - override def doReport(dia: Diagnostic)(implicit ctx: Context): Unit = { + override def doReport(dia: Diagnostic)(using Context): Unit = { // Here we add extra information that we should know about the error message val extra = dia.msg match { @@ -125,7 +125,7 @@ object TestReporter { def simplifiedReporter(writer: PrintWriter): TestReporter = { val rep = new TestReporter(writer, logPrintln, WARNING) { /** Prints the message with the given position indication in a simplified manner */ - override def printMessageAndPos(dia: Diagnostic, extra: String)(implicit ctx: Context): Unit = { + override def printMessageAndPos(dia: Diagnostic, extra: String)(using Context): Unit = { def report() = { val msg = s"${dia.pos.line + 1}: " + dia.msg.kind + extra val extraInfo = inlineInfo(dia.pos) diff --git a/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala b/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala index ba8d06aaa70f..b1b6ca0e0222 100644 --- a/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala +++ b/compiler/test/dotty/tools/dotc/transform/TreeTransformerTest.scala @@ -32,7 +32,7 @@ class TreeTransformerTest extends DottyTest { given Context = context class ConstantTransform extends MiniPhase { - override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = tpd.Literal(Constant(2)) + override def transformLiteral(tree: tpd.Literal)(using Context): tpd.Tree = tpd.Literal(Constant(2)) override def phaseName: String = "canReplaceConstant" init(ctx.base, ctx.period.firstPhaseId, ctx.period.lastPhaseId) } @@ -50,10 +50,10 @@ class TreeTransformerTest extends DottyTest { given Context = context class Transformation extends MiniPhase { - override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = tpd.Literal(Constant(-1)) + override def transformLiteral(tree: tpd.Literal)(using Context): tpd.Tree = tpd.Literal(Constant(-1)) override def phaseName: String = "canOverwrite" - override def transformValDef(tree: tpd.ValDef)(implicit ctx: Context): tpd.ValDef = { + override def transformValDef(tree: tpd.ValDef)(using Context): tpd.ValDef = { Assert.assertTrue("transformation of children succeeded", tree.rhs.toString == "Literal(Constant(-1))" ) @@ -77,14 +77,14 @@ class TreeTransformerTest extends DottyTest { class Transformation1 extends MiniPhase { override def phaseName: String = "transformationOrder1" - override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = { + override def transformLiteral(tree: tpd.Literal)(using Context): tpd.Tree = { Assert.assertTrue("correct constant", tree.const.toString == "Constant(1)" ) tpd.cpy.Literal(tree)(Constant(-1)) } - override def transformValDef(tree: tpd.ValDef)(implicit ctx: Context): tpd.ValDef = { + override def transformValDef(tree: tpd.ValDef)(using Context): tpd.ValDef = { Assert.assertTrue("transformation of children succeeded", tree.rhs.toString == "Literal(Constant(-1))" ) @@ -95,7 +95,7 @@ class TreeTransformerTest extends DottyTest { } class Transformation2 extends MiniPhase { override def phaseName: String = "transformationOrder2" - override def transformValDef(tree: tpd.ValDef)(implicit ctx: Context): tpd.ValDef = { + override def transformValDef(tree: tpd.ValDef)(using Context): tpd.ValDef = { Assert.assertTrue("transformation of children succeeded", tree.rhs.toString == "Literal(Constant(2))" ) @@ -119,7 +119,7 @@ class TreeTransformerTest extends DottyTest { var transformed1 = 0 class Transformation1 extends MiniPhase { override def phaseName: String = "invocationCount1" - override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = { + override def transformLiteral(tree: tpd.Literal)(using Context): tpd.Tree = { transformed1 += 1 Assert.assertTrue("correct constant", tree.const.toString == "Constant(1)" @@ -127,7 +127,7 @@ class TreeTransformerTest extends DottyTest { tpd.cpy.Literal(tree)(Constant(-1)) } - override def transformValDef(tree: tpd.ValDef)(implicit ctx: Context) = { + override def transformValDef(tree: tpd.ValDef)(using Context) = { transformed1 += 1 Assert.assertTrue("transformation of children succeeded", tree.rhs.toString == "Literal(Constant(-3))" @@ -141,7 +141,7 @@ class TreeTransformerTest extends DottyTest { class Transformation2 extends MiniPhase { var constantsSeen = 0 override def phaseName: String = "invocationCount2" - override def transformLiteral(tree: tpd.Literal)(implicit ctx: Context): tpd.Tree = { + override def transformLiteral(tree: tpd.Literal)(using Context): tpd.Tree = { transformed2 += 1 constantsSeen match { case 0 => @@ -158,7 +158,7 @@ class TreeTransformerTest extends DottyTest { tpd.cpy.Literal(tree)(Constant(-3)) } - override def transformValDef(tree: tpd.ValDef)(implicit ctx: Context) = { + override def transformValDef(tree: tpd.ValDef)(using Context) = { transformed2 += 1 Assert.assertTrue("transformation of children succeeded", tree.rhs.toString == "Literal(Constant(-3))" diff --git a/compiler/test/dotty/tools/vulpix/ParallelTesting.scala b/compiler/test/dotty/tools/vulpix/ParallelTesting.scala index 30c0df405054..77d9ab4c132f 100644 --- a/compiler/test/dotty/tools/vulpix/ParallelTesting.scala +++ b/compiler/test/dotty/tools/vulpix/ParallelTesting.scala @@ -467,7 +467,7 @@ trait ParallelTesting extends RunnerOrchestration { self => private def ntimes(n: Int)(op: Int => Reporter): Reporter = (1 to n).foldLeft(emptyReporter) ((_, i) => op(i)) - override def doCompile(comp: Compiler, files: List[String])(implicit ctx: Context) = + override def doCompile(comp: Compiler, files: List[String])(using Context) = ntimes(times) { run => val start = System.nanoTime() val rep = super.doCompile(comp, files) From b76d2e42c48b0b5895427206f06afb28237637b1 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 12:23:48 +0200 Subject: [PATCH 32/41] Make Contexts.ctx an inline function --- compiler/src/dotty/tools/dotc/core/Contexts.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 4d3b5e6b52d2..6c29eb504d47 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -51,7 +51,7 @@ object Contexts { private val initialStore = store8 /** The current context */ - def ctx(using ctx: Context): Context = ctx + inline def ctx(using ctx: Context): Context = ctx /** Run `op` with given context */ inline def inContext[T](c: Context)(inline op: Context ?=> T): T = From a9c405fccd72d1c8feebeb843b129773f5925f0f Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 11:24:49 +0200 Subject: [PATCH 33/41] Omit redundant (using ctx) --- .../dotty/tools/backend/jvm/GenBCode.scala | 11 +-- compiler/src/dotty/tools/dotc/Resident.scala | 4 +- .../ZipAndJarFileLookupFactory.scala | 1 - .../dotty/tools/dotc/core/Definitions.scala | 2 +- .../dotty/tools/dotc/core/SymbolLoaders.scala | 2 +- .../dotty/tools/dotc/core/TyperState.scala | 2 +- .../tools/dotc/core/tasty/TreeUnpickler.scala | 7 +- .../tools/dotc/interactive/Interactive.scala | 2 +- .../dotty/tools/dotc/reporting/Reporter.scala | 2 +- .../tools/dotc/sbt/ExtractDependencies.scala | 2 +- .../dotty/tools/dotc/transform/CtxLazy.scala | 2 +- .../dotty/tools/dotc/transform/LazyVals.scala | 2 +- .../tools/dotc/transform/MegaPhase.scala | 70 +++++++++---------- .../dotc/transform/PCPCheckAndHeal.scala | 2 +- .../tools/dotc/transform/TreeChecker.scala | 8 ++- .../dotty/tools/dotc/typer/Applications.scala | 2 +- .../dotty/tools/dotc/typer/Implicits.scala | 2 +- .../dotty/tools/dotc/typer/ImportInfo.scala | 2 +- .../dotty/tools/dotc/typer/Synthesizer.scala | 4 +- .../tools/dotc/typer/VarianceChecker.scala | 2 +- .../dotty/tools/dotc/util/ParsedComment.scala | 13 ++-- .../tools/dotc/parsing/desugarPackage.scala | 2 +- .../tools/dotc/parsing/parsePackage.scala | 2 +- 23 files changed, 78 insertions(+), 70 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index ff32aa3733ff..3082e851fd21 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -46,10 +46,13 @@ class GenBCode extends Phase { myOutput } - def run(using Context): Unit = { - new GenBCodePipeline(new DottyBackendInterface( - outputDir, superCallsMap.toMap)(using ctx))(using ctx).run(ctx.compilationUnit.tpdTree) - } + def run(using Context): Unit = + new GenBCodePipeline( + new DottyBackendInterface( + outputDir, superCallsMap.toMap + ) + ).run(ctx.compilationUnit.tpdTree) + override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = { try super.runOn(units) diff --git a/compiler/src/dotty/tools/dotc/Resident.scala b/compiler/src/dotty/tools/dotc/Resident.scala index 3a2df21b151d..116011942bd4 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} +import core.Contexts.{Context, ctx, inContext} import reporting.Reporter import java.io.EOFException import scala.annotation.tailrec @@ -41,7 +41,7 @@ class Resident extends Driver { final override def process(args: Array[String], rootCtx: Context): Reporter = { @tailrec def loop(args: Array[String], prevCtx: Context): Reporter = { var (fileNames, ctx) = setup(args, prevCtx) - doCompile(residentCompiler, fileNames)(using ctx) + inContext(ctx){doCompile(residentCompiler, fileNames)} var nextCtx = ctx var line = getLine() while (line == reset) { diff --git a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala index 8d74503fdcd3..75dcdf3c1979 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ZipAndJarFileLookupFactory.scala @@ -12,7 +12,6 @@ import scala.annotation.tailrec import dotty.tools.io.{AbstractFile, ClassPath, ClassRepresentation, FileZipArchive, ManifestResources} import dotty.tools.dotc.core.Contexts.{Context, ctx} import FileUtils._ -import dotty.tools.dotc.core.Contexts.{Context, ctx} /** * A trait providing an optional cache for classpath entries obtained from zip and jar files. diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index b6df0be591d9..e4a651325d9e 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -1012,7 +1012,7 @@ class Definitions { else if (isErased) ctx.requiredClass("scala.ErasedFunction" + n.toString) else if (n <= MaxImplementedFunctionArity) - FunctionClassPerRun()(using ctx)(n) + FunctionClassPerRun()(n) else ctx.requiredClass("scala.Function" + n.toString) diff --git a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala index 8d0fcede5f6e..8409ce080360 100644 --- a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala +++ b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala @@ -285,7 +285,7 @@ object SymbolLoaders { enterFlatClasses = Some { ctx => enterFlatClasses = None - enterClasses(root, packageName, flat = true)(using ctx) + inContext(ctx){enterClasses(root, packageName, flat = true)} } enterClasses(root, packageName, flat = false) if (!root.isEmptyPackage) diff --git a/compiler/src/dotty/tools/dotc/core/TyperState.scala b/compiler/src/dotty/tools/dotc/core/TyperState.scala index aace096fb776..c3e8db6b2db8 100644 --- a/compiler/src/dotty/tools/dotc/core/TyperState.scala +++ b/compiler/src/dotty/tools/dotc/core/TyperState.scala @@ -113,7 +113,7 @@ class TyperState(private val previous: TyperState /* | Null */) { testReporter.inUse = true testReporter } - try op(using ctx) + try op finally { testReporter.inUse = false resetConstraintTo(savedConstraint) diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index 81ff5890cab7..df415c73ac67 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -964,8 +964,9 @@ class TreeUnpickler(reader: TastyReader, readImport() case PACKAGE => val start = currentAddr - processPackage { (pid, end) => implicit ctx => - setSpan(start, PackageDef(pid, readIndexedStats(exprOwner, end)(using ctx))) + processPackage { (pid, end) => ctx => + given Context = ctx + setSpan(start, PackageDef(pid, readIndexedStats(exprOwner, end))) } case _ => readTerm()(using ctx.withOwner(exprOwner)) @@ -1054,7 +1055,7 @@ class TreeUnpickler(reader: TastyReader, ConstFold(untpd.Select(qual, name).withType(tpe)) def completeSelect(name: Name, sig: Signature): Select = - val qual = readTerm()(using ctx) + val qual = readTerm() val denot = accessibleDenot(qual.tpe.widenIfUnstable, name, sig) makeSelect(qual, name, denot) diff --git a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala index e5bffb2428b6..938cd3230054 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala @@ -269,7 +269,7 @@ object Interactive { case first :: _ if first eq stat => ctx.exprContext(stat, exprOwner) case (imp: Import) :: rest => - contextOfStat(rest, stat, exprOwner, ctx.importContext(imp, imp.symbol(using ctx))) + contextOfStat(rest, stat, exprOwner, ctx.importContext(imp, inContext(ctx){imp.symbol})) case _ :: rest => contextOfStat(rest, stat, exprOwner, ctx) } diff --git a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala index fbf2031adb97..b846ba7d9f17 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala @@ -146,7 +146,7 @@ trait Reporting { thisCtx: Context => error(msg.mapMsg("Implementation restriction: " + _), pos) def incompleteInputError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - reporter.incomplete(new Error(msg, pos))(using 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 diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala index 9044a7e9f71a..fa58b4a7c569 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractDependencies.scala @@ -415,7 +415,7 @@ private class ExtractDependenciesCollector extends tpd.TreeTraverser { thisTreeT * The tests in sbt `types-in-used-names-a`, `types-in-used-names-b`, * `as-seen-from-a` and `as-seen-from-b` rely on this. */ - private abstract class TypeDependencyTraverser(using Context) extends TypeTraverser()(using ctx) { + private abstract class TypeDependencyTraverser(using Context) extends TypeTraverser() { protected def addDependency(symbol: Symbol): Unit val seen = new mutable.HashSet[Type] diff --git a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala index 6b35ba2dedff..dfc1089ad4ca 100644 --- a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala +++ b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala @@ -16,7 +16,7 @@ class CtxLazy[T](expr: Context ?=> T) { private var forced = false def apply()(using Context): T = { if (!forced) { - myValue = expr(using ctx) + myValue = expr forced = true } myValue diff --git a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala index c11f80ae8d74..5a1c05a3ad5d 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -153,7 +153,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { // val x$lzy = new scala.runtime.LazyInt() val holderName = LazyLocalName.fresh(xname) - val holderImpl = defn.LazyHolder()(using ctx)(tpe.typeSymbol) + val holderImpl = defn.LazyHolder()(tpe.typeSymbol) val holderSymbol = ctx.newSymbol(x.symbol.owner, holderName, containerFlags, holderImpl.typeRef, coord = x.span) val holderTree = ValDef(holderSymbol, New(holderImpl.typeRef, Nil)) diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index 6be02e43712d..988bb6d2f0d4 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -405,13 +405,13 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { case Thicket(stats) => cpy.Thicket(stat)(stats.mapConserve(transformStat)) case _ => transformTree(stat, start)(using ctx.exprContext(stat, exprOwner)) } - val nestedCtx = prepStats(trees, start)(using ctx) + val nestedCtx = prepStats(trees, start) val trees1 = flatten(trees.mapConserve(transformStat(_)(using nestedCtx))) goStats(trees1, start)(using nestedCtx) } def transformUnit(tree: Tree)(using Context): Tree = { - val nestedCtx = prepUnit(tree, 0)(using ctx) + val nestedCtx = prepUnit(tree, 0) val tree1 = transformTree(tree, 0)(using nestedCtx) goUnit(tree1, 0)(using nestedCtx) } @@ -548,7 +548,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goIdent(tree: Ident, start: Int)(using Context): Tree = { val phase = nxIdentTransPhase(start) if (phase == null) tree - else phase.transformIdent(tree)(using ctx) match { + else phase.transformIdent(tree) match { case tree1: Ident => goIdent(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -563,7 +563,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goSelect(tree: Select, start: Int)(using Context): Tree = { val phase = nxSelectTransPhase(start) if (phase == null) tree - else phase.transformSelect(tree)(using ctx) match { + else phase.transformSelect(tree) match { case tree1: Select => goSelect(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -578,7 +578,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goThis(tree: This, start: Int)(using Context): Tree = { val phase = nxThisTransPhase(start) if (phase == null) tree - else phase.transformThis(tree)(using ctx) match { + else phase.transformThis(tree) match { case tree1: This => goThis(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -593,7 +593,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goSuper(tree: Super, start: Int)(using Context): Tree = { val phase = nxSuperTransPhase(start) if (phase == null) tree - else phase.transformSuper(tree)(using ctx) match { + else phase.transformSuper(tree) match { case tree1: Super => goSuper(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -608,7 +608,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goApply(tree: Apply, start: Int)(using Context): Tree = { val phase = nxApplyTransPhase(start) if (phase == null) tree - else phase.transformApply(tree)(using ctx) match { + else phase.transformApply(tree) match { case tree1: Apply => goApply(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -623,7 +623,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goTypeApply(tree: TypeApply, start: Int)(using Context): Tree = { val phase = nxTypeApplyTransPhase(start) if (phase == null) tree - else phase.transformTypeApply(tree)(using ctx) match { + else phase.transformTypeApply(tree) match { case tree1: TypeApply => goTypeApply(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -638,7 +638,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goLiteral(tree: Literal, start: Int)(using Context): Tree = { val phase = nxLiteralTransPhase(start) if (phase == null) tree - else phase.transformLiteral(tree)(using ctx) match { + else phase.transformLiteral(tree) match { case tree1: Literal => goLiteral(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -653,7 +653,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goNew(tree: New, start: Int)(using Context): Tree = { val phase = nxNewTransPhase(start) if (phase == null) tree - else phase.transformNew(tree)(using ctx) match { + else phase.transformNew(tree) match { case tree1: New => goNew(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -668,7 +668,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goTyped(tree: Typed, start: Int)(using Context): Tree = { val phase = nxTypedTransPhase(start) if (phase == null) tree - else phase.transformTyped(tree)(using ctx) match { + else phase.transformTyped(tree) match { case tree1: Typed => goTyped(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -683,7 +683,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goAssign(tree: Assign, start: Int)(using Context): Tree = { val phase = nxAssignTransPhase(start) if (phase == null) tree - else phase.transformAssign(tree)(using ctx) match { + else phase.transformAssign(tree) match { case tree1: Assign => goAssign(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -698,7 +698,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goBlock(tree: Block, start: Int)(using Context): Tree = { val phase = nxBlockTransPhase(start) if (phase == null) tree - else phase.transformBlock(tree)(using ctx) match { + else phase.transformBlock(tree) match { case tree1: Block => goBlock(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -713,7 +713,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goIf(tree: If, start: Int)(using Context): Tree = { val phase = nxIfTransPhase(start) if (phase == null) tree - else phase.transformIf(tree)(using ctx) match { + else phase.transformIf(tree) match { case tree1: If => goIf(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -728,7 +728,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goClosure(tree: Closure, start: Int)(using Context): Tree = { val phase = nxClosureTransPhase(start) if (phase == null) tree - else phase.transformClosure(tree)(using ctx) match { + else phase.transformClosure(tree) match { case tree1: Closure => goClosure(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -743,7 +743,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goMatch(tree: Match, start: Int)(using Context): Tree = { val phase = nxMatchTransPhase(start) if (phase == null) tree - else phase.transformMatch(tree)(using ctx) match { + else phase.transformMatch(tree) match { case tree1: Match => goMatch(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -758,7 +758,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goCaseDef(tree: CaseDef, start: Int)(using Context): Tree = { val phase = nxCaseDefTransPhase(start) if (phase == null) tree - else phase.transformCaseDef(tree)(using ctx) match { + else phase.transformCaseDef(tree) match { case tree1: CaseDef => goCaseDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -773,7 +773,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goLabeled(tree: Labeled, start: Int)(using Context): Tree = { val phase = nxLabeledTransPhase(start) if (phase == null) tree - else phase.transformLabeled(tree)(using ctx) match { + else phase.transformLabeled(tree) match { case tree1: Labeled => goLabeled(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -788,7 +788,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goReturn(tree: Return, start: Int)(using Context): Tree = { val phase = nxReturnTransPhase(start) if (phase == null) tree - else phase.transformReturn(tree)(using ctx) match { + else phase.transformReturn(tree) match { case tree1: Return => goReturn(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -803,7 +803,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goWhileDo(tree: WhileDo, start: Int)(using Context): Tree = { val phase = nxWhileDoTransPhase(start) if (phase == null) tree - else phase.transformWhileDo(tree)(using ctx) match { + else phase.transformWhileDo(tree) match { case tree1: WhileDo => goWhileDo(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -818,7 +818,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goTry(tree: Try, start: Int)(using Context): Tree = { val phase = nxTryTransPhase(start) if (phase == null) tree - else phase.transformTry(tree)(using ctx) match { + else phase.transformTry(tree) match { case tree1: Try => goTry(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -833,7 +833,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goSeqLiteral(tree: SeqLiteral, start: Int)(using Context): Tree = { val phase = nxSeqLiteralTransPhase(start) if (phase == null) tree - else phase.transformSeqLiteral(tree)(using ctx) match { + else phase.transformSeqLiteral(tree) match { case tree1: SeqLiteral => goSeqLiteral(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -848,7 +848,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goInlined(tree: Inlined, start: Int)(using Context): Tree = { val phase = nxInlinedTransPhase(start) if (phase == null) tree - else phase.transformInlined(tree)(using ctx) match { + else phase.transformInlined(tree) match { case tree1: Inlined => goInlined(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -863,7 +863,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goTypeTree(tree: TypeTree, start: Int)(using Context): Tree = { val phase = nxTypeTreeTransPhase(start) if (phase == null) tree - else phase.transformTypeTree(tree)(using ctx) match { + else phase.transformTypeTree(tree) match { case tree1: TypeTree => goTypeTree(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -878,7 +878,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goBind(tree: Bind, start: Int)(using Context): Tree = { val phase = nxBindTransPhase(start) if (phase == null) tree - else phase.transformBind(tree)(using ctx) match { + else phase.transformBind(tree) match { case tree1: Bind => goBind(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -893,7 +893,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goAlternative(tree: Alternative, start: Int)(using Context): Tree = { val phase = nxAlternativeTransPhase(start) if (phase == null) tree - else phase.transformAlternative(tree)(using ctx) match { + else phase.transformAlternative(tree) match { case tree1: Alternative => goAlternative(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -908,7 +908,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goUnApply(tree: UnApply, start: Int)(using Context): Tree = { val phase = nxUnApplyTransPhase(start) if (phase == null) tree - else phase.transformUnApply(tree)(using ctx) match { + else phase.transformUnApply(tree) match { case tree1: UnApply => goUnApply(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -923,7 +923,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goValDef(tree: ValDef, start: Int)(using Context): Tree = { val phase = nxValDefTransPhase(start) if (phase == null) tree - else phase.transformValDef(tree)(using ctx) match { + else phase.transformValDef(tree) match { case tree1: ValDef => goValDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -938,7 +938,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goDefDef(tree: DefDef, start: Int)(using Context): Tree = { val phase = nxDefDefTransPhase(start) if (phase == null) tree - else phase.transformDefDef(tree)(using ctx) match { + else phase.transformDefDef(tree) match { case tree1: DefDef => goDefDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -953,7 +953,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goTypeDef(tree: TypeDef, start: Int)(using Context): Tree = { val phase = nxTypeDefTransPhase(start) if (phase == null) tree - else phase.transformTypeDef(tree)(using ctx) match { + else phase.transformTypeDef(tree) match { case tree1: TypeDef => goTypeDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -968,7 +968,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goTemplate(tree: Template, start: Int)(using Context): Tree = { val phase = nxTemplateTransPhase(start) if (phase == null) tree - else phase.transformTemplate(tree)(using ctx) match { + else phase.transformTemplate(tree) match { case tree1: Template => goTemplate(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -983,7 +983,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goPackageDef(tree: PackageDef, start: Int)(using Context): Tree = { val phase = nxPackageDefTransPhase(start) if (phase == null) tree - else phase.transformPackageDef(tree)(using ctx) match { + else phase.transformPackageDef(tree) match { case tree1: PackageDef => goPackageDef(tree1, phase.idxInGroup + 1) case tree1 => transformNode(tree1, phase.idxInGroup + 1) } @@ -998,7 +998,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goStats(trees: List[Tree], start: Int)(using Context): List[Tree] = { val phase = nxStatsTransPhase(start) if (phase == null) trees - else goStats(phase.transformStats(trees)(using ctx), phase.idxInGroup + 1) + else goStats(phase.transformStats(trees), phase.idxInGroup + 1) } def prepUnit(tree: Tree, start: Int)(using Context): Context = { @@ -1010,7 +1010,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goUnit(tree: Tree, start: Int)(using Context): Tree = { val phase = nxUnitTransPhase(start) if (phase == null) tree - else goUnit(phase.transformUnit(tree)(using ctx), phase.idxInGroup + 1) + else goUnit(phase.transformUnit(tree), phase.idxInGroup + 1) } def prepOther(tree: Tree, start: Int)(using Context): Context = { @@ -1022,6 +1022,6 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { def goOther(tree: Tree, start: Int)(using Context): Tree = { val phase = nxOtherTransPhase(start) if (phase == null) tree - else goOther(phase.transformOther(tree)(using ctx), phase.idxInGroup + 1) + else goOther(phase.transformOther(tree), phase.idxInGroup + 1) } } diff --git a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala index 7e101b652fdf..191a5f286024 100644 --- a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala +++ b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala @@ -101,7 +101,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( /** Transform quoted trees while maintaining phase correctness */ override protected def transformQuotation(body: Tree, quote: Tree)(using Context): Tree = { - val taggedTypes = new PCPCheckAndHeal.QuoteTypeTags(quote.span)(using ctx) + val taggedTypes = new PCPCheckAndHeal.QuoteTypeTags(quote.span) if (ctx.property(InAnnotation).isDefined) ctx.error("Cannot have a quote in an annotation", quote.sourcePos) diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index df0655d8df2c..ffd480c4d3f8 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -137,14 +137,18 @@ class TreeChecker extends Phase with SymTransformer { val squahsedPhase = ctx.base.squashed(prevPhase) ctx.echo(s"checking ${ctx.compilationUnit} after phase ${squahsedPhase}") - assertSelectWrapsNew(ctx.compilationUnit.tpdTree)(using ctx) + inContext(ctx) { + assertSelectWrapsNew(ctx.compilationUnit.tpdTree) + } val checkingCtx = ctx .fresh .setMode(Mode.ImplicitsEnabled) .setReporter(new ThrowingReporter(ctx.reporter)) - val checker = new Checker(previousPhases(phasesToRun.toList)(using ctx)) + val checker = inContext(ctx) { + new Checker(previousPhases(phasesToRun.toList)) + } try checker.typedExpr(ctx.compilationUnit.tpdTree)(using checkingCtx) catch { case NonFatal(ex) => //TODO CHECK. Check that we are bootstrapped diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index f03374313693..8181791a705d 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -681,7 +681,7 @@ trait Applications extends Compatibility { * argument trees. */ class ApplicableToTreesDirectly(methRef: TermRef, args: List[Tree], resultType: Type)(using Context) - extends ApplicableToTrees(methRef, args, resultType)(using ctx) { + extends ApplicableToTrees(methRef, args, resultType) { override def argOK(arg: TypedArg, formal: Type): Boolean = argType(arg, formal) relaxed_<:< formal.widenExpr } diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index e7a7a2222f3d..99cd865babec 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -777,7 +777,7 @@ trait Implicits { self: Typer => * Return a failure as a SearchFailureType in the type of the returned tree. */ def inferImplicitArg(formal: Type, span: Span)(using Context): Tree = - inferImplicit(formal, EmptyTree, span)(using ctx) match + inferImplicit(formal, EmptyTree, span) match case SearchSuccess(arg, _, _) => arg case fail @ SearchFailure(failed) => if fail.isAmbiguous then failed diff --git a/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala b/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala index d0e684782cf7..6ac9fa4535a2 100644 --- a/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala +++ b/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala @@ -52,7 +52,7 @@ class ImportInfo(symf: Context ?=> Symbol, def sym(using Context): Symbol = { if (mySym == null) { - mySym = symf(using ctx) + mySym = symf assert(mySym != null) } mySym diff --git a/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala b/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala index 54c459647ec0..8d71ddb9d9f5 100644 --- a/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala @@ -391,9 +391,9 @@ class Synthesizer(typer: Typer)(using @constructorOnly c: Context): if mirroredType.termSymbol.is(CaseVal) || mirroredType.classSymbol.isGenericProduct then - synthesizedProductMirror(formal, span)(using ctx) + synthesizedProductMirror(formal, span) else - synthesizedSumMirror(formal, span)(using ctx) + synthesizedSumMirror(formal, span) case _ => EmptyTree val specialHandlers = List( diff --git a/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala b/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala index 0fbdb84c54a9..469960b1dacd 100644 --- a/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala +++ b/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala @@ -20,7 +20,7 @@ import reporting.trace object VarianceChecker { case class VarianceError(tvar: Symbol, required: Variance) def check(tree: tpd.Tree)(using Context): Unit = - new VarianceChecker(using ctx).Traverser.traverse(tree) + VarianceChecker().Traverser.traverse(tree) /** Check that variances of type lambda correspond to their occurrences in its body. * Note: this is achieved by a mechanism separate from checking class type parameters. diff --git a/compiler/src/dotty/tools/dotc/util/ParsedComment.scala b/compiler/src/dotty/tools/dotc/util/ParsedComment.scala index 5609e0009a6c..3a53f9399b23 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} +import dotty.tools.dotc.core.Contexts.{Context, ctx, inContext} import dotty.tools.dotc.core.Names.TermName import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.printing.SyntaxHighlighting @@ -135,10 +135,10 @@ object ParsedComment { * @param items The items to format into a list. * @return A markdown list of descriptions. */ - private def toDescriptionList(ctx: Context, items: List[String]): String = { + private def toDescriptionList(ctx: Context, items: List[String]): String = inContext(ctx) { val formattedItems = items.map { p => val name :: rest = p.split(" ", 2).toList - s"${bold(name)(using ctx)} ${rest.mkString("").trim}" + s"${bold(name)} ${rest.mkString("").trim}" } toMarkdownList(ctx, formattedItems) } @@ -175,13 +175,14 @@ object ParsedComment { * @param snippet The code snippet * @return `snippet`, wrapped in a code fence. */ - private def toCodeFence(language: String)(ctx: Context, snippet: String): String = - if (colorEnabled(using ctx)) - SyntaxHighlighting.highlight(snippet)(using ctx) + private def toCodeFence(language: String)(ctx: Context, snippet: String): String = inContext(ctx) { + if colorEnabled then + SyntaxHighlighting.highlight(snippet) else s"""```$language |$snippet |```""".stripMargin + } /** * Format the elements of documentation associated with a given tag using `fn`, and starts the diff --git a/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala b/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala index 89b295d1cf49..8016a74d4052 100644 --- a/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala +++ b/compiler/test/dotty/tools/dotc/parsing/desugarPackage.scala @@ -17,7 +17,7 @@ object desugarPackage extends DeSugarTest { val buf = parsedTrees map desugarTree val ms2 = (System.nanoTime() - start)/1000000 println(s"$parsed files parsed in ${ms1}ms, ${nodes - startNodes} nodes desugared in ${ms2-ms1}ms, total trees created = ${Trees.ntrees - startNodes}") - ctx.reporter.printSummary(using ctx) + ctx.reporter.printSummary } def main(args: Array[String]): Unit = { diff --git a/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala b/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala index f55da0d9a7d0..4ea586624933 100644 --- a/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala +++ b/compiler/test/dotty/tools/dotc/parsing/parsePackage.scala @@ -70,7 +70,7 @@ object parsePackage extends ParserTest { val buf = parsedTrees map transformer.transform val ms2 = (System.nanoTime() - start)/1000000 println(s"$parsed files parsed in ${ms1}ms, $nodes nodes transformed in ${ms2-ms1}ms, total trees created = ${Trees.ntrees}") - ctx.reporter.printSummary(using ctx) + ctx.reporter.printSummary } def main(args: Array[String]): Unit = { From f3e03fc4df6a679b299dc12fd0d2c02f6f3d6774 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 13:21:07 +0200 Subject: [PATCH 34/41] Move atPhase and friends to Contexts --- .../tools/backend/jvm/BCodeBodyBuilder.scala | 3 ++- .../dotty/tools/backend/jvm/BCodeHelpers.scala | 6 +++--- .../tools/backend/jvm/BTypesFromSymbols.scala | 4 ++-- .../backend/jvm/DottyBackendInterface.scala | 2 +- .../src/dotty/tools/backend/jvm/GenBCode.scala | 4 ++-- .../dotty/tools/backend/sjs/JSCodeGen.scala | 6 +++--- .../dotty/tools/backend/sjs/JSInterop.scala | 4 ++-- .../src/dotty/tools/dotc/config/Feature.scala | 2 +- .../src/dotty/tools/dotc/core/Contexts.scala | 18 ++++++++++++++++++ .../src/dotty/tools/dotc/core/Periods.scala | 10 +--------- .../src/dotty/tools/dotc/core/Phases.scala | 9 --------- .../tools/dotc/transform/ElimByName.scala | 4 ++-- .../tools/dotc/transform/ElimRepeated.scala | 4 ++-- .../dotty/tools/dotc/transform/Erasure.scala | 2 +- .../tools/dotc/transform/ExplicitOuter.scala | 2 +- .../dotc/transform/ExtensionMethods.scala | 2 +- .../dotc/transform/FunctionalInterfaces.scala | 2 +- .../dotc/transform/GenericSignatures.scala | 4 ++-- .../tools/dotc/transform/LambdaLift.scala | 2 +- .../src/dotty/tools/dotc/transform/Mixin.scala | 4 ++-- .../dotty/tools/dotc/transform/MixinOps.scala | 2 +- .../tools/dotc/transform/TreeChecker.scala | 2 +- .../tools/dotc/transform/ValueClasses.scala | 2 +- .../src/dotty/tools/dotc/typer/RefChecks.scala | 2 +- compiler/src/dotty/tools/repl/ReplDriver.scala | 4 ++-- .../test/dotty/tools/AnnotationsTests.scala | 2 +- compiler/test/dotty/tools/SignatureTest.scala | 4 ++-- 27 files changed, 57 insertions(+), 55 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala index 986d13372789..e3ac6545d41d 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala @@ -19,6 +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} /* * @@ -1460,7 +1461,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { // TODO specialization val constrainedType = new MethodBType(lambdaParamTypes.map(p => toTypeKind(p)), toTypeKind(lambdaTarget.info.resultType)).toASMType - val abstractMethod = ctx.atPhase(ctx.erasurePhase) { + val abstractMethod = atPhase(ctx.erasurePhase) { val samMethods = toDenot(functionalInterface).info.possibleSamMethods.toList samMethods match { case x :: Nil => x.symbol diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index a62829ae2476..f3131e6b205d 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 +import dotty.tools.dotc.core.Contexts.{Context, atPhase} import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Names.Name @@ -478,7 +478,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { * @see https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.4 */ def getGenericSignature(sym: Symbol, owner: Symbol): String = { - ctx.atPhase(ctx.erasurePhase) { + atPhase(ctx.erasurePhase) { val memberTpe = if (sym.is(Method)) sym.denot.info else owner.denot.thisType.memberInfo(sym) @@ -913,7 +913,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { // But for now, just like we did in mixin, we just avoid writing a wrong generic signature // (one that doesn't erase to the actual signature). See run/t3452b for a test case. - val memberTpe = ctx.atPhase(ctx.erasurePhase) { moduleClass.denot.thisType.memberInfo(sym) } + val memberTpe = atPhase(ctx.erasurePhase) { moduleClass.denot.thisType.memberInfo(sym) } val erasedMemberType = TypeErasure.erasure(memberTpe) if (erasedMemberType =:= sym.denot.info) getGenericSignatureHelper(sym, moduleClass, memberTpe).orNull diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index bffb1d106801..44294b10c464 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 +import dotty.tools.dotc.core.Contexts.{inContext, atPhase} import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Phases.Phase import dotty.tools.dotc.transform.SymUtils._ @@ -212,7 +212,7 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { private def definedClasses(sym: Symbol, phase: Phase) = if (sym.isDefinedInCurrentRun) - ctx.atPhase(phase) { + atPhase(phase) { toDenot(sym).info.decls.filter(_.isClass) } else Nil diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index e84266f34eb2..1d0a8f767f0b 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -160,7 +160,7 @@ object DottyBackendInterface { */ def isTopLevelModuleClass(using Context): Boolean = sym.is(ModuleClass) && - ctx.atPhase(ctx.flattenPhase) { + atPhase(ctx.flattenPhase) { toDenot(sym).owner.is(PackageClass) } diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index 3082e851fd21..cf91ccef3ef7 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -166,7 +166,7 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten if (classSymbol.effectiveName.toString < dupClassSym.effectiveName.toString) (classSymbol, dupClassSym) else (dupClassSym, classSymbol) val same = classSymbol.effectiveName.toString == dupClassSym.effectiveName.toString - ctx.atPhase(ctx.typerPhase) { + atPhase(ctx.typerPhase) { if (same) summon[Context].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) @@ -271,7 +271,7 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten // ----------- compiler and sbt's callbacks - val (fullClassName, isLocal) = ctx.atPhase(ctx.sbtExtractDependenciesPhase) { + val (fullClassName, isLocal) = atPhase(ctx.sbtExtractDependenciesPhase) { (ExtractDependencies.classNameAsString(claszSymbol), claszSymbol.isLocal) } diff --git a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala index 5dc4db30eade..985a05a4524b 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala @@ -2121,7 +2121,7 @@ class JSCodeGen()(using genCtx: Context) { if (isStat) { boxedResult } else { - val tpe = ctx.atPhase(ctx.elimErasedValueTypePhase) { + val tpe = atPhase(ctx.elimErasedValueTypePhase) { sym.info.finalResultType } unbox(boxedResult, tpe) @@ -2735,14 +2735,14 @@ class JSCodeGen()(using genCtx: Context) { def paramNamesAndTypes(using Context): List[(Names.TermName, Type)] = sym.info.paramNamess.flatten.zip(sym.info.paramInfoss.flatten) - val wereRepeated = ctx.atPhase(ctx.elimRepeatedPhase) { + val wereRepeated = atPhase(ctx.elimRepeatedPhase) { val list = for ((name, tpe) <- paramNamesAndTypes) yield (name -> tpe.isRepeatedParam) list.toMap } - val paramTypes = ctx.atPhase(ctx.elimErasedValueTypePhase) { + val paramTypes = atPhase(ctx.elimErasedValueTypePhase) { paramNamesAndTypes.toMap } diff --git a/compiler/src/dotty/tools/backend/sjs/JSInterop.scala b/compiler/src/dotty/tools/backend/sjs/JSInterop.scala index 8fe20566fe47..be4506500a02 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSInterop.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSInterop.scala @@ -16,7 +16,7 @@ object JSInterop { /** Is this symbol a JavaScript type? */ def isJSType(sym: Symbol)(using Context): Boolean = { //sym.hasAnnotation(jsdefn.RawJSTypeAnnot) - ctx.atPhase(ctx.erasurePhase) { + atPhase(ctx.erasurePhase) { sym.derivesFrom(jsdefn.JSAnyClass) } } @@ -32,7 +32,7 @@ object JSInterop { * much as *accessor* methods created for `val`s and `var`s. */ def isJSGetter(sym: Symbol)(using Context): Boolean = { - sym.info.firstParamTypes.isEmpty && ctx.atPhase(ctx.erasurePhase) { + sym.info.firstParamTypes.isEmpty && atPhase(ctx.erasurePhase) { sym.info.isParameterless } } diff --git a/compiler/src/dotty/tools/dotc/config/Feature.scala b/compiler/src/dotty/tools/dotc/config/Feature.scala index 25d79bc50f2f..84b5a154eb22 100644 --- a/compiler/src/dotty/tools/dotc/config/Feature.scala +++ b/compiler/src/dotty/tools/dotc/config/Feature.scala @@ -36,7 +36,7 @@ object Feature: * import owner.{ feature => _ } */ def enabledByImport(feature: TermName, owner: Symbol = NoSymbol)(using Context): Boolean = - ctx.atPhase(ctx.typerPhase) { + atPhase(ctx.typerPhase) { ctx.importInfo != null && ctx.importInfo.featureImported(feature, if owner.exists then owner else defn.LanguageModule.moduleClass) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 6c29eb504d47..20ffe2a8aaef 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -57,6 +57,24 @@ object Contexts { inline def inContext[T](c: Context)(inline op: Context ?=> T): T = op(using c) + /** Execute `op` at given period */ + inline def atPeriod[T](pd: Period)(inline op: Context ?=> T)(using Context): T = + op(using ctx.fresh.setPeriod(pd)) + + /** Execute `op` at given phase id */ + inline def atPhase[T](pid: PhaseId)(inline op: Context ?=> T)(using Context): T = + op(using ctx.withPhase(pid)) + + /** Execute `op` at given phase */ + inline def atPhase[T](phase: Phase)(inline op: Context ?=> T)(using Context): T = + atPhase(phase.id)(op) + + inline def atNextPhase[T](inline op: Context ?=> T)(using Context): T = + atPhase(ctx.phase.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)) + /** A context is passed basically everywhere in dotc. * This is convenient but carries the risk of captured contexts in * objects that turn into space leaks. To combat this risk, here are some diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index 433a6752875e..63970489810f 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc.core import Contexts._ -/** Periods are the central "clock" of the compiler. +/** 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 @@ -16,14 +16,6 @@ abstract class Periods { thisCtx: Context => /** The current run identifier */ def runId: Int = period.runId - /** Execute `op` at given period */ - def atPeriod[T](pd: Period)(op: Context => T): T = - op(thisCtx.fresh.setPeriod(pd)) - - /** Execute `op` at given phase id */ - inline def atPhase[T](pid: PhaseId)(inline op: Context ?=> T): T = - op(using thisCtx.withPhase(pid)) - /** 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 diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index 53a8e9524575..39fb5708085b 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -30,15 +30,6 @@ trait Phases { phase :: (if (rest.hasNext) rest.next().phasesStack else Nil) } - /** Execute `op` at given phase */ - inline def atPhase[T](phase: Phase)(inline op: Context ?=> T): T = - atPhase(phase.id)(op) - - def atNextPhase[T](op: Context ?=> T): T = atPhase(phase.next)(op) - - def atPhaseNotLaterThan[T](limit: Phase)(op: Context ?=> T): T = - if (!limit.exists || phase <= limit) op(using this) else atPhase(limit)(op) - def isAfterTyper: Boolean = base.isAfterTyper(phase) } diff --git a/compiler/src/dotty/tools/dotc/transform/ElimByName.scala b/compiler/src/dotty/tools/dotc/transform/ElimByName.scala index ddd8d3c6e162..bdc57529d2ce 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimByName.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimByName.scala @@ -42,7 +42,7 @@ class ElimByName extends TransformByNameApply with InfoTransformer { private def applyIfFunction(tree: Tree, ftree: Tree)(using Context) = if (isByNameRef(ftree)) { val tree0 = transformFollowing(tree) - ctx.atPhase(next) { tree0.select(defn.Function0_apply).appliedToNone } + atPhase(next) { tree0.select(defn.Function0_apply).appliedToNone } } else tree @@ -61,7 +61,7 @@ class ElimByName extends TransformByNameApply with InfoTransformer { } override def transformValDef(tree: ValDef)(using Context): Tree = - ctx.atPhase(next) { + atPhase(next) { if (exprBecomesFunction(tree.symbol)) cpy.ValDef(tree)(tpt = tree.tpt.withType(tree.symbol.info)) else tree diff --git a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala index abbd2a271120..069575176bea 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala @@ -7,7 +7,7 @@ import Types._ import dotty.tools.dotc.transform.MegaPhase._ import ast.Trees._ import Flags._ -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Constants._ import Decorators._ @@ -113,7 +113,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => * Also transform trees inside method annotation */ override def transformDefDef(tree: DefDef)(using Context): Tree = - ctx.atPhase(thisPhase) { + atPhase(thisPhase) { if (tree.symbol.info.isVarArgsMethod && overridesJava(tree.symbol)) addVarArgsBridge(tree) else diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index d81074264aca..7e47ec4df25a 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -904,7 +904,7 @@ object Erasure { case stat: DefDef @unchecked if stat.symbol.name.is(BodyRetainerName) => val retainer = stat.symbol val origName = retainer.name.asTermName.exclude(BodyRetainerName) - val inlineMeth = ctx.atPhase(ctx.typerPhase) { + val inlineMeth = atPhase(ctx.typerPhase) { retainer.owner.info.decl(origName) .matchingDenotation(retainer.owner.thisType, stat.symbol.info) .symbol diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index 194175d0b7a6..55ec86295b95 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -127,7 +127,7 @@ object ExplicitOuter { /** Ensure that class `cls` has outer accessors */ def ensureOuterAccessors(cls: ClassSymbol)(using Context): Unit = - ctx.atPhase(ctx.explicitOuterPhase.next) { + atPhase(ctx.explicitOuterPhase.next) { if (!hasOuter(cls)) newOuterAccessors(cls).foreach(_.enteredAfter(ctx.explicitOuterPhase.asInstanceOf[DenotTransformer])) } diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index eb056c77e81b..975fa26ad1f7 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -184,7 +184,7 @@ object ExtensionMethods { /** Return the extension method that corresponds to given instance method `meth`. */ def extensionMethod(imeth: Symbol)(using Context): TermSymbol = - ctx.atPhase(ctx.extensionMethodsPhase.next) { + atPhase(ctx.extensionMethodsPhase.next) { // FIXME use toStatic instead? val companion = imeth.owner.companionModule val companionInfo = companion.info diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala index 7dda4cf97d89..eb0e8da166ba 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala @@ -35,7 +35,7 @@ class FunctionalInterfaces extends MiniPhase { if (defn.isSpecializableFunction(cls, implParamTypes, implResultType) && !ctx.settings.scalajs.value) { // never do anything for Scala.js, but do this test as late as possible not to slow down Scala/JVM - val names = ctx.atPhase(ctx.erasurePhase) { cls.typeParams.map(_.name) } + val names = atPhase(ctx.erasurePhase) { cls.typeParams.map(_.name) } 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 diff --git a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala index 640099529533..95bef5f49243 100644 --- a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala +++ b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala @@ -3,7 +3,7 @@ package dotc package transform import core.Annotations._ -import core.Contexts.{Context, ctx} +import core.Contexts._ import core.Definitions import core.Flags._ import core.Names.{DerivedName, Name, SimpleName, TypeName} @@ -112,7 +112,7 @@ object GenericSignatures { // a type parameter or similar) must go through here or the signature is // likely to end up with Foo.Empty where it needs Foo.Empty$. def fullNameInSig(sym: Symbol): Unit = { - val name = ctx.atPhase(ctx.genBCodePhase) { sanitizeName(sym.fullName).replace('.', '/') } + val name = atPhase(ctx.genBCodePhase) { sanitizeName(sym.fullName).replace('.', '/') } builder.append('L').append(name) } diff --git a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala index 1e683547f5b5..40040d4447b0 100644 --- a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala +++ b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala @@ -370,7 +370,7 @@ object LambdaLift { } // initialization - ctx.atPhase(thisPhase) { + atPhase(thisPhase) { (new CollectDependencies).traverse(ctx.compilationUnit.tpdTree) computeFreeVars() computeLiftedOwners() diff --git a/compiler/src/dotty/tools/dotc/transform/Mixin.scala b/compiler/src/dotty/tools/dotc/transform/Mixin.scala index 0a35f48d86c6..6b44c8887763 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} +import Contexts.{Context, ctx, atPhase} import Flags._ import SymUtils._ import Symbols._ @@ -222,7 +222,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => transformFollowingDeep(superRef(baseCls.primaryConstructor).appliedToNone) :: Nil def wasOneOf(sym: Symbol, flags: FlagSet) = - ctx.atPhase(thisPhase) { sym.isOneOf(flags) } + atPhase(thisPhase) { sym.isOneOf(flags) } def traitInits(mixin: ClassSymbol): List[Tree] = { val argsIt = superCallsAndArgs.get(mixin) match diff --git a/compiler/src/dotty/tools/dotc/transform/MixinOps.scala b/compiler/src/dotty/tools/dotc/transform/MixinOps.scala index 090ad4543e88..c08797f78749 100644 --- a/compiler/src/dotty/tools/dotc/transform/MixinOps.scala +++ b/compiler/src/dotty/tools/dotc/transform/MixinOps.scala @@ -43,7 +43,7 @@ class MixinOps(cls: ClassSymbol, thisPhase: DenotTransformer)(using Context) { * The test is performed at phase `thisPhase`. */ def isCurrent(sym: Symbol): Boolean = - ctx.atPhase(thisPhase) { + atPhase(thisPhase) { cls.info.nonPrivateMember(sym.name).hasAltWith(_.symbol == sym) } diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index ffd480c4d3f8..cf284b48636d 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -59,7 +59,7 @@ class TreeChecker extends Phase with SymTransformer { def checkCompanion(symd: SymDenotation)(using Context): Unit = { val cur = symd.linkedClass - val prev = ctx.atPhase(ctx.phase.prev) { + val prev = atPhase(ctx.phase.prev) { symd.symbol.linkedClass } diff --git a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala index 1653cf9bc36a..41727e3e8fa9 100644 --- a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala +++ b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala @@ -22,7 +22,7 @@ object ValueClasses { } def isMethodWithExtension(sym: Symbol)(using Context): Boolean = - ctx.atPhaseNotLaterThan(ctx.extensionMethodsPhase) { + atPhaseNotLaterThan(ctx.extensionMethodsPhase) { val d = sym.denot d.validFor.containsPhaseId(summon[Context].phaseId) && d.isRealMethod && diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index 549268fab3b9..8b813bb5022f 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -451,7 +451,7 @@ object RefChecks { def hasJavaErasedOverriding(sym: Symbol): Boolean = !ctx.erasurePhase.exists || // can't do the test, assume the best - ctx.atPhase(ctx.erasurePhase.next) { + atPhase(ctx.erasurePhase.next) { clazz.info.nonPrivateMember(sym.name).hasAltWith { alt => alt.symbol.is(JavaDefined, butNot = Deferred) && !sym.owner.derivesFrom(alt.symbol.owner) && diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index cd924b1867e0..8c892d4c8441 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -4,7 +4,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.{Context, ctx, inContext} +import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Denotations.Denotation import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Mode @@ -320,7 +320,7 @@ class ReplDriver(settings: Array[String], rendering.renderTypeDef(x) } - ctx.atPhase(ctx.typerPhase.next) { + atPhase(ctx.typerPhase.next) { // Display members of wrapped module: tree.symbol.info.memberClasses .find(_.symbol.name == newestWrapper.moduleClassName) diff --git a/compiler/test/dotty/tools/AnnotationsTests.scala b/compiler/test/dotty/tools/AnnotationsTests.scala index 2a25025c2848..9459bc235648 100644 --- a/compiler/test/dotty/tools/AnnotationsTests.scala +++ b/compiler/test/dotty/tools/AnnotationsTests.scala @@ -25,7 +25,7 @@ class AnnotationsTest: val annotCls = ctx.requiredClass("Annot") val arrayOfString = defn.ArrayType.appliedTo(List(defn.StringType)) - ctx.atPhase(ctx.erasurePhase.next) { + atPhase(ctx.erasurePhase.next) { val annot = cls.getAnnotation(annotCls) // Even though we're forcing the annotation after erasure, // the typed trees should be unerased, so the type of diff --git a/compiler/test/dotty/tools/SignatureTest.scala b/compiler/test/dotty/tools/SignatureTest.scala index 474e06d9a8aa..1a5420a60865 100644 --- a/compiler/test/dotty/tools/SignatureTest.scala +++ b/compiler/test/dotty/tools/SignatureTest.scala @@ -15,12 +15,12 @@ import java.nio.file._ class SignatureTest: @Test def signatureCaching: Unit = inCompilerContext(TestConfiguration.basicClasspath, separateRun = true, "case class Foo(value: Unit)") { - val (ref, refSig) = ctx.atPhase(ctx.erasurePhase.next) { + val (ref, refSig) = atPhase(ctx.erasurePhase.next) { val cls = ctx.requiredClass("Foo") val ref = cls.requiredMethod("value").termRef (ref, ref.signature) } - ctx.atPhase(ctx.typerPhase) { + atPhase(ctx.typerPhase) { // NamedType#signature is always computed before erasure, which ensures // that it stays stable and therefore can be cached as long as // signatures are guaranteed to be stable before erasure, see the From 0ece69a20eb15d8daa0a93b4c42f72d1101efe45 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 13:27:58 +0200 Subject: [PATCH 35/41] Use atPhase instead of inContext where possible --- compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala | 2 +- .../src/dotty/tools/backend/jvm/DottyBackendInterface.scala | 4 ++-- compiler/src/dotty/tools/dotc/core/SymDenotations.scala | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index 44294b10c464..1dfc1b6124b7 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala @@ -229,7 +229,7 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { // After lambdalift (which is where we are), the rawowoner field contains the enclosing class. val enclosingClassSym = { if (innerClassSym.isClass) { - inContext(ctx.withPhase(ctx.flattenPhase.prev)) { + atPhase(ctx.flattenPhase.prev) { toDenot(innerClassSym).owner.enclosingClass } } diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index 1d0a8f767f0b..8fbd3aa62342 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -137,7 +137,7 @@ object DottyBackendInterface { // for example by specialization val original = toDenot(sym).initial val validity = original.validFor - inContext(ctx.withPhase(validity.phaseId)) { + atPhase(validity.phaseId) { toDenot(sym).isStatic } } @@ -149,7 +149,7 @@ object DottyBackendInterface { // it is very tricky in presence of classes(and annonymous classes) defined inside supper calls. if (sym.exists) { val validity = toDenot(sym).initial.validFor - inContext(ctx.withPhase(validity.phaseId)) { + atPhase(validity.phaseId) { toDenot(sym).lexicallyEnclosingClass } } else NoSymbol diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index d38657ad5616..cb9235851a34 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -2201,7 +2201,7 @@ object SymDenotations { def ensureFreshScopeAfter(phase: DenotTransformer)(using Context): Unit = if (ctx.phaseId != phase.next.id) ensureFreshScopeAfter(phase)(using ctx.withPhase(phase.next)) else { - val prevClassInfo = inContext(ctx.withPhase(phase)) { + val prevClassInfo = atPhase(phase) { current.asInstanceOf[ClassDenotation].classInfo } val ClassInfo(pre, _, ps, decls, selfInfo) = classInfo From da6829bcfd5db8d98189d9be509e01e47d3841b6 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 15:05:19 +0200 Subject: [PATCH 36/41] Rename Context#phases -> Phases.curPhases --- compiler/src/dotty/tools/dotc/Run.scala | 3 ++- compiler/src/dotty/tools/dotc/core/Contexts.scala | 1 - compiler/src/dotty/tools/dotc/core/Periods.scala | 5 +++-- compiler/src/dotty/tools/dotc/core/Phases.scala | 3 +++ compiler/src/dotty/tools/dotc/core/SymDenotations.scala | 4 ++-- compiler/src/dotty/tools/repl/ReplDriver.scala | 3 ++- 6 files changed, 12 insertions(+), 7 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 1fc18c64a4bf..41e1177698c4 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -10,6 +10,7 @@ import Scopes._ import typer.{ImportInfo, Typer} import Decorators._ import io.{AbstractFile, PlainFile} +import Phases.curPhases import scala.io.Codec import util.{Set => _, _} @@ -194,7 +195,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint val runCtx = ctx.fresh runCtx.setProfiler(Profiler()) - ctx.phases.foreach(_.initContext(runCtx)) + curPhases.foreach(_.initContext(runCtx)) runPhases(using runCtx) if (!ctx.reporter.hasErrors) Rewrites.writeBack() while (finalizeActions.nonEmpty) { diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 20ffe2a8aaef..cea60a5fe88a 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -533,7 +533,6 @@ object Contexts { def lambdaLiftPhase: Phase = base.lambdaLiftPhase def flattenPhase: Phase = base.flattenPhase def genBCodePhase: Phase = base.genBCodePhase - def phases: Array[Phase] = base.phases def settings: ScalaSettings = base.settings def definitions: Definitions = base.definitions diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index 63970489810f..c6de89ba9399 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -1,6 +1,7 @@ package dotty.tools.dotc.core import Contexts._ +import Phases.curPhases /** Periods are the central "clock" of the compiler * A period consists of a run id and a phase id. @@ -34,8 +35,8 @@ abstract class Periods { thisCtx: Context => val period = thisCtx.period period == p || period.runId == p.runId && - thisCtx.phases(period.phaseId).sameBaseTypesStartId == - thisCtx.phases(p.phaseId).sameBaseTypesStartId + curPhases(period.phaseId).sameBaseTypesStartId == + curPhases(p.phaseId).sameBaseTypesStartId } } diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index 39fb5708085b..77c87d6e64f7 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -411,6 +411,9 @@ object Phases { override def toString: String = phaseName } + def curPhases(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/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index cb9235851a34..a6fa3f6302f7 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -2582,8 +2582,8 @@ object SymDenotations { def isValidAt(phase: Phase)(using Context) = checkedPeriod == ctx.period || createdAt.runId == ctx.runId && - createdAt.phaseId < ctx.phases.length && - sameGroup(ctx.phases(createdAt.phaseId), phase) && + createdAt.phaseId < curPhases.length && + sameGroup(curPhases(createdAt.phaseId), phase) && { checkedPeriod = ctx.period; true } } diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 8c892d4c8441..700124a9a46d 100644 --- a/compiler/src/dotty/tools/repl/ReplDriver.scala +++ b/compiler/src/dotty/tools/repl/ReplDriver.scala @@ -5,6 +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 import dotty.tools.dotc.core.Denotations.Denotation import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Mode @@ -222,7 +223,7 @@ class ReplDriver(settings: Array[String], } def extractTopLevelImports(ctx: Context): List[tpd.Import] = - ctx.phases.collectFirst { case phase: CollectTopLevelImports => phase.imports }.get + curPhases(using ctx).collectFirst { case phase: CollectTopLevelImports => phase.imports }.get implicit val state = { val state0 = newRun(istate) From cd9f05da1e8f881f5356a87260d74ed66d70a378 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 15:14:03 +0200 Subject: [PATCH 37/41] Move individual phases to Phases --- .../tools/backend/jvm/BCodeBodyBuilder.scala | 3 ++- .../tools/backend/jvm/BCodeHelpers.scala | 7 ++++--- .../tools/backend/jvm/BTypesFromSymbols.scala | 11 ++++++----- .../tools/backend/jvm/CollectSuperCalls.scala | 3 ++- .../backend/jvm/DottyBackendInterface.scala | 2 +- .../dotty/tools/backend/jvm/GenBCode.scala | 5 +++-- .../dotty/tools/backend/sjs/JSCodeGen.scala | 6 +++--- .../dotty/tools/backend/sjs/JSInterop.scala | 5 +++-- .../src/dotty/tools/dotc/ast/Desugar.scala | 4 ++-- .../src/dotty/tools/dotc/config/Feature.scala | 4 ++-- .../dotty/tools/dotc/core/Annotations.scala | 4 ++-- .../src/dotty/tools/dotc/core/Contexts.scala | 18 ------------------ .../dotty/tools/dotc/core/Definitions.scala | 4 ++-- .../src/dotty/tools/dotc/core/Phases.scala | 19 +++++++++++++++++-- .../src/dotty/tools/dotc/core/Scopes.scala | 3 ++- .../tools/dotc/core/SymDenotations.scala | 3 ++- .../src/dotty/tools/dotc/core/Symbols.scala | 7 ++++--- .../dotty/tools/dotc/core/TypeComparer.scala | 4 ++-- .../dotty/tools/dotc/core/TypeErasure.scala | 4 ++-- .../src/dotty/tools/dotc/core/Types.scala | 7 ++++--- .../dotc/core/classfile/ClassfileParser.scala | 3 ++- .../tools/dotc/core/tasty/TreeUnpickler.scala | 5 +++-- .../core/unpickleScala2/Scala2Unpickler.scala | 4 ++-- .../dotty/tools/dotc/reporting/messages.scala | 4 ++-- .../dotty/tools/dotc/transform/Bridges.scala | 8 ++++---- .../transform/ContextFunctionResults.scala | 6 +++--- .../dotc/transform/ElimErasedValueType.scala | 4 ++-- .../dotty/tools/dotc/transform/Erasure.scala | 10 +++++----- .../tools/dotc/transform/ExplicitOuter.scala | 11 ++++++----- .../dotc/transform/ExtensionMethods.scala | 4 ++-- .../dotc/transform/FunctionalInterfaces.scala | 5 +++-- .../dotc/transform/GenericSignatures.scala | 5 +++-- .../dotty/tools/dotc/transform/Staging.scala | 3 ++- .../tools/dotc/transform/TreeChecker.scala | 4 ++-- .../tools/dotc/transform/ValueClasses.scala | 3 ++- .../dotc/transform/YCheckPositions.scala | 6 +++--- .../src/dotty/tools/dotc/typer/Checking.scala | 3 ++- .../dotty/tools/dotc/typer/RefChecks.scala | 6 +++--- .../src/dotty/tools/repl/ReplDriver.scala | 4 ++-- .../test/dotty/tools/AnnotationsTests.scala | 3 ++- compiler/test/dotty/tools/SignatureTest.scala | 5 +++-- 41 files changed, 123 insertions(+), 106 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala index e3ac6545d41d..84cb98b8046f 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala @@ -20,6 +20,7 @@ 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.Phases._ /* * @@ -1461,7 +1462,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { // TODO specialization val constrainedType = new MethodBType(lambdaParamTypes.map(p => toTypeKind(p)), toTypeKind(lambdaTarget.info.resultType)).toASMType - val abstractMethod = atPhase(ctx.erasurePhase) { + val abstractMethod = atPhase(erasurePhase) { val samMethods = toDenot(functionalInterface).info.possibleSamMethods.toList samMethods match { case x :: Nil => x.symbol diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index f3131e6b205d..46e403e72c8b 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala @@ -14,6 +14,7 @@ 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.Phases._ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Names.Name @@ -360,7 +361,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { val narg = normalizeArgument(arg) // Transformation phases are not run on annotation trees, so we need to run // `constToLiteral` at this point. - val t = constToLiteral(narg)(using ctx.withPhase(ctx.erasurePhase)) + val t = atPhase(erasurePhase)(constToLiteral(narg)) t match { case Literal(const @ Constant(_)) => const.tag match { @@ -478,7 +479,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { * @see https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.4 */ def getGenericSignature(sym: Symbol, owner: Symbol): String = { - atPhase(ctx.erasurePhase) { + atPhase(erasurePhase) { val memberTpe = if (sym.is(Method)) sym.denot.info else owner.denot.thisType.memberInfo(sym) @@ -913,7 +914,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters { // But for now, just like we did in mixin, we just avoid writing a wrong generic signature // (one that doesn't erase to the actual signature). See run/t3452b for a test case. - val memberTpe = atPhase(ctx.erasurePhase) { moduleClass.denot.thisType.memberInfo(sym) } + val memberTpe = atPhase(erasurePhase) { moduleClass.denot.thisType.memberInfo(sym) } val erasedMemberType = TypeErasure.erasure(memberTpe) if (erasedMemberType =:= sym.denot.info) getGenericSignatureHelper(sym, moduleClass, memberTpe).orNull diff --git a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala index 1dfc1b6124b7..000a9e851da1 100644 --- a/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala +++ b/compiler/src/dotty/tools/backend/jvm/BTypesFromSymbols.scala @@ -9,6 +9,7 @@ import scala.collection.generic.Clearable import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Contexts.{inContext, atPhase} +import dotty.tools.dotc.core.Phases._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Phases.Phase import dotty.tools.dotc.transform.SymUtils._ @@ -203,12 +204,12 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { /** For currently compiled classes: All locally defined classes including local classes. * The empty list for classes that are not currently compiled. */ - private def getNestedClasses(sym: Symbol): List[Symbol] = definedClasses(sym, ctx.flattenPhase) + private def getNestedClasses(sym: Symbol): List[Symbol] = definedClasses(sym, flattenPhase) /** For currently compiled classes: All classes that are declared as members of this class * (but not inherited ones). The empty list for classes that are not currently compiled. */ - private def getMemberClasses(sym: Symbol): List[Symbol] = definedClasses(sym, ctx.lambdaLiftPhase) + private def getMemberClasses(sym: Symbol): List[Symbol] = definedClasses(sym, lambdaLiftPhase) private def definedClasses(sym: Symbol, phase: Phase) = if (sym.isDefinedInCurrentRun) @@ -229,11 +230,11 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { // After lambdalift (which is where we are), the rawowoner field contains the enclosing class. val enclosingClassSym = { if (innerClassSym.isClass) { - atPhase(ctx.flattenPhase.prev) { + atPhase(flattenPhase.prev) { toDenot(innerClassSym).owner.enclosingClass } } - else innerClassSym.enclosingClass(using ctx.withPhase(ctx.flattenPhase.prev)) + else atPhase(flattenPhase.prev)(innerClassSym.enclosingClass) } //todo is handled specially for JavaDefined symbols in scalac val enclosingClass: ClassBType = classBTypeFromSymbol(enclosingClassSym) @@ -257,7 +258,7 @@ class BTypesFromSymbols[I <: DottyBackendInterface](val int: I) extends BTypes { if (innerClassSym.isAnonymousClass || innerClassSym.isAnonymousFunction) None else { val original = innerClassSym.initial - Some(innerClassSym.name(using ctx.withPhase(original.validFor.phaseId)).mangledString) // moduleSuffix for module classes + Some(atPhase(original.validFor.phaseId)(innerClassSym.name).mangledString) // moduleSuffix for module classes } } diff --git a/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala b/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala index b190b38450ed..82aed9648aba 100644 --- a/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala +++ b/compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala @@ -2,6 +2,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.Phases._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Flags.Trait import dotty.tools.dotc.transform.MegaPhase.MiniPhase @@ -32,7 +33,7 @@ class CollectSuperCalls extends MiniPhase { } private def registerSuperCall(sym: ClassSymbol, calls: ClassSymbol)(using Context) = { - ctx.genBCodePhase match { + genBCodePhase match { case genBCodePhase: GenBCode => genBCodePhase.registerSuperCall(sym, calls) case _ => diff --git a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala index 8fbd3aa62342..411e2a90fd14 100644 --- a/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala +++ b/compiler/src/dotty/tools/backend/jvm/DottyBackendInterface.scala @@ -160,7 +160,7 @@ object DottyBackendInterface { */ def isTopLevelModuleClass(using Context): Boolean = sym.is(ModuleClass) && - atPhase(ctx.flattenPhase) { + atPhase(flattenPhase) { toDenot(sym).owner.is(PackageClass) } diff --git a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala index cf91ccef3ef7..b153fb5b0c2e 100644 --- a/compiler/src/dotty/tools/backend/jvm/GenBCode.scala +++ b/compiler/src/dotty/tools/backend/jvm/GenBCode.scala @@ -15,6 +15,7 @@ import java.util.Optional import dotty.tools.dotc.core._ import dotty.tools.dotc.sbt.ExtractDependencies import Contexts._ +import Phases._ import Symbols._ import Decorators._ @@ -166,7 +167,7 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten if (classSymbol.effectiveName.toString < dupClassSym.effectiveName.toString) (classSymbol, dupClassSym) else (dupClassSym, classSymbol) val same = classSymbol.effectiveName.toString == dupClassSym.effectiveName.toString - atPhase(ctx.typerPhase) { + atPhase(typerPhase) { if (same) summon[Context].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) @@ -271,7 +272,7 @@ class GenBCodePipeline(val int: DottyBackendInterface)(using ctx: Context) exten // ----------- compiler and sbt's callbacks - val (fullClassName, isLocal) = atPhase(ctx.sbtExtractDependenciesPhase) { + val (fullClassName, isLocal) = atPhase(sbtExtractDependenciesPhase) { (ExtractDependencies.classNameAsString(claszSymbol), claszSymbol.isLocal) } diff --git a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala index 985a05a4524b..3e5cebe508a1 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala @@ -2121,7 +2121,7 @@ class JSCodeGen()(using genCtx: Context) { if (isStat) { boxedResult } else { - val tpe = atPhase(ctx.elimErasedValueTypePhase) { + val tpe = atPhase(elimErasedValueTypePhase) { sym.info.finalResultType } unbox(boxedResult, tpe) @@ -2735,14 +2735,14 @@ class JSCodeGen()(using genCtx: Context) { def paramNamesAndTypes(using Context): List[(Names.TermName, Type)] = sym.info.paramNamess.flatten.zip(sym.info.paramInfoss.flatten) - val wereRepeated = atPhase(ctx.elimRepeatedPhase) { + val wereRepeated = atPhase(elimRepeatedPhase) { val list = for ((name, tpe) <- paramNamesAndTypes) yield (name -> tpe.isRepeatedParam) list.toMap } - val paramTypes = atPhase(ctx.elimErasedValueTypePhase) { + val paramTypes = atPhase(elimErasedValueTypePhase) { paramNamesAndTypes.toMap } diff --git a/compiler/src/dotty/tools/backend/sjs/JSInterop.scala b/compiler/src/dotty/tools/backend/sjs/JSInterop.scala index be4506500a02..3b1420c2d44e 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSInterop.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSInterop.scala @@ -6,6 +6,7 @@ import Flags._ import Symbols._ import NameOps._ import StdNames._ +import Phases._ import NameKinds.DefaultGetterName import JSDefinitions._ @@ -16,7 +17,7 @@ object JSInterop { /** Is this symbol a JavaScript type? */ def isJSType(sym: Symbol)(using Context): Boolean = { //sym.hasAnnotation(jsdefn.RawJSTypeAnnot) - atPhase(ctx.erasurePhase) { + atPhase(erasurePhase) { sym.derivesFrom(jsdefn.JSAnyClass) } } @@ -32,7 +33,7 @@ object JSInterop { * much as *accessor* methods created for `val`s and `var`s. */ def isJSGetter(sym: Symbol)(using Context): Boolean = { - sym.info.firstParamTypes.isEmpty && atPhase(ctx.erasurePhase) { + sym.info.firstParamTypes.isEmpty && atPhase(erasurePhase) { sym.info.isParameterless } } diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index e96ef12f931a..e17b85ee113f 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._ +import Symbols._, StdNames._, Trees._, Phases._ import Decorators.{given _}, transform.SymUtils._ import NameKinds.{UniqueName, EvidenceParamName, DefaultGetterName} import typer.{FrontEnd, Namer} @@ -1402,7 +1402,7 @@ object desugar { */ def makeAnnotated(fullName: String, tree: Tree)(using Context): Annotated = { val parts = fullName.split('.') - val ttree = ctx.typerPhase match { + val ttree = typerPhase match { case phase: FrontEnd if phase.stillToBeEntered(parts.last) => val prefix = parts.init.foldLeft(Ident(nme.ROOTPKG): Tree)((qual, name) => diff --git a/compiler/src/dotty/tools/dotc/config/Feature.scala b/compiler/src/dotty/tools/dotc/config/Feature.scala index 84b5a154eb22..46f80ce1287b 100644 --- a/compiler/src/dotty/tools/dotc/config/Feature.scala +++ b/compiler/src/dotty/tools/dotc/config/Feature.scala @@ -3,7 +3,7 @@ package dotc package config import core._ -import Contexts._, Symbols._, Names._, NameOps._ +import Contexts._, Symbols._, Names._, NameOps._, Phases._ import StdNames.nme import Decorators.{given _} import util.SourcePosition @@ -36,7 +36,7 @@ object Feature: * import owner.{ feature => _ } */ def enabledByImport(feature: TermName, owner: Symbol = NoSymbol)(using Context): Boolean = - atPhase(ctx.typerPhase) { + atPhase(typerPhase) { ctx.importInfo != null && ctx.importInfo.featureImported(feature, if owner.exists then owner else defn.LanguageModule.moduleClass) diff --git a/compiler/src/dotty/tools/dotc/core/Annotations.scala b/compiler/src/dotty/tools/dotc/core/Annotations.scala index 0220a496a03a..b8366c01d5d3 100644 --- a/compiler/src/dotty/tools/dotc/core/Annotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Annotations.scala @@ -1,7 +1,7 @@ package dotty.tools.dotc package core -import Symbols._, Types._, Contexts._, Constants._, ast.tpd._ +import Symbols._, Types._, Contexts._, Constants._, ast.tpd._, Phases._ import config.ScalaVersion import StdNames._ import dotty.tools.dotc.ast.tpd @@ -58,7 +58,7 @@ object Annotations { // 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(ctx.picklerPhase) + ctx.withPhaseNoLater(picklerPhase) abstract class LazyAnnotation extends Annotation { protected var mySym: Symbol | (Context => Symbol) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index cea60a5fe88a..660f15f6ebf6 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -517,30 +517,12 @@ object Contexts { (outersIterator.map(ctx => s" owner = ${ctx.owner}, scope = ${ctx.scope}, import = ${iinfo(using ctx)}").mkString("\n")) } - def typerPhase: Phase = base.typerPhase - def postTyperPhase: Phase = base.postTyperPhase - def sbtExtractDependenciesPhase: Phase = base.sbtExtractDependenciesPhase - def picklerPhase: Phase = base.picklerPhase - def reifyQuotesPhase: Phase = base.reifyQuotesPhase - def refchecksPhase: Phase = base.refchecksPhase - def patmatPhase: Phase = base.patmatPhase - def elimRepeatedPhase: Phase = base.elimRepeatedPhase - def extensionMethodsPhase: Phase = base.extensionMethodsPhase - def explicitOuterPhase: Phase = base.explicitOuterPhase - def gettersPhase: Phase = base.gettersPhase - def erasurePhase: Phase = base.erasurePhase - def elimErasedValueTypePhase: Phase = base.elimErasedValueTypePhase - def lambdaLiftPhase: Phase = base.lambdaLiftPhase - def flattenPhase: Phase = base.flattenPhase - def genBCodePhase: Phase = base.genBCodePhase - def settings: ScalaSettings = base.settings def definitions: Definitions = base.definitions def platform: Platform = base.platform def pendingUnderlying: mutable.HashSet[Type] = base.pendingUnderlying def uniqueNamedTypes: Uniques.NamedTypeUniques = base.uniqueNamedTypes def uniques: util.HashSet[Type] = base.uniques - def nextSymId: Int = base.nextSymId def initialize()(using Context): Unit = base.initialize() } diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index e4a651325d9e..da53b41fa46c 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -3,7 +3,7 @@ package dotc package core import scala.annotation.{threadUnsafe => tu} -import Types._, Contexts._, Symbols._, SymDenotations._, StdNames._, Names._ +import Types._, Contexts._, Symbols._, SymDenotations._, StdNames._, Names._, Phases._ import Flags._, Scopes._, Decorators._, NameOps._, Periods._, NullOpsDecorator._ import unpickleScala2.Scala2Unpickler.ensureConstructor import scala.collection.mutable @@ -1285,7 +1285,7 @@ class Definitions { object ContextFunctionType: def unapply(tp: Type)(using Context): Option[(List[Type], Type, Boolean)] = if ctx.erasedTypes then - unapply(tp)(using ctx.withPhase(ctx.erasurePhase)) + unapply(tp)(using ctx.withPhase(erasurePhase)) else val tp1 = tp.dealias if isContextFunctionClass(tp1.typeSymbol) then diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index 77c87d6e64f7..7513d19109fb 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -411,13 +411,28 @@ object Phases { override def toString: String = phaseName } - def curPhases(using Context): Array[Phase] = ctx.base.phases + def typerPhase(using Context): Phase = ctx.base.typerPhase + def postTyperPhase(using Context): Phase = ctx.base.postTyperPhase + def sbtExtractDependenciesPhase(using Context): Phase = ctx.base.sbtExtractDependenciesPhase + def picklerPhase(using Context): Phase = ctx.base.picklerPhase + def reifyQuotesPhase(using Context): Phase = ctx.base.reifyQuotesPhase + def refchecksPhase(using Context): Phase = ctx.base.refchecksPhase + def elimRepeatedPhase(using Context): Phase = ctx.base.elimRepeatedPhase + def extensionMethodsPhase(using Context): Phase = ctx.base.extensionMethodsPhase + def explicitOuterPhase(using Context): Phase = ctx.base.explicitOuterPhase + def gettersPhase(using Context): Phase = ctx.base.gettersPhase + def erasurePhase(using Context): Phase = ctx.base.erasurePhase + def elimErasedValueTypePhase(using Context): Phase = ctx.base.elimErasedValueTypePhase + def lambdaLiftPhase(using Context): Phase = ctx.base.lambdaLiftPhase + 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 /** Replace all instances of `oldPhaseClass` in `current` phases * by the result of `newPhases` applied to the old phase. */ - def replace(oldPhaseClass: Class[? <: Phase], newPhases: Phase => List[Phase], current: List[List[Phase]]): List[List[Phase]] = + private def replace(oldPhaseClass: Class[? <: Phase], newPhases: Phase => List[Phase], current: List[List[Phase]]): List[List[Phase]] = current.map(_.flatMap(phase => if (oldPhaseClass.isInstance(phase)) newPhases(phase) else phase :: Nil)) } diff --git a/compiler/src/dotty/tools/dotc/core/Scopes.scala b/compiler/src/dotty/tools/dotc/core/Scopes.scala index b2e0db8b9ac7..289ca55eb91a 100644 --- a/compiler/src/dotty/tools/dotc/core/Scopes.scala +++ b/compiler/src/dotty/tools/dotc/core/Scopes.scala @@ -12,6 +12,7 @@ import Types.{TermRef, NoPrefix} import Flags._ import Names._ import Contexts._ +import Phases._ import Denotations._ import SymDenotations._ import printing.Texts._ @@ -265,7 +266,7 @@ object Scopes { /** enter a symbol in this scope. */ final def enter[T <: Symbol](sym: T)(using Context): T = { - if (sym.isType && ctx.phaseId <= ctx.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 a6fa3f6302f7..0b1940980e6c 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -5,6 +5,7 @@ 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 Constants.Constant import TypeApplications.TypeParamInfo import Scopes.Scope @@ -53,7 +54,7 @@ trait SymDenotations { thisCtx: Context => if (denot.isOneOf(ValidForeverFlags) || denot.isRefinementClass || denot.isImport) true else { val initial = denot.initial - val firstPhaseId = initial.validFor.firstPhaseId.max(thisCtx.typerPhase.id) + val firstPhaseId = initial.validFor.firstPhaseId.max(typerPhase.id) if ((initial ne denot) || thisCtx.phaseId != firstPhaseId) thisCtx.withPhase(firstPhaseId).stillValidInOwner(initial) else diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index a2d739445df8..e63db4aa6d57 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -9,6 +9,7 @@ import Flags._ import Decorators._ import Symbols._ import Contexts._ +import Phases._ import SymDenotations._ import printing.Texts._ import printing.Printer @@ -45,11 +46,11 @@ trait Symbols { thisCtx: Context => * 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.nextSymId).asInstanceOf[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.nextSymId) + new ClassSymbol(coord, assocFile, ctx.base.nextSymId) // ---- Symbol creation methods ---------------------------------- @@ -814,7 +815,7 @@ object Symbols { } case none => NoSource } - sourceFromTopLevel(using ctx.withPhaseNoLater(ctx.flattenPhase)) + sourceFromTopLevel(using ctx.withPhaseNoLater(flattenPhase)) } } mySource diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index ed241bac56af..f0615f8afeda 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -3,7 +3,7 @@ package dotc package core import Types._, Contexts._, Symbols._, Flags._, Names._, NameOps._, Denotations._ -import Decorators._ +import Decorators._, Phases._ import StdNames.nme import TypeOps.refineUsingParent import collection.mutable @@ -807,7 +807,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w case _ => tp2.isAnyRef } compareJavaArray - case tp1: ExprType if ctx.phase.id > ctx.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 _ => diff --git a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala index c10111c6f6ad..ecc5b14a2536 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeErasure.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeErasure.scala @@ -2,7 +2,7 @@ package dotty.tools package dotc package core -import Symbols._, Types._, Contexts._, Flags._, Names._, StdNames._ +import Symbols._, Types._, Contexts._, Flags._, Names._, StdNames._, Phases._ import Flags.JavaDefined import Uniques.unique import TypeOps.makePackageObjPrefixExplicit @@ -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(ctx.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. * diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index 2075974c1617..f68953d007aa 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -12,6 +12,7 @@ import NameKinds.SkolemName import Scopes._ import Constants._ import Contexts._ +import Phases._ import Annotations._ import SymDenotations._ import Decorators._ @@ -1903,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 computeSignature(using ctx.withPhase(ctx.erasurePhase)) + else if ctx.erasedTypes then computeSignature(using ctx.withPhase(erasurePhase)) else symbol.asSeenFrom(prefix).signature /** The signature computed from the current denotation with `sigFromDenot` if it is @@ -1917,7 +1918,7 @@ object Types { else val lastd = lastDenotation if lastd != null then sigFromDenot(lastd) - else if ctx.erasedTypes then currentSignature(using ctx.withPhase(ctx.erasurePhase)) + else if ctx.erasedTypes then currentSignature(using ctx.withPhase(erasurePhase)) else val sym = currentSymbol if sym.exists then sym.asSeenFrom(prefix).signature @@ -1925,7 +1926,7 @@ object Types { /** The signature of a pre-erasure version of denotation `lastd`. */ private def sigFromDenot(lastd: Denotation)(using Context) = - if lastd.validFor.firstPhaseId <= ctx.erasurePhase.id then lastd.signature + if lastd.validFor.firstPhaseId <= erasurePhase.id then lastd.signature else lastd match case lastd: SingleDenotation => lastd.initial.signature case _ => Signature.OverloadedSignature diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index 828577216419..b865791cc8a0 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -7,6 +7,7 @@ import dotty.tools.tasty.{ TastyReader, TastyHeaderUnpickler } import Contexts._, Symbols._, Types._, Names._, StdNames._, NameOps._, Scopes._, Decorators._ import SymDenotations._, unpickleScala2.Scala2Unpickler._, Constants._, Annotations._, util.Spans._ +import Phases._ import NameKinds.DefaultGetterName import ast.{ tpd, untpd } import ast.tpd._, util._ @@ -939,7 +940,7 @@ class ClassfileParser( val outerName = entry.outerName.stripModuleClassSuffix val innerName = entry.originalName val owner = classNameToSymbol(outerName) - val result = getMember(owner, innerName.toTypeName)(using ctx.withPhase(ctx.typerPhase)) + val result = getMember(owner, innerName.toTypeName)(using ctx.withPhase(typerPhase)) assert(result ne NoSymbol, i"""failure to resolve inner class: |externalName = ${entry.externalName}, diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index df415c73ac67..ed39a3bb0caa 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -5,6 +5,7 @@ package tasty import Comments.CommentsContext import Contexts._ +import Phases._ import Symbols._ import Types._ import Scopes._ @@ -115,7 +116,7 @@ class TreeUnpickler(reader: TastyReader, def complete(denot: SymDenotation)(using Context): Unit = treeAtAddr(currentAddr) = new TreeReader(reader).readIndexedDef()( - using ctx.withPhaseNoLater(ctx.picklerPhase).withOwner(owner).withSource(source)) + using ctx.withPhaseNoLater(picklerPhase).withOwner(owner).withSource(source)) } class TreeReader(val reader: TastyReader) { @@ -1378,7 +1379,7 @@ class TreeUnpickler(reader: TastyReader, def complete(using Context): T = { pickling.println(i"starting to read at ${reader.reader.currentAddr} with owner $owner") op(reader)(ctx - .withPhaseNoLater(ctx.picklerPhase) + .withPhaseNoLater(picklerPhase) .withOwner(owner) .withModeBits(mode) .withSource(source)) diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index 72890bc0b259..0d0f4fca3222 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -8,7 +8,7 @@ import java.lang.Float.intBitsToFloat import java.lang.Double.longBitsToDouble import Contexts._, Symbols._, Types._, Scopes._, SymDenotations._, Names._, NameOps._ -import StdNames._, Denotations._, NameOps._, Flags._, Constants._, Annotations._ +import StdNames._, Denotations._, NameOps._, Flags._, Constants._, Annotations._, Phases._ import NameKinds.{Scala2MethodNameKinds, SuperAccessorName, ExpandedName} import util.Spans._ import dotty.tools.dotc.ast.{tpd, untpd}, ast.tpd._ @@ -608,7 +608,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas } atReadPos(startCoord(denot).toIndex, () => parseToCompletion(denot)( - using ctx.addMode(Mode.Scala2Unpickling).withPhaseNoLater(ctx.picklerPhase))) + using ctx.addMode(Mode.Scala2Unpickling).withPhaseNoLater(picklerPhase))) } catch { case ex: RuntimeException => handleRuntimeException(ex) diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index 44e194759276..2ab3f1439e24 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -4,7 +4,7 @@ package reporting import core._ import Contexts.{Context, ctx} -import Decorators._, Symbols._, Names._, NameOps._, Types._, Flags._ +import Decorators._, Symbols._, Names._, NameOps._, Types._, Flags._, Phases._ import Denotations.SingleDenotation import SymDenotations.SymDenotation import util.SourcePosition @@ -2022,7 +2022,7 @@ 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(ctx.elimErasedValueTypePhase.next) + val elimErasedCtx = ctx.withPhaseNoEarlier(elimErasedValueTypePhase.next) if (elimErasedCtx != ctx) details(using elimErasedCtx) else diff --git a/compiler/src/dotty/tools/dotc/transform/Bridges.scala b/compiler/src/dotty/tools/dotc/transform/Bridges.scala index 4a24344ed8d4..b9c30746169b 100644 --- a/compiler/src/dotty/tools/dotc/transform/Bridges.scala +++ b/compiler/src/dotty/tools/dotc/transform/Bridges.scala @@ -3,7 +3,7 @@ package dotc package transform import core._ -import Symbols._, Types._, Contexts._, Decorators._, Flags._, Scopes._ +import Symbols._, Types._, Contexts._, Decorators._, Flags._, Scopes._, Phases._ import DenotTransformers._ import ast.untpd import collection.{mutable, immutable} @@ -14,9 +14,9 @@ import util.SourcePosition class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { import ast.tpd._ - assert(ctx.phase == ctx.erasurePhase.next) - private val preErasureCtx = ctx.withPhase(ctx.erasurePhase) - private lazy val elimErasedCtx = ctx.withPhase(ctx.elimErasedValueTypePhase.next) + assert(ctx.phase == erasurePhase.next) + private val preErasureCtx = ctx.withPhase(erasurePhase) + private lazy val elimErasedCtx = ctx.withPhase(elimErasedValueTypePhase.next) private class BridgesCursor(using Context) extends OverridingPairs.Cursor(root) { diff --git a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala index 1c57294c1f60..eb4cf2880365 100644 --- a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala +++ b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala @@ -3,7 +3,7 @@ package dotc package transform import core._ -import Contexts._, Symbols._, Types._, Annotations._, Constants._ +import Contexts._, Symbols._, Types._, Annotations._, Constants._, Phases._ import StdNames.nme import ast.untpd import ast.tpd._ @@ -100,7 +100,7 @@ object ContextFunctionResults: * parameter count. */ def contextFunctionResultTypeCovering(meth: Symbol, paramCount: Int)(using Context) = - inContext(ctx.withPhase(ctx.erasurePhase)) { + inContext(ctx.withPhase(erasurePhase)) { // Recursive instances return pairs of context types and the // # of parameters they represent. def missingCR(tp: Type, crCount: Int): (Type, Int) = @@ -121,7 +121,7 @@ object ContextFunctionResults: */ def integrateSelect(tree: untpd.Tree, n: Int = 0)(using Context): Boolean = if ctx.erasedTypes then - integrateSelect(tree, n)(using ctx.withPhase(ctx.erasurePhase)) + integrateSelect(tree, n)(using ctx.withPhase(erasurePhase)) else tree match case Select(qual, name) => if name == nme.apply && defn.isContextFunctionClass(tree.symbol.maybeOwner) then diff --git a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala index 6afe1fa8ee03..c632b46d6de2 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala @@ -4,7 +4,7 @@ package transform import ast.{Trees, tpd} import core._, core.Decorators._ import MegaPhase._ -import Types._, Contexts._, Flags._, DenotTransformers._ +import Types._, Contexts._, Flags._, DenotTransformers._, Phases._ import Symbols._, StdNames._, Trees._ import TypeErasure.ErasedValueType, ValueClasses._ import reporting.messages.DoubleDefinition @@ -103,7 +103,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => !info1.matchesLoosely(info2) && !bothPolyApply) ctx.error(DoubleDefinition(sym1, sym2, root), root.sourcePos) } - val earlyCtx = ctx.withPhase(ctx.elimRepeatedPhase.next) + val earlyCtx = ctx.withPhase(elimRepeatedPhase.next) while (opc.hasNext) { val sym1 = opc.overriding val sym2 = opc.overridden diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 7e47ec4df25a..8363bec635a1 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -514,7 +514,7 @@ object Erasure { val app = untpd.cpy.Apply(tree1)(tree1, args) assert(ctx.typer.isInstanceOf[Erasure.Typer]) ctx.typer.typed(app, pt) - .changeOwnerAfter(origOwner, ctx.owner, ctx.erasurePhase.asInstanceOf[Erasure]) + .changeOwnerAfter(origOwner, ctx.owner, erasurePhase.asInstanceOf[Erasure]) seq(defs.toList, abstracted(Nil, origType, pt)) end etaExpand @@ -717,7 +717,7 @@ object Erasure { } override def typedTypeApply(tree: untpd.TypeApply, pt: Type)(using Context): Tree = { - val ntree = interceptTypeApply(tree.asInstanceOf[TypeApply])(using ctx.withPhase(ctx.erasurePhase)).withSpan(tree.span) + val ntree = interceptTypeApply(tree.asInstanceOf[TypeApply])(using ctx.withPhase(erasurePhase)).withSpan(tree.span) ntree match { case TypeApply(fun, args) => @@ -904,7 +904,7 @@ object Erasure { case stat: DefDef @unchecked if stat.symbol.name.is(BodyRetainerName) => val retainer = stat.symbol val origName = retainer.name.asTermName.exclude(BodyRetainerName) - val inlineMeth = atPhase(ctx.typerPhase) { + val inlineMeth = atPhase(typerPhase) { retainer.owner.info.decl(origName) .matchingDenotation(retainer.owner.thisType, stat.symbol.info) .symbol @@ -950,10 +950,10 @@ 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 != ctx.erasurePhase && ctx.phase != ctx.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. - adapt(tree, pt, locked)(using ctx.withPhase(ctx.erasurePhase.next)) + adapt(tree, pt, locked)(using ctx.withPhase(erasurePhase.next)) else if (tree.isEmpty) tree else if (ctx.mode is Mode.Pattern) tree // TODO: replace with assertion once pattern matcher is active else adaptToType(tree, pt) diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index 55ec86295b95..590816f8ddf7 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -6,6 +6,7 @@ import MegaPhase._ import core.DenotTransformers._ import core.Symbols._ import core.Contexts._ +import core.Phases._ import core.Types._ import core.Flags._ import core.Decorators._ @@ -127,9 +128,9 @@ object ExplicitOuter { /** Ensure that class `cls` has outer accessors */ def ensureOuterAccessors(cls: ClassSymbol)(using Context): Unit = - atPhase(ctx.explicitOuterPhase.next) { + atPhase(explicitOuterPhase.next) { if (!hasOuter(cls)) - newOuterAccessors(cls).foreach(_.enteredAfter(ctx.explicitOuterPhase.asInstanceOf[DenotTransformer])) + newOuterAccessors(cls).foreach(_.enteredAfter(explicitOuterPhase.asInstanceOf[DenotTransformer])) } /** The outer accessor and potentially outer param accessor needed for class `cls` */ @@ -173,7 +174,7 @@ 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(ctx.explicitOuterPhase.next) // outer accessors are entered at explicitOuter + 1, should not be defined before. + 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) } @@ -298,7 +299,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(ctx.erasurePhase))) + outerPrefix(tpe.underlying(using ctx.withPhaseNoLater(erasurePhase))) } case tpe: TypeProxy => outerPrefix(tpe.underlying) @@ -395,7 +396,7 @@ object ExplicitOuter { try @tailrec def loop(tree: Tree, count: Int): Tree = val treeCls = tree.tpe.widen.classSymbol - val outerAccessorCtx = ctx.withPhaseNoLater(ctx.lambdaLiftPhase) // lambdalift mangles local class names, which means we cannot reliably find outer acessors anymore + 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") if (count == 0 || count < 0 && treeCls == toCls) tree else diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index 975fa26ad1f7..885da16b3447 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -10,7 +10,7 @@ import ValueClasses._ import dotty.tools.dotc.ast.tpd import scala.collection.mutable import core._ -import Types._, Contexts._, Names._, Flags._, DenotTransformers._ +import Types._, Contexts._, Names._, Flags._, DenotTransformers._, Phases._ import SymDenotations._, Symbols._, StdNames._, Denotations._ import TypeErasure.{ valueErasure, ErasedValueType } import NameKinds.{ExtMethName, UniqueExtMethName} @@ -184,7 +184,7 @@ object ExtensionMethods { /** Return the extension method that corresponds to given instance method `meth`. */ def extensionMethod(imeth: Symbol)(using Context): TermSymbol = - atPhase(ctx.extensionMethodsPhase.next) { + atPhase(extensionMethodsPhase.next) { // FIXME use toStatic instead? val companion = imeth.owner.companionModule val companionInfo = companion.info diff --git a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala index eb0e8da166ba..1449db02b51e 100644 --- a/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala +++ b/compiler/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala @@ -8,6 +8,7 @@ import Symbols._ import Contexts._ import Decorators._ import NameOps._ +import Phases._ import dotty.tools.dotc.ast.tpd @@ -35,11 +36,11 @@ class FunctionalInterfaces extends MiniPhase { if (defn.isSpecializableFunction(cls, implParamTypes, implResultType) && !ctx.settings.scalajs.value) { // never do anything for Scala.js, but do this test as late as possible not to slow down Scala/JVM - val names = atPhase(ctx.erasurePhase) { cls.typeParams.map(_.name) } + val names = atPhase(erasurePhase) { cls.typeParams.map(_.name) } 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(ctx.typerPhase).requiredClass(functionPackage ++ interfaceName) + val interface = ctx.withPhase(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/GenericSignatures.scala b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala index 95bef5f49243..11dc4dfa0c06 100644 --- a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala +++ b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala @@ -4,6 +4,7 @@ package transform import core.Annotations._ import core.Contexts._ +import core.Phases._ import core.Definitions import core.Flags._ import core.Names.{DerivedName, Name, SimpleName, TypeName} @@ -34,7 +35,7 @@ object GenericSignatures { def javaSig(sym0: Symbol, info: Type)(using Context): Option[String] = // Avoid generating a signature for local symbols. if (sym0.isLocal) None - else javaSig0(sym0, info)(using ctx.withPhase(ctx.erasurePhase)) + else javaSig0(sym0, info)(using ctx.withPhase(erasurePhase)) @noinline private final def javaSig0(sym0: Symbol, info: Type)(using Context): Option[String] = { @@ -112,7 +113,7 @@ object GenericSignatures { // a type parameter or similar) must go through here or the signature is // likely to end up with Foo.Empty where it needs Foo.Empty$. def fullNameInSig(sym: Symbol): Unit = { - val name = atPhase(ctx.genBCodePhase) { sanitizeName(sym.fullName).replace('.', '/') } + val name = atPhase(genBCodePhase) { sanitizeName(sym.fullName).replace('.', '/') } builder.append('L').append(name) } diff --git a/compiler/src/dotty/tools/dotc/transform/Staging.scala b/compiler/src/dotty/tools/dotc/transform/Staging.scala index 09410c176a3c..6138ad5b42bb 100644 --- a/compiler/src/dotty/tools/dotc/transform/Staging.scala +++ b/compiler/src/dotty/tools/dotc/transform/Staging.scala @@ -5,6 +5,7 @@ import dotty.tools.dotc.ast.Trees._ import dotty.tools.dotc.ast.{TreeTypeMap, tpd, untpd} import dotty.tools.dotc.core.Constants._ import dotty.tools.dotc.core.Contexts._ +import dotty.tools.dotc.core.Phases._ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.quoted._ @@ -38,7 +39,7 @@ class Staging extends MacroTransform { override def allowsImplicitSearch: Boolean = true override def checkPostCondition(tree: Tree)(using Context): Unit = - if (ctx.phase <= ctx.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/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index cf284b48636d..e8f93f15d417 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -11,7 +11,7 @@ import core.Flags._ import core.StdNames._ import core.NameKinds.{DocArtifactName, OuterSelectName} import core.Decorators._ -import core.Phases.Phase +import core.Phases._ import core.Mode import typer._ import typer.ErrorReporting._ @@ -90,7 +90,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 <= ctx.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 41727e3e8fa9..2b9d786bffe1 100644 --- a/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala +++ b/compiler/src/dotty/tools/dotc/transform/ValueClasses.scala @@ -5,6 +5,7 @@ import core._ import Types._ import Symbols._ import Contexts._ +import Phases._ import Flags._ import StdNames._ import SymUtils._ @@ -22,7 +23,7 @@ object ValueClasses { } def isMethodWithExtension(sym: Symbol)(using Context): Boolean = - atPhaseNotLaterThan(ctx.extensionMethodsPhase) { + atPhaseNotLaterThan(extensionMethodsPhase) { val d = sym.denot d.validFor.containsPhaseId(summon[Context].phaseId) && d.isRealMethod && diff --git a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala index 30238309a826..6722701ad448 100644 --- a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala +++ b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala @@ -6,12 +6,12 @@ import dotty.tools.dotc.ast.{tpd, untpd} import dotty.tools.dotc.core.Contexts._ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Flags._ -import dotty.tools.dotc.core.Phases +import dotty.tools.dotc.core.Phases.{Phase, postTyperPhase} import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.util.{SourceFile, SourcePosition} /** Ycheck inlined positions */ -class YCheckPositions extends Phases.Phase { +class YCheckPositions extends Phase { import tpd._ def phaseName: String = "inlinedPositions" @@ -55,7 +55,7 @@ class YCheckPositions extends Phases.Phase { } private def isMacro(call: Tree)(using Context) = - if (ctx.phase <= ctx.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 80b59d4f52f0..248afc958ff6 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -18,6 +18,7 @@ import CheckRealizable._ import ErrorReporting.errorTree import rewrites.Rewrites.patch import util.Spans.Span +import Phases.refchecksPhase import util.SourcePosition import util.Spans.Span @@ -740,7 +741,7 @@ trait Checking { tp.underlyingClassRef(refinementOK = false) match { case tref: TypeRef => if (traitReq && !tref.symbol.is(Trait)) ctx.error(TraitIsExpected(tref.symbol), pos) - if (stablePrefixReq && ctx.phase <= ctx.refchecksPhase) checkStable(tref.prefix, pos, "class prefix") + if (stablePrefixReq && ctx.phase <= refchecksPhase) checkStable(tref.prefix, pos, "class prefix") tp case _ => ctx.error(ex"$tp is not a class type", pos) diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index 8b813bb5022f..b9546bb25746 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -4,7 +4,7 @@ package typer import transform._ import core._ import Symbols._, Types._, Contexts._, Flags._, Names._, NameOps._ -import StdNames._, Denotations._, SymUtils._ +import StdNames._, Denotations._, SymUtils._, Phases._ import NameKinds.DefaultGetterName import Annotations._ import util.Spans._ @@ -450,8 +450,8 @@ object RefChecks { } def hasJavaErasedOverriding(sym: Symbol): Boolean = - !ctx.erasurePhase.exists || // can't do the test, assume the best - atPhase(ctx.erasurePhase.next) { + !erasurePhase.exists || // can't do the test, assume the best + atPhase(erasurePhase.next) { clazz.info.nonPrivateMember(sym.name).hasAltWith { alt => alt.symbol.is(JavaDefined, butNot = Deferred) && !sym.owner.derivesFrom(alt.symbol.owner) && diff --git a/compiler/src/dotty/tools/repl/ReplDriver.scala b/compiler/src/dotty/tools/repl/ReplDriver.scala index 700124a9a46d..679c5531b574 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 +import dotty.tools.dotc.core.Phases.{curPhases, typerPhase} import dotty.tools.dotc.core.Denotations.Denotation import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Mode @@ -321,7 +321,7 @@ class ReplDriver(settings: Array[String], rendering.renderTypeDef(x) } - atPhase(ctx.typerPhase.next) { + atPhase(typerPhase.next) { // Display members of wrapped module: tree.symbol.info.memberClasses .find(_.symbol.name == newestWrapper.moduleClassName) diff --git a/compiler/test/dotty/tools/AnnotationsTests.scala b/compiler/test/dotty/tools/AnnotationsTests.scala index 9459bc235648..a468f22ecf54 100644 --- a/compiler/test/dotty/tools/AnnotationsTests.scala +++ b/compiler/test/dotty/tools/AnnotationsTests.scala @@ -7,6 +7,7 @@ import org.junit.Test import dotc.ast.Trees._ import dotc.core.Decorators._ import dotc.core.Contexts._ +import dotc.core.Phases._ import dotc.core.Types._ import java.io.File @@ -25,7 +26,7 @@ class AnnotationsTest: val annotCls = ctx.requiredClass("Annot") val arrayOfString = defn.ArrayType.appliedTo(List(defn.StringType)) - atPhase(ctx.erasurePhase.next) { + atPhase(erasurePhase.next) { val annot = cls.getAnnotation(annotCls) // Even though we're forcing the annotation after erasure, // the typed trees should be unerased, so the type of diff --git a/compiler/test/dotty/tools/SignatureTest.scala b/compiler/test/dotty/tools/SignatureTest.scala index 1a5420a60865..b5644b09950f 100644 --- a/compiler/test/dotty/tools/SignatureTest.scala +++ b/compiler/test/dotty/tools/SignatureTest.scala @@ -7,6 +7,7 @@ import org.junit.Test import dotc.ast.Trees._ import dotc.core.Decorators._ import dotc.core.Contexts._ +import dotc.core.Phases._ import dotc.core.Types._ import java.io.File @@ -15,12 +16,12 @@ import java.nio.file._ class SignatureTest: @Test def signatureCaching: Unit = inCompilerContext(TestConfiguration.basicClasspath, separateRun = true, "case class Foo(value: Unit)") { - val (ref, refSig) = atPhase(ctx.erasurePhase.next) { + val (ref, refSig) = atPhase(erasurePhase.next) { val cls = ctx.requiredClass("Foo") val ref = cls.requiredMethod("value").termRef (ref, ref.signature) } - atPhase(ctx.typerPhase) { + atPhase(typerPhase) { // NamedType#signature is always computed before erasure, which ensures // that it stays stable and therefore can be cached as long as // signatures are guaranteed to be stable before erasure, see the From 165b7d8390d3fbbe2581005ed4f7bccc8d11c85b Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 17:37:37 +0200 Subject: [PATCH 38/41] Use atPhase instead of passing ctx.withPhase --- compiler/src/dotty/tools/dotc/ast/tpd.scala | 4 ++-- .../src/dotty/tools/dotc/core/Definitions.scala | 2 +- .../src/dotty/tools/dotc/core/Denotations.scala | 8 ++++---- .../src/dotty/tools/dotc/core/SymDenotations.scala | 13 ++++++------- compiler/src/dotty/tools/dotc/core/Symbols.scala | 4 ++-- compiler/src/dotty/tools/dotc/core/Types.scala | 6 +++--- .../tools/dotc/core/classfile/ClassfileParser.scala | 2 +- .../dotc/core/unpickleScala2/Scala2Unpickler.scala | 2 +- .../dotty/tools/dotc/transform/CapturedVars.scala | 11 ++++++----- .../src/dotty/tools/dotc/transform/Erasure.scala | 6 ++++-- .../tools/dotc/transform/ExtensionMethods.scala | 4 ++-- .../dotty/tools/dotc/transform/FirstTransform.scala | 4 ++-- .../tools/dotc/transform/GenericSignatures.scala | 2 +- .../src/dotty/tools/dotc/transform/LambdaLift.scala | 8 +++++--- .../dotty/tools/dotc/transform/MacroTransform.scala | 2 +- .../src/dotty/tools/dotc/transform/MegaPhase.scala | 2 +- .../tools/dotc/transform/ParamForwarding.scala | 2 +- .../dotty/tools/dotc/transform/SuperAccessors.scala | 2 +- .../tools/dotc/transform/TransformByNameApply.scala | 2 +- 19 files changed, 45 insertions(+), 41 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 57227b2eb3e5..18a8d3f4e836 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -833,7 +833,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { def traverse(tree: Tree)(using Context) = tree match { case tree: DefTree => val sym = tree.symbol - val prevDenot = sym.denot(using ctx.withPhase(trans)) + val prevDenot = atPhase(trans)(sym.denot) if (prevDenot.effectiveOwner == from.skipWeakOwner) { val d = sym.copySymDenotation(owner = to) d.installAfter(trans) @@ -847,7 +847,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { traverser.traverse(tree) tree } - else changeOwnerAfter(from, to, trans)(using ctx.withPhase(trans.next)) + else atPhase(trans.next)(changeOwnerAfter(from, to, trans)) /** A select node with the given selector name and a computed type */ def select(name: Name)(using Context): Select = diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index da53b41fa46c..875916c62a39 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -1285,7 +1285,7 @@ class Definitions { object ContextFunctionType: def unapply(tp: Type)(using Context): Option[(List[Type], Type, Boolean)] = if ctx.erasedTypes then - unapply(tp)(using ctx.withPhase(erasurePhase)) + atPhase(erasurePhase)(unapply(tp)) else val tp1 = tp.dealias if isContextFunctionClass(tp1.typeSymbol) then diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index 9ecd73f8561d..11314ce11666 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -3,7 +3,7 @@ package dotc package core import SymDenotations.{ SymDenotation, ClassDenotation, NoDenotation, LazyType } -import Contexts.{Context, ctx, ContextBase} +import Contexts._ import Names._ import NameKinds._ import StdNames._ @@ -797,7 +797,7 @@ object Denotations { val transformer = ctx.base.denotTransformers(nextTransformerId) //println(s"transforming $this with $transformer") try - next = transformer.transform(cur)(using ctx.withPhase(transformer)) + next = atPhase(transformer)(transformer.transform(cur)) catch { case ex: CyclicReference => println(s"error while transforming $this") // DEBUG @@ -834,7 +834,7 @@ object Denotations { // 10 times. Best out of 10: 18154ms with `prev` field, 17777ms without. cnt += 1 if (cnt > MaxPossiblePhaseId) - return current(using ctx.withPhase(coveredInterval.firstPhaseId)) + return atPhase(coveredInterval.firstPhaseId)(current) } cur } @@ -851,7 +851,7 @@ object Denotations { */ protected def installAfter(phase: DenotTransformer)(using Context): Unit = { val targetId = phase.next.id - if (ctx.phaseId != targetId) installAfter(phase)(using ctx.withPhase(phase.next)) + 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}") diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index 0b1940980e6c..051b904897fa 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -243,7 +243,7 @@ object SymDenotations { myFlags |= Touched // completions.println(s"completing ${this.debugString}") - try completer.complete(this)(using ctx.withPhase(validFor.firstPhaseId)) + try atPhase(validFor.firstPhaseId)(completer.complete(this)) catch { case ex: CyclicReference => println(s"error while completing ${this.debugString}") @@ -257,7 +257,7 @@ object SymDenotations { else { if (myFlags.is(Touched)) throw CyclicReference(this) myFlags |= Touched - completer.complete(this)(using ctx.withPhase(validFor.firstPhaseId)) + atPhase(validFor.firstPhaseId)(completer.complete(this)) } protected[dotc] def info_=(tp: Type): Unit = { @@ -847,13 +847,12 @@ object SymDenotations { isClass && derivesFrom(defn.JavaSerializableClass) /** Is this symbol a class that extends `AnyVal`? */ - final def isValueClass(using Context): Boolean = { + final def isValueClass(using Context): Boolean = val di = initial - di.isClass && - di.derivesFrom(defn.AnyValClass)(using ctx.withPhase(di.validFor.firstPhaseId)) + di.isClass + && atPhase(di.validFor.firstPhaseId)(di.derivesFrom(defn.AnyValClass)) // We call derivesFrom at the initial phase both because AnyVal does not exist // after Erasure and to avoid cyclic references caused by forcing denotations - } /** Is this symbol a class of which `null` is a value? */ final def isNullableClass(using Context): Boolean = @@ -2200,7 +2199,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) ensureFreshScopeAfter(phase)(using ctx.withPhase(phase.next)) + if (ctx.phaseId != phase.next.id) atPhase(phase.next)(ensureFreshScopeAfter(phase)) else { val prevClassInfo = atPhase(phase) { current.asInstanceOf[ClassDenotation].classInfo diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index e63db4aa6d57..ee64ef087ef1 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -585,7 +585,7 @@ object Symbols { */ def enteredAfter(phase: DenotTransformer)(using Context): this.type = if ctx.phaseId != phase.next.id then - enteredAfter(phase)(using ctx.withPhase(phase.next)) + atPhase(phase.next)(enteredAfter(phase)) else this.owner match { case owner: ClassSymbol => if (owner.is(Package)) { @@ -610,7 +610,7 @@ object Symbols { */ def dropAfter(phase: DenotTransformer)(using Context): Unit = if ctx.phaseId != phase.next.id then - dropAfter(phase)(using ctx.withPhase(phase.next)) + atPhase(phase.next)(dropAfter(phase)) else { assert (!this.owner.is(Package)) this.owner.asClass.ensureFreshScopeAfter(phase) diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index f68953d007aa..ed3ba9a562af 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -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 computeSignature(using ctx.withPhase(erasurePhase)) + 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 ctx.erasedTypes then currentSignature(using ctx.withPhase(erasurePhase)) + else if ctx.erasedTypes then atPhase(erasurePhase)(currentSignature) else val sym = currentSymbol if sym.exists then sym.asSeenFrom(prefix).signature @@ -2053,7 +2053,7 @@ object Types { d = memberDenot(prefix, name, true) if (!d.exists && ctx.phaseId > FirstPhaseId && lastDenotation.isInstanceOf[SymDenotation]) // name has changed; try load in earlier phase and make current - d = memberDenot(name, allowPrivate)(using ctx.withPhase(ctx.phaseId - 1)).current + d = atPhase(ctx.phaseId - 1)(memberDenot(name, allowPrivate)).current if (d.isOverloaded) d = disambiguate(d) d diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index b865791cc8a0..d612d80d44af 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -940,7 +940,7 @@ class ClassfileParser( val outerName = entry.outerName.stripModuleClassSuffix val innerName = entry.originalName val owner = classNameToSymbol(outerName) - val result = getMember(owner, innerName.toTypeName)(using ctx.withPhase(typerPhase)) + val result = atPhase(typerPhase)(getMember(owner, innerName.toTypeName)) assert(result ne NoSymbol, i"""failure to resolve inner class: |externalName = ${entry.externalName}, diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index 0d0f4fca3222..85c8f6a8d071 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 val atp = readTypeRef() val phase = ctx.phase Annotation.deferred(atp.typeSymbol)( - atReadPos(start, () => readAnnotationContents(end)(using ctx.withPhase(phase)))) + atReadPos(start, () => atPhase(phase)(readAnnotationContents(end)))) } /* Read an abstract syntax tree */ diff --git a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala index 01f770a19432..7e7a517b5dfc 100644 --- a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala +++ b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala @@ -75,8 +75,9 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = } override def prepareForUnit(tree: Tree)(using Context): Context = { - val captured = (new CollectCaptured) - .runOver(ctx.compilationUnit.tpdTree)(using ctx.withPhase(thisPhase)) + val captured = atPhase(thisPhase) { + CollectCaptured().runOver(ctx.compilationUnit.tpdTree) + } ctx.fresh.updateStore(Captured, captured) } @@ -91,9 +92,9 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = } override def prepareForValDef(vdef: ValDef)(using Context): Context = { - val sym = vdef.symbol(using ctx.withPhase(thisPhase)) + val sym = atPhase(thisPhase)(vdef.symbol) if (captured contains sym) { - val newd = sym.denot(using ctx.withPhase(thisPhase)).copySymDenotation( + val newd = atPhase(thisPhase)(sym.denot).copySymDenotation( info = refClass(sym.info.classSymbol, sym.hasAnnotation(defn.VolatileAnnot)).typeRef, initFlags = sym.flags &~ Mutable) newd.removeAnnotation(defn.VolatileAnnot) @@ -117,7 +118,7 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer { thisPhase = override def transformIdent(id: Ident)(using Context): Tree = { val vble = id.symbol if (captured.contains(vble)) - id.select(nme.elem).ensureConforms(vble.denot(using ctx.withPhase(thisPhase)).info) + id.select(nme.elem).ensureConforms(atPhase(thisPhase)(vble.denot).info) else id } diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 8363bec635a1..686a53aea51c 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -717,7 +717,9 @@ object Erasure { } override def typedTypeApply(tree: untpd.TypeApply, pt: Type)(using Context): Tree = { - val ntree = interceptTypeApply(tree.asInstanceOf[TypeApply])(using ctx.withPhase(erasurePhase)).withSpan(tree.span) + val ntree = atPhase(erasurePhase)( + interceptTypeApply(tree.asInstanceOf[TypeApply]) + ).withSpan(tree.span) ntree match { case TypeApply(fun, args) => @@ -953,7 +955,7 @@ object Erasure { 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. - adapt(tree, pt, locked)(using ctx.withPhase(erasurePhase.next)) + atPhase(erasurePhase.next)(adapt(tree, pt, locked)) else if (tree.isEmpty) tree else if (ctx.mode is Mode.Pattern) tree // TODO: replace with assertion once pattern matcher is active else adaptToType(tree, pt) diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index 885da16b3447..863e19372774 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 = cls.denot(using ctx.withPhase(ctx.phase.next)).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 } @@ -135,7 +135,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete (imeth.flags | Final) &~ (Override | Protected | AbsOverride), fullyParameterizedType(imeth.info, imeth.owner.asClass), privateWithin = imeth.privateWithin, coord = imeth.coord) - extensionMeth.addAnnotations(imeth.annotations)(using ctx.withPhase(thisPhase)) + atPhase(thisPhase)(extensionMeth.addAnnotations(imeth.annotations)) // need to change phase to add tailrec annotation which gets removed from original method in the same phase. extensionMeth } diff --git a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala index c1e82b2bbb57..085fea1a2d0b 100644 --- a/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/FirstTransform.scala @@ -9,7 +9,7 @@ import ast.untpd import Flags._ import Types._ import Constants.Constant -import Contexts.{Context, ctx} +import Contexts._ import Symbols._ import Decorators._ import scala.collection.mutable @@ -129,7 +129,7 @@ class FirstTransform extends MiniPhase with InfoTransformer { thisPhase => } override def transformStats(trees: List[Tree])(using Context): List[Tree] = - ast.Trees.flatten(reorderAndComplete(trees)(using ctx.withPhase(thisPhase.next))) + ast.Trees.flatten(atPhase(thisPhase.next)(reorderAndComplete(trees))) private object collectBinders extends TreeAccumulator[List[Ident]] { def apply(annots: List[Ident], t: Tree)(using Context): List[Ident] = t match { diff --git a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala index 11dc4dfa0c06..e2d6362ce1ff 100644 --- a/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala +++ b/compiler/src/dotty/tools/dotc/transform/GenericSignatures.scala @@ -35,7 +35,7 @@ object GenericSignatures { def javaSig(sym0: Symbol, info: Type)(using Context): Option[String] = // Avoid generating a signature for local symbols. if (sym0.isLocal) None - else javaSig0(sym0, info)(using ctx.withPhase(erasurePhase)) + else atPhase(erasurePhase)(javaSig0(sym0, info)) @noinline private final def javaSig0(sym0: Symbol, info: Type)(using Context): Option[String] = { diff --git a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala index 40040d4447b0..a87e9f00bd6b 100644 --- a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala +++ b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala @@ -374,8 +374,10 @@ object LambdaLift { (new CollectDependencies).traverse(ctx.compilationUnit.tpdTree) computeFreeVars() computeLiftedOwners() - generateProxies()(using ctx.withPhase(thisPhase.next)) - liftLocals()(using ctx.withPhase(thisPhase.next)) + } + atPhase(thisPhase.next) { + generateProxies() + liftLocals() } def currentEnclosure(using Context): Symbol = @@ -421,7 +423,7 @@ object LambdaLift { } def proxyRef(sym: Symbol)(using Context): Tree = { - val psym = proxy(sym)(using ctx.withPhase(thisPhase)) + val psym = atPhase(thisPhase)(proxy(sym)) thisPhase.transformFollowingDeep(if (psym.owner.isTerm) ref(psym) else memberRef(psym)) } diff --git a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala index 76987308809d..947a80711842 100644 --- a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala @@ -18,7 +18,7 @@ abstract class MacroTransform extends Phase { override def run(using Context): Unit = { val unit = ctx.compilationUnit - unit.tpdTree = newTransformer.transform(unit.tpdTree)(using ctx.withPhase(transformPhase)) + unit.tpdTree = atPhase(transformPhase)(newTransformer.transform(unit.tpdTree)) } protected def newTransformer(using Context): Transformer diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index 988bb6d2f0d4..7963428f8847 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -424,7 +424,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { override def run(using Context): Unit = ctx.compilationUnit.tpdTree = - transformUnit(ctx.compilationUnit.tpdTree)(using ctx.withPhase(miniPhases.last.next)) + atPhase(miniPhases.last.next)(transformUnit(ctx.compilationUnit.tpdTree)) // Initialization code diff --git a/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala b/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala index 29503f8ae535..0bac0f073398 100644 --- a/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala +++ b/compiler/src/dotty/tools/dotc/transform/ParamForwarding.scala @@ -56,7 +56,7 @@ class ParamForwarding extends MiniPhase with IdentityDenotTransformer: val sym = mdef.symbol.asTerm if sym.is(SuperParamAlias) then assert(sym.is(ParamAccessor, butNot = Mutable)) - val alias = inheritedAccessor(sym)(using ctx.withPhase(thisPhase)) + val alias = atPhase(thisPhase)(inheritedAccessor(sym)) if alias.exists then sym.copySymDenotation( name = ParamAccessorName(sym.name), diff --git a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala index 0dc2b33ddb80..c3cffc0814cf 100644 --- a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala @@ -147,7 +147,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { } if (name.isTermName && mix.name.isEmpty && (clazz.is(Trait) || clazz != ctx.owner.enclosingClass || !validCurrentClass)) - superAccessorCall(sel)(using ctx.withPhase(thisPhase.next)) + atPhase(thisPhase.next)(superAccessorCall(sel)) else sel } diff --git a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala index a9bcfe44bbaa..90f7488b973d 100644 --- a/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/TransformByNameApply.scala @@ -23,7 +23,7 @@ abstract class TransformByNameApply extends MiniPhase { thisPhase: DenotTransfor /** The info of the tree's symbol before it is potentially transformed in this phase */ private def originalDenotation(tree: Tree)(using Context) = - tree.symbol.denot(using ctx.withPhase(thisPhase)) + atPhase(thisPhase)(tree.symbol.denot) /** If denotation had an ExprType before, it now gets a function type */ protected def exprBecomesFunction(symd: SymDenotation)(using Context): Boolean = From 5442a4f7a1f91de871cf71d95ae5bfd8ef4c19c9 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 17:45:11 +0200 Subject: [PATCH 39/41] Use atPhase for ContextFunctionResults --- .../src/dotty/tools/dotc/transform/ContextFunctionResults.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala index eb4cf2880365..39055a56845e 100644 --- a/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala +++ b/compiler/src/dotty/tools/dotc/transform/ContextFunctionResults.scala @@ -121,7 +121,7 @@ object ContextFunctionResults: */ def integrateSelect(tree: untpd.Tree, n: Int = 0)(using Context): Boolean = if ctx.erasedTypes then - integrateSelect(tree, n)(using ctx.withPhase(erasurePhase)) + atPhase(erasurePhase)(integrateSelect(tree, n)) else tree match case Select(qual, name) => if name == nme.apply && defn.isContextFunctionClass(tree.symbol.maybeOwner) then From 1236d8cf370875c1bed9de21d7bf93c3a0ed2f93 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 17:52:43 +0200 Subject: [PATCH 40/41] Convert remaining instance to atPhase This was tricky because if the implicit toDenot conversion --- compiler/src/dotty/tools/dotc/transform/Erasure.scala | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 686a53aea51c..3fc92aa5e4ca 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -47,9 +47,9 @@ class Erasure extends Phase with DenotTransformer { def transform(ref: SingleDenotation)(using Context): SingleDenotation = ref match { case ref: SymDenotation => - def isCompacted(sym: Symbol) = - sym.isAnonymousFunction && { - sym.info(using ctx.withPhase(ctx.phase.next)) match { + def isCompacted(symd: SymDenotation) = + symd.isAnonymousFunction && { + atPhase(ctx.phase.next)(symd.info) match { case MethodType(nme.ALLARGS :: Nil) => true case _ => false } @@ -81,7 +81,7 @@ class Erasure extends Phase with DenotTransformer { val newInfo = transformInfo(oldSymbol, oldInfo) val oldFlags = ref.flags var newFlags = - if (oldSymbol.is(Flags.TermParam) && isCompacted(oldSymbol.owner)) oldFlags &~ Flags.Param + if (oldSymbol.is(Flags.TermParam) && isCompacted(oldSymbol.owner.denot)) oldFlags &~ Flags.Param else oldFlags val oldAnnotations = ref.annotations var newAnnotations = oldAnnotations From 159486adbf18f22f3dd0c658547a4c474c96aced Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Fri, 10 Jul 2020 18:01:22 +0200 Subject: [PATCH 41/41] Move plugins to ContextBase Plugins creates two variables which are the same for all contexts in a run. So they should go to ContextBase, not contexts. For background: We are creating upwards of 500'000 contexts per second. So every variable in there counts. --- compiler/src/dotty/tools/dotc/Run.scala | 2 +- .../dotty/tools/dotc/config/CompilerCommand.scala | 2 +- compiler/src/dotty/tools/dotc/core/Contexts.scala | 4 ++-- compiler/src/dotty/tools/dotc/plugins/Plugins.scala | 12 ++++++------ 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/Run.scala b/compiler/src/dotty/tools/dotc/Run.scala index 41e1177698c4..222e63372c75 100644 --- a/compiler/src/dotty/tools/dotc/Run.scala +++ b/compiler/src/dotty/tools/dotc/Run.scala @@ -164,7 +164,7 @@ class Run(comp: Compiler, ictx: Context) extends ImplicitRunInfo with Constraint if (ctx.settings.YtestPickler.value) List("pickler") else ctx.settings.YstopAfter.value - val pluginPlan = ctx.addPluginPhases(ctx.base.phasePlan) + val pluginPlan = ctx.base.addPluginPhases(ctx.base.phasePlan) val phases = ctx.base.squashPhases(pluginPlan, ctx.settings.Yskip.value, ctx.settings.YstopBefore.value, stopAfter, ctx.settings.Ycheck.value) ctx.base.usePhases(phases) diff --git a/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala b/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala index 88ddf4aef0bd..75155d967e61 100644 --- a/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala +++ b/compiler/src/dotty/tools/dotc/config/CompilerCommand.scala @@ -127,7 +127,7 @@ object CompilerCommand { if (help.value) usageMessage else if (Xhelp.value) xusageMessage else if (Yhelp.value) yusageMessage - else if (showPlugins.value) ctx.pluginDescriptions + else if (showPlugins.value) ctx.base.pluginDescriptions else if (XshowPhases.value) phasesMessage else "" } diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 660f15f6ebf6..8ee1a67850da 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -102,7 +102,6 @@ object Contexts { with SymDenotations with Reporting with NamerContextOps - with Plugins with Cloneable { thiscontext => given Context = this @@ -661,7 +660,8 @@ object Contexts { */ class ContextBase extends ContextState with Denotations.DenotationsBase - with Phases.PhasesBase { + with Phases.PhasesBase + with Plugins { /** The applicable settings */ val settings: ScalaSettings = new ScalaSettings diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala index 653d593b66eb..8f20515d7813 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala @@ -16,7 +16,7 @@ import config.Printers.plugins.{ println => debug } * Updated 2009/1/2 by Anders Bach Nielsen: Added features to implement SIP 00002 */ trait Plugins { - self: Context => + self: ContextBase => /** Load a rough list of the plugins. For speed, it * does not instantiate a compiler run. Therefore it cannot @@ -35,8 +35,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 => warning(e.getMessage) - case e: Exception => inform(e.getMessage) + case e: MissingPluginException => ctx.warning(e.getMessage) + case e: Exception => ctx.inform(e.getMessage) }) goods map (_.get) @@ -65,7 +65,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) inform(msg format plug.name) + def note(msg: String): Unit = if (ctx.settings.verbose.value) ctx.inform(msg format plug.name) def fail(msg: String) = { note(msg) ; withoutPlug } if (plugNames contains plug.name) @@ -103,11 +103,11 @@ trait Plugins { else _plugins /** A description of all the plugins that are loaded */ - def pluginDescriptions: String = + def pluginDescriptions(using Context): String = roughPluginsList map (x => "%s - %s".format(x.name, x.description)) mkString "\n" /** Summary of the options for all loaded plugins */ - def pluginOptionsHelp: String = + def pluginOptionsHelp(using Context): String = (for (plug <- roughPluginsList ; help <- plug.optionsHelp) yield { "\nOptions for plugin '%s':\n%s\n".format(plug.name, help) }).mkString