From f8162e5c91839612c25c4c7900da2409c4b8a32c Mon Sep 17 00:00:00 2001 From: Nicolas Stucki Date: Fri, 7 Feb 2020 11:16:42 +0100 Subject: [PATCH] Update to new context function and arguments syntax --- .../dotty/tools/dotc/CompilationUnit.scala | 4 +- .../src/dotty/tools/dotc/ast/Desugar.scala | 6 +- .../dotty/tools/dotc/ast/MainProxies.scala | 4 +- .../src/dotty/tools/dotc/ast/TreeInfo.scala | 4 +- compiler/src/dotty/tools/dotc/ast/tpd.scala | 6 +- compiler/src/dotty/tools/dotc/ast/untpd.scala | 2 +- .../dotty/tools/dotc/core/Annotations.scala | 16 ++--- .../src/dotty/tools/dotc/core/Contexts.scala | 4 +- .../dotty/tools/dotc/core/Decorators.scala | 4 +- .../dotty/tools/dotc/core/Definitions.scala | 36 +++++----- .../src/dotty/tools/dotc/core/Periods.scala | 4 +- .../src/dotty/tools/dotc/core/Phases.scala | 8 +-- .../tools/dotc/core/SymDenotations.scala | 12 ++-- .../dotty/tools/dotc/core/TypeComparer.scala | 8 +-- .../dotty/tools/dotc/core/TyperState.scala | 6 +- .../src/dotty/tools/dotc/core/Types.scala | 24 +++---- .../tools/dotc/core/tasty/TreePickler.scala | 2 +- .../tools/dotc/core/tasty/TreeUnpickler.scala | 6 +- .../tools/dotc/interactive/Interactive.scala | 4 +- .../tools/dotc/printing/Formatting.scala | 4 +- .../tools/dotc/quoted/QuoteContext.scala | 6 +- .../dotty/tools/dotc/reporting/Reporter.scala | 2 +- .../dotty/tools/dotc/rewrites/Rewrites.scala | 2 +- .../dotc/semanticdb/ExtractSemanticDB.scala | 70 +++++++++---------- .../dotty/tools/dotc/semanticdb/Scala3.scala | 18 ++--- .../dotty/tools/dotc/semanticdb/Tools.scala | 6 +- .../ReflectionCompilerInterface.scala | 2 +- .../dotc/tastyreflect/ReflectionImpl.scala | 2 +- .../dotty/tools/dotc/transform/CtxLazy.scala | 4 +- .../dotty/tools/dotc/transform/Erasure.scala | 2 +- .../dotty/tools/dotc/transform/Getters.scala | 2 +- .../dotc/transform/NonLocalReturns.scala | 2 +- .../dotc/transform/PCPCheckAndHeal.scala | 4 +- .../tools/dotc/transform/ReifyQuotes.scala | 2 +- .../dotty/tools/dotc/transform/Splicer.scala | 26 +++---- .../dotty/tools/dotc/transform/SymUtils.scala | 2 +- .../dotty/tools/dotc/typer/Applications.scala | 2 +- .../src/dotty/tools/dotc/typer/Checking.scala | 4 +- .../dotty/tools/dotc/typer/EtaExpansion.scala | 2 +- .../dotty/tools/dotc/typer/Implicits.scala | 2 +- .../dotty/tools/dotc/typer/ImportInfo.scala | 4 +- .../tools/dotc/typer/ImportSuggestions.scala | 22 +++--- .../src/dotty/tools/dotc/typer/Inliner.scala | 14 ++-- .../dotty/tools/dotc/typer/Nullables.scala | 48 ++++++------- .../tools/dotc/typer/PrepareInlineable.scala | 4 +- .../dotty/tools/dotc/typer/ProtoTypes.scala | 2 +- .../dotty/tools/dotc/typer/TypeAssigner.scala | 2 +- .../src/dotty/tools/dotc/typer/Typer.scala | 36 +++++----- compiler/src/dotty/tools/package.scala | 2 +- compiler/test-resources/repl-macros/i5551 | 4 +- compiler/test-resources/repl/3932 | 2 +- .../tools/backend/jvm/ArrayApplyOptTest.scala | 2 +- .../dotc/semanticdb/SemanticdbTests.scala | 2 +- .../dotty/internal/StringContextMacro.scala | 8 +-- library/src/dotty/DottyPredef.scala | 2 +- library/src/scala/IArray.scala | 8 +-- library/src/scala/Tuple.scala | 2 +- .../src/scala/internal/quoted/Matcher.scala | 8 +-- library/src/scala/quoted/Expr.scala | 6 +- library/src/scala/quoted/matching/Sym.scala | 2 +- .../src/scala/quoted/matching/package.scala | 2 +- .../src/scala/quoted/unsafe/UnsafeExpr.scala | 14 ++-- library/src/scala/quoted/util/ExprMap.scala | 2 +- library/src/scala/quoted/util/Var.scala | 4 +- .../tasty/reflect/SourceCodePrinter.scala | 14 ++-- .../scala/tasty/reflect/TreeAccumulator.scala | 10 +-- library/src/scala/tasty/reflect/TreeMap.scala | 30 ++++---- .../scala/tasty/reflect/TreeTraverser.scala | 6 +- .../src/scala/util/CommandLineParser.scala | 6 +- .../scala/util/control/NonLocalReturns.scala | 6 +- 70 files changed, 300 insertions(+), 300 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/CompilationUnit.scala b/compiler/src/dotty/tools/dotc/CompilationUnit.scala index efe6fd2829f4..043775349689 100644 --- a/compiler/src/dotty/tools/dotc/CompilationUnit.scala +++ b/compiler/src/dotty/tools/dotc/CompilationUnit.scala @@ -43,7 +43,7 @@ class CompilationUnit protected (val source: SourceFile) { var suspended: Boolean = false - def suspend()(given ctx: Context): Nothing = + def suspend()(using ctx: Context): Nothing = if !suspended then if (ctx.settings.XprintSuspension.value) ctx.echo(i"suspended: $this") @@ -57,7 +57,7 @@ class CompilationUnit protected (val source: SourceFile) { * that can be tracked for being not null to the list of spans of assignments * to these variables. */ - def assignmentSpans(given Context): Map[Int, List[Span]] = + def assignmentSpans(using Context): Map[Int, List[Span]] = if myAssignmentSpans == null then myAssignmentSpans = Nullables.assignmentSpans myAssignmentSpans } diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index 098920f7dbcb..2dee456f0187 100644 --- a/compiler/src/dotty/tools/dotc/ast/Desugar.scala +++ b/compiler/src/dotty/tools/dotc/ast/Desugar.scala @@ -929,7 +929,7 @@ object desugar { */ def makeExtensionDef(mdef: Tree, tparams: List[TypeDef], leadingParams: List[ValDef], - givenParamss: List[List[ValDef]])(given ctx: Context): Tree = { + givenParamss: List[List[ValDef]])(using ctx: Context): Tree = { val allowed = "allowed here, since collective parameters are given" mdef match { case mdef: DefDef => @@ -986,7 +986,7 @@ object desugar { } /** Invent a name for an anonympus given or extension of type or template `impl`. */ - def inventGivenOrExtensionName(impl: Tree)(given ctx: Context): SimpleName = + def inventGivenOrExtensionName(impl: Tree)(using ctx: Context): SimpleName = val str = impl match case impl: Template => if impl.parents.isEmpty then @@ -1253,7 +1253,7 @@ object desugar { else Apply(ref(tupleTypeRef.classSymbol.companionModule.termRef), ts) } - private def isTopLevelDef(stat: Tree)(given Context): Boolean = stat match + private def isTopLevelDef(stat: Tree)(using Context): Boolean = stat match case _: ValDef | _: PatDef | _: DefDef | _: Export => true case stat: ModuleDef => stat.mods.isOneOf(GivenOrImplicit) diff --git a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala index 92427c4586de..98fd94f37d04 100644 --- a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala +++ b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala @@ -26,7 +26,7 @@ import ast.Trees._ */ object MainProxies { - def mainProxies(stats: List[tpd.Tree])(given Context): List[untpd.Tree] = { + def mainProxies(stats: List[tpd.Tree])(using Context): List[untpd.Tree] = { import tpd._ def mainMethods(stats: List[Tree]): List[Symbol] = stats.flatMap { case stat: DefDef if stat.symbol.hasAnnotation(defn.MainAnnot) => @@ -40,7 +40,7 @@ object MainProxies { } import untpd._ - def mainProxy(mainFun: Symbol)(given ctx: Context): List[TypeDef] = { + def mainProxy(mainFun: Symbol)(using ctx: Context): List[TypeDef] = { val mainAnnotSpan = mainFun.getAnnotation(defn.MainAnnot).get.tree.span def pos = mainFun.sourcePos val argsRef = Ident(nme.args) diff --git a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala index b3da00fa6f63..e80d9b27a980 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala @@ -869,10 +869,10 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => * A not-null assertion for reference `x` has the form `x.$asInstanceOf$[x.type & T]`. */ object AssertNotNull with - def apply(tree: tpd.Tree, tpnn: Type)(given Context): tpd.Tree = + def apply(tree: tpd.Tree, tpnn: Type)(using Context): tpd.Tree = tree.select(defn.Any_typeCast).appliedToType(AndType(tree.tpe, tpnn)) - def unapply(tree: tpd.TypeApply)(given Context): Option[tpd.Tree] = tree match + def unapply(tree: tpd.TypeApply)(using Context): Option[tpd.Tree] = tree match case TypeApply(Select(qual: RefTree, nme.asInstanceOfPM), arg :: Nil) => arg.tpe match case AndType(ref, _) if qual.tpe eq ref => Some(qual) diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index b93c22208070..21bc91de2806 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -878,7 +878,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { Apply(tree, args) /** An applied node that accepts only varargs as arguments */ - def appliedToVarargs(args: List[Tree], tpt: Tree)(given Context): Tree = + def appliedToVarargs(args: List[Tree], tpt: Tree)(using Context): Tree = appliedTo(repeated(args, tpt)) /** The current tree applied to given argument lists: @@ -1378,7 +1378,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** Convert a list of trees to a vararg-compatible tree. * Used to make arguments for methods that accept varargs. */ - def repeated(trees: List[Tree], tpt: Tree)(given ctx: Context): Tree = + def repeated(trees: List[Tree], tpt: Tree)(using ctx: Context): Tree = ctx.typeAssigner.arrayToRepeated(JavaSeqLiteral(trees, tpt)) /** Create a tree representing a list containing all @@ -1390,7 +1390,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { * @param tpe the type of the elements of the resulting list. * */ - def mkList(trees: List[Tree], tpe: Tree)(given Context): Tree = + def mkList(trees: List[Tree], tpe: Tree)(using Context): Tree = ref(defn.ListModule).select(nme.apply) .appliedToTypeTree(tpe) .appliedToVarargs(trees, tpe) diff --git a/compiler/src/dotty/tools/dotc/ast/untpd.scala b/compiler/src/dotty/tools/dotc/ast/untpd.scala index d59683a50253..179443a7d6e4 100644 --- a/compiler/src/dotty/tools/dotc/ast/untpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/untpd.scala @@ -246,7 +246,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { * describe the core of a construct whereas the existing set are the modifiers * given in the source. */ - def withAddedFlags(flags: FlagSet, span: Span)(given ctx: Context): Modifiers = + def withAddedFlags(flags: FlagSet, span: Span)(using ctx: Context): Modifiers = if this.flags.isAllOf(flags) then this else if compatible(this.flags, flags) then this | flags else diff --git a/compiler/src/dotty/tools/dotc/core/Annotations.scala b/compiler/src/dotty/tools/dotc/core/Annotations.scala index 38a0fe1ef40e..6ed5640bfcc4 100644 --- a/compiler/src/dotty/tools/dotc/core/Annotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Annotations.scala @@ -10,7 +10,7 @@ import util.Spans.Span object Annotations { - def annotClass(tree: Tree)(given Context) = + def annotClass(tree: Tree)(using Context) = if (tree.symbol.isConstructor) tree.symbol.owner else tree.tpe.typeSymbol @@ -118,25 +118,25 @@ object Annotations { apply(New(atp, args)) /** Create an annotation where the tree is computed lazily. */ - def deferred(sym: Symbol)(treeFn: (given Context) => Tree)(implicit ctx: Context): Annotation = + def deferred(sym: Symbol)(treeFn: Context ?=> Tree)(implicit ctx: Context): Annotation = new LazyAnnotation { override def symbol(implicit ctx: Context): Symbol = sym - def complete(implicit ctx: Context) = treeFn(given ctx) + def complete(implicit ctx: Context) = treeFn(using ctx) } /** Create an annotation where the symbol and the tree are computed lazily. */ - def deferredSymAndTree(symf: (given Context) => Symbol)(treeFn: (given Context) => Tree)(implicit ctx: Context): Annotation = + def deferredSymAndTree(symf: Context ?=> Symbol)(treeFn: Context ?=> Tree)(implicit ctx: Context): Annotation = new LazyAnnotation { private var mySym: Symbol = _ override def symbol(implicit ctx: Context): Symbol = { if (mySym == null || mySym.defRunId != ctx.runId) { - mySym = symf(given ctx) + mySym = symf(using ctx) assert(mySym != null) } mySym } - def complete(implicit ctx: Context) = treeFn(given ctx) + def complete(implicit ctx: Context) = treeFn(using ctx) } def deferred(atp: Type, args: List[Tree])(implicit ctx: Context): Annotation = @@ -153,8 +153,8 @@ object Annotations { object Child { /** A deferred annotation to the result of a given child computation */ - def later(delayedSym: (given Context) => Symbol, span: Span)(implicit ctx: Context): Annotation = { - def makeChildLater(given ctx: Context) = { + def later(delayedSym: Context ?=> Symbol, span: Span)(implicit ctx: Context): Annotation = { + def makeChildLater(using ctx: Context) = { val sym = delayedSym New(defn.ChildAnnot.typeRef.appliedTo(sym.owner.thisType.select(sym.name, sym)), Nil) .withSpan(span) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index ca304c2e7aa3..0750a7483e8b 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 curCtx(given ctx: Context): Context = ctx + def curCtx(using ctx: Context): Context = ctx /** A context is passed basically everywhere in dotc. * This is convenient but carries the risk of captured contexts in @@ -319,7 +319,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: (given Context) => T): T = typerState.test(op)(this) + final def test[T](op: Context ?=> T): T = typerState.test(op)(this) /** Is this a context for the members of a class definition? */ def isClassDefContext: Boolean = diff --git a/compiler/src/dotty/tools/dotc/core/Decorators.scala b/compiler/src/dotty/tools/dotc/core/Decorators.scala index 71ba89770625..ee6f06b37059 100644 --- a/compiler/src/dotty/tools/dotc/core/Decorators.scala +++ b/compiler/src/dotty/tools/dotc/core/Decorators.scala @@ -188,9 +188,9 @@ object Decorators { implicit class reportDeco[T](x: T) extends AnyVal { def reporting( - op: (given WrappedResult[T]) => String, + op: WrappedResult[T] ?=> String, printer: config.Printers.Printer = config.Printers.default): T = { - printer.println(op(given WrappedResult(x))) + printer.println(op(using WrappedResult(x))) x } } diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index 51eece14c4f2..3b471d97087e 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -92,7 +92,7 @@ class Definitions { * ContextFunctionN traits follow this template: * * trait ContextFunctionN[T0,...,T{N-1}, R] extends Object { - * def apply(given $x0: T0, ..., $x{N_1}: T{N-1}): R + * def apply(using $x0: T0, ..., $x{N_1}: T{N-1}): R * } * * ErasedFunctionN traits follow this template: @@ -104,7 +104,7 @@ class Definitions { * ErasedContextFunctionN traits follow this template: * * trait ErasedContextFunctionN[T0,...,T{N-1}, R] extends Object { - * def apply (given erased $x0: T0, ..., $x{N_1}: T{N-1}): R + * def apply(using erased $x0: T0, ..., $x{N_1}: T{N-1}): R * } * * ErasedFunctionN and ErasedContextFunctionN erase to Function0. @@ -439,7 +439,7 @@ class Definitions { @tu lazy val CollectionSeqType: TypeRef = ctx.requiredClassRef("scala.collection.Seq") @tu lazy val SeqType: TypeRef = ctx.requiredClassRef("scala.collection.immutable.Seq") - def SeqClass(given Context): ClassSymbol = SeqType.symbol.asClass + def SeqClass(using Context): ClassSymbol = SeqType.symbol.asClass @tu lazy val Seq_apply : Symbol = SeqClass.requiredMethod(nme.apply) @tu lazy val Seq_head : Symbol = SeqClass.requiredMethod(nme.head) @tu lazy val Seq_drop : Symbol = SeqClass.requiredMethod(nme.drop) @@ -448,7 +448,7 @@ class Definitions { @tu lazy val Seq_toSeq : Symbol = SeqClass.requiredMethod(nme.toSeq) @tu lazy val ArrayType: TypeRef = ctx.requiredClassRef("scala.Array") - def ArrayClass(given Context): ClassSymbol = ArrayType.symbol.asClass + def ArrayClass(using Context): ClassSymbol = ArrayType.symbol.asClass @tu lazy val Array_apply : Symbol = ArrayClass.requiredMethod(nme.apply) @tu lazy val Array_update : Symbol = ArrayClass.requiredMethod(nme.update) @tu lazy val Array_length : Symbol = ArrayClass.requiredMethod(nme.length) @@ -458,10 +458,10 @@ class Definitions { @tu lazy val ArrayModule: Symbol = ctx.requiredModule("scala.Array") @tu lazy val UnitType: TypeRef = valueTypeRef("scala.Unit", java.lang.Void.TYPE, UnitEnc, nme.specializedTypeNames.Void) - def UnitClass(given Context): ClassSymbol = UnitType.symbol.asClass - def UnitModuleClass(given Context): Symbol = UnitType.symbol.asClass.linkedClass + def UnitClass(using Context): ClassSymbol = UnitType.symbol.asClass + def UnitModuleClass(using Context): Symbol = UnitType.symbol.asClass.linkedClass @tu lazy val BooleanType: TypeRef = valueTypeRef("scala.Boolean", java.lang.Boolean.TYPE, BooleanEnc, nme.specializedTypeNames.Boolean) - def BooleanClass(given Context): ClassSymbol = BooleanType.symbol.asClass + def BooleanClass(using Context): ClassSymbol = BooleanType.symbol.asClass @tu lazy val Boolean_! : Symbol = BooleanClass.requiredMethod(nme.UNARY_!) @tu lazy val Boolean_&& : Symbol = BooleanClass.requiredMethod(nme.ZAND) // ### harmonize required... calls @tu lazy val Boolean_|| : Symbol = BooleanClass.requiredMethod(nme.ZOR) @@ -477,13 +477,13 @@ class Definitions { }).symbol @tu lazy val ByteType: TypeRef = valueTypeRef("scala.Byte", java.lang.Byte.TYPE, ByteEnc, nme.specializedTypeNames.Byte) - def ByteClass(given Context): ClassSymbol = ByteType.symbol.asClass + def ByteClass(using Context): ClassSymbol = ByteType.symbol.asClass @tu lazy val ShortType: TypeRef = valueTypeRef("scala.Short", java.lang.Short.TYPE, ShortEnc, nme.specializedTypeNames.Short) - def ShortClass(given Context): ClassSymbol = ShortType.symbol.asClass + def ShortClass(using Context): ClassSymbol = ShortType.symbol.asClass @tu lazy val CharType: TypeRef = valueTypeRef("scala.Char", java.lang.Character.TYPE, CharEnc, nme.specializedTypeNames.Char) - def CharClass(given Context): ClassSymbol = CharType.symbol.asClass + def CharClass(using Context): ClassSymbol = CharType.symbol.asClass @tu lazy val IntType: TypeRef = valueTypeRef("scala.Int", java.lang.Integer.TYPE, IntEnc, nme.specializedTypeNames.Int) - def IntClass(given Context): ClassSymbol = IntType.symbol.asClass + def IntClass(using Context): ClassSymbol = IntType.symbol.asClass @tu lazy val Int_- : Symbol = IntClass.requiredMethod(nme.MINUS, List(IntType)) @tu lazy val Int_+ : Symbol = IntClass.requiredMethod(nme.PLUS, List(IntType)) @tu lazy val Int_/ : Symbol = IntClass.requiredMethod(nme.DIV, List(IntType)) @@ -492,19 +492,19 @@ class Definitions { @tu lazy val Int_>= : Symbol = IntClass.requiredMethod(nme.GE, List(IntType)) @tu lazy val Int_<= : Symbol = IntClass.requiredMethod(nme.LE, List(IntType)) @tu lazy val LongType: TypeRef = valueTypeRef("scala.Long", java.lang.Long.TYPE, LongEnc, nme.specializedTypeNames.Long) - def LongClass(given Context): ClassSymbol = LongType.symbol.asClass + def LongClass(using Context): ClassSymbol = LongType.symbol.asClass @tu lazy val Long_+ : Symbol = LongClass.requiredMethod(nme.PLUS, List(LongType)) @tu lazy val Long_* : Symbol = LongClass.requiredMethod(nme.MUL, List(LongType)) @tu lazy val Long_/ : Symbol = LongClass.requiredMethod(nme.DIV, List(LongType)) @tu lazy val FloatType: TypeRef = valueTypeRef("scala.Float", java.lang.Float.TYPE, FloatEnc, nme.specializedTypeNames.Float) - def FloatClass(given Context): ClassSymbol = FloatType.symbol.asClass + def FloatClass(using Context): ClassSymbol = FloatType.symbol.asClass @tu lazy val DoubleType: TypeRef = valueTypeRef("scala.Double", java.lang.Double.TYPE, DoubleEnc, nme.specializedTypeNames.Double) - def DoubleClass(given Context): ClassSymbol = DoubleType.symbol.asClass + def DoubleClass(using Context): ClassSymbol = DoubleType.symbol.asClass @tu lazy val BoxedUnitClass: ClassSymbol = ctx.requiredClass("scala.runtime.BoxedUnit") - def BoxedUnit_UNIT(given Context): TermSymbol = BoxedUnitClass.linkedClass.requiredValue("UNIT") - def BoxedUnit_TYPE(given Context): TermSymbol = BoxedUnitClass.linkedClass.requiredValue("TYPE") + def BoxedUnit_UNIT(using Context): TermSymbol = BoxedUnitClass.linkedClass.requiredValue("UNIT") + def BoxedUnit_TYPE(using Context): TermSymbol = BoxedUnitClass.linkedClass.requiredValue("TYPE") @tu lazy val BoxedBooleanClass: ClassSymbol = ctx.requiredClass("java.lang.Boolean") @tu lazy val BoxedByteClass : ClassSymbol = ctx.requiredClass("java.lang.Byte") @@ -574,9 +574,9 @@ class Definitions { // in scalac modified to have Any as parent @tu lazy val ThrowableType: TypeRef = ctx.requiredClassRef("java.lang.Throwable") - def ThrowableClass(given Context): ClassSymbol = ThrowableType.symbol.asClass + def ThrowableClass(using Context): ClassSymbol = ThrowableType.symbol.asClass @tu lazy val SerializableType: TypeRef = JavaSerializableClass.typeRef - def SerializableClass(given Context): ClassSymbol = SerializableType.symbol.asClass + def SerializableClass(using Context): ClassSymbol = SerializableType.symbol.asClass @tu lazy val JavaEnumClass: ClassSymbol = { val cls = ctx.requiredClass("java.lang.Enum") diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index 8393dab6cfc6..b1e8d0667637 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -21,8 +21,8 @@ abstract class Periods { self: Context => op(ctx.fresh.setPeriod(pd)) /** Execute `op` at given phase id */ - def atPhase[T](pid: PhaseId)(op: (given Context) => T): T = - op(given ctx.withPhase(pid)) + def atPhase[T](pid: PhaseId)(op: Context ?=> T): T = + op(using ctx.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 diff --git a/compiler/src/dotty/tools/dotc/core/Phases.scala b/compiler/src/dotty/tools/dotc/core/Phases.scala index ef8866711fef..68d2e99e4127 100644 --- a/compiler/src/dotty/tools/dotc/core/Phases.scala +++ b/compiler/src/dotty/tools/dotc/core/Phases.scala @@ -31,13 +31,13 @@ trait Phases { } /** Execute `op` at given phase */ - def atPhase[T](phase: Phase)(op: (given Context) => T): T = + def atPhase[T](phase: Phase)(op: Context ?=> T): T = atPhase(phase.id)(op) - def atNextPhase[T](op: (given Context) => T): T = atPhase(phase.next)(op) + def atNextPhase[T](op: Context ?=> T): T = atPhase(phase.next)(op) - def atPhaseNotLaterThan[T](limit: Phase)(op: (given Context) => T): T = - if (!limit.exists || phase <= limit) op(given this) else atPhase(limit)(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/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index 6081bd5a9686..fe4fd0aed96c 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -436,7 +436,7 @@ object SymDenotations { * of the opaque type definition. * @param rhs The right hand side tree of the type definition */ - def opaqueToBounds(info: Type, rhs: tpd.Tree)(given Context): Type = + def opaqueToBounds(info: Type, rhs: tpd.Tree)(using Context): Type = def setAlias(tp: Type) = def recur(self: Type): Unit = self match @@ -636,7 +636,7 @@ object SymDenotations { name.isPackageObjectName && owner.is(Package) && this.is(Module) /** Is this symbol a toplevel definition in a package object? */ - def isWrappedToplevelDef(given Context): Boolean = + def isWrappedToplevelDef(using Context): Boolean = !isConstructor && owner.isPackageObject /** Is this symbol an abstract type? */ @@ -1086,7 +1086,7 @@ object SymDenotations { /** A class is effectively sealed if has the `final` or `sealed` modifier, or it * is defined in Scala 3 and is neither abstract nor open. */ - final def isEffectivelySealed(given Context): Boolean = + final def isEffectivelySealed(using Context): Boolean = isOneOf(FinalOrSealed) || isClass && !isOneOf(EffectivelyOpenFlags) /** The class containing this denotation which has the given effective name. */ @@ -1546,7 +1546,7 @@ object SymDenotations { myBaseTypeCachePeriod = Nowhere } - def invalidateMemberCaches(sym: Symbol)(given Context): Unit = + def invalidateMemberCaches(sym: Symbol)(using Context): Unit = if myMemberCache != null then myMemberCache.invalidate(sym.name) if !sym.flagsUNSAFE.is(Private) then invalidateMemberNamesCache() @@ -1753,7 +1753,7 @@ object SymDenotations { } /** Enter a symbol in given `scope` without potentially replacing the old copy. */ - def enterNoReplace(sym: Symbol, scope: MutableScope)(given Context): Unit = + def enterNoReplace(sym: Symbol, scope: MutableScope)(using Context): Unit = scope.enter(sym) invalidateMemberCaches(sym) @@ -2267,7 +2267,7 @@ object SymDenotations { * - parameters and parameter accessors, since their Local status is already * determined by whether they have a `val` or `var` or not. */ - def canBeLocal(name: Name, flags: FlagSet)(given Context) = + def canBeLocal(name: Name, flags: FlagSet)(using Context) = !name.isConstructorName && !flags.is(Param) && !flags.is(ParamAccessor) // ---- Completion -------------------------------------------------------- diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index ae8cf5d15cfa..e6fbd1019c84 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -1116,7 +1116,7 @@ class TypeComparer(initctx: Context) extends ConstraintHandling[AbsentContext] w } } - private def nonExprBaseType(tp: Type, cls: Symbol)(given Context): Type = + private def nonExprBaseType(tp: Type, cls: Symbol)(using Context): Type = if tp.isInstanceOf[ExprType] then NoType else tp.baseType(cls) @@ -2379,14 +2379,14 @@ object TypeComparer { val FreshApprox: ApproxState = new ApproxState(4) /** Show trace of comparison operations when performing `op` */ - def explaining[T](say: String => Unit)(op: (given Context) => T)(implicit ctx: Context): T = { + def explaining[T](say: String => Unit)(op: Context ?=> T)(implicit ctx: Context): T = { val nestedCtx = ctx.fresh.setTypeComparerFn(new ExplainingTypeComparer(_)) - val res = try { op(given nestedCtx) } finally { say(nestedCtx.typeComparer.lastTrace()) } + val res = try { op(using nestedCtx) } finally { say(nestedCtx.typeComparer.lastTrace()) } res } /** Like [[explaining]], but returns the trace instead */ - def explained[T](op: (given Context) => T)(implicit ctx: Context): String = { + def explained[T](op: Context ?=> T)(implicit ctx: Context): String = { var trace: String = null try { explaining(trace = _)(op) } catch { case ex: Throwable => ex.printStackTrace } trace diff --git a/compiler/src/dotty/tools/dotc/core/TyperState.scala b/compiler/src/dotty/tools/dotc/core/TyperState.scala index 8cadf30cdfc0..64c72c7bc539 100644 --- a/compiler/src/dotty/tools/dotc/core/TyperState.scala +++ b/compiler/src/dotty/tools/dotc/core/TyperState.scala @@ -96,9 +96,9 @@ 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: (given Context) => T)(implicit ctx: Context): T = + def test[T](op: Context ?=> T)(implicit ctx: Context): T = if (isShared) - op(given ctx.fresh.setExploreTyperState()) + op(using ctx.fresh.setExploreTyperState()) else { val savedConstraint = myConstraint val savedReporter = myReporter @@ -113,7 +113,7 @@ class TyperState(private val previous: TyperState /* | Null */) { testReporter.inUse = true testReporter } - try op(given ctx) + try op(using ctx) finally { testReporter.inUse = false resetConstraintTo(savedConstraint) diff --git a/compiler/src/dotty/tools/dotc/core/Types.scala b/compiler/src/dotty/tools/dotc/core/Types.scala index 726810ea4b6b..b1412318c2de 100644 --- a/compiler/src/dotty/tools/dotc/core/Types.scala +++ b/compiler/src/dotty/tools/dotc/core/Types.scala @@ -201,9 +201,9 @@ object Types { false } - def isAny(given Context): Boolean = isRef(defn.AnyClass, skipRefined = false) - def isAnyRef(given Context): Boolean = isRef(defn.ObjectClass, skipRefined = false) - def isAnyKind(given Context): Boolean = isRef(defn.AnyKindClass, skipRefined = false) + def isAny(using Context): Boolean = isRef(defn.AnyClass, skipRefined = false) + def isAnyRef(using Context): Boolean = isRef(defn.ObjectClass, skipRefined = false) + def isAnyKind(using Context): Boolean = isRef(defn.AnyKindClass, skipRefined = false) /** 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 @@ -1051,7 +1051,7 @@ object Types { } /** Strip LazyRef wrappers */ - def stripLazyRef(given Context): Type = this match + def stripLazyRef(using Context): Type = this match case lzy: LazyRef => lzy.ref.stripLazyRef case _ => this @@ -1469,7 +1469,7 @@ object Types { } /** Is this (an alias of) the `scala.Null` type? */ - final def isNullType(given Context) = isRef(defn.NullClass) + 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 @@ -2979,9 +2979,9 @@ object Types { * case _ => // tp was not a nullable union */ object OrNull { - def apply(tp: Type)(given Context) = + def apply(tp: Type)(using Context) = OrType(tp, defn.NullType) - def unapply(tp: Type)(given ctx: Context): Option[Type] = + def unapply(tp: Type)(using ctx: Context): Option[Type] = if (ctx.explicitNulls) { val tp1 = tp.stripNull() if tp1 ne tp then Some(tp1) else None @@ -2997,9 +2997,9 @@ object Types { * case _ => // tp was not a Java-nullable union */ object OrUncheckedNull { - def apply(tp: Type)(given Context) = + def apply(tp: Type)(using Context) = OrType(tp, defn.UncheckedNullAliasType) - def unapply(tp: Type)(given ctx: Context): Option[Type] = + def unapply(tp: Type)(using ctx: Context): Option[Type] = if (ctx.explicitNulls) { val tp1 = tp.stripUncheckedNull if tp1 ne tp then Some(tp1) else None @@ -4315,7 +4315,7 @@ object Types { parentsCache } - protected def newLikeThis(prefix: Type, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol)(given Context): ClassInfo = + 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 = @@ -4331,7 +4331,7 @@ object Types { * Otherwise, this classInfo. * If there are opaque alias members, updates `cls` to have `Opaque` flag as a side effect. */ - def integrateOpaqueMembers(given Context): ClassInfo = + def integrateOpaqueMembers(using Context): ClassInfo = decls.toList.foldLeft(this) { (cinfo, sym) => if sym.isOpaqueAlias then cls.setFlag(Opaque) @@ -4396,7 +4396,7 @@ object Types { def finalized(parents: List[Type])(implicit ctx: Context): ClassInfo = ClassInfo(prefix, cls, parents, decls, selfInfo) - override def newLikeThis(prefix: Type, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol)(given Context): ClassInfo = + override def newLikeThis(prefix: Type, classParents: List[Type], decls: Scope, selfInfo: TypeOrSymbol)(using Context): ClassInfo = TempClassInfo(prefix, cls, decls, selfInfo) override def toString: String = s"TempClassInfo($prefix, $cls)" diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala index f35f72e7c237..0afaab9d757f 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala @@ -134,7 +134,7 @@ class TreePickler(pickler: TastyPickler) { pickleType(c.symbolValue.termRef) } - def pickleVariances(tp: Type)(given Context): Unit = tp match + def pickleVariances(tp: Type)(using Context): Unit = tp match case tp: HKTypeLambda if tp.isDeclaredVarianceLambda => for v <- tp.declaredVariances do writeByte( diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala index b0dd7af6bd05..96a8cfe5e8a2 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala @@ -1294,7 +1294,7 @@ class TreeUnpickler(reader: TastyReader, val args = until(end)(readTerm()) val splice = splices(idx) def wrap(arg: Tree) = - if (arg.isTerm) (given qctx: scala.quoted.QuoteContext) => new TastyTreeExpr(arg, QuoteContext.scopeId) + if (arg.isTerm) (qctx: scala.quoted.QuoteContext) ?=> new TastyTreeExpr(arg, QuoteContext.scopeId) else new TreeType(arg, QuoteContext.scopeId) val reifiedArgs = args.map(wrap) val filled = if (isType) { @@ -1302,8 +1302,8 @@ class TreeUnpickler(reader: TastyReader, PickledQuotes.quotedTypeToTree(quotedType) } else { - val splice1 = splice.asInstanceOf[Seq[Any] => (given scala.quoted.QuoteContext) => quoted.Expr[?]] - val quotedExpr = splice1(reifiedArgs)(given dotty.tools.dotc.quoted.QuoteContext()) + val splice1 = splice.asInstanceOf[Seq[Any] => scala.quoted.QuoteContext ?=> quoted.Expr[?]] + val quotedExpr = splice1(reifiedArgs)(using dotty.tools.dotc.quoted.QuoteContext()) PickledQuotes.quotedExprToTree(quotedExpr) } // We need to make sure a hole is created with the source file of the surrounding context, even if diff --git a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala index a8e7305f1add..b03d69ad4a0d 100644 --- a/compiler/src/dotty/tools/dotc/interactive/Interactive.scala +++ b/compiler/src/dotty/tools/dotc/interactive/Interactive.scala @@ -379,8 +379,8 @@ object Interactive { */ def localize(symbol: Symbol, sourceDriver: InteractiveDriver, targetDriver: InteractiveDriver): Symbol = { - def in[T](driver: InteractiveDriver)(fn: (given Context) => T): T = - fn(given driver.currentCtx) + def in[T](driver: InteractiveDriver)(fn: Context ?=> T): T = + fn(using driver.currentCtx) if (sourceDriver == targetDriver) symbol else { diff --git a/compiler/src/dotty/tools/dotc/printing/Formatting.scala b/compiler/src/dotty/tools/dotc/printing/Formatting.scala index 5558c100dc4a..57872eccc01c 100644 --- a/compiler/src/dotty/tools/dotc/printing/Formatting.scala +++ b/compiler/src/dotty/tools/dotc/printing/Formatting.scala @@ -267,9 +267,9 @@ object Formatting { * ex"disambiguate $tpe1 and $tpe2" * ``` */ - def explained(op: (given Context) => String)(implicit ctx: Context): String = { + def explained(op: Context ?=> String)(implicit ctx: Context): String = { val seen = new Seen - val msg = op(given explainCtx(seen)) + val msg = op(using explainCtx(seen)) val addendum = explanations(seen) if (addendum.isEmpty) msg else msg ++ "\n\n" ++ addendum } diff --git a/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala b/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala index 4ba056389d26..b9e762c7001b 100644 --- a/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala +++ b/compiler/src/dotty/tools/dotc/quoted/QuoteContext.scala @@ -5,17 +5,17 @@ import dotty.tools.dotc.tastyreflect.ReflectionImpl object QuoteContext { - def apply()(given Context): scala.quoted.QuoteContext = + def apply()(using Context): scala.quoted.QuoteContext = new scala.quoted.QuoteContext(ReflectionImpl(summon[Context])) type ScopeId = Int - private[dotty] def checkScopeId(id: ScopeId)(given Context): Unit = + private[dotty] def checkScopeId(id: ScopeId)(using Context): Unit = if (id != scopeId) throw new scala.quoted.ScopeException("Cannot call `scala.quoted.staging.run(...)` within a macro or another `run(...)`") // TODO Explore more fine grained scope ids. // This id can only differentiate scope extrusion from one compiler instance to another. - private[dotty] def scopeId(given Context): ScopeId = + private[dotty] def scopeId(using Context): ScopeId = summon[Context].outersIterator.toList.last.hashCode() } diff --git a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala index 5afbb123143c..9eadb826aed1 100644 --- a/compiler/src/dotty/tools/dotc/reporting/Reporter.scala +++ b/compiler/src/dotty/tools/dotc/reporting/Reporter.scala @@ -252,7 +252,7 @@ abstract class Reporter extends interfaces.ReporterResult { /** Run `op` and return `true` if errors were reported by this reporter. */ - def reportsErrorsFor(op: Context => Unit)(given ctx: Context): Boolean = { + def reportsErrorsFor(op: Context => Unit)(using ctx: Context): Boolean = { val initial = errorCount op(ctx) errorCount > initial diff --git a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala index 20d28bd35f71..ed30bb217b6e 100644 --- a/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala +++ b/compiler/src/dotty/tools/dotc/rewrites/Rewrites.scala @@ -75,7 +75,7 @@ object Rewrites { patch(ctx.compilationUnit.source, span, replacement) /** Does `span` overlap with a patch region of `source`? */ - def overlapsPatch(source: SourceFile, span: Span)(given ctx: Context): Boolean = + def overlapsPatch(source: SourceFile, span: Span)(using ctx: Context): Boolean = ctx.settings.rewrite.value.exists(rewrites => rewrites.patched.get(source).exists(patches => patches.pbuf.exists(patch => patch.span.overlaps(span)))) diff --git a/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala b/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala index 57f92a71d640..7d07fd155ee3 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala @@ -73,38 +73,38 @@ class ExtractSemanticDB extends Phase with private val generated = new mutable.HashSet[SymbolOccurrence] /** Definitions of this symbol should be excluded from semanticdb */ - private def excludeDef(sym: Symbol)(given Context): Boolean = + private def excludeDef(sym: Symbol)(using Context): Boolean = !sym.exists || sym.isLocalDummy || sym.is(Synthetic) || sym.isSetter || excludeDefOrUse(sym) - private def excludeDefOrUse(sym: Symbol)(given Context): Boolean = + private def excludeDefOrUse(sym: Symbol)(using Context): Boolean = sym.name.is(NameKinds.DefaultGetterName) || sym.isConstructor && (sym.owner.is(ModuleClass) || !sym.isGlobal) || excludeSymbol(sym) - private def excludeSymbol(sym: Symbol)(given Context): Boolean = + private def excludeSymbol(sym: Symbol)(using Context): Boolean = sym.name.isWildcard || excludeQual(sym) - private def excludeQual(sym: Symbol)(given Context): Boolean = + private def excludeQual(sym: Symbol)(using Context): Boolean = sym.isAnonymousFunction || sym.isAnonymousModuleVal || sym.name.isEmptyNumbered - private def excludeChildren(sym: Symbol)(given Context): Boolean = + private def excludeChildren(sym: Symbol)(using Context): Boolean = sym.isAllOf(HigherKinded | Param) /** Uses of this symbol where the reference has given span should be excluded from semanticdb */ - private def excludeUse(qualifier: Option[Symbol], sym: Symbol)(given Context): Boolean = + private def excludeUse(qualifier: Option[Symbol], sym: Symbol)(using Context): Boolean = excludeDefOrUse(sym) || sym.isConstructor && sym.owner.isAnnotation || sym == defn.Any_typeCast || qualifier.exists(excludeQual) - override def traverse(tree: Tree)(given Context): Unit = + override def traverse(tree: Tree)(using Context): Unit = inline def traverseCtorParamTpt(ctorSym: Symbol, tpt: Tree): Unit = val tptSym = tpt.symbol @@ -234,7 +234,7 @@ class ExtractSemanticDB extends Phase with end traverse - private def funParamSymbol(funSym: Symbol)(given Context): Name => String = + private def funParamSymbol(funSym: Symbol)(using Context): Name => String = if funSym.isGlobal then val funSymbol = symbolName(funSym) name => s"$funSymbol($name)" @@ -244,7 +244,7 @@ class ExtractSemanticDB extends Phase with private object PatternValDef with - def unapply(tree: ValDef)(given Context): Option[(Tree, Tree)] = tree.rhs match + def unapply(tree: ValDef)(using Context): Option[(Tree, Tree)] = tree.rhs match case Match(Typed(selected: Tree, tpt: TypeTree), CaseDef(pat: Tree, _, _) :: Nil) if tpt.span.exists && !tpt.span.hasLength && tpt.tpe.isAnnotatedByUnchecked => @@ -252,7 +252,7 @@ class ExtractSemanticDB extends Phase with case _ => None - private inline def (tpe: Types.Type) isAnnotatedByUnchecked(given Context) = tpe match + private inline def (tpe: Types.Type) isAnnotatedByUnchecked(using Context) = tpe match case Types.AnnotatedType(_, annot) => annot.symbol == defn.UncheckedAnnot case _ => false @@ -274,14 +274,14 @@ class ExtractSemanticDB extends Phase with end PatternValDef - private def (tree: NamedDefTree) adjustedNameSpan(given Context): Span = + private def (tree: NamedDefTree) adjustedNameSpan(using Context): Span = if tree.span.exists && tree.name.isAnonymousFunctionName || tree.name.isAnonymousClassName Span(tree.span.point) else tree.nameSpan /** Add semanticdb name of the given symbol to string builder */ - private def addSymName(b: StringBuilder, sym: Symbol)(given ctx: Context): Unit = + private def addSymName(b: StringBuilder, sym: Symbol)(using ctx: Context): Unit = def addName(name: Name) = val str = name.toString.unescapeUnicode @@ -331,7 +331,7 @@ class ExtractSemanticDB extends Phase with /** The index of local symbol `sym`. Symbols with the same name and * the same starting position have the same index. */ - def localIdx(sym: Symbol)(given Context): Int = + def localIdx(sym: Symbol)(using Context): Int = def computeLocalIdx(): Int = symsAtOffset(sym.span.start).find(_.name == sym.name) match case Some(other) => localIdx(other) @@ -352,20 +352,20 @@ class ExtractSemanticDB extends Phase with end addSymName /** The semanticdb name of the given symbol */ - private def symbolName(sym: Symbol)(given ctx: Context): String = + private def symbolName(sym: Symbol)(using ctx: Context): String = val b = StringBuilder(20) addSymName(b, sym) b.toString - inline private def source(given ctx: Context) = ctx.compilationUnit.source + inline private def source(using ctx: Context) = ctx.compilationUnit.source - private def range(span: Span)(given ctx: Context): Option[Range] = + private def range(span: Span)(using ctx: Context): Option[Range] = def lineCol(offset: Int) = (source.offsetToLine(offset), source.column(offset)) val (startLine, startCol) = lineCol(span.start) val (endLine, endCol) = lineCol(span.end) Some(Range(startLine, startCol, endLine, endCol)) - private def symbolKind(sym: Symbol, symkinds: Set[SymbolKind])(given Context): SymbolInformation.Kind = + private def symbolKind(sym: Symbol, symkinds: Set[SymbolKind])(using Context): SymbolInformation.Kind = if sym.isTypeParam SymbolInformation.Kind.TYPE_PARAMETER else if sym.is(TermParam) @@ -399,7 +399,7 @@ class ExtractSemanticDB extends Phase with else SymbolInformation.Kind.UNKNOWN_KIND - private def symbolProps(sym: Symbol, symkinds: Set[SymbolKind])(given Context): Int = + private def symbolProps(sym: Symbol, symkinds: Set[SymbolKind])(using Context): Int = if sym.is(ModuleClass) return symbolProps(sym.sourceModule, symkinds) var props = 0 @@ -433,7 +433,7 @@ class ExtractSemanticDB extends Phase with props |= SymbolInformation.Property.ENUM.value props - private def symbolInfo(sym: Symbol, symbolName: String, symkinds: Set[SymbolKind])(given Context): SymbolInformation = + private def symbolInfo(sym: Symbol, symbolName: String, symkinds: Set[SymbolKind])(using Context): SymbolInformation = SymbolInformation( symbol = symbolName, language = Language.SCALA, @@ -442,39 +442,39 @@ class ExtractSemanticDB extends Phase with displayName = Symbols.displaySymbol(sym) ) - private def registerSymbol(sym: Symbol, symbolName: String, symkinds: Set[SymbolKind])(given Context): Unit = + private def registerSymbol(sym: Symbol, symbolName: String, symkinds: Set[SymbolKind])(using Context): Unit = val isLocal = symbolName.isLocal if !isLocal || !localNames.contains(symbolName) if isLocal localNames += symbolName symbolInfos += symbolInfo(sym, symbolName, symkinds) - private def registerSymbolSimple(sym: Symbol)(given Context): Unit = + private def registerSymbolSimple(sym: Symbol)(using Context): Unit = registerSymbol(sym, symbolName(sym), Set.empty) - private def registerOccurrence(symbol: String, span: Span, role: SymbolOccurrence.Role)(given Context): Unit = + private def registerOccurrence(symbol: String, span: Span, role: SymbolOccurrence.Role)(using Context): Unit = val occ = SymbolOccurrence(symbol, range(span), role) if !generated.contains(occ) && occ.symbol.nonEmpty then occurrences += occ generated += occ - private def registerUseGuarded(qualSym: Option[Symbol], sym: Symbol, span: Span)(given Context) = + private def registerUseGuarded(qualSym: Option[Symbol], sym: Symbol, span: Span)(using Context) = if !excludeUse(qualSym, sym) then registerUse(sym, span) - private def registerUse(sym: Symbol, span: Span)(given Context): Unit = + private def registerUse(sym: Symbol, span: Span)(using Context): Unit = registerUse(symbolName(sym), span) - private def registerUse(symbol: String, span: Span)(given Context): Unit = + private def registerUse(symbol: String, span: Span)(using Context): Unit = registerOccurrence(symbol, span, SymbolOccurrence.Role.REFERENCE) - private def registerDefinition(sym: Symbol, span: Span, symkinds: Set[SymbolKind])(given Context) = + private def registerDefinition(sym: Symbol, span: Span, symkinds: Set[SymbolKind])(using Context) = val symbol = symbolName(sym) registerOccurrence(symbol, span, SymbolOccurrence.Role.DEFINITION) if !sym.is(Package) registerSymbol(sym, symbol, symkinds) - private def spanOfSymbol(sym: Symbol, span: Span)(given Context): Span = + private def spanOfSymbol(sym: Symbol, span: Span)(using Context): Span = val contents = if source.exists then source.content() else Array.empty[Char] val idx = contents.indexOfSlice(sym.name.show, span.start) val start = if idx >= 0 then idx else span.start @@ -484,10 +484,10 @@ class ExtractSemanticDB extends Phase with case (_::Nil)::Nil => true case _ => false - private def (tree: DefDef) isSetterDef(given Context): Boolean = + private def (tree: DefDef) isSetterDef(using Context): Boolean = tree.name.isSetterName && tree.mods.is(Accessor) && tree.vparamss.isSingleArg - private def findGetters(ctorParams: Set[Names.TermName], body: List[Tree])(given Context): Map[Names.TermName, ValDef] = + private def findGetters(ctorParams: Set[Names.TermName], body: List[Tree])(using Context): Map[Names.TermName, ValDef] = if ctorParams.isEmpty || body.isEmpty then Map.empty else @@ -499,7 +499,7 @@ class ExtractSemanticDB extends Phase with }).toMap end findGetters - private def adjustSpanToName(span: Span, qualSpan: Span, name: Name)(given Context) = + private def adjustSpanToName(span: Span, qualSpan: Span, name: Name)(using Context) = val end = span.end val limit = qualSpan.end val start = @@ -525,18 +525,18 @@ class ExtractSemanticDB extends Phase with rest.foreachUntilImport(op) case Nil => Nil - private def (sym: Symbol) adjustIfCtorTyparam(given Context) = + private def (sym: Symbol) adjustIfCtorTyparam(using Context) = if sym.isType && sym.owner.exists && sym.owner.isConstructor matchingMemberType(sym, sym.owner.owner) else sym - private inline def matchingMemberType(ctorTypeParam: Symbol, classSym: Symbol)(given Context) = + private inline def matchingMemberType(ctorTypeParam: Symbol, classSym: Symbol)(using Context) = classSym.info.member(ctorTypeParam.name).symbol /**Necessary because not all of the eventual flags are propagated from the Tree to the symbol yet. */ - private def symbolKinds(tree: NamedDefTree)(given Context): Set[SymbolKind] = + private def symbolKinds(tree: NamedDefTree)(using Context): Set[SymbolKind] = if tree.symbol.isSelfSym Set.empty else @@ -558,7 +558,7 @@ class ExtractSemanticDB extends Phase with symkinds.toSet private inline def ctorParams( - vparamss: List[List[ValDef]], body: List[Tree])(traverseTpt: => Tree => Unit)(given Context): Unit = + vparamss: List[List[ValDef]], body: List[Tree])(traverseTpt: => Tree => Unit)(using Context): Unit = @tu lazy val getters = findGetters(vparamss.flatMap(_.map(_.name)).toSet, body) for vparams <- vparamss @@ -578,7 +578,7 @@ object ExtractSemanticDB with val name: String = "extractSemanticDB" - def write(source: SourceFile, occurrences: List[SymbolOccurrence], symbolInfos: List[SymbolInformation])(given ctx: Context): Unit = + def write(source: SourceFile, occurrences: List[SymbolOccurrence], symbolInfos: List[SymbolInformation])(using ctx: Context): Unit = def absolutePath(path: Path): Path = path.toAbsolutePath.normalize val sourcePath = absolutePath(source.file.jpath) val sourceRoot = absolutePath(Paths.get(ctx.settings.sourceroot.value)) diff --git a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala index 1cbc90bd8282..78c62c208037 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala @@ -53,7 +53,7 @@ object Scala3 with val s"${RootPackageName @ _}/" = RootPackage val s"${EmptyPackageName @ _}/" = EmptyPackage - def displaySymbol(symbol: Symbol)(given Context): String = + def displaySymbol(symbol: Symbol)(using Context): String = if symbol.isPackageObject then displaySymbol(symbol.owner) else if symbol.is(ModuleClass) then @@ -91,17 +91,17 @@ object Scala3 with extension SymbolOps on (sym: Symbol) with - def ifExists(given Context): Option[Symbol] = if sym.exists then Some(sym) else None + def ifExists(using Context): Option[Symbol] = if sym.exists then Some(sym) else None - def isScala2PackageObject(given Context): Boolean = + def isScala2PackageObject(using Context): Boolean = sym.name.isScala2PackageObjectName && sym.owner.is(Package) && sym.is(Module) - def isAnonymous(given Context): Boolean = + def isAnonymous(using Context): Boolean = sym.isAnonymousClass || sym.isAnonymousModuleVal || sym.isAnonymousFunction - def matchingSetter(given Context): Symbol = + def matchingSetter(using Context): Symbol = val setterName = sym.name.toTermName.setterName @@ -112,18 +112,18 @@ object Scala3 with sym.owner.info.decls.find(s => s.name == setterName && s.info.matchingType) /** Is symbol global? Non-global symbols get localN names */ - def isGlobal(given Context): Boolean = + def isGlobal(using Context): Boolean = sym.is(Package) || !sym.isSelfSym && (sym.is(Param) || sym.owner.isClass) && sym.owner.isGlobal - def isLocalWithinSameName(given Context): Boolean = + def isLocalWithinSameName(using Context): Boolean = sym.exists && !sym.isGlobal && sym.name == sym.owner.name /** Synthetic symbols that are not anonymous or numbered empty ident */ - def isSyntheticWithIdent(given Context): Boolean = + def isSyntheticWithIdent(using Context): Boolean = sym.is(Synthetic) && !sym.isAnonymous && !sym.name.isEmptyNumbered - def isAnnotation(given Context): Boolean = + def isAnnotation(using Context): Boolean = sym.derivesFrom(defn.AnnotationClass) // end SymbolOps diff --git a/compiler/src/dotty/tools/dotc/semanticdb/Tools.scala b/compiler/src/dotty/tools/dotc/semanticdb/Tools.scala index 08b1a15590de..21d57d28929a 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/Tools.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/Tools.scala @@ -39,7 +39,7 @@ object Tools with val bytes = Files.readAllBytes(path) // NOTE: a semanticdb file is a TextDocuments message, not TextDocument TextDocuments.parseFrom(bytes) - def metac(doc: TextDocument, realPath: Path)(given sb: StringBuilder): StringBuilder = + def metac(doc: TextDocument, realPath: Path)(using sb: StringBuilder): StringBuilder = val realURI = realPath.toString given SourceFile = SourceFile.virtual(doc.uri, doc.text) sb.append(realURI).nl @@ -78,7 +78,7 @@ object Tools with case UNKNOWN_LANGUAGE | Unrecognized(_) => "unknown" end languageString - private def processSymbol(info: SymbolInformation)(given sb: StringBuilder): Unit = + private def processSymbol(info: SymbolInformation)(using sb: StringBuilder): Unit = import SymbolInformation.Kind._ sb.append(info.symbol).append(" => ") if info.isAbstract then sb.append("abstract ") @@ -115,7 +115,7 @@ object Tools with sb.append(info.displayName).nl end processSymbol - private def processOccurrence(occ: SymbolOccurrence)(given sb: StringBuilder, sourceFile: SourceFile): Unit = + private def processOccurrence(occ: SymbolOccurrence)(using sb: StringBuilder, sourceFile: SourceFile): Unit = occ.range match case Some(range) => sb.append('[') diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala index 201d18e558e9..e0fdfa303f75 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionCompilerInterface.scala @@ -2070,7 +2070,7 @@ class ReflectionCompilerInterface(val rootContext: core.Contexts.Context) extend if (tree.isEmpty) None else Some(tree) private def withDefaultPos[T <: Tree](fn: Context ?=> T)(using ctx: Context): T = - fn(given ctx.withSource(rootPosition.source)).withSpan(rootPosition.span) + fn(using ctx.withSource(rootPosition.source)).withSpan(rootPosition.span) private def compilerId: Int = rootContext.outersIterator.toList.last.hashCode() } diff --git a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala index 47dc12cd7d98..1a5ae33a627a 100644 --- a/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala +++ b/compiler/src/dotty/tools/dotc/tastyreflect/ReflectionImpl.scala @@ -18,7 +18,7 @@ object ReflectionImpl { val syntaxHighlight = if (ctx.settings.color.value == "always") SyntaxHighlight.ANSI else SyntaxHighlight.plain - new scala.tasty.reflect.SourceCodePrinter[refl.type](refl)(syntaxHighlight).showTree(reflTree)(given reflCtx) + new scala.tasty.reflect.SourceCodePrinter[refl.type](refl)(syntaxHighlight).showTree(reflTree)(using reflCtx) } } diff --git a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala index 0fbf18f83763..68dfa7280097 100644 --- a/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala +++ b/compiler/src/dotty/tools/dotc/transform/CtxLazy.scala @@ -11,12 +11,12 @@ import core.Contexts.Context * A typical use case is a lazy val in a phase object which exists once per root context where * the expression intiializing the lazy val depends only on the root context, but not any changes afterwards. */ -class CtxLazy[T](expr: (given Context) => T) { +class CtxLazy[T](expr: Context ?=> T) { private var myValue: T = _ private var forced = false def apply()(implicit ctx: Context): T = { if (!forced) { - myValue = expr(given ctx) + myValue = expr(using ctx) forced = true } myValue diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 7c882040cdd7..d325efe9e52a 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -753,7 +753,7 @@ object Erasure { if ctx.phase != ctx.erasurePhase && ctx.phase != ctx.erasurePhase.next then // this can happen when reading annotations loaded during erasure, // since these are loaded at phase typer. - adapt(tree, pt, locked)(given ctx.withPhase(ctx.erasurePhase.next)) + adapt(tree, pt, locked)(using ctx.withPhase(ctx.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/Getters.scala b/compiler/src/dotty/tools/dotc/transform/Getters.scala index 8e6dde316fad..4f7fdcbc2bb9 100644 --- a/compiler/src/dotty/tools/dotc/transform/Getters.scala +++ b/compiler/src/dotty/tools/dotc/transform/Getters.scala @@ -93,7 +93,7 @@ class Getters extends MiniPhase with SymTransformer { thisPhase => val newSetters = mutable.HashSet[Symbol]() - def ensureSetter(sym: TermSymbol)(given Context) = + def ensureSetter(sym: TermSymbol)(using Context) = if !sym.setter.exists then newSetters += sym.copy( name = sym.name.setterName, diff --git a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala index 295ce2b5761e..d72d7bc6f9fa 100644 --- a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala +++ b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala @@ -26,7 +26,7 @@ class NonLocalReturns extends MiniPhase { if (tree.tpe <:< pt) tree else Erasure.Boxing.adaptToType(tree, pt) - private def nonLocalReturnControl(given Context) = defn.NonLocalReturnControlClass.typeRef + 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) = diff --git a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala index d7fa5ababa5f..254f03ffd61a 100644 --- a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala +++ b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala @@ -46,7 +46,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( lazy val annotCtx = ctx.fresh.setProperty(InAnnotation, true).withOwner(tree.symbol) for (annot <- tree.symbol.annotations) annot match { case annot: BodyAnnotation => annot // already checked in PrepareInlineable before the creation of the BodyAnnotation - case annot => transform(annot.tree)(given annotCtx) + case annot => transform(annot.tree)(using annotCtx) } checkLevel(super.transform(tree)) case _ => checkLevel(super.transform(tree)) @@ -229,7 +229,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( | The access would be accepted with a given $reqType""") } - private def levelError(sym: Symbol, tp: Type, pos: SourcePosition, errMsg: String)(given Context) = { + private def levelError(sym: Symbol, tp: Type, pos: SourcePosition, errMsg: String)(using Context) = { def symStr = if (!tp.isInstanceOf[ThisType]) sym.show else if (sym.is(ModuleClass)) sym.sourceModule.show diff --git a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala index 0ed3e18429c8..404cdb1e4c52 100644 --- a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala @@ -405,7 +405,7 @@ class ReifyQuotes extends MacroTransform { case tree: DefTree if level >= 1 => val newAnnotations = tree.symbol.annotations.mapconserve { annot => - val newAnnotTree = transform(annot.tree)(given ctx.withOwner(tree.symbol)) + val newAnnotTree = transform(annot.tree)(using ctx.withOwner(tree.symbol)) if (annot.tree == newAnnotTree) annot else ConcreteAnnotation(newAnnotTree) } diff --git a/compiler/src/dotty/tools/dotc/transform/Splicer.scala b/compiler/src/dotty/tools/dotc/transform/Splicer.scala index ddab4c1e04fe..7c747b6cc92a 100644 --- a/compiler/src/dotty/tools/dotc/transform/Splicer.scala +++ b/compiler/src/dotty/tools/dotc/transform/Splicer.scala @@ -37,7 +37,7 @@ object Splicer { * * See: `Staging` */ - def splice(tree: Tree, pos: SourcePosition, classLoader: ClassLoader)(given ctx: Context): Tree = tree match { + def splice(tree: Tree, pos: SourcePosition, classLoader: ClassLoader)(using ctx: Context): Tree = tree match { case Quoted(quotedTree) => quotedTree case _ => val interpreter = new Interpreter(pos, classLoader) @@ -70,7 +70,7 @@ object Splicer { } /** Checks that no symbol that whas generated within the macro expansion has an out of scope reference */ - def checkEscapedVariables(tree: Tree, expansionOwner: Symbol)(given ctx: Context): tree.type = + def checkEscapedVariables(tree: Tree, expansionOwner: Symbol)(using ctx: Context): tree.type = new TreeTraverser { private[this] var locals = Set.empty[Symbol] private def markSymbol(sym: Symbol)(implicit ctx: Context): Unit = @@ -79,7 +79,7 @@ object Splicer { case tree: DefTree => markSymbol(tree.symbol) case _ => } - def traverse(tree: Tree)(given ctx: Context): Unit = + def traverse(tree: Tree)(using ctx: Context): Unit = def traverseOver(lastEntered: Set[Symbol]) = try traverseChildren(tree) finally locals = lastEntered @@ -98,7 +98,7 @@ object Splicer { case _ => markDef(tree) traverseChildren(tree) - private def isEscapedVariable(sym: Symbol)(given ctx: Context): Boolean = + private def isEscapedVariable(sym: Symbol)(using ctx: Context): Boolean = sym.exists && !sym.is(Package) && sym.owner.ownersIterator.exists(x => x == expansionOwner || // symbol was generated within this macro expansion @@ -120,7 +120,7 @@ object Splicer { case _ => type Env = Set[Symbol] - def checkValidStat(tree: Tree)(given Env): Env = tree match { + def checkValidStat(tree: Tree)(using Env): Env = tree match { case tree: ValDef if tree.symbol.is(Synthetic) => // Check val from `foo(j = x, i = y)` which it is expanded to // `val j$1 = x; val i$1 = y; foo(i = i$1, j = j$1)` @@ -131,7 +131,7 @@ object Splicer { summon[Env] } - def checkIfValidArgument(tree: Tree)(given Env): Unit = tree match { + def checkIfValidArgument(tree: Tree)(using Env): Unit = tree match { case Block(Nil, expr) => checkIfValidArgument(expr) case Typed(expr, _) => checkIfValidArgument(expr) @@ -170,13 +170,13 @@ object Splicer { |""".stripMargin, tree.sourcePos) } - def checkIfValidStaticCall(tree: Tree)(given Env): Unit = tree match { + def checkIfValidStaticCall(tree: Tree)(using Env): Unit = tree match { case closureDef(ddef @ DefDef(_, Nil, (ev :: Nil) :: Nil, _, _)) if ddef.symbol.info.isContextualMethod => - checkIfValidStaticCall(ddef.rhs)(given summon[Env] + ev.symbol) + checkIfValidStaticCall(ddef.rhs)(using summon[Env] + ev.symbol) case Block(stats, expr) => - val newEnv = stats.foldLeft(summon[Env])((env, stat) => checkValidStat(stat)(given env)) - checkIfValidStaticCall(expr)(given newEnv) + val newEnv = stats.foldLeft(summon[Env])((env, stat) => checkValidStat(stat)(using env)) + checkIfValidStaticCall(expr)(using newEnv) case Typed(expr, _) => checkIfValidStaticCall(expr) @@ -197,7 +197,7 @@ object Splicer { |""".stripMargin, tree.sourcePos) } - checkIfValidStaticCall(tree)(given Set.empty) + checkIfValidStaticCall(tree)(using Set.empty) } /** Tree interpreter that evaluates the tree */ @@ -262,7 +262,7 @@ object Splicer { unexpectedTree(tree) case closureDef((ddef @ DefDef(_, _, (arg :: Nil) :: Nil, _, _))) => - (obj: AnyRef) => interpretTree(ddef.rhs)(given env.updated(arg.symbol, obj)) + (obj: AnyRef) => interpretTree(ddef.rhs)(using env.updated(arg.symbol, obj)) // Interpret `foo(j = x, i = y)` which it is expanded to // `val j$1 = x; val i$1 = y; foo(i = i$1, j = j$1)` @@ -418,7 +418,7 @@ object Splicer { } private object MissingClassDefinedInCurrentRun { - def unapply(targetException: NoClassDefFoundError)(given ctx: Context): Option[Symbol] = { + def unapply(targetException: NoClassDefFoundError)(using ctx: Context): Option[Symbol] = { val className = targetException.getMessage if (className eq null) None else { diff --git a/compiler/src/dotty/tools/dotc/transform/SymUtils.scala b/compiler/src/dotty/tools/dotc/transform/SymUtils.scala index a749651e326d..cee9866c8a02 100644 --- a/compiler/src/dotty/tools/dotc/transform/SymUtils.scala +++ b/compiler/src/dotty/tools/dotc/transform/SymUtils.scala @@ -178,7 +178,7 @@ class SymUtils(val self: Symbol) extends AnyVal { /** Is this symbol defined locally (i.e. at some level owned by a term) so that * it cannot be seen from parent class `cls`? */ - def isInaccessibleChildOf(cls: Symbol)(given Context): Boolean = + def isInaccessibleChildOf(cls: Symbol)(using Context): Boolean = def isAccessible(sym: Symbol, cls: Symbol): Boolean = if cls.isType && !cls.is(Package) then isAccessible(sym, cls.owner) diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index a91dda90b85d..80fd763abe9e 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -863,7 +863,7 @@ trait Applications extends Compatibility { new ApplyToTyped(tree, fun1, funRef, proto.typedArgs(), pt) else new ApplyToUntyped(tree, fun1, funRef, proto, pt)( - given fun1.nullableInArgContext(given argCtx(tree))) + given fun1.nullableInArgContext(using argCtx(tree))) convertNewGenericArray( postProcessByNameArgs(funRef, app.result).computeNullable()) case _ => diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index f3f7e511966f..b261e8bbd9a4 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -1106,7 +1106,7 @@ trait Checking { } /** check that annotation `annot` is applicable to symbol `sym` */ - def checkAnnotApplicable(annot: Tree, sym: Symbol)(given ctx: Context): Boolean = + def checkAnnotApplicable(annot: Tree, sym: Symbol)(using ctx: Context): Boolean = !ctx.reporter.reportsErrorsFor { implicit ctx => val annotCls = Annotations.annotClass(annot) val pos = annot.sourcePos @@ -1140,7 +1140,7 @@ trait ReChecking extends Checking { override def checkEnum(cdef: untpd.TypeDef, cls: Symbol, firstParent: Symbol)(implicit ctx: Context): Unit = () override def checkRefsLegal(tree: tpd.Tree, badOwner: Symbol, allowed: (Name, Symbol) => Boolean, where: String)(implicit ctx: Context): Unit = () override def checkEnumCaseRefsLegal(cdef: TypeDef, enumCtx: Context)(implicit ctx: Context): Unit = () - override def checkAnnotApplicable(annot: Tree, sym: Symbol)(given ctx: Context): Boolean = true + override def checkAnnotApplicable(annot: Tree, sym: Symbol)(using ctx: Context): Boolean = true } trait NoChecking extends ReChecking { diff --git a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala index 33e112db700a..49f82e74f763 100644 --- a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala +++ b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala @@ -183,7 +183,7 @@ object EtaExpansion extends LiftImpure { * If `expr` has implicit function type, the arguments are passed with `given`. * E.g. for (1): * - * { val xs = es; (x1, ..., xn) => expr(given x1, ..., xn) } + * { val xs = es; (x1, ..., xn) => expr(using x1, ..., xn) } * * Case (3) applies if the method is curried, i.e. its result type is again a method * type. Case (2) applies if the expected arity of the function type `xarity` differs diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index 73b23b6f35df..39e1ec9a3779 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -70,7 +70,7 @@ object Implicits { /** If `expected` is a selection prototype, does `tp` have an extension * method with the selecting name? False otherwise. */ - def hasExtMethod(tp: Type, expected: Type)(given Context) = expected match + def hasExtMethod(tp: Type, expected: Type)(using Context) = expected match case SelectionProto(name, _, _, _) => tp.memberBasedOnFlags(name, required = ExtensionMethod).exists case _ => false diff --git a/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala b/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala index 621b4424ebfe..158bdf6f17ed 100644 --- a/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala +++ b/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala @@ -43,7 +43,7 @@ object ImportInfo { * @param isRootImport true if this is one of the implicit imports of scala, java.lang, * scala.Predef or dotty.DottyPredef in the start context, false otherwise. */ -class ImportInfo(symf: (given Context) => Symbol, +class ImportInfo(symf: Context ?=> Symbol, val selectors: List[untpd.ImportSelector], symNameOpt: Option[TermName], val isRootImport: Boolean = false) extends Showable { @@ -52,7 +52,7 @@ class ImportInfo(symf: (given Context) => Symbol, // that we cannot use one for `DottyPredefModuleRef`. def sym(implicit ctx: Context): Symbol = { if (mySym == null) { - mySym = symf(given ctx) + mySym = symf(using ctx) assert(mySym != null) } mySym diff --git a/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala b/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala index 0843adb925f1..a28c0a04b709 100644 --- a/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala +++ b/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala @@ -53,16 +53,16 @@ trait ImportSuggestions with * - Any members of the java or java.lang packages. These are * skipped as an optimization, since they won't contain implicits anyway. */ - private def suggestionRoots(given Context) = + private def suggestionRoots(using Context) = val seen = mutable.Set[TermRef]() - def lookInside(root: Symbol)(given Context): Boolean = + def lookInside(root: Symbol)(using Context): Boolean = if root.is(Package) then root.isTerm && root.isCompleted else !root.name.is(FlatName) && !root.name.lastPart.contains('$') && root.is(ModuleVal, butNot = JavaDefined) - def nestedRoots(site: Type)(given Context): List[Symbol] = + def nestedRoots(site: Type)(using Context): List[Symbol] = val seenNames = mutable.Set[Name]() site.baseClasses.flatMap { bc => bc.info.decls.filter { dcl => @@ -72,7 +72,7 @@ trait ImportSuggestions with } } - def rootsStrictlyIn(ref: Type)(given Context): List[TermRef] = + def rootsStrictlyIn(ref: Type)(using Context): List[TermRef] = val site = ref.widen val refSym = site.typeSymbol val nested = @@ -91,18 +91,18 @@ trait ImportSuggestions with .flatMap(rootsIn) .toList - def rootsIn(ref: TermRef)(given Context): List[TermRef] = + def rootsIn(ref: TermRef)(using Context): List[TermRef] = if seen.contains(ref) then Nil else implicits.println(i"search for suggestions in ${ref.symbol.fullName}") seen += ref ref :: rootsStrictlyIn(ref) - def rootsOnPath(tp: Type)(given Context): List[TermRef] = tp match + def rootsOnPath(tp: Type)(using Context): List[TermRef] = tp match case ref: TermRef => rootsIn(ref) ::: rootsOnPath(ref.prefix) case _ => Nil - def recur(given ctx: Context): List[TermRef] = + def recur(using ctx: Context): List[TermRef] = if ctx.owner.exists then val defined = if ctx.owner.isClass then @@ -118,7 +118,7 @@ trait ImportSuggestions with else ctx.importInfo.sym.info match case ImportType(expr) => rootsOnPath(expr.tpe) case _ => Nil - defined ++ imported ++ recur(given ctx.outer) + defined ++ imported ++ recur(using ctx.outer) else Nil recur @@ -137,7 +137,7 @@ trait ImportSuggestions with * return instead a list of all possible references to extension methods named * `name` that are applicable to `T`. */ - private def importSuggestions(pt: Type)(given ctx: Context): (List[TermRef], List[TermRef]) = + private def importSuggestions(pt: Type)(using ctx: Context): (List[TermRef], List[TermRef]) = val timer = new Timer() val deadLine = System.currentTimeMillis() + suggestImplicitTimeOut @@ -239,9 +239,9 @@ trait ImportSuggestions with * The addendum suggests given imports that might fix the problem. * If there's nothing to suggest, an empty string is returned. */ - override def importSuggestionAddendum(pt: Type)(given ctx: Context): String = + override def importSuggestionAddendum(pt: Type)(using ctx: Context): String = val (fullMatches, headMatches) = - importSuggestions(pt)(given ctx.fresh.setExploreTyperState()) + importSuggestions(pt)(using ctx.fresh.setExploreTyperState()) implicits.println(i"suggestions for $pt in ${ctx.owner} = ($fullMatches%, %, $headMatches%, %)") val (suggestedRefs, help) = if fullMatches.nonEmpty then (fullMatches, "fix") diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index ff468264da3b..bd33974d755e 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -200,7 +200,7 @@ object Inliner { private enum ErrorKind case Parser, Typer - private def compileForErrors(tree: Tree, stopAfterParser: Boolean)(given ctx: Context): List[(ErrorKind, Error)] = + private def compileForErrors(tree: Tree, stopAfterParser: Boolean)(using ctx: Context): List[(ErrorKind, Error)] = assert(tree.symbol == defn.CompiletimeTesting_typeChecks || tree.symbol == defn.CompiletimeTesting_typeCheckErrors) def stripTyped(t: Tree): Tree = t match { case Typed(t2, _) => stripTyped(t2) @@ -228,7 +228,7 @@ object Inliner { Nil } - private def packError(kind: ErrorKind, error: Error)(given Context): Tree = + private def packError(kind: ErrorKind, error: Error)(using Context): Tree = def lit(x: Any) = Literal(Constant(x)) val constructor: Tree = ref(defn.CompiletimeTesting_Error_apply) val parserErrorKind: Tree = ref(defn.CompiletimeTesting_ErrorKind_Parser) @@ -240,18 +240,18 @@ object Inliner { lit(error.pos.column), if kind == ErrorKind.Parser then parserErrorKind else typerErrorKind) - private def packErrors(errors: List[(ErrorKind, Error)])(given Context): Tree = + private def packErrors(errors: List[(ErrorKind, Error)])(using Context): Tree = val individualErrors: List[Tree] = errors.map(packError) val errorTpt = ref(defn.CompiletimeTesting_ErrorClass) mkList(individualErrors, errorTpt) /** Expand call to scala.compiletime.testing.typeChecks */ - def typeChecks(tree: Tree)(given Context): Tree = + def typeChecks(tree: Tree)(using Context): Tree = val errors = compileForErrors(tree, true) Literal(Constant(errors.isEmpty)) /** Expand call to scala.compiletime.testing.typeCheckErrors */ - def typeCheckErrors(tree: Tree)(given Context): Tree = + def typeCheckErrors(tree: Tree)(using Context): Tree = val errors = compileForErrors(tree, false) packErrors(errors) } @@ -1156,7 +1156,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(implicit ctx: Context) { override def newLikeThis: Typer = new InlineTyper(initialErrorCount) /** Suppress further inlining if this inline typer has already issued errors */ - override def suppressInline(given ctx: Context) = + override def suppressInline(using ctx: Context) = ctx.reporter.errorCount > initialErrorCount || super.suppressInline } @@ -1278,7 +1278,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(implicit ctx: Context) { ctx.compilationUnit.suspend() // this throws a SuspendException val evaluatedSplice = { - given Context = tastyreflect.MacroExpansion.context(inlinedFrom)(given ctx) + given Context = tastyreflect.MacroExpansion.context(inlinedFrom)(using ctx) Splicer.splice(body, inlinedFrom.sourcePos, MacroClassLoader.fromContext) } val inlinedNormailizer = new TreeMap { diff --git a/compiler/src/dotty/tools/dotc/typer/Nullables.scala b/compiler/src/dotty/tools/dotc/typer/Nullables.scala index 7f4113bd1486..f5b5b58d56bc 100644 --- a/compiler/src/dotty/tools/dotc/typer/Nullables.scala +++ b/compiler/src/dotty/tools/dotc/typer/Nullables.scala @@ -81,7 +81,7 @@ object Nullables with * * The second boolean result is true for equality tests, false for inequality tests */ - def unapply(tree: Tree)(given Context): Option[(Tree, Boolean)] = tree match + def unapply(tree: Tree)(using Context): Option[(Tree, Boolean)] = tree match case Apply(Select(l, _), Literal(Constant(null)) :: Nil) => testSym(tree.symbol, l) case Apply(Select(Literal(Constant(null)), _), r :: Nil) => @@ -89,7 +89,7 @@ object Nullables with case _ => None - private def testSym(sym: Symbol, operand: Tree)(given Context) = + private def testSym(sym: Symbol, operand: Tree)(using Context) = if sym == defn.Any_== || sym == defn.Object_eq then Some((operand, true)) else if sym == defn.Any_!= || sym == defn.Object_ne then Some((operand, false)) else None @@ -98,7 +98,7 @@ object Nullables with /** An extractor for null-trackable references */ object TrackedRef - def unapply(tree: Tree)(given Context): Option[TermRef] = tree.typeOpt match + def unapply(tree: Tree)(using Context): Option[TermRef] = tree.typeOpt match case ref: TermRef if isTracked(ref) => Some(ref) case _ => None end TrackedRef @@ -130,7 +130,7 @@ object Nullables with * Check `usedOutOfOrder` to see the explaination and example of "out of order". * See more examples in `tests/explicit-nulls/neg/var-ref-in-closure.scala`. */ - def isTracked(ref: TermRef)(given Context) = + def isTracked(ref: TermRef)(using Context) = ref.isStable || { val sym = ref.symbol !ref.usedOutOfOrder @@ -142,7 +142,7 @@ object Nullables with /** The nullability context to be used after a case that matches pattern `pat`. * If `pat` is `null`, this will assert that the selector `sel` is not null afterwards. */ - def afterPatternContext(sel: Tree, pat: Tree)(given ctx: Context) = (sel, pat) match + def afterPatternContext(sel: Tree, pat: Tree)(using ctx: Context) = (sel, pat) match case (TrackedRef(ref), Literal(Constant(null))) => ctx.addNotNullRefs(Set(ref)) case _ => ctx @@ -150,11 +150,11 @@ object Nullables with * given pattern `pat`. If the pattern can only match non-null values, this * will assert that the selector `sel` is not null in these regions. */ - def caseContext(sel: Tree, pat: Tree)(given ctx: Context): Context = sel match + def caseContext(sel: Tree, pat: Tree)(using ctx: Context): Context = sel match case TrackedRef(ref) if matchesNotNull(pat) => ctx.addNotNullRefs(Set(ref)) case _ => ctx - private def matchesNotNull(pat: Tree)(given Context): Boolean = pat match + private def matchesNotNull(pat: Tree)(using Context): Boolean = pat match case _: Typed | _: UnApply => true case Alternative(pats) => pats.forall(matchesNotNull) // TODO: Add constant pattern if the constant type is not nullable @@ -185,7 +185,7 @@ object Nullables with else info :: infos /** Retract all references to mutable variables */ - def retractMutables(given Context) = + def retractMutables(using Context) = val mutables = infos.foldLeft(Set[TermRef]())((ms, info) => ms.union(info.asserted.filter(_.symbol.is(Mutable)))) infos.extendWith(NotNullInfo(Set(), mutables)) @@ -229,7 +229,7 @@ object Nullables with * } * ``` */ - def usedOutOfOrder(given Context): Boolean = + def usedOutOfOrder(using Context): Boolean = val refSym = ref.symbol val refOwner = refSym.owner @@ -253,13 +253,13 @@ object Nullables with tree /* The nullability info of `tree` */ - def notNullInfo(given Context): NotNullInfo = + def notNullInfo(using Context): NotNullInfo = stripInlined(tree).getAttachment(NNInfo) match case Some(info) if !curCtx.erasedTypes => info case _ => NotNullInfo.empty /* The nullability info of `tree`, assuming it is a condition that evaluates to `c` */ - def notNullInfoIf(c: Boolean)(given Context): NotNullInfo = + def notNullInfoIf(c: Boolean)(using Context): NotNullInfo = val cond = tree.notNullConditional if cond.isEmpty then tree.notNullInfo else tree.notNullInfo.seq(NotNullInfo(if c then cond.ifTrue else cond.ifFalse, Set())) @@ -268,13 +268,13 @@ object Nullables with * by `tree` yields `true` or `false`. Two empty sets if `tree` is not * a condition. */ - def notNullConditional(given Context): NotNullConditional = + def notNullConditional(using Context): NotNullConditional = stripBlock(tree).getAttachment(NNConditional) match case Some(cond) if !curCtx.erasedTypes => cond case _ => NotNullConditional.empty /** The current context augmented with nullability information of `tree` */ - def nullableContext(given Context): Context = + def nullableContext(using Context): Context = val info = tree.notNullInfo if info.isEmpty then curCtx else curCtx.addNotNullInfo(info) @@ -282,7 +282,7 @@ object Nullables with * assuming the result of the condition represented by `tree` is the same as * the value of `c`. */ - def nullableContextIf(c: Boolean)(given Context): Context = + def nullableContextIf(c: Boolean)(using Context): Context = val info = tree.notNullInfoIf(c) if info.isEmpty then curCtx else curCtx.addNotNullInfo(info) @@ -290,7 +290,7 @@ object Nullables with * This is the current context, augmented with nullability information * of the left argument, if the application is a boolean `&&` or `||`. */ - def nullableInArgContext(given Context): Context = tree match + def nullableInArgContext(using Context): Context = tree match case Select(x, _) if !curCtx.erasedTypes => if tree.symbol == defn.Boolean_&& then x.nullableContextIf(true) else if tree.symbol == defn.Boolean_|| then x.nullableContextIf(false) @@ -304,7 +304,7 @@ object Nullables with * a path (i.e. a stable TermRef) * 2. Boolean &&, ||, ! */ - def computeNullable()(given Context): tree.type = + def computeNullable()(using Context): tree.type = def setConditional(ifTrue: Set[TermRef], ifFalse: Set[TermRef]) = tree.putAttachment(NNConditional, NotNullConditional(ifTrue, ifFalse)) if !curCtx.erasedTypes && analyzedOps.contains(tree.symbol.name.toTermName) then @@ -328,7 +328,7 @@ object Nullables with tree /** Compute nullability information for this tree and all its subtrees */ - def computeNullableDeeply()(given Context): Unit = + def computeNullableDeeply()(using Context): Unit = new TreeTraverser { def traverse(tree: Tree)(implicit ctx: Context) = traverseChildren(tree) @@ -336,7 +336,7 @@ object Nullables with }.traverse(tree) extension assignOps on (tree: Assign) with - def computeAssignNullable()(given Context): tree.type = tree.lhs match + def computeAssignNullable()(using Context): tree.type = tree.lhs match case TrackedRef(ref) => val rhstp = tree.rhs.typeOpt if curCtx.explicitNulls && ref.isNullableUnion then @@ -367,7 +367,7 @@ object Nullables with * Note: we track the local variables through their offset and not through their name * because of shadowing. */ - def assignmentSpans(given Context): Map[Int, List[Span]] = + def assignmentSpans(using Context): Map[Int, List[Span]] = import ast.untpd._ object populate extends UntypedTreeTraverser with @@ -443,7 +443,7 @@ object Nullables with * ys = Links(xs.elem, ys.next) // error in unrefined: ys is potentially null here * xs = xs.next */ - def whileContext(whileSpan: Span)(given Context): Context = + def whileContext(whileSpan: Span)(using Context): Context = def isRetracted(ref: TermRef): Boolean = val sym = ref.symbol sym.span.exists @@ -462,14 +462,14 @@ object Nullables with * flow assumptions about mutable variables and suggest that it is enclosed * in a `byName(...)` call instead. */ - def postProcessByNameArgs(fn: TermRef, app: Tree)(given ctx: Context): Tree = + def postProcessByNameArgs(fn: TermRef, app: Tree)(using ctx: Context): Tree = fn.widen match case mt: MethodType if mt.paramInfos.exists(_.isInstanceOf[ExprType]) && !fn.symbol.is(Inline) => app match case Apply(fn, args) => val dropNotNull = new TreeMap with - override def transform(t: Tree)(given Context) = t match + override def transform(t: Tree)(using Context) = t match case AssertNotNull(t0) if t0.symbol.is(Mutable) => nullables.println(i"dropping $t") transform(t0) @@ -489,10 +489,10 @@ object Nullables with def postProcess(formal: Type, arg: Tree): Tree = val nestedCtx = ctx.fresh.setNewTyperState() - val arg1 = dropNotNull.transform(arg)(given nestedCtx) + val arg1 = dropNotNull.transform(arg)(using nestedCtx) if arg1 eq arg then arg else - val arg2 = retyper.typed(arg1, formal)(given nestedCtx) + val arg2 = retyper.typed(arg1, formal)(using nestedCtx) if nestedCtx.reporter.hasErrors || !(arg2.tpe <:< formal) then ctx.error(em"""This argument was typed using flow assumptions about mutable variables |but it is passed to a by-name parameter where such flow assumptions are unsound. diff --git a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala index 7091f8771408..9c1c52aa7d8c 100644 --- a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala +++ b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala @@ -258,9 +258,9 @@ object PrepareInlineable { case Block(DefDef(nme.ANON_FUN, _, _, _, _) :: Nil, Closure(_, fn, _)) if fn.symbol.info.isImplicitMethod => // TODO Support this pattern ctx.error( - """Macros using a return type of the form `foo(): (given X) => Y` are not yet supported. + """Macros using a return type of the form `foo(): X ?=> Y` are not yet supported. | - |Place the implicit as an argument (`foo()(given X): Y`) to overcome this limitation. + |Place the implicit as an argument (`foo()(using X): Y`) to overcome this limitation. |""".stripMargin, tree.sourcePos) case _ => ctx.error( diff --git a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala index ea7a05abbd9a..7656d7cc3ef7 100644 --- a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala +++ b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala @@ -337,7 +337,7 @@ object ProtoTypes { else ctx.withNotNullInfos(ctx.notNullInfos.retractMutables) val locked = ctx.typerState.ownedVars val targ = cacheTypedArg(arg, - typer.typedUnadapted(_, wideFormal, locked)(given argCtx), + typer.typedUnadapted(_, wideFormal, locked)(using argCtx), force = true) typer.adapt(targ, wideFormal, locked) } diff --git a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala index 794eba08f866..f6d4259fdb6b 100644 --- a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala +++ b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala @@ -295,7 +295,7 @@ trait TypeAssigner { } } - def importSuggestionAddendum(pt: Type)(given Context): String = "" + def importSuggestionAddendum(pt: Type)(using Context): String = "" /** The type of the selection in `tree`, where `qual1` is the typed qualifier part. * The selection type is additionally checked for accessibility. diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 603b170417bf..85eb64491377 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -179,7 +179,7 @@ class Typer extends Namer * outer package-level definition might trump two conflicting inner * imports, so no error should be issued in that case. See i7876.scala. */ - def recurAndCheckNewOrShadowed(previous: Type, prevPrec: BindingPrec, prevCtx: Context)(given Context): Type = + def recurAndCheckNewOrShadowed(previous: Type, prevPrec: BindingPrec, prevCtx: Context)(using Context): Type = val found = findRefRecur(previous, prevPrec, prevCtx) if found eq previous then checkNewOrShadowed(found, prevPrec) else found @@ -333,11 +333,11 @@ class Typer extends Namer else if (isPossibleImport(NamedImport) && (curImport ne outer.importInfo)) { val namedImp = namedImportRef(curImport) if (namedImp.exists) - recurAndCheckNewOrShadowed(namedImp, NamedImport, ctx)(given outer) + recurAndCheckNewOrShadowed(namedImp, NamedImport, ctx)(using outer) else if (isPossibleImport(WildImport) && !curImport.sym.isCompleting) { val wildImp = wildImportRef(curImport) if (wildImp.exists) - recurAndCheckNewOrShadowed(wildImp, WildImport, ctx)(given outer) + recurAndCheckNewOrShadowed(wildImp, WildImport, ctx)(using outer) else { updateUnimported() loop(ctx)(outer) @@ -498,7 +498,7 @@ class Typer extends Namer case _ => errorTree(tree, "cannot convert to type selection") // will never be printed due to fallback } - def selectWithFallback(fallBack: (given Context) => Tree) = + def selectWithFallback(fallBack: Context ?=> Tree) = tryAlternatively(typeSelectOnTerm)(fallBack) if (tree.qualifier.isType) { @@ -797,8 +797,8 @@ class Typer extends Namer def typedBlock(tree: untpd.Block, pt: Type)(implicit ctx: Context): Tree = { val localCtx = ctx.retractMode(Mode.Pattern) - val (stats1, exprCtx) = typedBlockStats(tree.stats)(given localCtx) - val expr1 = typedExpr(tree.expr, pt.dropIfProto)(given exprCtx) + val (stats1, exprCtx) = typedBlockStats(tree.stats)(using localCtx) + val expr1 = typedExpr(tree.expr, pt.dropIfProto)(using exprCtx) ensureNoLocalRefs( cpy.Block(tree)(stats1, expr1) .withType(expr1.tpe) @@ -850,13 +850,13 @@ class Typer extends Namer val result = if tree.elsep.isEmpty then - val thenp1 = typed(tree.thenp, defn.UnitType)(given cond1.nullableContextIf(true)) + val thenp1 = typed(tree.thenp, defn.UnitType)(using cond1.nullableContextIf(true)) val elsep1 = tpd.unitLiteral.withSpan(tree.span.endPos) cpy.If(tree)(cond1, thenp1, elsep1).withType(defn.UnitType) else val thenp1 :: elsep1 :: Nil = harmonic(harmonize, pt) { - val thenp0 = typed(tree.thenp, pt.dropIfProto)(given cond1.nullableContextIf(true)) - val elsep0 = typed(tree.elsep, pt.dropIfProto)(given cond1.nullableContextIf(false)) + val thenp0 = typed(tree.thenp, pt.dropIfProto)(using cond1.nullableContextIf(true)) + val elsep0 = typed(tree.elsep, pt.dropIfProto)(using cond1.nullableContextIf(false)) thenp0 :: elsep0 :: Nil } assignType(cpy.If(tree)(cond1, thenp1, elsep1), thenp1, elsep1) @@ -1187,7 +1187,7 @@ class Typer extends Namer def typedCases(cases: List[untpd.CaseDef], sel: Tree, wideSelType: Type, pt: Type)(implicit ctx: Context): List[CaseDef] = var caseCtx = ctx cases.mapconserve { cas => - val case1 = typedCase(cas, sel, wideSelType, pt)(given caseCtx) + val case1 = typedCase(cas, sel, wideSelType, pt)(using caseCtx) caseCtx = Nullables.afterPatternContext(sel, case1.pat) case1 } @@ -1302,11 +1302,11 @@ class Typer extends Namer } def typedWhileDo(tree: untpd.WhileDo)(implicit ctx: Context): Tree = { - given whileCtx: Context = Nullables.whileContext(tree.span)(given ctx) + given whileCtx: Context = Nullables.whileContext(tree.span)(using ctx) val cond1 = if (tree.cond eq EmptyTree) EmptyTree else typed(tree.cond, defn.BooleanType) - val body1 = typed(tree.body, defn.UnitType)(given cond1.nullableContextIf(true)) + val body1 = typed(tree.body, defn.UnitType)(using cond1.nullableContextIf(true)) assignType(cpy.WhileDo(tree)(cond1, body1)) .withNotNullInfo(body1.notNullInfo.retractedInfo.seq(cond1.notNullInfoIf(false))) } @@ -2278,7 +2278,7 @@ class Typer extends Namer case none => val newCtx = if (ctx.owner.isTerm && adaptCreationContext(mdef)) ctx else ctx.withNotNullInfos(initialNotNullInfos) - typed(mdef)(given newCtx) match { + typed(mdef)(using newCtx) match { case mdef1: DefDef if !Inliner.bodyToInline(mdef1.symbol).isEmpty => buf += inlineExpansion(mdef1) // replace body with expansion, because it will be used as inlined body @@ -2303,7 +2303,7 @@ class Typer extends Namer val stat1 = typed(stat)(ctx.exprContext(stat, exprOwner)) checkStatementPurity(stat1)(stat, exprOwner) buf += stat1 - traverse(rest)(given stat1.nullableContext) + traverse(rest)(using stat1.nullableContext) case nil => (buf.toList, ctx) } @@ -2370,9 +2370,9 @@ class Typer extends Namer def typedPattern(tree: untpd.Tree, selType: Type = WildcardType)(implicit ctx: Context): Tree = typed(tree, selType)(ctx addMode Mode.Pattern) - def tryEither[T](op: (given Context) => T)(fallBack: (T, TyperState) => T)(implicit ctx: Context): T = { + def tryEither[T](op: Context ?=> T)(fallBack: (T, TyperState) => T)(implicit ctx: Context): T = { val nestedCtx = ctx.fresh.setNewTyperState() - val result = op(given nestedCtx) + val result = op(using nestedCtx) if (nestedCtx.reporter.hasErrors && !nestedCtx.reporter.hasStickyErrors) { record("tryEither.fallBack") fallBack(result, nestedCtx.typerState) @@ -2387,7 +2387,7 @@ class Typer extends Namer /** Try `op1`, if there are errors, try `op2`, if `op2` also causes errors, fall back * to errors and result of `op1`. */ - def tryAlternatively[T](op1: (given Context) => T)(op2: (given Context) => T)(implicit ctx: Context): T = + def tryAlternatively[T](op1: Context ?=> T)(op2: Context ?=> T)(implicit ctx: Context): T = tryEither(op1) { (failedVal, failedState) => tryEither(op2) { (_, _) => failedState.commit() @@ -3189,7 +3189,7 @@ class Typer extends Namer } // Overridden in InlineTyper - def suppressInline(given ctx: Context): Boolean = ctx.isAfterTyper + def suppressInline(using ctx: Context): Boolean = ctx.isAfterTyper /** Does the "contextuality" of the method type `methType` match the one of the prototype `pt`? * This is the case if diff --git a/compiler/src/dotty/tools/package.scala b/compiler/src/dotty/tools/package.scala index 870148fcd5d4..0bf617895b2c 100644 --- a/compiler/src/dotty/tools/package.scala +++ b/compiler/src/dotty/tools/package.scala @@ -31,5 +31,5 @@ package object tools { } type WrappedResult[T] = resultWrapper.WrappedResult[T] def WrappedResult[T](x: T) = resultWrapper.wrap(x) - def result[T](given x: WrappedResult[T]): T = resultWrapper.unwrap(x) + def result[T](using x: WrappedResult[T]): T = resultWrapper.unwrap(x) } diff --git a/compiler/test-resources/repl-macros/i5551 b/compiler/test-resources/repl-macros/i5551 index d3c7539a64ee..a7e8b1df0ac9 100644 --- a/compiler/test-resources/repl-macros/i5551 +++ b/compiler/test-resources/repl-macros/i5551 @@ -1,8 +1,8 @@ scala> import scala.quoted._ -scala> def assertImpl(expr: Expr[Boolean])(given qctx: QuoteContext) = '{ if !($expr) then throw new AssertionError("failed assertion")} +scala> def assertImpl(expr: Expr[Boolean])(using qctx: QuoteContext) = '{ if !($expr) then throw new AssertionError("failed assertion")} def assertImpl (expr: quoted.Expr[Boolean]) - (given qctx: quoted.QuoteContext): quoted.Expr[Unit] + (using qctx: quoted.QuoteContext): quoted.Expr[Unit] scala> inline def assert(expr: => Boolean): Unit = ${ assertImpl('{expr}) } def assert(expr: => Boolean): Unit diff --git a/compiler/test-resources/repl/3932 b/compiler/test-resources/repl/3932 index 33f1592f98c1..a32d502581f3 100644 --- a/compiler/test-resources/repl/3932 +++ b/compiler/test-resources/repl/3932 @@ -1,2 +1,2 @@ -scala> def fun[T](x: T): (given List[T]) => Int = ??? +scala> def fun[T](x: T): List[T] ?=> Int = ??? def fun[T](x: T): (List[T]) ?=> Int \ No newline at end of file diff --git a/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala b/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala index 0b387aead267..e08e0618dcb7 100644 --- a/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala +++ b/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala @@ -127,7 +127,7 @@ class ArrayApplyOptTest extends DottyBytecodeTest { @Test def testArrayInlined3 = test( """{ - | inline def array[T](inline xs: T*)(given inline ct: scala.reflect.ClassTag[T]): Array[T] = Array(xs: _*) + | inline def array[T](inline xs: T*)(using inline ct: scala.reflect.ClassTag[T]): Array[T] = Array(xs: _*) | array(1, 2) |}""".stripMargin, newArray2Opcodes(T_INT, List(Op(DUP), Op(ICONST_0), Op(ICONST_1), Op(IASTORE), Op(DUP), Op(ICONST_1), Op(ICONST_2), Op(IASTORE), TypeOp(CHECKCAST, "[I"))) diff --git a/compiler/test/dotty/tools/dotc/semanticdb/SemanticdbTests.scala b/compiler/test/dotty/tools/dotc/semanticdb/SemanticdbTests.scala index 008b10acdabc..05aa7086a404 100644 --- a/compiler/test/dotty/tools/dotc/semanticdb/SemanticdbTests.scala +++ b/compiler/test/dotty/tools/dotc/semanticdb/SemanticdbTests.scala @@ -63,7 +63,7 @@ class SemanticdbTests with .resolveSibling(filename + ".semanticdb") val expectPath = source.resolveSibling(filename.replaceAllLiterally(".scala", ".expect.scala")) val doc = Tools.loadTextDocument(source, relpath, semanticdbPath) - Tools.metac(doc, rootSrc.relativize(source))(given metacSb) + Tools.metac(doc, rootSrc.relativize(source))(using metacSb) val obtained = trimTrailingWhitespace(SemanticdbTests.printTextDocument(doc)) collectErrorOrUpdate(expectPath, obtained) collectErrorOrUpdate(metacExpectFile, metacSb.toString) diff --git a/library/src-bootstrapped/dotty/internal/StringContextMacro.scala b/library/src-bootstrapped/dotty/internal/StringContextMacro.scala index 3ed195bdedfb..23fde323041f 100644 --- a/library/src-bootstrapped/dotty/internal/StringContextMacro.scala +++ b/library/src-bootstrapped/dotty/internal/StringContextMacro.scala @@ -59,7 +59,7 @@ object StringContextMacro { * @return a list of Expr containing Strings, each corresponding to one parts of the given StringContext * quotes an error if the given Expr does not correspond to a StringContext */ - def getPartsExprs(strCtxExpr: Expr[scala.StringContext])(given qctx: QuoteContext): Option[(List[Expr[String]], List[String])] = { + def getPartsExprs(strCtxExpr: Expr[scala.StringContext])(using qctx: QuoteContext): Option[(List[Expr[String]], List[String])] = { def notStatic = { qctx.error("Expected statically known String Context", strCtxExpr) None @@ -81,7 +81,7 @@ object StringContextMacro { * @return a list of Expr containing arguments * quotes an error if the given Expr does not contain a list of arguments */ - def getArgsExprs(argsExpr: Expr[Seq[Any]])(given qctx: QuoteContext): Option[List[Expr[Any]]] = { + def getArgsExprs(argsExpr: Expr[Seq[Any]])(using qctx: QuoteContext): Option[List[Expr[Any]]] = { import qctx.tasty.{_, given} argsExpr.unseal.underlyingArgument match { case Typed(Repeated(args, _), _) => @@ -98,7 +98,7 @@ object StringContextMacro { * @param args the Expr that holds the sequence of arguments to interpolate to the String in the correct format * @return the Expr containing the formatted and interpolated String or an error/warning if the parameters are not correct */ - private def interpolate(strCtxExpr: Expr[StringContext], argsExpr: Expr[Seq[Any]])(given qctx: QuoteContext): Expr[String] = { + private def interpolate(strCtxExpr: Expr[StringContext], argsExpr: Expr[Seq[Any]])(using qctx: QuoteContext): Expr[String] = { import qctx.tasty.{_, given} val sourceFile = strCtxExpr.unseal.pos.sourceFile @@ -164,7 +164,7 @@ object StringContextMacro { * @param reporter the reporter to return any error/warning when a problem is encountered * @return the Expr containing the formatted and interpolated String or an error/warning report if the parameters are not correct */ - def interpolate(parts0 : List[String], args : List[Expr[Any]], argsExpr: Expr[Seq[Any]], reporter : Reporter)(given qctx: QuoteContext) : Expr[String] = { + def interpolate(parts0 : List[String], args : List[Expr[Any]], argsExpr: Expr[Seq[Any]], reporter : Reporter)(using qctx: QuoteContext) : Expr[String] = { import qctx.tasty.{_, given} /** Checks if the number of arguments are the same as the number of formatting strings diff --git a/library/src/dotty/DottyPredef.scala b/library/src/dotty/DottyPredef.scala index 175687be6b53..7936a054c675 100644 --- a/library/src/dotty/DottyPredef.scala +++ b/library/src/dotty/DottyPredef.scala @@ -37,7 +37,7 @@ object DottyPredef { case ev: ValueOf[T] => ev.value } - inline def summon[T](given x: T): x.type = x + inline def summon[T](using x: T): x.type = x // Extension methods for working with explicit nulls diff --git a/library/src/scala/IArray.scala b/library/src/scala/IArray.scala index 985fa12e744c..defb5abc7548 100644 --- a/library/src/scala/IArray.scala +++ b/library/src/scala/IArray.scala @@ -86,7 +86,7 @@ object opaques /** Flattens a two-dimensional array by concatenating all its rows * into a single array. */ - def [T, U: ClassTag](arr: IArray[T]) flatten(given T => Iterable[U]): IArray[U] = + def [T, U: ClassTag](arr: IArray[T]) flatten(using T => Iterable[U]): IArray[U] = genericArrayOps(arr).flatten.asInstanceOf[IArray[U]] /** Folds the elements of this array using the specified associative binary operator. */ @@ -201,7 +201,7 @@ object opaques /** Sorts this array according to the Ordering which results from transforming * an implicitly given Ordering with a transformation function. */ - def [T, U: ClassTag](arr: IArray[T]) sortBy(f: T => U)(given math.Ordering[U]): IArray[T] = + def [T, U: ClassTag](arr: IArray[T]) sortBy(f: T => U)(using math.Ordering[U]): IArray[T] = genericArrayOps(arr).sortBy(f).asInstanceOf[IArray[T]] /** Sorts this array according to a comparison function. */ @@ -209,7 +209,7 @@ object opaques genericArrayOps(arr).sortWith(f).asInstanceOf[IArray[T]] /** Sorts this array according to an Ordering. */ - def [T](arr: IArray[T]) sorted(given math.Ordering[T]): IArray[T] = + def [T](arr: IArray[T]) sorted(using math.Ordering[T]): IArray[T] = genericArrayOps(arr).sorted.asInstanceOf[IArray[T]] /** Splits this array into a prefix/suffix pair according to a predicate. */ @@ -285,7 +285,7 @@ object IArray { def emptyObjectIArray = Array.emptyObjectArray.asInstanceOf[IArray[Object]] /** An immutable array with given elements. */ - inline def apply[T](inline xs: T*)(given inline ct: ClassTag[T]): IArray[T] = Array(xs: _*).asInstanceOf + inline def apply[T](inline xs: T*)(using inline ct: ClassTag[T]): IArray[T] = Array(xs: _*).asInstanceOf /** An immutable array with given elements. */ inline def apply(inline x: Boolean, inline xs: Boolean*): IArray[Boolean] = Array(x, xs: _*).asInstanceOf /** An immutable array with given elements. */ diff --git a/library/src/scala/Tuple.scala b/library/src/scala/Tuple.scala index dbb1abccb840..9547df5f5cca 100644 --- a/library/src/scala/Tuple.scala +++ b/library/src/scala/Tuple.scala @@ -183,7 +183,7 @@ object Tuple { def fromProduct(product: Product): Tuple = runtime.DynamicTuple.dynamicFromProduct[Tuple](product) - def fromProductTyped[P <: Product](p: P)(given m: scala.deriving.Mirror.ProductOf[P]): m.MirroredElemTypes = + def fromProductTyped[P <: Product](p: P)(using m: scala.deriving.Mirror.ProductOf[P]): m.MirroredElemTypes = Tuple.fromArray(p.productIterator.toArray).asInstanceOf[m.MirroredElemTypes] // TODO use toIArray of Object to avoid double/triple array copy } diff --git a/library/src/scala/internal/quoted/Matcher.scala b/library/src/scala/internal/quoted/Matcher.scala index 6da973f04f3c..5392889f2ff0 100644 --- a/library/src/scala/internal/quoted/Matcher.scala +++ b/library/src/scala/internal/quoted/Matcher.scala @@ -25,7 +25,7 @@ private[quoted] object Matcher { */ private type Env = Map[Symbol, Symbol] - inline private def withEnv[T](env: Env)(body: => Env ?=> T): T = body(given env) + inline private def withEnv[T](env: Env)(body: => Env ?=> T): T = body(using env) class SymBinding(val sym: Symbol, val fromAbove: Boolean) @@ -252,7 +252,7 @@ private[quoted] object Matcher { if (hasBindAnnotation(pattern.symbol) || hasBindTypeAnnotation(tpt2)) bindingMatch(scrutinee.symbol) else matched def rhsEnv = summon[Env] + (scrutinee.symbol -> pattern.symbol) - bindMatch && tpt1 =?= tpt2 && treeOptMatches(rhs1, rhs2)(given summon[Context], rhsEnv) + bindMatch && tpt1 =?= tpt2 && treeOptMatches(rhs1, rhs2)(using summon[Context], rhsEnv) case (DefDef(_, typeParams1, paramss1, tpt1, Some(rhs1)), DefDef(_, typeParams2, paramss2, tpt2, Some(rhs2))) => val bindMatch = @@ -376,7 +376,7 @@ private[quoted] object Matcher { case (Bind(name1, body1), Bind(name2, body2)) => val bindEnv = summon[Env] + (scrutinee.symbol -> pattern.symbol) - patternsMatches(body1, body2)(given summon[Context], bindEnv) + patternsMatches(body1, body2)(using summon[Context], bindEnv) case (Unapply(fun1, implicits1, patterns1), Unapply(fun2, implicits2, patterns2)) => val (patEnv, patternsMatch) = foldPatterns(patterns1, patterns2) @@ -415,7 +415,7 @@ private[quoted] object Matcher { private def foldPatterns(patterns1: List[Tree], patterns2: List[Tree])(using Context, Env): (Env, Matching) = { if (patterns1.size != patterns2.size) (summon[Env], notMatched) else patterns1.zip(patterns2).foldLeft((summon[Env], matched)) { (acc, x) => - val (env, res) = patternsMatches(x._1, x._2)(given summon[Context], acc._1) + val (env, res) = patternsMatches(x._1, x._2)(using summon[Context], acc._1) (env, acc._2 && res) } } diff --git a/library/src/scala/quoted/Expr.scala b/library/src/scala/quoted/Expr.scala index d243c9af3afa..466734f60bdf 100644 --- a/library/src/scala/quoted/Expr.scala +++ b/library/src/scala/quoted/Expr.scala @@ -35,7 +35,7 @@ class Expr[+T] private[scala] { * ``` */ final def matches(that: Expr[Any])(using qctx: QuoteContext): Boolean = - !scala.internal.quoted.Expr.unapply[Unit, Unit](this)(given that, false, qctx).isEmpty + !scala.internal.quoted.Expr.unapply[Unit, Unit](this)(using that, false, qctx).isEmpty } @@ -57,8 +57,8 @@ object Expr { tg.untupled(args => qctx.tasty.internal.betaReduce(f.unseal, args.toArray.toList.map(_.asInstanceOf[QuoteContext => Expr[_]](qctx).unseal)).seal.asInstanceOf[Expr[R]]) } - /** `Expr.betaReduceGiven(f)(x1, ..., xn)` is functionally the same as `'{($f)(given $x1, ..., $xn)}`, however it optimizes this call - * by returning the result of beta-reducing `f(given x1, ..., xn)` if `f` is a known lambda expression. + /** `Expr.betaReduceGiven(f)(x1, ..., xn)` is functionally the same as `'{($f)(using $x1, ..., $xn)}`, however it optimizes this call + * by returning the result of beta-reducing `f(using x1, ..., xn)` if `f` is a known lambda expression. * * `Expr.betaReduceGiven` distributes applications of `Expr` over function arrows * ```scala diff --git a/library/src/scala/quoted/matching/Sym.scala b/library/src/scala/quoted/matching/Sym.scala index 47fd87d3335a..0521576f1930 100644 --- a/library/src/scala/quoted/matching/Sym.scala +++ b/library/src/scala/quoted/matching/Sym.scala @@ -21,7 +21,7 @@ class Sym[T <: AnyKind] private[scala](val name: String, private[Sym] val id: Ob object Sym { - def unapply[T](expr: Expr[T])(given qctx: QuoteContext): Option[Sym[T]] = { + def unapply[T](expr: Expr[T])(using qctx: QuoteContext): Option[Sym[T]] = { import qctx.tasty.{_, given} expr.unseal match { case ref: Ident => diff --git a/library/src/scala/quoted/matching/package.scala b/library/src/scala/quoted/matching/package.scala index 49165d0d6bfb..88374d273af5 100644 --- a/library/src/scala/quoted/matching/package.scala +++ b/library/src/scala/quoted/matching/package.scala @@ -10,7 +10,7 @@ package object matching { * @param tpe quoted type of the implicit parameter * @param qctx current context */ - def summonExpr[T](given tpe: Type[T])(using qctx: QuoteContext): Option[Expr[T]] = { + def summonExpr[T](using tpe: Type[T])(using qctx: QuoteContext): Option[Expr[T]] = { import qctx.tasty.{_, given} searchImplicit(tpe.unseal.tpe) match { case iss: ImplicitSearchSuccess => Some(iss.tree.seal.asInstanceOf[Expr[T]]) diff --git a/library/src/scala/quoted/unsafe/UnsafeExpr.scala b/library/src/scala/quoted/unsafe/UnsafeExpr.scala index 3730241c1cc5..53ab3d46f089 100644 --- a/library/src/scala/quoted/unsafe/UnsafeExpr.scala +++ b/library/src/scala/quoted/unsafe/UnsafeExpr.scala @@ -19,7 +19,7 @@ object UnsafeExpr { * Warning: Using the undelying argument directly in the expansion of a macro may * change the parameter semantics as by-value parameter could be re-evaluated. */ - def underlyingArgument[T](expr: Expr[T])(given qctx: QuoteContext): Expr[T] = { + def underlyingArgument[T](expr: Expr[T])(using qctx: QuoteContext): Expr[T] = { import qctx.tasty.{given, _} expr.unseal.underlyingArgument.seal.asInstanceOf[Expr[T]] } @@ -38,35 +38,35 @@ object UnsafeExpr { * } * ``` */ - def open[T1, R, X](f: Expr[T1 => R])(content: (Expr[R], [t] => Expr[t] => Expr[T1] => Expr[t]) => X)(given qctx: QuoteContext): X = { + def open[T1, R, X](f: Expr[T1 => R])(content: (Expr[R], [t] => Expr[t] => Expr[T1] => Expr[t]) => X)(using qctx: QuoteContext): X = { import qctx.tasty.{given, _} val (params, bodyExpr) = paramsAndBody[R](f) content(bodyExpr, [t] => (e: Expr[t]) => (v: Expr[T1]) => bodyFn[t](e.unseal, params, List(v.unseal)).seal.asInstanceOf[Expr[t]]) } - def open[T1, T2, R, X](f: Expr[(T1, T2) => R])(content: (Expr[R], [t] => Expr[t] => (Expr[T1], Expr[T2]) => Expr[t]) => X)(given qctx: QuoteContext)(given DummyImplicit): X = { + def open[T1, T2, R, X](f: Expr[(T1, T2) => R])(content: (Expr[R], [t] => Expr[t] => (Expr[T1], Expr[T2]) => Expr[t]) => X)(using qctx: QuoteContext)(using DummyImplicit): X = { import qctx.tasty.{given, _} val (params, bodyExpr) = paramsAndBody[R](f) content(bodyExpr, [t] => (e: Expr[t]) => (v1: Expr[T1], v2: Expr[T2]) => bodyFn[t](e.unseal, params, List(v1.unseal, v2.unseal)).seal.asInstanceOf[Expr[t]]) } - def open[T1, T2, T3, R, X](f: Expr[(T1, T2, T3) => R])(content: (Expr[R], [t] => Expr[t] => (Expr[T1], Expr[T2], Expr[T3]) => Expr[t]) => X)(given qctx: QuoteContext)(given DummyImplicit, DummyImplicit): X = { + def open[T1, T2, T3, R, X](f: Expr[(T1, T2, T3) => R])(content: (Expr[R], [t] => Expr[t] => (Expr[T1], Expr[T2], Expr[T3]) => Expr[t]) => X)(using qctx: QuoteContext)(using DummyImplicit, DummyImplicit): X = { import qctx.tasty.{given, _} val (params, bodyExpr) = paramsAndBody[R](f) content(bodyExpr, [t] => (e: Expr[t]) => (v1: Expr[T1], v2: Expr[T2], v3: Expr[T3]) => bodyFn[t](e.unseal, params, List(v1.unseal, v2.unseal, v3.unseal)).seal.asInstanceOf[Expr[t]]) } - private def paramsAndBody[R](given qctx: QuoteContext)(f: Expr[Any]): (List[qctx.tasty.ValDef], Expr[R]) = { + private def paramsAndBody[R](using qctx: QuoteContext)(f: Expr[Any]): (List[qctx.tasty.ValDef], Expr[R]) = { import qctx.tasty.{given, _} val Block(List(DefDef("$anonfun", Nil, List(params), _, Some(body))), Closure(Ident("$anonfun"), None)) = f.unseal.etaExpand (params, body.seal.asInstanceOf[Expr[R]]) } - private def bodyFn[t](given qctx: QuoteContext)(e: qctx.tasty.Term, params: List[qctx.tasty.ValDef], args: List[qctx.tasty.Term]): qctx.tasty.Term = { + private def bodyFn[t](using qctx: QuoteContext)(e: qctx.tasty.Term, params: List[qctx.tasty.ValDef], args: List[qctx.tasty.Term]): qctx.tasty.Term = { import qctx.tasty.{given, _} val map = params.map(_.symbol).zip(args).toMap new TreeMap { - override def transformTerm(tree: Term)(given ctx: Context): Term = + override def transformTerm(tree: Term)(using ctx: Context): Term = super.transformTerm(tree) match case tree: Ident => map.getOrElse(tree.symbol, tree) case tree => tree diff --git a/library/src/scala/quoted/util/ExprMap.scala b/library/src/scala/quoted/util/ExprMap.scala index 5f1704a18597..56ac5dbedd6a 100644 --- a/library/src/scala/quoted/util/ExprMap.scala +++ b/library/src/scala/quoted/util/ExprMap.scala @@ -113,7 +113,7 @@ trait ExprMap { type X val expr = tree.seal.asInstanceOf[Expr[X]] val t = tpe.seal.asInstanceOf[quoted.Type[X]] - transform(expr)(given qctx, t).unseal + transform(expr)(using qctx, t).unseal } } diff --git a/library/src/scala/quoted/util/Var.scala b/library/src/scala/quoted/util/Var.scala index 670f7ee9183a..207766fd5ce1 100644 --- a/library/src/scala/quoted/util/Var.scala +++ b/library/src/scala/quoted/util/Var.scala @@ -10,7 +10,7 @@ sealed trait Var[T] { def get(using qctx: QuoteContext): Expr[T] // Update the variable with the expression of a value (`e` corresponds to the RHS of variable assignment `x = e`) - def update(e: Expr[T])(given qctx: QuoteContext): Expr[Unit] + def update(e: Expr[T])(using qctx: QuoteContext): Expr[Unit] } object Var { @@ -34,7 +34,7 @@ object Var { * x * } */ - def apply[T: Type, U: Type](init: Expr[T])(body: Var[T] => Expr[U])(given qctx: QuoteContext): Expr[U] = '{ + def apply[T: Type, U: Type](init: Expr[T])(body: Var[T] => Expr[U])(using qctx: QuoteContext): Expr[U] = '{ var x = $init ${ body( diff --git a/library/src/scala/tasty/reflect/SourceCodePrinter.scala b/library/src/scala/tasty/reflect/SourceCodePrinter.scala index 64c93426e208..51351643b7e4 100644 --- a/library/src/scala/tasty/reflect/SourceCodePrinter.scala +++ b/library/src/scala/tasty/reflect/SourceCodePrinter.scala @@ -12,7 +12,7 @@ class SourceCodePrinter[R <: Reflection & Singleton](val tasty: R)(syntaxHighlig (new Buffer).printTree(tree).result() def showTypeOrBounds(tpe: TypeOrBounds)(using ctx: Context): String = - (new Buffer).printTypeOrBound(tpe)(given None).result() + (new Buffer).printTypeOrBound(tpe)(using None).result() def showConstant(const: Constant)(using ctx: Context): String = (new Buffer).printConstant(const).result() @@ -160,19 +160,19 @@ class SourceCodePrinter[R <: Reflection & Singleton](val tasty: R)(syntaxHighlig def printParent(parent: Tree /* Term | TypeTree */, needEmptyParens: Boolean = false): Unit = parent match { case parent: TypeTree => - printTypeTree(parent)(given Some(cdef.symbol)) + printTypeTree(parent)(using Some(cdef.symbol)) case TypeApply(fun, targs) => printParent(fun) case Apply(fun@Apply(_,_), args) => printParent(fun, true) if (!args.isEmpty || needEmptyParens) - inParens(printTrees(args, ", ")(given Some(cdef.symbol))) + inParens(printTrees(args, ", ")(using Some(cdef.symbol))) case Apply(fun, args) => printParent(fun) if (!args.isEmpty || needEmptyParens) - inParens(printTrees(args, ", ")(given Some(cdef.symbol))) + inParens(printTrees(args, ", ")(using Some(cdef.symbol))) case Select(newTree: New, _) => - printType(newTree.tpe)(given Some(cdef.symbol)) + printType(newTree.tpe)(using Some(cdef.symbol)) case parent: Term => throw new MatchError(parent.showExtractors) } @@ -224,7 +224,7 @@ class SourceCodePrinter[R <: Reflection & Singleton](val tasty: R)(syntaxHighlig indented { val name1 = if (name == "_") "this" else name this += " " += highlightValDef(name1) += ": " - printTypeTree(tpt)(given Some(cdef.symbol)) + printTypeTree(tpt)(using Some(cdef.symbol)) this += " =>" } } @@ -861,7 +861,7 @@ class SourceCodePrinter[R <: Reflection & Singleton](val tasty: R)(syntaxHighlig indented { caseDef.rhs match { case Block(stats, expr) => - printStats(stats, expr)(given None) + printStats(stats, expr)(using None) case body => this += lineBreak() printTree(body) diff --git a/library/src/scala/tasty/reflect/TreeAccumulator.scala b/library/src/scala/tasty/reflect/TreeAccumulator.scala index f1a3b0f6576a..5f21afd0593b 100644 --- a/library/src/scala/tasty/reflect/TreeAccumulator.scala +++ b/library/src/scala/tasty/reflect/TreeAccumulator.scala @@ -8,7 +8,7 @@ package reflect * class MyTreeAccumulator[R <: scala.tasty.Reflection & Singleton](val reflect: R) * extends scala.tasty.reflect.TreeAccumulator[X] { * import reflect.{given, _} - * def foldTree(x: X, tree: Tree)(given ctx: Context): X = ... + * def foldTree(x: X, tree: Tree)(using ctx: Context): X = ... * } * ``` */ @@ -18,11 +18,11 @@ trait TreeAccumulator[X] { import reflect.{given, _} // Ties the knot of the traversal: call `foldOver(x, tree))` to dive in the `tree` node. - def foldTree(x: X, tree: Tree)(given ctx: Context): X + def foldTree(x: X, tree: Tree)(using ctx: Context): X - def foldTrees(x: X, trees: Iterable[Tree])(given ctx: Context): X = trees.foldLeft(x)(foldTree) + def foldTrees(x: X, trees: Iterable[Tree])(using ctx: Context): X = trees.foldLeft(x)(foldTree) - def foldOverTree(x: X, tree: Tree)(given ctx: Context): X = { + def foldOverTree(x: X, tree: Tree)(using ctx: Context): X = { def localCtx(definition: Definition): Context = definition.symbol.localContext tree match { case Ident(_) => @@ -84,7 +84,7 @@ trait TreeAccumulator[X] { case Import(expr, _) => foldTree(x, expr) case clause @ PackageClause(pid, stats) => - foldTrees(foldTree(x, pid), stats)(given clause.symbol.localContext) + foldTrees(foldTree(x, pid), stats)(using clause.symbol.localContext) case Inferred() => x case TypeIdent(_) => x case TypeSelect(qualifier, _) => foldTree(x, qualifier) diff --git a/library/src/scala/tasty/reflect/TreeMap.scala b/library/src/scala/tasty/reflect/TreeMap.scala index aa926de83c96..5cf52c000976 100644 --- a/library/src/scala/tasty/reflect/TreeMap.scala +++ b/library/src/scala/tasty/reflect/TreeMap.scala @@ -17,10 +17,10 @@ trait TreeMap { val reflect: Reflection import reflect.{given, _} - def transformTree(tree: Tree)(given ctx: Context): Tree = { + def transformTree(tree: Tree)(using ctx: Context): Tree = { tree match { case tree: PackageClause => - PackageClause.copy(tree)(transformTerm(tree.pid).asInstanceOf[Ref], transformTrees(tree.stats)(given tree.symbol.localContext)) + PackageClause.copy(tree)(transformTerm(tree.pid).asInstanceOf[Ref], transformTrees(tree.stats)(using tree.symbol.localContext)) case tree: Import => Import.copy(tree)(transformTerm(tree.expr), tree.selectors) case tree: Statement => @@ -41,7 +41,7 @@ trait TreeMap { } } - def transformStatement(tree: Statement)(given ctx: Context): Statement = { + def transformStatement(tree: Statement)(using ctx: Context): Statement = { def localCtx(definition: Definition): Context = definition.symbol.localContext tree match { case tree: Term => @@ -67,7 +67,7 @@ trait TreeMap { } } - def transformTerm(tree: Term)(given ctx: Context): Term = { + def transformTerm(tree: Term)(using ctx: Context): Term = { tree match { case Ident(name) => tree @@ -112,7 +112,7 @@ trait TreeMap { } } - def transformTypeTree(tree: TypeTree)(given ctx: Context): TypeTree = tree match { + def transformTypeTree(tree: TypeTree)(using ctx: Context): TypeTree = tree match { case Inferred() => tree case tree: TypeIdent => tree case tree: TypeSelect => @@ -132,40 +132,40 @@ trait TreeMap { case tree: ByName => ByName.copy(tree)(transformTypeTree(tree.result)) case tree: LambdaTypeTree => - LambdaTypeTree.copy(tree)(transformSubTrees(tree.tparams), transformTree(tree.body))(given tree.symbol.localContext) + LambdaTypeTree.copy(tree)(transformSubTrees(tree.tparams), transformTree(tree.body))(using tree.symbol.localContext) case tree: TypeBind => TypeBind.copy(tree)(tree.name, tree.body) case tree: TypeBlock => TypeBlock.copy(tree)(tree.aliases, tree.tpt) } - def transformCaseDef(tree: CaseDef)(given ctx: Context): CaseDef = { + def transformCaseDef(tree: CaseDef)(using ctx: Context): CaseDef = { CaseDef.copy(tree)(transformTree(tree.pattern), tree.guard.map(transformTerm), transformTerm(tree.rhs)) } - def transformTypeCaseDef(tree: TypeCaseDef)(given ctx: Context): TypeCaseDef = { + def transformTypeCaseDef(tree: TypeCaseDef)(using ctx: Context): TypeCaseDef = { TypeCaseDef.copy(tree)(transformTypeTree(tree.pattern), transformTypeTree(tree.rhs)) } - def transformStats(trees: List[Statement])(given ctx: Context): List[Statement] = + def transformStats(trees: List[Statement])(using ctx: Context): List[Statement] = trees mapConserve (transformStatement(_)) - def transformTrees(trees: List[Tree])(given ctx: Context): List[Tree] = + def transformTrees(trees: List[Tree])(using ctx: Context): List[Tree] = trees mapConserve (transformTree(_)) - def transformTerms(trees: List[Term])(given ctx: Context): List[Term] = + def transformTerms(trees: List[Term])(using ctx: Context): List[Term] = trees mapConserve (transformTerm(_)) - def transformTypeTrees(trees: List[TypeTree])(given ctx: Context): List[TypeTree] = + def transformTypeTrees(trees: List[TypeTree])(using ctx: Context): List[TypeTree] = trees mapConserve (transformTypeTree(_)) - def transformCaseDefs(trees: List[CaseDef])(given ctx: Context): List[CaseDef] = + def transformCaseDefs(trees: List[CaseDef])(using ctx: Context): List[CaseDef] = trees mapConserve (transformCaseDef(_)) - def transformTypeCaseDefs(trees: List[TypeCaseDef])(given ctx: Context): List[TypeCaseDef] = + def transformTypeCaseDefs(trees: List[TypeCaseDef])(using ctx: Context): List[TypeCaseDef] = trees mapConserve (transformTypeCaseDef(_)) - def transformSubTrees[Tr <: Tree](trees: List[Tr])(given ctx: Context): List[Tr] = + def transformSubTrees[Tr <: Tree](trees: List[Tr])(using ctx: Context): List[Tr] = transformTrees(trees).asInstanceOf[List[Tr]] } diff --git a/library/src/scala/tasty/reflect/TreeTraverser.scala b/library/src/scala/tasty/reflect/TreeTraverser.scala index d5604ffafd8e..4159883b4351 100644 --- a/library/src/scala/tasty/reflect/TreeTraverser.scala +++ b/library/src/scala/tasty/reflect/TreeTraverser.scala @@ -16,10 +16,10 @@ trait TreeTraverser extends TreeAccumulator[Unit] { import reflect._ - def traverseTree(tree: Tree)(given ctx: Context): Unit = traverseTreeChildren(tree) + def traverseTree(tree: Tree)(using ctx: Context): Unit = traverseTreeChildren(tree) - def foldTree(x: Unit, tree: Tree)(given ctx: Context): Unit = traverseTree(tree) + def foldTree(x: Unit, tree: Tree)(using ctx: Context): Unit = traverseTree(tree) - protected def traverseTreeChildren(tree: Tree)(given ctx: Context): Unit = foldOverTree((), tree) + protected def traverseTreeChildren(tree: Tree)(using ctx: Context): Unit = foldOverTree((), tree) } diff --git a/library/src/scala/util/CommandLineParser.scala b/library/src/scala/util/CommandLineParser.scala index f9dbc7daa878..50de98040e2d 100644 --- a/library/src/scala/util/CommandLineParser.scala +++ b/library/src/scala/util/CommandLineParser.scala @@ -12,7 +12,7 @@ object CommandLineParser { /** Parse command line argument `s`, which has index `n`, as a value of type `T` * @throws ParseError if argument cannot be converted to type `T`. */ - def parseString[T](str: String, n: Int)(given fs: FromString[T]): T = { + def parseString[T](str: String, n: Int)(using fs: FromString[T]): T = { try fs.fromString(str) catch { case ex: IllegalArgumentException => throw ParseError(n, ex.toString) @@ -22,14 +22,14 @@ object CommandLineParser { /** Parse `n`'th argument in `args` (counting from 0) as a value of type `T` * @throws ParseError if argument does not exist or cannot be converted to type `T`. */ - def parseArgument[T](args: Array[String], n: Int)(given fs: FromString[T]): T = + def parseArgument[T](args: Array[String], n: Int)(using fs: FromString[T]): T = if n < args.length then parseString(args(n), n) else throw ParseError(n, "more arguments expected") /** Parse all arguments from `n`'th one (counting from 0) as a list of values of type `T` * @throws ParseError if some of the arguments cannot be converted to type `T`. */ - def parseRemainingArguments[T](args: Array[String], n: Int)(given fs: FromString[T]): List[T] = + def parseRemainingArguments[T](args: Array[String], n: Int)(using fs: FromString[T]): List[T] = if n < args.length then parseString(args(n), n) :: parseRemainingArguments(args, n + 1) else Nil diff --git a/library/src/scala/util/control/NonLocalReturns.scala b/library/src/scala/util/control/NonLocalReturns.scala index 57702db534e7..8496f68af234 100644 --- a/library/src/scala/util/control/NonLocalReturns.scala +++ b/library/src/scala/util/control/NonLocalReturns.scala @@ -19,13 +19,13 @@ object NonLocalReturns { } /** Performs a nonlocal return by throwing an exception. */ - def throwReturn[T](result: T)(given returner: ReturnThrowable[T]): Nothing = + def throwReturn[T](result: T)(using returner: ReturnThrowable[T]): Nothing = returner.throwReturn(result) /** Enable nonlocal returns in `op`. */ - def returning[T](op: (given ReturnThrowable[T]) => T): T = { + def returning[T](op: ReturnThrowable[T] ?=> T): T = { val returner = new ReturnThrowable[T] - try op(given returner) + try op(using returner) catch { case ex: ReturnThrowable[T] => if (ex.eq(returner)) ex.result else throw ex