From 27da113f3d9271244ada7da3bbd43becdb989cd5 Mon Sep 17 00:00:00 2001 From: odersky Date: Mon, 22 Sep 2025 10:14:33 +0200 Subject: [PATCH 1/6] Put source version 2.13 in its proper place It should come before 3.0 --- compiler/src/dotty/tools/dotc/config/SourceVersion.scala | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/src/dotty/tools/dotc/config/SourceVersion.scala b/compiler/src/dotty/tools/dotc/config/SourceVersion.scala index 0360d578da0d..950a4bd8c677 100644 --- a/compiler/src/dotty/tools/dotc/config/SourceVersion.scala +++ b/compiler/src/dotty/tools/dotc/config/SourceVersion.scala @@ -8,6 +8,8 @@ import Feature.isPreviewEnabled import util.Property enum SourceVersion: + case `2.13` + case `3.0-migration`, `3.0` case `3.1-migration`, `3.1` case `3.2-migration`, `3.2` @@ -20,7 +22,6 @@ enum SourceVersion: case `3.9-migration`, `3.9` // Add 3.x-migration and 3.x here // !!! Keep in sync with scala.runtime.stdlibPatches.language !!! - case `2.13` case `future-migration`, `future` case `never` // needed for MigrationVersion.errorFrom if we never want to issue an error From 52b2ec6f29b425cdf30a90522586868a5cf90493 Mon Sep 17 00:00:00 2001 From: odersky Date: Mon, 22 Sep 2025 12:11:05 +0200 Subject: [PATCH 2/6] Fix some warnings in compiler codebase --- .../src/dotty/tools/dotc/ast/Desugar.scala | 4 ++-- compiler/src/dotty/tools/dotc/ast/tpd.scala | 2 +- .../src/dotty/tools/dotc/core/Comments.scala | 2 +- .../dotty/tools/dotc/core/ContextOps.scala | 2 +- .../src/dotty/tools/dotc/core/Contexts.scala | 2 +- .../dotty/tools/dotc/core/Denotations.scala | 4 ++-- compiler/src/dotty/tools/dotc/core/Mode.scala | 2 +- .../src/dotty/tools/dotc/core/Scopes.scala | 2 +- .../tools/dotc/core/SymDenotations.scala | 6 ++--- .../dotty/tools/dotc/core/TyperState.scala | 2 +- .../core/unpickleScala2/Scala2Unpickler.scala | 8 +++---- .../dotty/tools/dotc/parsing/Parsers.scala | 4 ++-- .../src/dotty/tools/dotc/plugins/Plugin.scala | 4 ++-- .../dotty/tools/dotc/profile/FileUtils.scala | 3 ++- .../tools/dotc/quoted/QuotePatterns.scala | 4 ++-- .../dotty/tools/dotc/reporting/messages.scala | 6 ++--- .../src/dotty/tools/dotc/sbt/ExtractAPI.scala | 4 ++-- .../src/dotty/tools/dotc/sbt/ShowAPI.scala | 14 +++++------ .../dotc/semanticdb/ExtractSemanticDB.scala | 2 +- .../dotty/tools/dotc/semanticdb/Scala3.scala | 6 ++--- .../dotty/tools/dotc/semanticdb/TypeOps.scala | 2 +- .../tools/dotc/transform/BeanProperties.scala | 2 +- .../tools/dotc/transform/CapturedVars.scala | 6 ++--- .../dotty/tools/dotc/transform/Erasure.scala | 10 ++++---- .../tools/dotc/transform/ExplicitOuter.scala | 4 ++-- .../dotc/transform/ExtensionMethods.scala | 2 +- .../dotc/transform/FullParameterization.scala | 2 +- .../tools/dotc/transform/LambdaLift.scala | 23 +++++++++--------- .../tools/dotc/transform/SelectStatic.scala | 6 ++--- .../dotc/transform/SyntheticMembers.scala | 6 ++--- .../tools/dotc/transform/TreeChecker.scala | 4 ++-- .../dotc/transform/sjs/PrepJSInterop.scala | 4 ++-- .../dotty/tools/dotc/typer/Applications.scala | 2 +- .../src/dotty/tools/dotc/typer/Checking.scala | 22 +++++++---------- .../dotty/tools/dotc/typer/EtaExpansion.scala | 5 ++-- .../dotty/tools/dotc/typer/Implicits.scala | 6 ++--- .../dotty/tools/dotc/typer/ImportInfo.scala | 2 +- .../tools/dotc/typer/ImportSuggestions.scala | 2 +- .../src/dotty/tools/dotc/typer/Namer.scala | 8 +++---- .../dotty/tools/dotc/typer/Nullables.scala | 2 +- .../dotty/tools/dotc/typer/ProtoTypes.scala | 4 ++-- .../dotty/tools/dotc/typer/RefChecks.scala | 19 ++++++++------- .../src/dotty/tools/dotc/typer/Typer.scala | 24 +++++++++---------- .../tools/dotc/util/CommentParsing.scala | 24 +++++++++---------- .../dotty/tools/dotc/util/ShowPickled.scala | 10 ++++---- .../dotty/tools/dotc/util/SourceFile.scala | 6 ++--- .../src/dotty/tools/io/AbstractFile.scala | 4 ++-- compiler/src/dotty/tools/io/ClassPath.scala | 6 ++--- compiler/src/dotty/tools/io/File.scala | 6 ++--- compiler/src/dotty/tools/io/FileWriters.scala | 5 ++-- compiler/src/dotty/tools/io/Jar.scala | 9 ++++--- compiler/src/dotty/tools/io/Path.scala | 8 +++---- compiler/src/dotty/tools/io/Streamable.scala | 4 ++-- compiler/src/dotty/tools/package.scala | 7 ------ .../tools/backend/jvm/DottyBytecodeTest.scala | 4 ++-- .../tools/dotc/parsing/DocstringTest.scala | 2 +- 56 files changed, 165 insertions(+), 180 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index 2ed3415ebe70..225f12de67c6 100644 --- a/compiler/src/dotty/tools/dotc/ast/Desugar.scala +++ b/compiler/src/dotty/tools/dotc/ast/Desugar.scala @@ -2344,9 +2344,9 @@ object desugar { val nspace = if (ctx.mode.is(Mode.Type)) tpnme else nme Select(t, nspace.UNARY_PREFIX ++ op.name) case ForDo(enums, body) => - makeFor(nme.foreach, nme.foreach, enums, body) orElse tree + makeFor(nme.foreach, nme.foreach, enums, body) `orElse` tree case ForYield(enums, body) => - makeFor(nme.map, nme.flatMap, enums, body) orElse tree + makeFor(nme.map, nme.flatMap, enums, body) `orElse` tree case PatDef(mods, pats, tpt, rhs) => val pats1 = if (tpt.isEmpty) pats else pats map (Typed(_, tpt)) flatTree(pats1 map (makePatDef(tree, mods, _, rhs))) diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index b64d9065227f..f7683e52c5fd 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -601,7 +601,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { */ def ModuleDef(sym: TermSymbol, body: List[Tree])(using Context): tpd.Thicket = { val modcls = sym.moduleClass.asClass - val constrSym = modcls.primaryConstructor orElse newDefaultConstructor(modcls).entered + val constrSym = modcls.primaryConstructor `orElse` newDefaultConstructor(modcls).entered val constr = DefDef(constrSym.asTerm, EmptyTree) val clsdef = ClassDef(modcls, constr, body) val valdef = ValDef(sym, New(modcls.typeRef).select(constrSym).appliedToNone) diff --git a/compiler/src/dotty/tools/dotc/core/Comments.scala b/compiler/src/dotty/tools/dotc/core/Comments.scala index 00f5b578b4d1..886747041fa2 100644 --- a/compiler/src/dotty/tools/dotc/core/Comments.scala +++ b/compiler/src/dotty/tools/dotc/core/Comments.scala @@ -429,7 +429,7 @@ object Comments { searchList collectFirst { case x if defs(x) contains vble => defs(x)(vble) } match { case Some(str) if str startsWith "$" => lookupVariable(str.tail, site) - case res => res orElse lookupVariable(vble, site.owner) + case res => res `orElse` lookupVariable(vble, site.owner) } } diff --git a/compiler/src/dotty/tools/dotc/core/ContextOps.scala b/compiler/src/dotty/tools/dotc/core/ContextOps.scala index c307b6ac569e..d4890cc02a1f 100644 --- a/compiler/src/dotty/tools/dotc/core/ContextOps.scala +++ b/compiler/src/dotty/tools/dotc/core/ContextOps.scala @@ -92,7 +92,7 @@ object ContextOps: }.find(_.exists).getOrElse(NoDenotation) if preSym.isClass then - directSearch orElse searchCompanionClass orElse searchSuperCompanionObjects + directSearch `orElse` searchCompanionClass `orElse` searchSuperCompanionObjects else directSearch } diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 51b42a3eb5f5..171b98a8cdf4 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -377,7 +377,7 @@ object Contexts { def isImportContext: Boolean = (this ne NoContext) && (outer ne NoContext) - && (this.importInfo nen outer.importInfo) + && (this.importInfo ne outer.importInfo) /** Is this a context that introduces a non-empty scope? */ def isNonEmptyScopeContext: Boolean = diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index ee832cac7269..b77209c675eb 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -288,7 +288,7 @@ object Denotations { */ inline def disambiguate(inline p: Symbol => Boolean)(using Context): SingleDenotation = this match { case sdenot: SingleDenotation => sdenot - case mdenot => suchThat(p) orElse NoQualifyingRef(alternatives) + case mdenot => suchThat(p) `orElse` NoQualifyingRef(alternatives) } /** Return symbol in this denotation that satisfies the given predicate. @@ -1237,7 +1237,7 @@ object Denotations { g(denot1.aggregate(f, g), denot2.aggregate(f, g)) protected def derivedUnion(denot1: PreDenotation, denot2: PreDenotation) = if ((denot1 eq this.denot1) && (denot2 eq this.denot2)) this - else denot1 union denot2 + else denot1 `union` denot2 } final case class DenotUnion(denot1: PreDenotation, denot2: PreDenotation) extends MultiPreDenotation { diff --git a/compiler/src/dotty/tools/dotc/core/Mode.scala b/compiler/src/dotty/tools/dotc/core/Mode.scala index 571a786e9106..44efbedf0f68 100644 --- a/compiler/src/dotty/tools/dotc/core/Mode.scala +++ b/compiler/src/dotty/tools/dotc/core/Mode.scala @@ -14,7 +14,7 @@ case class Mode(val bits: Int) extends AnyVal { def | (that: Mode): Mode = Mode(bits | that.bits) def & (that: Mode): Mode = Mode(bits & that.bits) def &~ (that: Mode): Mode = Mode(bits & ~that.bits) - def is (that: Mode): Boolean = (bits & that.bits) == that.bits + infix def is (that: Mode): Boolean = (bits & that.bits) == that.bits def isExpr: Boolean = (this & PatternOrTypeBits) == None diff --git a/compiler/src/dotty/tools/dotc/core/Scopes.scala b/compiler/src/dotty/tools/dotc/core/Scopes.scala index d6387ea1fe46..7e2fea6cb2fd 100644 --- a/compiler/src/dotty/tools/dotc/core/Scopes.scala +++ b/compiler/src/dotty/tools/dotc/core/Scopes.scala @@ -152,7 +152,7 @@ object Scopes { var syms: PreDenotation = NoDenotation var e = lookupEntry(name) while (e != null) { - syms = syms union e.sym.denot + syms = syms `union` e.sym.denot e = lookupNextEntry(e) } syms diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index 004fc39e1298..384531c135de 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -1161,7 +1161,7 @@ object SymDenotations { val d = owner.info.decl(fieldName) val field = d.suchThat(!_.is(Method)).symbol def getter = d.suchThat(_.info.isParameterless).symbol - field orElse getter + field `orElse` getter } /** The field accessed by a getter or setter, or @@ -1169,7 +1169,7 @@ object SymDenotations { * if that does not exist the symbol itself. */ def underlyingSymbol(using Context): Symbol = - if (is(Accessor)) accessedFieldOrGetter orElse symbol else symbol + if (is(Accessor)) accessedFieldOrGetter `orElse` symbol else symbol /** The chain of owners of this denotation, starting with the denoting symbol itself */ final def ownersIterator(using Context): Iterator[Symbol] = new Iterator[Symbol] { @@ -2588,7 +2588,7 @@ object SymDenotations { else val assocFiles = multi .filterWithPredicate(_.symbol.maybeOwner.isPackageObject) - .aggregate(d => Set(d.symbol.associatedFile.nn), _ union _) + .aggregate(d => Set(d.symbol.associatedFile.nn), _ `union` _) if assocFiles.size == 1 then multi // they are all overloaded variants from the same file else diff --git a/compiler/src/dotty/tools/dotc/core/TyperState.scala b/compiler/src/dotty/tools/dotc/core/TyperState.scala index c0db3301b8b5..ddc5e36520a2 100644 --- a/compiler/src/dotty/tools/dotc/core/TyperState.scala +++ b/compiler/src/dotty/tools/dotc/core/TyperState.scala @@ -291,7 +291,7 @@ class TyperState() { val toCollect = new mutable.ListBuffer[TypeLambda] for tvar <- ownedVars do val tvarState = tvar.owningState.nn.get - assert(tvarState eqn this, s"Inconsistent state in $this: it owns $tvar whose owningState is ${tvarState}") + assert(tvarState eq this, s"Inconsistent state in $this: it owns $tvar whose owningState is ${tvarState}") assert(!tvar.isPermanentlyInstantiated, s"Inconsistent state in $this: it owns $tvar which is already instantiated") val inst = constraint.instType(tvar) if inst.exists then diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index e97e73dc5760..7f560a53aae3 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -407,15 +407,15 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas // println(s"read ext symbol $name from ${owner.denot.debugString} in ${classRoot.debugString}") // !!! DEBUG // (1) Try name. - fromName(name) orElse { + fromName(name) `orElse` { // (2) Try with expanded name. Can happen if references to private // symbols are read from outside: for instance when checking the children // of a class. See #1722. - fromName(name.toTermName.expandedName(owner)) orElse { + fromName(name.toTermName.expandedName(owner)) `orElse` { // (3) Try as a nested object symbol. - nestedObjectSymbol orElse { + nestedObjectSymbol `orElse` { // (4) Call the mirror's "missing" hook. - adjust(missingHook(owner, name)) orElse { + adjust(missingHook(owner, name)) `orElse` { // println(owner.info.decls.toList.map(_.debugString).mkString("\n ")) // !!! DEBUG // } // (5) Create a stub symbol to defer hard failure a little longer. diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index f198caad0084..f4d3d14628df 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -1138,7 +1138,7 @@ object Parsers { opStack = opStack.tail recur { migrateInfixOp(opInfo, isType): - atSpan(opInfo.operator.span union opInfo.operand.span union top.span): + atSpan(opInfo.operator.span `union` opInfo.operand.span `union` top.span): InfixOp(opInfo.operand, opInfo.operator, top) } } @@ -2257,7 +2257,7 @@ object Parsers { val t = typeBounds() val cbs = contextBounds(pname) if (cbs.isEmpty) t - else atSpan((t.span union cbs.head.span).start) { ContextBounds(t, cbs) } + else atSpan((t.span `union` cbs.head.span).start) { ContextBounds(t, cbs) } } /** ContextBound ::= Type [`as` id] */ diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugin.scala b/compiler/src/dotty/tools/dotc/plugins/Plugin.scala index fdb41fc56689..5838f5df7e97 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugin.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugin.scala @@ -171,8 +171,8 @@ object Plugin { def loop(qs: List[Path]): Try[String] = qs match { case Nil => Failure(new MissingPluginException(ps)) case p :: rest => - if (p.isDirectory) loadDescriptionFromDir(p.toDirectory) orElse loop(rest) - else if (p.isFile) loadDescriptionFromJar(p.toFile) orElse loop(rest) + if (p.isDirectory) loadDescriptionFromDir(p.toDirectory) `orElse` loop(rest) + else if (p.isFile) loadDescriptionFromJar(p.toFile) `orElse` loop(rest) else loop(rest) } loop(ps) diff --git a/compiler/src/dotty/tools/dotc/profile/FileUtils.scala b/compiler/src/dotty/tools/dotc/profile/FileUtils.scala index 4aec428c05bf..180eecbe5587 100644 --- a/compiler/src/dotty/tools/dotc/profile/FileUtils.scala +++ b/compiler/src/dotty/tools/dotc/profile/FileUtils.scala @@ -28,6 +28,7 @@ import scala.concurrent.duration.Duration import scala.concurrent.{Await, Promise} import scala.util.{Failure, Success} import scala.annotation.internal.sharable +import compiletime.uninitialized object FileUtils { def newAsyncBufferedWriter(path: Path, charset: Charset = StandardCharsets.UTF_8.nn, options: Array[OpenOption] = NO_OPTIONS, threadsafe: Boolean = false): LineWriter = { @@ -151,7 +152,7 @@ object FileUtils { //a failure detected will case an Failure, Success indicates a close val asyncStatus = Promise[Unit]() private val scheduled = new AtomicBoolean - @volatile var reuseBuffer: CharBuffer = _ + @volatile var reuseBuffer: CharBuffer = uninitialized def ensureProcessed(buffer: CharBuffer): Unit = { if (asyncStatus.isCompleted) { diff --git a/compiler/src/dotty/tools/dotc/quoted/QuotePatterns.scala b/compiler/src/dotty/tools/dotc/quoted/QuotePatterns.scala index 82701dafd2c9..1ec54577da23 100644 --- a/compiler/src/dotty/tools/dotc/quoted/QuotePatterns.scala +++ b/compiler/src/dotty/tools/dotc/quoted/QuotePatterns.scala @@ -32,10 +32,10 @@ object QuotePatterns: // Collect type variables val typevars1 = tree match case tree @ DefDef(_, paramss, _, _) => - typevars union paramss.flatMap{ params => params match + typevars `union` paramss.flatMap{ params => params match case TypeDefs(tdefs) => tdefs.map(_.symbol) case _ => List.empty - }.toSet union typevars + }.toSet `union` typevars case _ => typevars // Validate pattern diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index 2bad86f8967b..9c4ee9926bf2 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -1199,7 +1199,7 @@ extends DeclarationMsg(OverrideErrorID), NoDisambiguation: withDisambiguation(Disambiguation.AllExcept(List(member.name.toString))) def msg(using Context) = val isConcreteOverAbstract = - (other.owner isSubClass member.owner) && other.is(Deferred) && !member.is(Deferred) + other.owner.isSubClass(member.owner) && other.is(Deferred) && !member.is(Deferred) def addendum = if isConcreteOverAbstract then i"""| @@ -1614,7 +1614,7 @@ class MissingTypeParameterInTypeApp(tpe: Type)(using Context) class MissingArgument(pname: Name, methString: String)(using Context) extends TypeMsg(MissingArgumentID): def msg(using Context) = - if pname.firstPart contains '$' then s"not enough arguments for $methString" + if pname.firstPart.contains('$') then s"not enough arguments for $methString" else s"missing argument for parameter $pname of $methString" def explain(using Context) = "" @@ -2376,7 +2376,7 @@ class ParamsNoInline(owner: Symbol)(using Context) class SymbolIsNotAValue(symbol: Symbol)(using Context) extends TypeMsg(SymbolIsNotAValueID) { def msg(using Context) = val kind = - if symbol is Package then i"$symbol" + if symbol.is(Package) then i"$symbol" else i"Java defined ${hl("class " + symbol.name)}" s"$kind is not a value" def explain(using Context) = "" diff --git a/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala b/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala index 5f3eeff91ff3..41a586b46b43 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ExtractAPI.scala @@ -305,7 +305,7 @@ private class ExtractAPICollector(nonLocalClassSymbols: mutable.HashSet[Symbol]) val modifiers = apiModifiers(sym) val anns = apiAnnotations(sym, inlineOrigin = NoSymbol).toArray val topLevel = sym.isTopLevelClass - val childrenOfSealedClass = sym.sealedDescendants.sorted(classFirstSort).map(c => + val childrenOfSealedClass = sym.sealedDescendants.sorted(using classFirstSort).map(c => if (c.isClass) apiType(c.typeRef) else @@ -407,7 +407,7 @@ private class ExtractAPICollector(nonLocalClassSymbols: mutable.HashSet[Symbol]) } def apiDefinitions(defs: List[Symbol]): List[api.ClassDefinition] = - defs.sorted(classFirstSort).map(apiDefinition(_, inlineOrigin = NoSymbol)) + defs.sorted(using classFirstSort).map(apiDefinition(_, inlineOrigin = NoSymbol)) /** `inlineOrigin` denotes an optional inline method that we are * currently hashing the body of. If it exists, include extra information diff --git a/compiler/src/dotty/tools/dotc/sbt/ShowAPI.scala b/compiler/src/dotty/tools/dotc/sbt/ShowAPI.scala index a16c135deef7..80ad093b0a6b 100644 --- a/compiler/src/dotty/tools/dotc/sbt/ShowAPI.scala +++ b/compiler/src/dotty/tools/dotc/sbt/ShowAPI.scala @@ -16,9 +16,9 @@ import scala.util.Try object DefaultShowAPI { private lazy val defaultNesting = Try { java.lang.Integer.parseInt(sys.props.get("sbt.inc.apidiff.depth").get) } getOrElse 2 - def apply(d: Definition): String = ShowAPI.showDefinition(d)(defaultNesting) - def apply(d: Type): String = ShowAPI.showType(d)(defaultNesting) - def apply(a: ClassLike): String = ShowAPI.showApi(a)(defaultNesting) + def apply(d: Definition): String = ShowAPI.showDefinition(d)(using defaultNesting) + def apply(d: Type): String = ShowAPI.showType(d)(using defaultNesting) + def apply(a: ClassLike): String = ShowAPI.showApi(a)(using defaultNesting) } object ShowAPI { @@ -152,9 +152,9 @@ object ShowAPI { } // limit nesting to prevent cycles and generally keep output from getting humongous - private def showNestedType(tp: Type)(implicit nesting: Int) = showType(tp)(nesting - 1) - private def showNestedTypeParameter(tp: TypeParameter)(implicit nesting: Int) = showTypeParameter(tp)(nesting - 1) - private def showNestedTypeParameters(tps: Seq[TypeParameter])(implicit nesting: Int) = showTypeParameters(tps)(nesting - 1) - private def showNestedDefinition(d: Definition)(implicit nesting: Int) = showDefinition(d)(nesting - 1) + private def showNestedType(tp: Type)(implicit nesting: Int) = showType(tp)(using nesting - 1) + private def showNestedTypeParameter(tp: TypeParameter)(implicit nesting: Int) = showTypeParameter(tp)(using nesting - 1) + private def showNestedTypeParameters(tps: Seq[TypeParameter])(implicit nesting: Int) = showTypeParameters(tps)(using nesting - 1) + private def showNestedDefinition(d: Definition)(implicit nesting: Int) = showDefinition(d)(using nesting - 1) } diff --git a/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala b/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala index b07963b28182..4dd8efc9506d 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/ExtractSemanticDB.scala @@ -610,7 +610,7 @@ object ExtractSemanticDB: tree match case tree: ValDef => if !tree.symbol.is(Param) then - symkinds += (if tree.mods is Mutable then SymbolKind.Var else SymbolKind.Val) + symkinds += (if tree.mods.is(Mutable) then SymbolKind.Var else SymbolKind.Val) if tree.rhs.isEmpty && !tree.symbol.isOneOf(TermParam | CaseAccessor | ParamAccessor) then symkinds += SymbolKind.Abstract case tree: DefDef => diff --git a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala index a20a0d181a55..3d81408e8482 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/Scala3.scala @@ -406,9 +406,9 @@ object Scala3: def isGlobal: Boolean = !symbol.isEmpty && !symbol.isMulti && symbol.last.isGlobalTerminal def isLocal: Boolean = !symbol.isEmpty && !symbol.isMulti && !symbol.last.isGlobalTerminal - def isMulti: Boolean = symbol startsWith ";" + def isMulti: Boolean = symbol.startsWith(";") - def isConstructor: Boolean = ctor matches symbol + def isConstructor: Boolean = ctor.matches(symbol) def isPackage: Boolean = !symbol.isEmpty && !symbol.isMulti && symbol.last == '/' def isTerm: Boolean = !symbol.isEmpty && !symbol.isMulti && symbol.last == '.' def isType: Boolean = !symbol.isEmpty && !symbol.isMulti && symbol.last == '#' @@ -484,7 +484,7 @@ object Scala3: /** Sort symbol occurrences by their start position. */ given Ordering[SymbolOccurrence] = (x, y) => compareRange(x.range, y.range) - given Ordering[SymbolInformation] = Ordering.by[SymbolInformation, String](_.symbol)(IdentifierOrdering()) + given Ordering[SymbolInformation] = Ordering.by[SymbolInformation, String](_.symbol)(using IdentifierOrdering()) given Ordering[Diagnostic] = (x, y) => compareRange(x.range, y.range) diff --git a/compiler/src/dotty/tools/dotc/semanticdb/TypeOps.scala b/compiler/src/dotty/tools/dotc/semanticdb/TypeOps.scala index 11467e216aba..3f156e5a7b40 100644 --- a/compiler/src/dotty/tools/dotc/semanticdb/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/semanticdb/TypeOps.scala @@ -407,7 +407,7 @@ class TypeOps: // `Seq[Int] @Repeated` (or `Array[Int] @Repeated`) // See: Desugar.scala and TypeApplications.scala case AnnotatedType(AppliedType(_, targs), annot) - if (annot matches defn.RepeatedAnnot) && (targs.length == 1) => + if annot.matches(defn.RepeatedAnnot) && (targs.length == 1) => val stpe = loop(targs(0)) s.RepeatedType(stpe) diff --git a/compiler/src/dotty/tools/dotc/transform/BeanProperties.scala b/compiler/src/dotty/tools/dotc/transform/BeanProperties.scala index 57aeb93a3b61..a1492fb374d0 100644 --- a/compiler/src/dotty/tools/dotc/transform/BeanProperties.scala +++ b/compiler/src/dotty/tools/dotc/transform/BeanProperties.scala @@ -25,7 +25,7 @@ class BeanProperties(thisPhase: DenotTransformer): def generateAccessors(valDef: ValDef)(using Context): List[Tree] = def generateGetter(valDef: ValDef, annot: Annotation)(using Context) : Tree = - val prefix = if annot matches defn.BooleanBeanPropertyAnnot then "is" else "get" + val prefix = if annot.matches(defn.BooleanBeanPropertyAnnot) then "is" else "get" val meth = newSymbol( owner = ctx.owner, name = prefixedName(prefix, valDef.name), diff --git a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala index 7263bce0478c..2bf164f4b2a3 100644 --- a/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala +++ b/compiler/src/dotty/tools/dotc/transform/CapturedVars.scala @@ -67,17 +67,15 @@ class CapturedVars extends MiniPhase with IdentityDenotTransformer: else refMap(defn.ObjectClass) } - override def prepareForValDef(vdef: ValDef)(using Context): Context = { + override def prepareForValDef(vdef: ValDef)(using Context): Context = val sym = atPhase(thisPhase)(vdef.symbol) - if (captured contains sym) { + if captured.contains(sym) then val newd = atPhase(thisPhase)(sym.denot).copySymDenotation( info = refClass(sym.info.classSymbol, sym.hasAnnotation(defn.VolatileAnnot)).typeRef, initFlags = sym.flags &~ Mutable) newd.removeAnnotation(defn.VolatileAnnot) newd.installAfter(thisPhase) - } ctx - } override def transformValDef(vdef: ValDef)(using Context): Tree = { val vble = vdef.symbol diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index c4a5b35da90c..9a8f5596471f 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -296,19 +296,17 @@ object Erasure { // "Unboxing" null to underlying is equivalent to doing null.asInstanceOf[underlying] // See tests/pos/valueclasses/nullAsInstanceOfVC.scala for cases where this might happen. val tree1 = - if (tree.tpe isRef defn.NullClass) + if tree.tpe.isRef(defn.NullClass) then adaptToType(tree, underlying) - else if (!(tree.tpe <:< tycon)) { + else if !(tree.tpe <:< tycon) then assert(!(tree.tpe.typeSymbol.isPrimitiveValueClass)) val nullTree = nullLiteral val unboxedNull = adaptToType(nullTree, underlying) - evalOnce(tree) { t => + evalOnce(tree): t => If(t.select(defn.Object_eq).appliedTo(nullTree), unboxedNull, unboxedTree(t)) - } - } else unboxedTree(tree) cast(tree1, pt) @@ -334,7 +332,7 @@ object Erasure { ref(evt2u(tycon.typeSymbol.asClass)).appliedTo(tree) assert(!pt.isInstanceOf[SingletonType], pt) - if (pt isRef defn.UnitClass) unbox(tree, pt) + if pt.isRef(defn.UnitClass) then unbox(tree, pt) else (tree.tpe.widen, pt) match { // Convert primitive arrays into reference arrays, this path is only // needed to handle repeated arguments, see diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index 0db1ddc5750c..c1b3c5a6493d 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -247,8 +247,8 @@ object ExplicitOuter { */ def outerAccessor(cls: ClassSymbol)(using Context): Symbol = if (cls.isStatic) NoSymbol // fast return to avoid scanning package decls - else cls.info.member(outerAccName(cls)).suchThat(_.is(OuterAccessor)).symbol orElse - cls.info.decls.find(_.is(OuterAccessor)) + else cls.info.member(outerAccName(cls)).suchThat(_.is(OuterAccessor)).symbol + `orElse` cls.info.decls.find(_.is(OuterAccessor)) /** Class has an outer accessor. Can be called only after phase ExplicitOuter. */ private def hasOuter(cls: ClassSymbol)(using Context): Boolean = diff --git a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala index cd78e6da36d7..5b0fac4133f6 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExtensionMethods.scala @@ -112,7 +112,7 @@ class ExtensionMethods extends MiniPhase with DenotTransformer with FullParamete ref1 case _ => ref.info match { - case ClassInfo(pre, cls, _, _, _) if cls is ModuleClass => + case ClassInfo(pre, cls, _, _, _) if cls.is(ModuleClass) => cls.linkedClass match { case valueClass: ClassSymbol if isDerivedValueClass(valueClass) => val info1 = atPhase(ctx.phase.next)(cls.denot).asClass.classInfo.derivedClassInfo(prefix = pre) diff --git a/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala b/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala index dbb4c72ab311..35797922482d 100644 --- a/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala +++ b/compiler/src/dotty/tools/dotc/transform/FullParameterization.scala @@ -207,7 +207,7 @@ trait FullParameterization { .substThisUnlessStatic(origClass, thisRef.tpe), treeMap = { case tree: This if tree.symbol == origClass => thisRef.withSpan(tree.span) - case tree => rewireTree(tree, Nil) orElse tree + case tree => rewireTree(tree, Nil) `orElse` tree }, oldOwners = origMeth :: Nil, newOwners = derived :: Nil diff --git a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala index af168b563048..775806c7ae6d 100644 --- a/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala +++ b/compiler/src/dotty/tools/dotc/transform/LambdaLift.scala @@ -96,12 +96,13 @@ object LambdaLift: private def liftLocals()(using Context): Unit = { for ((local, lOwner) <- deps.logicalOwner) { val (newOwner, maybeStatic) = - if lOwner is Package then (local.topLevelClass, JavaStatic) + if lOwner.is(Package) + then (local.topLevelClass, JavaStatic) else (lOwner, EmptyFlags) // Drop Module because class is no longer a singleton in the lifted context. var initFlags = local.flags &~ Module | Private | Lifted | maybeStatic - if (local is Method) - if (newOwner is Trait) + if local.is(Method) then + if newOwner.is(Trait) then // Drop Final when a method is lifted into a trait. // According to the JVM specification, a method declared inside interface cannot have the final flag. // "Methods of interfaces may have any of the flags in Table 4.6-A set except ACC_PROTECTED, ACC_FINAL, ..." @@ -277,24 +278,22 @@ class LambdaLift extends MiniPhase with IdentityDenotTransformer { thisPhase => override def prepareForUnit(tree: Tree)(using Context): Context = ctx.fresh.updateStore(Lifter, new Lifter(thisPhase)) - override def transformIdent(tree: Ident)(using Context): Tree = { + override def transformIdent(tree: Ident)(using Context): Tree = val sym = tree.symbol - tree.tpe match { + tree.tpe match case tpe @ TermRef(prefix, _) => val lft = lifter - if (prefix eq NoPrefix) - if (sym.enclosure != lft.currentEnclosure && !sym.isStatic) - (if (sym is Method) lft.memberRef(sym) else lft.proxyRef(sym)).withSpan(tree.span) - else if (sym.owner.isClass) // sym was lifted out + if prefix eq NoPrefix then + if sym.enclosure != lft.currentEnclosure && !sym.isStatic then + (if sym.is(Method) then lft.memberRef(sym) else lft.proxyRef(sym)).withSpan(tree.span) + else if sym.owner.isClass then // sym was lifted out ref(sym).withSpan(tree.span) else tree - else if (!prefixIsElidable(tpe)) ref(tpe) + else if !prefixIsElidable(tpe) then ref(tpe) else tree case _ => tree - } - } override def transformSelect(tree: Select)(using Context): Tree = val denot = tree.denot diff --git a/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala b/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala index 36a40658ffa5..1f5886b17535 100644 --- a/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/SelectStatic.scala @@ -52,9 +52,9 @@ class SelectStatic extends MiniPhase with IdentityDenotTransformer { override def transformSelect(tree: tpd.Select)(using Context): tpd.Tree = { val sym = tree.symbol def isStaticMember = - (sym is Flags.Module) && sym.initial.maybeOwner.initial.isStaticOwner || - (sym is Flags.JavaStatic) || - sym.isScalaStatic + sym.is(Flags.Module) && sym.initial.maybeOwner.initial.isStaticOwner + || sym.is(Flags.JavaStatic) + || sym.isScalaStatic val isStaticRef = !sym.is(Package) && !sym.maybeOwner.is(Package) && isStaticMember val tree1 = if isStaticRef && !tree.qualifier.symbol.isAllOf(JavaModule) && !tree.qualifier.isType then diff --git a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala index fbff51acb514..f54e69d971f8 100644 --- a/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala +++ b/compiler/src/dotty/tools/dotc/transform/SyntheticMembers.scala @@ -263,7 +263,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { m.paramInfos.head.stripNull() == defn.StringType case _ => false } - val constructor = ioob.typeSymbol.info.decls.find(filterStringConstructor _).asTerm + val constructor = ioob.typeSymbol.info.decls.find(filterStringConstructor(_)).asTerm val stringIndex = Apply(Select(index, nme.toString_), Nil) val error = Throw(New(ioob, constructor, List(stringIndex))) @@ -303,7 +303,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { val comparisons = sortedAccessors.map { accessor => This(clazz).withSpan(ctx.owner.span.focus).select(accessor).equal(ref(thatAsClazz).select(accessor)) } var rhs = // this.x == this$0.x && this.y == x$0.y && that.canEqual(this) - if comparisons.isEmpty then Literal(Constant(true)) else comparisons.reduceBalanced(_ and _) + if comparisons.isEmpty then Literal(Constant(true)) else comparisons.reduceBalanced(_ `and` _) val canEqualMeth = existingDef(defn.Product_canEqual, clazz) if !clazz.is(Final) || canEqualMeth.exists && !canEqualMeth.is(Synthetic) then rhs = rhs.and( @@ -316,7 +316,7 @@ class SyntheticMembers(thisPhase: DenotTransformer) { if (isDerivedValueClass(clazz)) matchExpr else { val eqCompare = This(clazz).select(defn.Object_eq).appliedTo(that.cast(defn.ObjectType)) - eqCompare or matchExpr + eqCompare `or` matchExpr } } diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index b43acce78d35..9f3629866a52 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -343,7 +343,7 @@ object TreeChecker { // case tree: untpd.TypeDef => case Apply(fun, args) => assertIdentNotJavaClass(fun) - args.foreach(assertIdentNotJavaClass _) + args.foreach(assertIdentNotJavaClass(_)) // case tree: untpd.This => // case tree: untpd.Literal => // case tree: untpd.New => @@ -354,7 +354,7 @@ object TreeChecker { case Assign(_, rhs) => assertIdentNotJavaClass(rhs) case Block(stats, expr) => - stats.foreach(assertIdentNotJavaClass _) + stats.foreach(assertIdentNotJavaClass(_)) assertIdentNotJavaClass(expr) case If(_, thenp, elsep) => assertIdentNotJavaClass(thenp) diff --git a/compiler/src/dotty/tools/dotc/transform/sjs/PrepJSInterop.scala b/compiler/src/dotty/tools/dotc/transform/sjs/PrepJSInterop.scala index 13fcbe542448..bd4c0673aee7 100644 --- a/compiler/src/dotty/tools/dotc/transform/sjs/PrepJSInterop.scala +++ b/compiler/src/dotty/tools/dotc/transform/sjs/PrepJSInterop.scala @@ -1170,10 +1170,10 @@ object PrepJSInterop { @inline def |(that: OwnerKind): OwnerKind = new OwnerKind(this.baseKinds | that.baseKinds) - inline def is(that: OwnerKind): Boolean = + inline infix def is(that: OwnerKind): Boolean = (this.baseKinds & that.baseKinds) != 0 - inline def isnt(that: OwnerKind): Boolean = + inline infix def isnt(that: OwnerKind): Boolean = !this.is(that) } diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index 15e2bcb7427d..611ca8cf781a 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -1751,7 +1751,7 @@ trait Applications extends Compatibility { case tp => val unapplyErr = if (tp.isError) unapplyFn else notAnExtractor(unapplyFn) val typedArgsErr = unadaptedArgs.mapconserve(typed(_, defn.AnyType)) - cpy.UnApply(tree)(unapplyErr, Nil, typedArgsErr) withType unapplyErr.tpe + cpy.UnApply(tree)(unapplyErr, Nil, typedArgsErr).withType(unapplyErr.tpe) } } diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index 493a4207717d..aa5ac72c2aa5 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -1089,7 +1089,7 @@ trait Checking { val pos = if isPatDef then reason match case NonConforming => sel.srcPos - case RefutableExtractor => pat.source.atSpan(pat.span union sel.span) + case RefutableExtractor => pat.source.atSpan(pat.span `union` sel.span) else pat.srcPos def rewriteMsg = Message.rewriteNotice("This patch", `3.2-migration`) report.errorOrMigrationWarning( @@ -1335,39 +1335,35 @@ trait Checking { decl.matches(other) && !staticNonStaticPair /** Check that class does not declare same symbol twice */ - def checkNoDoubleDeclaration(cls: Symbol)(using Context): Unit = { + def checkNoDoubleDeclaration(cls: Symbol)(using Context): Unit = val seen = new mutable.HashMap[Name, List[Symbol]].withDefaultValue(Nil) typr.println(i"check no double declarations $cls") - def checkDecl(decl: Symbol): Unit = { - for (other <- seen(decl.name) if !decl.isAbsent() && !other.isAbsent()) { + def checkDecl(decl: Symbol): Unit = + for other <- seen(decl.name) if !decl.isAbsent() && !other.isAbsent() do typr.println(i"conflict? $decl $other") def javaFieldMethodPair = decl.is(JavaDefined) && other.is(JavaDefined) && decl.is(Method) != other.is(Method) - if (matchesSameStatic(decl, other) && !javaFieldMethodPair) { + if matchesSameStatic(decl, other) && !javaFieldMethodPair then def doubleDefError(decl: Symbol, other: Symbol): Unit = if (!decl.info.isErroneous && !other.info.isErroneous) report.error(DoubleDefinition(decl, other, cls), decl.srcPos) if decl.name.is(DefaultGetterName) && ctx.reporter.errorsReported then () // do nothing; we already have reported an error that overloaded variants cannot have default arguments - else if (decl is Synthetic) doubleDefError(other, decl) + else if decl.is(Synthetic) then doubleDefError(other, decl) else doubleDefError(decl, other) - } if decl.hasDefaultParams && other.hasDefaultParams then report.error(em"two or more overloaded variants of $decl have default arguments", decl.srcPos) decl.resetFlag(HasDefaultParams) - } - if (!excludeFromDoubleDeclCheck(decl)) + if !excludeFromDoubleDeclCheck(decl) then seen(decl.name) = decl :: seen(decl.name) - } cls.info.decls.foreach(checkDecl) - cls.info match { + cls.info match case ClassInfo(_, _, _, _, selfSym: Symbol) => checkDecl(selfSym) case _ => - } - } + end checkNoDoubleDeclaration def checkParentCall(call: Tree, caller: ClassSymbol)(using Context): Unit = if (!ctx.isAfterTyper) { diff --git a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala index 55778017b76f..317cce45995e 100644 --- a/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala +++ b/compiler/src/dotty/tools/dotc/typer/EtaExpansion.scala @@ -87,12 +87,11 @@ abstract class Lifter { def liftArgs(defs: mutable.ListBuffer[Tree], methRef: Type, args: List[Tree])(using Context): List[Tree] = methRef.widen match { case mt: MethodType => - args.lazyZip(mt.paramNames).lazyZip(mt.paramInfos).map { (arg, name, tp) => + args.lazyZip(mt.paramNames).lazyZip(mt.paramInfos).map: (arg, name, tp) => if tp.hasAnnotation(defn.InlineParamAnnot) then arg else val lifter = if (tp.isInstanceOf[ExprType]) exprLifter else this - lifter.liftArg(defs, arg, if (name.firstPart contains '$') EmptyTermName else name) - } + lifter.liftArg(defs, arg, if name.firstPart.contains('$') then EmptyTermName else name) case _ => args.mapConserve(liftArg(defs, _)) } diff --git a/compiler/src/dotty/tools/dotc/typer/Implicits.scala b/compiler/src/dotty/tools/dotc/typer/Implicits.scala index 8228bb5252f8..c1452732ee46 100644 --- a/compiler/src/dotty/tools/dotc/typer/Implicits.scala +++ b/compiler/src/dotty/tools/dotc/typer/Implicits.scala @@ -326,7 +326,7 @@ object Implicits: */ private def isOutermost = { val finalImplicits = NoContext.implicits - (this eq finalImplicits) || (outerImplicits eqn finalImplicits) + (this eq finalImplicits) || (outerImplicits eq finalImplicits) } def bindingPrec: BindingPrec = @@ -401,9 +401,9 @@ object Implicits: def exclude(root: Symbol): ContextualImplicits = if (this == NoContext.implicits) this else { - val outerExcluded = outerImplicits.nn exclude root + val outerExcluded = outerImplicits.nn.exclude(root) if (irefCtx.importInfo.nn.site.termSymbol == root) outerExcluded - else if (outerExcluded eqn outerImplicits) this + else if (outerExcluded eq outerImplicits) this else new ContextualImplicits(refs, outerExcluded, isImport)(irefCtx) } } diff --git a/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala b/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala index 78cba674bfff..e8698baa46ac 100644 --- a/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala +++ b/compiler/src/dotty/tools/dotc/typer/ImportInfo.scala @@ -220,7 +220,7 @@ class ImportInfo(symf: Context ?=> Symbol, case Some(bv) => bv case None => var c = ctx.outer - while c.importInfo eqn ctx.importInfo do c = c.outer + while c.importInfo eq ctx.importInfo do c = c.outer val cinfo = c.importInfo (cinfo != null) && cinfo.featureImported(feature)(using c) ) diff --git a/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala b/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala index f9027cf7a961..8c5a206a413a 100644 --- a/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala +++ b/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala @@ -127,7 +127,7 @@ trait ImportSuggestions: .filter(lookInside(_)) .flatMap(sym => rootsIn(sym.termRef)) val imported = - if ctx.importInfo eqn ctx.outer.importInfo then Nil + if ctx.importInfo eq ctx.outer.importInfo then Nil else ctx.importInfo.nn.importSym.info match case ImportType(expr) => rootsOnPath(expr.tpe) case _ => Nil diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index 2ca39b1615d4..65c9fa2f5ddc 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -468,13 +468,13 @@ class Namer { typer: Typer => def improve(candidate: ClassSymbol, parent: Type): ClassSymbol = val pcls = realClassParent(parent.classSymbol) - if (pcls derivesFrom candidate) pcls else candidate + if pcls.derivesFrom(candidate) then pcls else candidate parents match case p :: _ if p.classSymbol.isRealClass => parents case _ => val pcls = parents.foldLeft(defn.ObjectClass)(improve) - typr.println(i"ensure first is class $parents%, % --> ${parents map (_ baseType pcls)}%, %") + typr.println(i"ensure first is class $parents%, % --> ${parents.map(_.baseType(pcls))}%, %") val bases = parents.map(_.baseType(pcls)) var first = TypeComparer.glb(defn.ObjectType :: bases) val isProvisional = parents.exists(!_.baseType(defn.AnyClass).exists) @@ -1564,7 +1564,7 @@ class Namer { typer: Typer => val selfInfo: TypeOrSymbol = if (self.isEmpty) NoType else if (cls.is(Module)) { - val moduleType = cls.owner.thisType select sourceModule + val moduleType = cls.owner.thisType.select(sourceModule) if (self.name == nme.WILDCARD) moduleType else recordSym( newSymbol(cls, self.name, self.mods.flags, moduleType, coord = self.span), @@ -2272,7 +2272,7 @@ class Namer { typer: Typer => case _: ValDef if sym.owner.isType => missingType(sym, "") case _ => } - lhsType orElse WildcardType + lhsType `orElse` WildcardType } end inferredResultType diff --git a/compiler/src/dotty/tools/dotc/typer/Nullables.scala b/compiler/src/dotty/tools/dotc/typer/Nullables.scala index 609dad894b6c..ab2d80e4bda4 100644 --- a/compiler/src/dotty/tools/dotc/typer/Nullables.scala +++ b/compiler/src/dotty/tools/dotc/typer/Nullables.scala @@ -332,7 +332,7 @@ object Nullables: case Apply(fn, args) => val argsInfo = args.map(_.notNullInfo) val fnInfo = fn.notNullInfo - argsInfo.foldLeft(fnInfo)(_ seq _) + argsInfo.foldLeft(fnInfo)(_.seq(_)) case TypeApply(fn, _) => fn.notNullInfo case _ => diff --git a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala index 0b6688c6f5fe..4fc092d16007 100644 --- a/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala +++ b/compiler/src/dotty/tools/dotc/typer/ProtoTypes.scala @@ -696,7 +696,7 @@ object ProtoTypes { } class UnapplyFunProto(argType: Type, typer: Typer)(using Context) extends FunProto( - untpd.TypedSplice(dummyTreeOfType(argType)(ctx.source)) :: Nil, WildcardType)(typer, applyKind = ApplyKind.Regular) + untpd.TypedSplice(dummyTreeOfType(argType)(using ctx.source)) :: Nil, WildcardType)(typer, applyKind = ApplyKind.Regular) /** A prototype for expressions [] that are type-parameterized: * @@ -1054,7 +1054,7 @@ object ProtoTypes { /** Dummy tree to be used as an argument of a FunProto or ViewProto type */ object dummyTreeOfType { def apply(tp: Type)(implicit src: SourceFile): Tree = - untpd.Literal(Constant(null)) withTypeUnchecked tp + untpd.Literal(Constant(null)).withTypeUnchecked(tp) def unapply(tree: untpd.Tree): Option[Type] = untpd.unsplice(tree) match { case tree @ Literal(Constant(null)) => Some(tree.typeOpt) case _ => None diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index ba472512a953..0f1a251ccff8 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -69,8 +69,10 @@ object RefChecks { } // Check for doomed attempt to overload applyDynamic - if (clazz derivesFrom defn.DynamicClass) - for (case (_, m1 :: m2 :: _) <- (clazz.info member nme.applyDynamic).alternatives groupBy (_.symbol.typeParams.length)) + if clazz.derivesFrom(defn.DynamicClass) then + for case (_, m1 :: m2 :: _) <- clazz.info.member(nme.applyDynamic) + .alternatives.groupBy(_.symbol.typeParams.length) + do report.error("implementation restriction: applyDynamic cannot be overloaded except by methods with different numbers of type parameters, e.g. applyDynamic[T1](method: String)(arg: T1) and applyDynamic[T1, T2](method: String)(arg1: T1, arg2: T2)", m1.symbol.srcPos) } @@ -568,10 +570,11 @@ object RefChecks { overrideError("needs `abstract override` modifiers") else if member.is(Override) && other.isMutableVarOrAccessor then overrideError("cannot override a mutable variable") - else if (member.isAnyOverride && - !(member.owner.thisType.baseClasses exists (_ isSubClass other.owner)) && - !member.is(Deferred) && !other.is(Deferred) && - intersectionIsEmpty(member.extendedOverriddenSymbols, other.extendedOverriddenSymbols)) + else if member.isAnyOverride + && !(member.owner.thisType.baseClasses.exists(_.isSubClass(other.owner))) + && !member.is(Deferred) && !other.is(Deferred) + && intersectionIsEmpty(member.extendedOverriddenSymbols, other.extendedOverriddenSymbols) + then overrideError("cannot override a concrete member without a third member that's overridden by both " + "(this rule is designed to prevent ``accidental overrides'')") else if (other.isStableMember && !member.isStableMember) // (1.5) @@ -803,9 +806,9 @@ object RefChecks { case _ => "" } - else if (abstractSym isSubClass concreteSym) + else if abstractSym.isSubClass(concreteSym) then subclassMsg(abstractSym, concreteSym) - else if (concreteSym isSubClass abstractSym) + else if concreteSym.isSubClass(abstractSym) then subclassMsg(concreteSym, abstractSym) else "" diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index c6cb85ea43b6..749fefa512db 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -537,7 +537,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer if migrateTo3 && !foundUnderScala2.exists then foundUnderScala2 = checkNewOrShadowed(found, Definition, scala2pkg = true) if (defDenot.symbol.is(Package)) - result = checkNewOrShadowed(previous orElse found, PackageClause) + result = checkNewOrShadowed(previous `orElse` found, PackageClause) else if (prevPrec.ordinal < PackageClause.ordinal) result = findRefRecur(found, PackageClause, ctx)(using ctx.outer) } @@ -550,7 +550,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer if (curImport.nn.unimported ne NoSymbol) unimported += curImport.nn.unimported if (curOwner.is(Package) && curImport != null && curImport.isRootImport && previous.exists) previous // no more conflicts possible in this case - else if (isPossibleImport(NamedImport) && (curImport nen outer.importInfo)) { + else if (isPossibleImport(NamedImport) && (curImport ne outer.importInfo)) { val namedImp = namedImportRef(curImport.uncheckedNN) if (namedImp.exists) checkImportAlternatives(namedImp, NamedImport, ctx)(using outer) @@ -1250,7 +1250,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer val errorTp = errorType(CannotInstantiateQuotedTypeVar(tpt1.tpe.typeSymbol), tpt1.srcPos) return cpy.New(tree)(tpt1).withType(errorTp) if tsym.is(Package) then - report error(em"$tsym cannot be instantiated", tpt1.srcPos) + report.error(em"$tsym cannot be instantiated", tpt1.srcPos) tpt1 = tpt1.withType(ensureAccessible(tpt1.tpe, superAccess = false, tpt1.srcPos)) tpt1 match { case AppliedTypeTree(_, targs) => @@ -1459,7 +1459,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer // transform the `Ident` into a `Select` to ensure that the prefix // is retained with a `TypedSplice` (see `case Select` bellow). // See tests/pos/i18713.scala for an example. - fn.tpe match + fn.tpe.runtimeChecked match case TermRef(qual: TermRef, _) => toSetter(ref(qual).select(fn.symbol).withSpan(fn.span)) case TermRef(qual: ThisType, _) => @@ -1567,7 +1567,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer def ascribeType(tree: Tree, pt: Type): Tree = tree match { case block @ Block(stats, expr) if !expr.isInstanceOf[Closure] => val expr1 = ascribeType(expr, pt) - cpy.Block(block)(stats, expr1) withType expr1.tpe // no assignType here because avoid is redundant + cpy.Block(block)(stats, expr1).withType(expr1.tpe) // no assignType here because avoid is redundant case _ => val target = pt.simplified val targetTpt = TypeTree(target, inferred = true) @@ -1905,7 +1905,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer val outerCtx = ctx val nestedCtx = outerCtx.fresh.setNewTyperState() inContext(nestedCtx) { - val protoArgs = args map (_ withType WildcardType) + val protoArgs = args.map(_.withType(WildcardType)) val callProto = FunProto(protoArgs, WildcardType)(this, app.applyKind) val expr1 = typedExpr(expr, callProto) if nestedCtx.reporter.hasErrors then NoType @@ -2057,7 +2057,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer end typedPolyFunctionValue def typedClosure(tree: untpd.Closure, pt: Type)(using Context): Tree = { - val env1 = tree.env mapconserve (typed(_)) + val env1 = tree.env.mapconserve(typed(_)) val meth1 = typedUnadapted(tree.meth) val target = if (tree.tpt.isEmpty) @@ -2391,7 +2391,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer // because we do not know the internal type params and method params. // Hence no adaptation is possible, and we assume WildcardType as prototype. (from, proto) - val expr1 = typedExpr(tree.expr orElse untpd.syntheticUnitLiteral.withSpan(tree.span), proto) + val expr1 = typedExpr(tree.expr `orElse` untpd.syntheticUnitLiteral.withSpan(tree.span), proto) assignType(cpy.Return(tree)(expr1, from)).withNotNullInfo(expr1.notNullInfo.terminatedInfo) end typedReturn @@ -3175,7 +3175,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer ensureAccessible(constr.termRef, superAccess = true, tree.srcPos) else checkParentCall(result, cls) - if cls is Case then + if cls.is(Case) then checkCaseInheritance(psym, cls, tree.srcPos) result @@ -3875,7 +3875,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer typed(tree, pt, ctx.typerState.ownedVars) def typedTrees(trees: List[untpd.Tree])(using Context): List[Tree] = - trees mapconserve (typed(_)) + trees.mapconserve(typed(_)) def typedStats(stats: List[untpd.Tree], exprOwner: Symbol)(using Context): (List[Tree], Context) = { val buf = new mutable.ListBuffer[Tree] @@ -4816,7 +4816,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer return readapt(tree.cast(captured)) // drop type if prototype is Unit - if (pt isRef defn.UnitClass) { + if pt.isRef(defn.UnitClass) then // local adaptation makes sure every adapted tree conforms to its pt // so will take the code path that decides on inlining val tree1 = adapt(tree, WildcardType, locked) @@ -4831,7 +4831,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer report.warning(ValueDiscarding(tree.tpe), tree.srcPos) return tpd.Block(tree1 :: Nil, unitLiteral) - } + end if // convert function literal to SAM closure tree match { diff --git a/compiler/src/dotty/tools/dotc/util/CommentParsing.scala b/compiler/src/dotty/tools/dotc/util/CommentParsing.scala index 7224e28fe477..56c72457d02a 100644 --- a/compiler/src/dotty/tools/dotc/util/CommentParsing.scala +++ b/compiler/src/dotty/tools/dotc/util/CommentParsing.scala @@ -23,21 +23,21 @@ object CommentParsing { * sequence of whitespace characters characters (but no newlines) */ def skipWhitespace(str: String, start: Int): Int = - if (start < str.length && isWhitespace(str charAt start)) skipWhitespace(str, start + 1) + if (start < str.length && isWhitespace(str.charAt(start))) skipWhitespace(str, start + 1) else start /** Returns index of string `str` following `start` skipping * sequence of identifier characters. */ def skipIdent(str: String, start: Int): Int = - if (start < str.length && isIdentifierPart(str charAt start)) skipIdent(str, start + 1) + if (start < str.length && isIdentifierPart(str.charAt(start))) skipIdent(str, start + 1) else start /** Returns index of string `str` following `start` skipping * sequence of identifier characters. */ def skipTag(str: String, start: Int): Int = - if (start < str.length && (str charAt start) == '@') skipIdent(str, start + 1) + if (start < str.length && (str.charAt(start)) == '@') skipIdent(str, start + 1) else start @@ -50,8 +50,8 @@ object CommentParsing { if (start == str.length) start else { val idx = skipWhitespace(str, start + 1) - if (idx < str.length && (str charAt idx) == '*') skipWhitespace(str, idx + 1) - else if (idx + 2 < str.length && (str charAt idx) == '/' && (str charAt (idx + 1)) == '*' && (str charAt (idx + 2)) == '*') + if (idx < str.length && (str.charAt(idx)) == '*') skipWhitespace(str, idx + 1) + else if (idx + 2 < str.length && (str.charAt(idx)) == '/' && (str.charAt(idx + 1)) == '*' && (str.charAt(idx + 2)) == '*') skipWhitespace(str, idx + 3) else idx } @@ -59,8 +59,8 @@ object CommentParsing { /** Skips to next occurrence of `\n` or to the position after the `/``**` sequence following index `start`. */ def skipToEol(str: String, start: Int): Int = - if (start + 2 < str.length && (str charAt start) == '/' && (str charAt (start + 1)) == '*' && (str charAt (start + 2)) == '*') start + 3 - else if (start < str.length && (str charAt start) != '\n') skipToEol(str, start + 1) + if (start + 2 < str.length && (str.charAt(start)) == '/' && (str.charAt(start + 1)) == '*' && (str.charAt(start + 2)) == '*') start + 3 + else if (start < str.length && (str.charAt(start)) != '\n') skipToEol(str, start + 1) else start /** Returns first index following `start` and starting a line (i.e. after skipLineLead) or starting the comment @@ -128,7 +128,7 @@ object CommentParsing { startsWithTag(str, section._1, tag) def startsWithTag(str: String, start: Int, tag: String): Boolean = - str.startsWith(tag, start) && !isIdentifierPart(str charAt (start + tag.length)) + str.startsWith(tag, start) && !isIdentifierPart(str.charAt(start + tag.length)) /** The first start tag of a list of tag intervals, * or the end of the whole comment string - 2 if list is empty @@ -163,7 +163,7 @@ object CommentParsing { /** Extracts variable name from a string, stripping any pair of surrounding braces */ def variableName(str: String): String = - if (str.length >= 2 && (str charAt 0) == '{' && (str charAt (str.length - 1)) == '}') + if (str.length >= 2 && (str.charAt(0)) == '{' && (str.charAt(str.length - 1)) == '}') str.substring(1, str.length - 1) else str @@ -172,16 +172,16 @@ object CommentParsing { */ def skipVariable(str: String, start: Int): Int = { var idx = start - if (idx < str.length && (str charAt idx) == '{') { + if (idx < str.length && (str.charAt(idx)) == '{') { while ({ idx += 1 - idx < str.length && (str charAt idx) != '}' + idx < str.length && (str.charAt(idx)) != '}' }) () if (idx < str.length) idx + 1 else start } else { - while (idx < str.length && isVarPart(str charAt idx)) + while (idx < str.length && isVarPart(str.charAt(idx))) idx += 1 idx } diff --git a/compiler/src/dotty/tools/dotc/util/ShowPickled.scala b/compiler/src/dotty/tools/dotc/util/ShowPickled.scala index 15d553e703b3..a7f10fde20b2 100644 --- a/compiler/src/dotty/tools/dotc/util/ShowPickled.scala +++ b/compiler/src/dotty/tools/dotc/util/ShowPickled.scala @@ -119,14 +119,14 @@ object ShowPickled { val entryList = makeEntryList(buf, index) buf.readIndex = 0 - def p(s: String) = out print s + def p(s: String) = out.print(s) def printNameRef(): Unit = { val idx = buf.readNat() - val name = entryList nameAt idx + val name = entryList.nameAt(idx) val toPrint = " %s(%s)".format(idx, name) - out print toPrint + out.print(toPrint) } def printNat() = p(" " + buf.readNat()) @@ -146,7 +146,7 @@ object ShowPickled { def printFlags(privateWithin: Option[Int]) = { val accessBoundary = ( for (idx <- privateWithin) yield { - val s = entryList nameAt idx + val s = entryList.nameAt(idx) s"$idx($s)" } ) @@ -279,7 +279,7 @@ object ShowPickled { def main(args: Array[String]) { args foreach { arg => - (fromFile(arg) orElse fromName(arg)) match { + (fromFile(arg) `orElse` fromName(arg)) match { case Some(pb) => show(arg + ":", pb) case _ => Console.println("Cannot read " + arg) } diff --git a/compiler/src/dotty/tools/dotc/util/SourceFile.scala b/compiler/src/dotty/tools/dotc/util/SourceFile.scala index 9cc3dc5e731d..8800743c4f1c 100644 --- a/compiler/src/dotty/tools/dotc/util/SourceFile.scala +++ b/compiler/src/dotty/tools/dotc/util/SourceFile.scala @@ -40,8 +40,8 @@ object ScriptSourceFile { */ val headerLength = if (headerStarts exists (content startsWith _)) { - val matcher = headerPattern matcher content.mkString - if (matcher.find) matcher.end + val matcher = headerPattern.matcher(content.mkString) + if matcher.find then matcher.end else content.indexOf('\n') // end of first line } else 0 @@ -151,7 +151,7 @@ class SourceFile(val file: AbstractFile, computeContent: => Array[Char]) extends */ def positionInUltimateSource(position: SourcePosition): SourcePosition = if isSelfContained then position // return the argument - else SourcePosition(underlying, position.span shift start) + else SourcePosition(underlying, position.span.shift(start)) private def calculateLineIndicesFromContents() = { val cs = content() diff --git a/compiler/src/dotty/tools/io/AbstractFile.scala b/compiler/src/dotty/tools/io/AbstractFile.scala index 1bc9c051cdc6..69c4912886d1 100644 --- a/compiler/src/dotty/tools/io/AbstractFile.scala +++ b/compiler/src/dotty/tools/io/AbstractFile.scala @@ -42,7 +42,7 @@ object AbstractFile { */ def getDirectory(path: Path): AbstractFile = if (path.isDirectory) new PlainFile(path) - else if (path.isFile && Path.isExtensionJarOrZip(path.jpath)) ZipArchive fromFile path.toFile + else if (path.isFile && Path.isExtensionJarOrZip(path.jpath)) ZipArchive.fromFile(path.toFile) else null /** @@ -54,7 +54,7 @@ object AbstractFile { if (url.getProtocol != "file") null else new PlainFile(new Path(Paths.get(url.toURI))) - def getResources(url: URL): AbstractFile = ZipArchive fromManifestURL url + def getResources(url: URL): AbstractFile = ZipArchive.fromManifestURL(url) } /** diff --git a/compiler/src/dotty/tools/io/ClassPath.scala b/compiler/src/dotty/tools/io/ClassPath.scala index 01a3f2cc1870..92aeaa39ea18 100644 --- a/compiler/src/dotty/tools/io/ClassPath.scala +++ b/compiler/src/dotty/tools/io/ClassPath.scala @@ -136,12 +136,10 @@ object ClassPath { else split(path) /** Expand dir out to contents, a la extdir */ - def expandDir(extdir: String): List[String] = { - AbstractFile getDirectory extdir match { + def expandDir(extdir: String): List[String] = + AbstractFile.getDirectory(extdir) match case null => Nil case dir => dir.filter(_.isClassContainer).map(x => new java.io.File(dir.file, x.name).getPath).toList - } - } /** Expand manifest jar classpath entries: these are either urls, or paths * relative to the location of the jar. diff --git a/compiler/src/dotty/tools/io/File.scala b/compiler/src/dotty/tools/io/File.scala index ea48966de6fb..a761e0956a0a 100644 --- a/compiler/src/dotty/tools/io/File.scala +++ b/compiler/src/dotty/tools/io/File.scala @@ -73,20 +73,20 @@ class File(jpath: JPath)(implicit constructorCodec: Codec) extends Path(jpath) w /** Creates a new file and writes all the Strings to it. */ def writeAll(strings: String*): Unit = { val out = bufferedWriter() - try strings foreach (out write _) + try strings.foreach(out.write(_)) finally out.close() } def appendAll(strings: String*): Unit = { val out = bufferedWriter(append = true) - try strings foreach (out write _) + try strings.foreach(out.write(_)) finally out.close() } /** Calls println on each string (so it adds a newline in the PrintWriter fashion.) */ def printlnAll(strings: String*): Unit = { val out = printWriter() - try strings foreach (out println _) + try strings.foreach(out.println(_)) finally out.close() } diff --git a/compiler/src/dotty/tools/io/FileWriters.scala b/compiler/src/dotty/tools/io/FileWriters.scala index 849b80c5e745..8273a9fadfc4 100644 --- a/compiler/src/dotty/tools/io/FileWriters.scala +++ b/compiler/src/dotty/tools/io/FileWriters.scala @@ -365,8 +365,9 @@ object FileWriters { else throw new FileConflictException(s"${base.path}/${path}: ${dir.path} is not a directory") val components = path.split('/') var dir = base - for (i <- 0 until components.length - 1) dir = ensureDirectory(dir) subdirectoryNamed components(i).toString - ensureDirectory(dir) fileNamed components.last.toString + for i <- 0 until components.length - 1 do + dir = ensureDirectory(dir).subdirectoryNamed(components(i).toString) + ensureDirectory(dir).fileNamed(components.last.toString) } private def writeBytes(outFile: AbstractFile, bytes: Array[Byte]): Unit = { diff --git a/compiler/src/dotty/tools/io/Jar.scala b/compiler/src/dotty/tools/io/Jar.scala index eadc38e93007..847e9b6cdd82 100644 --- a/compiler/src/dotty/tools/io/Jar.scala +++ b/compiler/src/dotty/tools/io/Jar.scala @@ -69,10 +69,9 @@ class Jar(file: File) { Iterator.continually(in.getNextJarEntry()).takeWhile(_ != null).toList } - def getEntryStream(entry: JarEntry): java.io.InputStream = jarFile getInputStream entry match { + def getEntryStream(entry: JarEntry): java.io.InputStream = jarFile.getInputStream(entry) match case null => errorFn("No such entry: " + entry) ; null case x => x - } override def toString: String = "" + file } @@ -86,7 +85,7 @@ class JarWriter(val file: File, val manifest: Manifest) { */ def newOutputStream(path: String): DataOutputStream = { val entry = new JarEntry(path) - out putNextEntry entry + out.putNextEntry(entry) new DataOutputStream(out) } @@ -95,7 +94,7 @@ class JarWriter(val file: File, val manifest: Manifest) { finally out.close() } def addStream(entry: JarEntry, in: InputStream): Unit = { - out putNextEntry entry + out.putNextEntry(entry) try transfer(in, out) finally out.closeEntry() } @@ -169,6 +168,6 @@ object Jar { def create(file: File, sourceDir: Directory, mainClass: String): Unit = { val writer = new Jar(file).jarWriter(Name.MAIN_CLASS -> mainClass) - writer writeAllFrom sourceDir + writer.writeAllFrom(sourceDir) } } diff --git a/compiler/src/dotty/tools/io/Path.scala b/compiler/src/dotty/tools/io/Path.scala index 64137d691898..6aa7bba12b1c 100644 --- a/compiler/src/dotty/tools/io/Path.scala +++ b/compiler/src/dotty/tools/io/Path.scala @@ -105,8 +105,8 @@ class Path private[io] (val jpath: JPath) { * Iterator, and all sub-subdirectories are recursively evaluated */ def walkFilter(cond: Path => Boolean): Iterator[Path] = - if (isFile) toFile walkFilter cond - else if (isDirectory) toDirectory.walkFilter(cond) + if isFile then toFile.walkFilter(cond) + else if isDirectory then toDirectory.walkFilter(cond) else Iterator.empty /** Equivalent to walkFilter(_ => true). @@ -159,7 +159,7 @@ class Path private[io] (val jpath: JPath) { } def parents: List[Directory] = { val p = parent - if (p isSame this) Nil else p :: p.parents + if p.isSame(this) then Nil else p :: p.parents } def ext: FileExtension = Path.fileExtension(name) @@ -262,7 +262,7 @@ class Path private[io] (val jpath: JPath) { def truncate(): Boolean = isFile && { val raf = new RandomAccessFile(jpath.toFile, "rw") - raf setLength 0 + raf.setLength(0) raf.close() length == 0 } diff --git a/compiler/src/dotty/tools/io/Streamable.scala b/compiler/src/dotty/tools/io/Streamable.scala index fd72854a9127..2980cf2f2196 100644 --- a/compiler/src/dotty/tools/io/Streamable.scala +++ b/compiler/src/dotty/tools/io/Streamable.scala @@ -86,7 +86,7 @@ object Streamable { def creationCodec: Codec = implicitly[Codec] /** Caller is responsible for closing the returned BufferedSource. */ - def chars(codec: Codec): BufferedSource = Source.fromInputStream(inputStream())(codec) + def chars(codec: Codec): BufferedSource = Source.fromInputStream(inputStream())(using codec) /** Beware! Leaks an InputStream which will not be closed until it gets finalized. */ def lines(): Iterator[String] = lines(creationCodec) @@ -131,7 +131,7 @@ object Streamable { }.toByteArray() def slurp(is: => InputStream)(implicit codec: Codec): String = - new Chars { def inputStream() = is } slurp codec + new Chars { def inputStream() = is }.slurp(codec) def slurp(url: URL)(implicit codec: Codec): String = slurp(url.openStream()) diff --git a/compiler/src/dotty/tools/package.scala b/compiler/src/dotty/tools/package.scala index f90355b1fa8e..977805a8877e 100644 --- a/compiler/src/dotty/tools/package.scala +++ b/compiler/src/dotty/tools/package.scala @@ -20,13 +20,6 @@ package object tools { if x == null then None else Some(x.asInstanceOf[T]) end extension - /** Nullable eq and ne. */ - extension [T <: AnyRef](x: T | Null) - inline def eqn (y: T | Null) = - x.asInstanceOf[AnyRef] eq y.asInstanceOf[AnyRef] - - inline def nen(y: T | Null): Boolean = !eqn(y) - object resultWrapper { opaque type WrappedResult[T] = T private[tools] def unwrap[T](x: WrappedResult[T]): T = x diff --git a/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala b/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala index baae40841508..034cbcfcbd09 100644 --- a/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala +++ b/compiler/test/dotty/tools/backend/jvm/DottyBytecodeTest.scala @@ -149,8 +149,8 @@ trait DottyBytecodeTest { val width = isa.map(_.toString.length).max val lineWidth = len.toString.length (1 to len) foreach { line => - val isaPadded = isa.map(_.toString) orElse LazyList.continually("") - val isbPadded = isb.map(_.toString) orElse LazyList.continually("") + val isaPadded = isa.map(_.toString) `orElse` LazyList.continually("") + val isbPadded = isb.map(_.toString) `orElse` LazyList.continually("") val a = isaPadded(line-1) val b = isbPadded(line-1) diff --git a/compiler/test/dotty/tools/dotc/parsing/DocstringTest.scala b/compiler/test/dotty/tools/dotc/parsing/DocstringTest.scala index 829f71660fc0..83aed6976bce 100644 --- a/compiler/test/dotty/tools/dotc/parsing/DocstringTest.scala +++ b/compiler/test/dotty/tools/dotc/parsing/DocstringTest.scala @@ -27,7 +27,7 @@ trait DocstringTest extends DottyTest { def checkFrontend(source: String)(docAssert: PartialFunction[Tree[Untyped], Unit]): Unit = { checkCompile("typer", source) { (_, ctx) => implicit val c: Context = ctx - (docAssert orElse defaultAssertion)(ctx.compilationUnit.untpdTree) + (docAssert `orElse` defaultAssertion)(ctx.compilationUnit.untpdTree) } } } From 3b5c510f43fa65d23b6453ee980d72b15b00d808 Mon Sep 17 00:00:00 2001 From: odersky Date: Mon, 22 Sep 2025 12:15:33 +0200 Subject: [PATCH 3/6] Replace : _* with * Mostly in comments, the rest was already done. --- compiler/src/dotty/tools/dotc/ast/MainProxies.scala | 2 +- compiler/src/dotty/tools/dotc/ast/TreeInfo.scala | 2 +- compiler/src/dotty/tools/dotc/ast/untpd.scala | 2 +- compiler/src/dotty/tools/dotc/config/PathResolver.scala | 2 +- compiler/src/dotty/tools/dotc/core/Definitions.scala | 2 +- compiler/src/dotty/tools/dotc/profile/FileUtils.scala | 2 +- compiler/src/dotty/tools/dotc/typer/Applications.scala | 2 +- compiler/src/dotty/tools/dotc/typer/Typer.scala | 2 +- compiler/src/scala/quoted/runtime/impl/QuoteMatcher.scala | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala index 9ed19c93d1ba..8d5cd8d5d689 100644 --- a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala +++ b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala @@ -25,7 +25,7 @@ object MainProxies { * try * f( * parseArgument[S](args, 0), - * parseRemainingArguments[T](args, 1): _* + * parseRemainingArguments[T](args, 1)* * ) * catch case err: ParseError => showError(err) * } diff --git a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala index 5415a6e10609..94ef61c5d4bf 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala @@ -245,7 +245,7 @@ trait TreeInfo[T <: Untyped] { self: Trees.Instance[T] => def allParamSyms(ddef: DefDef)(using Context): List[Symbol] = ddef.paramss.flatten.map(_.symbol) - /** Does this argument list end with an argument of the form : _* ? */ + /** Does this argument list end with an argument of the form * ? */ def isWildcardStarArgList(trees: List[Tree])(using Context): Boolean = trees.nonEmpty && isWildcardStarArg(trees.last) diff --git a/compiler/src/dotty/tools/dotc/ast/untpd.scala b/compiler/src/dotty/tools/dotc/ast/untpd.scala index 3e4ecee8200f..a7e99ed2cdeb 100644 --- a/compiler/src/dotty/tools/dotc/ast/untpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/untpd.scala @@ -616,7 +616,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { case _ => Ident(tree.name) } - /** A repeated argument such as `arg: _*` */ + /** A repeated argument such as `arg*` */ def repeated(arg: Tree)(using Context): Typed = Typed(arg, Ident(tpnme.WILDCARD_STAR)) diff --git a/compiler/src/dotty/tools/dotc/config/PathResolver.scala b/compiler/src/dotty/tools/dotc/config/PathResolver.scala index 68960d5134ba..e21d452c4b76 100644 --- a/compiler/src/dotty/tools/dotc/config/PathResolver.scala +++ b/compiler/src/dotty/tools/dotc/config/PathResolver.scala @@ -110,7 +110,7 @@ object PathResolver { // scalaLibDirFound match { // case Some(dir) if scalaHomeExists => // val paths = ClassPath expandDir dir.path - // join(paths: _*) + // join(paths*) // case _ => "" // } diff --git a/compiler/src/dotty/tools/dotc/core/Definitions.scala b/compiler/src/dotty/tools/dotc/core/Definitions.scala index 8906fa2fd263..365969d2f74e 100644 --- a/compiler/src/dotty/tools/dotc/core/Definitions.scala +++ b/compiler/src/dotty/tools/dotc/core/Definitions.scala @@ -399,7 +399,7 @@ class Definitions { * meth8(1) // OK (creates a primitive array and copies it into a reference array at Erasure) * val ai = Array[Int](1) * meth7(ai: _*) // OK (will copy the array at Erasure) - * meth8(ai: _*) // OK (will copy the array at Erasure) + * meth8(ai*) // OK (will copy the array at Erasure) * * Java repeated arguments are erased to arrays, so it would be safe to treat * them in the same way: add an `& Object` to the parameter type to disallow diff --git a/compiler/src/dotty/tools/dotc/profile/FileUtils.scala b/compiler/src/dotty/tools/dotc/profile/FileUtils.scala index 180eecbe5587..28507d08bcd3 100644 --- a/compiler/src/dotty/tools/dotc/profile/FileUtils.scala +++ b/compiler/src/dotty/tools/dotc/profile/FileUtils.scala @@ -33,7 +33,7 @@ import compiletime.uninitialized object FileUtils { def newAsyncBufferedWriter(path: Path, charset: Charset = StandardCharsets.UTF_8.nn, options: Array[OpenOption] = NO_OPTIONS, threadsafe: Boolean = false): LineWriter = { val encoder: CharsetEncoder = charset.newEncoder - val writer = new OutputStreamWriter(Files.newOutputStream(path, options: _*), encoder) + val writer = new OutputStreamWriter(Files.newOutputStream(path, options*), encoder) newAsyncBufferedWriter(new BufferedWriter(writer), threadsafe) } def newAsyncBufferedWriter(underlying: Writer, threadsafe: Boolean): LineWriter = { diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index 611ca8cf781a..2929749e3f70 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -501,7 +501,7 @@ trait Applications extends Compatibility { */ protected def addArg(arg: TypedArg, formal: Type): Unit - /** Is this an argument of the form `expr: _*` or a RepeatedParamType + /** Is this an argument of the form `expr*` or a RepeatedParamType * derived from such an argument? */ protected def isVarArg(arg: Arg): Boolean diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 749fefa512db..3462e8455394 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -1307,7 +1307,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer | pt.translateFromRepeated(toArray = true, translateWildcard = true) def typedWildcardStarArgExpr = { - // A sequence argument `xs: _*` can be either a `Seq[T]` or an `Array[_ <: T]`, + // A sequence argument `xs*` can be either a `Seq[T]` or an `Array[_ <: T]`, // irrespective of whether the method we're calling is a Java or Scala method, // so the expected type is the union `Seq[T] | Array[_ <: T]`. val ptArg = fromRepeated(pt) diff --git a/compiler/src/scala/quoted/runtime/impl/QuoteMatcher.scala b/compiler/src/scala/quoted/runtime/impl/QuoteMatcher.scala index 221bcfc71c91..e4a17e04a7d1 100644 --- a/compiler/src/scala/quoted/runtime/impl/QuoteMatcher.scala +++ b/compiler/src/scala/quoted/runtime/impl/QuoteMatcher.scala @@ -88,7 +88,7 @@ import dotty.tools.dotc.ast.TreeTypeMap * '{ e.super } =?= '{ p.super } ===> '{e} =?= '{p} * * /* Match varargs */ - * '{ e: _* } =?= '{ p: _* } ===> '{e} =?= '{p} + * '{ e* } =?= '{ p* } ===> '{e} =?= '{p} * * /* Match val */ * '{ val x: T = e1; e2 } =?= '{ val y: P = p1; p2 } ===> withEnv(x -> y)('[T] =?= '[P] &&& '{e1} =?= '{p1} &&& '{e2} =?= '{p2}) From 2cd2472faa991c4fa8eabd580963124cb873f06f Mon Sep 17 00:00:00 2001 From: odersky Date: Mon, 22 Sep 2025 14:04:58 +0200 Subject: [PATCH 4/6] Remove warnings in rest of compiler codebase Still todo: remove warnings in shaded modules --- .../tools/backend/jvm/BCodeBodyBuilder.scala | 86 +++++++------- .../tools/backend/jvm/BCodeHelpers.scala | 8 +- .../tools/backend/jvm/BCodeSkelBuilder.scala | 4 +- .../tools/backend/jvm/BCodeSyncAndTry.scala | 16 +-- .../tools/backend/jvm/BackendUtils.scala | 2 +- .../tools/backend/jvm/ClassfileWriters.scala | 5 +- .../tools/backend/jvm/scalaPrimitives.scala | 2 +- .../dotty/tools/backend/sjs/JSCodeGen.scala | 28 ++--- .../tools/backend/sjs/JSExportsGen.scala | 8 +- .../tools/backend/sjs/JSPrimitives.scala | 2 +- compiler/src/dotty/tools/dotc/Resident.scala | 2 +- .../src/dotty/tools/dotc/ast/Desugar.scala | 11 +- .../src/dotty/tools/dotc/ast/Positioned.scala | 20 ++-- .../src/dotty/tools/dotc/ast/TreeInfo.scala | 9 +- .../dotty/tools/dotc/ast/TreeTypeMap.scala | 6 +- compiler/src/dotty/tools/dotc/ast/Trees.scala | 106 +++++++++--------- compiler/src/dotty/tools/dotc/ast/tpd.scala | 42 ++++--- compiler/src/dotty/tools/dotc/ast/untpd.scala | 44 ++++---- .../src/dotty/tools/dotc/cc/Capability.scala | 2 +- .../dotc/classpath/ClassPathFactory.scala | 8 +- .../dotty/tools/dotc/config/CliCommand.scala | 2 +- .../tools/dotc/config/JavaPlatform.scala | 14 +-- .../dotty/tools/dotc/config/OutputDirs.scala | 9 +- .../tools/dotc/config/PathResolver.scala | 2 +- .../dotty/tools/dotc/config/Properties.scala | 12 +- .../tools/dotc/config/ScalaSettings.scala | 16 +-- .../dotty/tools/dotc/config/Settings.scala | 2 +- .../tools/dotc/core/CheckRealizable.scala | 2 +- .../src/dotty/tools/dotc/core/Comments.scala | 11 +- .../tools/dotc/core/ConstraintHandling.scala | 4 +- .../src/dotty/tools/dotc/core/Contexts.scala | 2 +- .../dotty/tools/dotc/core/Denotations.scala | 10 +- .../src/dotty/tools/dotc/core/NameOps.scala | 6 +- .../src/dotty/tools/dotc/core/Periods.scala | 2 +- .../src/dotty/tools/dotc/core/Signature.scala | 2 +- .../dotty/tools/dotc/core/Substituters.scala | 2 +- .../tools/dotc/core/SymDenotations.scala | 16 ++- .../dotty/tools/dotc/core/SymbolLoaders.scala | 4 +- .../dotty/tools/dotc/core/TypeComparer.scala | 19 ++-- .../src/dotty/tools/dotc/core/TypeEval.scala | 4 +- .../src/dotty/tools/dotc/core/TypeOps.scala | 4 +- .../dotc/core/classfile/ClassfileParser.scala | 4 +- .../core/unpickleScala2/Scala2Unpickler.scala | 10 +- .../decompiler/DecompilationPrinter.scala | 2 +- .../dotty/tools/dotc/inlines/Inliner.scala | 2 +- .../dotty/tools/dotc/inlines/Inlines.scala | 12 +- .../tools/dotc/parsing/JavaParsers.scala | 6 +- .../dotty/tools/dotc/parsing/Parsers.scala | 2 +- .../dotc/parsing/xml/MarkupParserCommon.scala | 4 +- .../dotc/parsing/xml/SymbolicXMLBuilder.scala | 2 +- .../src/dotty/tools/dotc/plugins/Plugin.scala | 7 +- .../dotty/tools/dotc/plugins/Plugins.scala | 21 ++-- .../tools/dotc/printing/PlainPrinter.scala | 12 +- .../dotty/tools/dotc/printing/Printer.scala | 2 +- .../tools/dotc/printing/RefinedPrinter.scala | 33 +++--- .../src/dotty/tools/dotc/printing/Texts.scala | 18 +-- 56 files changed, 347 insertions(+), 346 deletions(-) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala index 1eba6c0b1bf8..41f295d11ef1 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeBodyBuilder.scala @@ -155,11 +155,11 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { stack.pop() (code: @switch) match { - case ADD => bc add resKind - case SUB => bc sub resKind - case MUL => bc mul resKind - case DIV => bc div resKind - case MOD => bc rem resKind + case ADD => bc.add(resKind) + case SUB => bc.sub(resKind) + case MUL => bc.mul(resKind) + case DIV => bc.div(resKind) + case MOD => bc.rem(resKind) case OR | XOR | AND => bc.genPrimitiveLogical(code, resKind) @@ -271,11 +271,11 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { genCond(tree, success, failure, targetIfNoJump = success) // success block markProgramPoint(success) - bc boolconst true - bc goTo after + bc.boolconst(true) + bc.goTo(after) // failure block markProgramPoint(failure) - bc boolconst false + bc.boolconst(false) // after markProgramPoint(after) @@ -501,16 +501,16 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { val stackDiff = stack.heightDiffWrt(targetStackSize) if stackDiff != 0 then if expectedType == UNIT then - bc dropMany stackDiff + bc.dropMany(stackDiff) else val loc = locals.makeTempLocal(expectedType) bc.store(loc.idx, expectedType) - bc dropMany stackDiff + bc.dropMany(stackDiff) bc.load(loc.idx, expectedType) end if - bc goTo label + bc.goTo(label) case LoadDestination.Return => - bc emitRETURN returnType + bc.emitRETURN(returnType) case LoadDestination.Throw => val thrownType = expectedType // `throw null` is valid although scala.Null (as defined in src/libray-aux) isn't a subtype of Throwable. @@ -634,7 +634,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { } locals.store(earlyReturnVar) } - bc goTo nextCleanup + bc.goTo(nextCleanup) shouldEmitCleanup = true } } else { @@ -697,20 +697,20 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { if (l.isPrimitive && r.isPrimitive) genConversion(l, r, cast) else if (l.isPrimitive) { - bc drop l + bc.drop(l) if (cast) { mnode.visitTypeInsn(asm.Opcodes.NEW, jlClassCastExceptionRef.internalName) - bc dup ObjectRef + bc.dup(ObjectRef) emit(asm.Opcodes.ATHROW) } else { - bc boolconst false + bc.boolconst(false) } } else if (r.isPrimitive && cast) { abort(s"Erasure should have added an unboxing operation to prevent this cast. Tree: $t") } else if (r.isPrimitive) { - bc isInstance boxedClassOfPrimitive(r.asPrimitiveBType) + bc.isInstance(boxedClassOfPrimitive(r.asPrimitiveBType)) } else { assert(r.isRef, r) // ensure that it's not a method @@ -737,7 +737,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { } genLoadArguments(args, List.fill(args.size)(INT)) (argsSize /*: @switch*/) match { - case 1 => bc newarray elemKind + case 1 => bc.newarray(elemKind) case _ => val descr = ("[" * argsSize) + elemKind.descriptor // denotes the same as: arrayN(elemKind, argsSize).descriptor mnode.visitMultiANewArrayInsn(descr, argsSize) @@ -792,7 +792,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { case rt: ClassBType => assert(classBTypeFromSymbol(ctor.owner) == rt, s"Symbol ${ctor.owner.showFullName} is different from $rt") mnode.visitTypeInsn(asm.Opcodes.NEW, rt.internalName) - bc dup generatedType + bc.dup(generatedType) stack.push(rt) stack.push(rt) genLoadArguments(args, paramTKs(app)) @@ -888,8 +888,8 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { val elmKind = toTypeKind(elemType) val generatedType = ArrayBType(elmKind) - bc iconst elems.length - bc newarray elmKind + bc.iconst(elems.length) + bc.newarray(elmKind) // during the genLoad below, there is the result, its dup, and the index stack.push(generatedType) @@ -899,10 +899,10 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { var i = 0 var rest = elems while (!rest.isEmpty) { - bc dup generatedType - bc iconst i + bc.dup( generatedType) + bc.iconst( i) genLoad(rest.head, elmKind) - bc astore elmKind + bc.astore( elmKind) rest = rest.tail i = i + 1 } @@ -1070,7 +1070,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { } markProgramPoint(keepGoing) } - bc goTo default + bc.goTo(default) } // emit blocks for common patterns @@ -1111,7 +1111,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { def adapt(from: BType, to: BType): Unit = { if (!from.conformsTo(to)) { to match { - case UNIT => bc drop from + case UNIT => bc.drop(from) case _ => bc.emitT2T(from, to) } } else if (from.isNothingType) { @@ -1174,7 +1174,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { * inserted instead - after all, an expression of type scala.runtime.Null$ can only be null. */ if (lastInsn.getOpcode != asm.Opcodes.ACONST_NULL) { - bc drop from + bc.drop(from) emit(asm.Opcodes.ACONST_NULL) } } @@ -1248,14 +1248,14 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { def genConversion(from: BType, to: BType, cast: Boolean): Unit = { if (cast) { bc.emitT2T(from, to) } else { - bc drop from - bc boolconst (from == to) + bc.drop(from) + bc.boolconst(from == to) } } def genCast(to: RefBType, cast: Boolean): Unit = { - if (cast) { bc checkCast to } - else { bc isInstance to } + if cast then bc.checkCast(to) + else bc.isInstance(to) } /* Is the given symbol a primitive operation? */ @@ -1504,7 +1504,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { } bc.emitIF(op, success) } - if (targetIfNoJump != failure) bc goTo failure + if (targetIfNoJump != failure) bc.goTo(failure) } } @@ -1517,8 +1517,8 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { bc.emitIF(op, success) } else if (tk.isRef) { // REFERENCE(_) | ARRAY(_) (op: @unchecked) match { // references are only compared with EQ and NE - case EQ => bc emitIFNULL success - case NE => bc emitIFNONNULL success + case EQ => bc.emitIFNULL( success) + case NE => bc.emitIFNONNULL(success) } } else { def useCmpG = if (negated) op == GT || op == GE else op == LT || op == LE @@ -1535,7 +1535,7 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { } bc.emitIF(op, success) } - if (targetIfNoJump != failure) bc goTo failure + if (targetIfNoJump != failure) bc.goTo(failure) } } @@ -1663,12 +1663,12 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { val areSameFinals = l.tpe.typeSymbol.is(Final) && r.tpe.typeSymbol.is(Final) && (l.tpe =:= r.tpe) // todo: remove def isMaybeBoxed(sym: Symbol): Boolean = { - (sym == defn.ObjectClass) || - (sym == defn.JavaSerializableClass) || - (sym == defn.ComparableClass) || - (sym derivesFrom defn.BoxedNumberClass) || - (sym derivesFrom defn.BoxedCharClass) || - (sym derivesFrom defn.BoxedBooleanClass) + sym == defn.ObjectClass + || sym == defn.JavaSerializableClass + || sym == defn.ComparableClass + || sym.derivesFrom(defn.BoxedNumberClass) + || sym.derivesFrom(defn.BoxedCharClass) + || sym.derivesFrom(defn.BoxedBooleanClass) } !areSameFinals && isMaybeBoxed(l.tpe.typeSymbol) && isMaybeBoxed(r.tpe.typeSymbol) } @@ -1722,11 +1722,11 @@ trait BCodeBodyBuilder extends BCodeSkelBuilder { genLoad(r, ObjectRef) stack.pop() locals.store(eqEqTempLocal) - bc dup ObjectRef + bc.dup(ObjectRef) genCZJUMP(lNull, lNonNull, Primitives.EQ, ObjectRef, targetIfNoJump = lNull) markProgramPoint(lNull) - bc drop ObjectRef + bc.drop(ObjectRef) locals.load(eqEqTempLocal) genCZJUMP(success, failure, Primitives.EQ, ObjectRef, targetIfNoJump = lNonNull) diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala index ab264fe4889d..61c883e1691f 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala @@ -107,9 +107,9 @@ trait BCodeHelpers extends BCodeIdiomatic { val versionPickle = { val vp = new PickleBuffer(new Array[Byte](16), -1, 0) assert(vp.writeIndex == 0, vp) - vp writeNat PickleFormat.MajorVersion - vp writeNat PickleFormat.MinorVersion - vp writeNat 0 + vp.writeNat(PickleFormat.MajorVersion) + vp.writeNat(PickleFormat.MinorVersion) + vp.writeNat(0) vp } @@ -531,7 +531,7 @@ trait BCodeHelpers extends BCodeIdiomatic { val buffer = mutable.ListBuffer[Symbol]() names.foreach { name => buffer ++= tp.memberBasedOnFlags(name, required, excluded) - .alternatives.sortBy(_.signature)(Signature.lexicographicOrdering).map(_.symbol) + .alternatives.sortBy(_.signature)(using Signature.lexicographicOrdering).map(_.symbol) } buffer.toList } diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala b/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala index 5390626eb2cc..f8185098390a 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeSkelBuilder.scala @@ -598,13 +598,13 @@ trait BCodeSkelBuilder extends BCodeHelpers { case labnode: asm.tree.LabelNode => labnode.getLabel case _ => val pp = new asm.Label - mnode visitLabel pp + mnode.visitLabel(pp) pp } } def markProgramPoint(lbl: asm.Label): Unit = { val skip = (lbl == null) || isAtProgramPoint(lbl) - if (!skip) { mnode visitLabel lbl } + if (!skip) { mnode.visitLabel(lbl) } } def isAtProgramPoint(lbl: asm.Label): Boolean = { def getNonLineNumberNode(a: asm.tree.AbstractInsnNode): asm.tree.AbstractInsnNode = a match { diff --git a/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala b/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala index 4e2ea6dd52b8..aca16707fd0f 100644 --- a/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala +++ b/compiler/src/dotty/tools/backend/jvm/BCodeSyncAndTry.scala @@ -40,7 +40,7 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { /* ------ (1) pushing and entering the monitor, also keeping a reference to it in a local var. ------ */ genLoadQualifier(fun) - bc dup ObjectRef + bc.dup(ObjectRef) locals.store(monitor) emit(asm.Opcodes.MONITORENTER) @@ -68,7 +68,7 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { emit(asm.Opcodes.MONITOREXIT) if (hasResult) { locals.load(monitorResult) } val postHandler = new asm.Label - bc goTo postHandler + bc.goTo(postHandler) /* ------ (4) exception-handler version of monitor-exit code. * Reached upon abrupt termination of (2). @@ -99,7 +99,7 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { * Protected by whatever protects the whole synchronized expression. * ------ */ - mnode visitLabel postHandler + mnode.visitLabel(postHandler) lineNumber(tree) @@ -258,7 +258,7 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { unregisterCleanup(finCleanup) nopIfNeeded(startTryBody) val endTryBody = currProgramPoint() - bc goTo postHandlers + bc.goTo(postHandlers) /** * A return within a `try` or `catch` block where a `finally` is present ("early return") @@ -305,7 +305,7 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { registerCleanup(finCleanup) ch match { case NamelessEH(typeToDrop, caseBody) => - bc drop typeToDrop + bc.drop(typeToDrop) genLoad(caseBody, kind) // adapts caseBody to `kind`, thus it can be stored, if `guardResult`, in `tmp`. nopIfNeeded(startHandler) endHandler = currProgramPoint() @@ -326,7 +326,7 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { // (2.b) mark the try-body as protected by this case clause. protect(startTryBody, endTryBody, startHandler, excType) // (2.c) emit jump to the program point where the finally-clause-for-normal-exit starts, or in effect `after` if no finally-clause was given. - bc goTo postHandlers + bc.goTo(postHandlers) } @@ -434,12 +434,12 @@ trait BCodeSyncAndTry extends BCodeBodyBuilder { locals.load(earlyReturnVar) bc.emitRETURN(locals(earlyReturnVar).tk) } else { - bc emitRETURN UNIT + bc.emitRETURN(UNIT) } shouldEmitCleanup = false case nextCleanup :: _ => - bc goTo nextCleanup + bc.goTo(nextCleanup) } } diff --git a/compiler/src/dotty/tools/backend/jvm/BackendUtils.scala b/compiler/src/dotty/tools/backend/jvm/BackendUtils.scala index dac019e985ef..653fa3e7bbdb 100644 --- a/compiler/src/dotty/tools/backend/jvm/BackendUtils.scala +++ b/compiler/src/dotty/tools/backend/jvm/BackendUtils.scala @@ -155,7 +155,7 @@ class BackendUtils(val postProcessor: PostProcessor) { */ final def addInnerClasses(jclass: asm.ClassVisitor, declaredInnerClasses: List[ClassBType], refedInnerClasses: List[ClassBType]): Unit = { // sorting ensures nested classes are listed after their enclosing class thus satisfying the Eclipse Java compiler - val allNestedClasses = new mutable.TreeSet[ClassBType]()(Ordering.by(_.internalName)) + val allNestedClasses = new mutable.TreeSet[ClassBType]()(using Ordering.by(_.internalName)) allNestedClasses ++= declaredInnerClasses refedInnerClasses.foreach(allNestedClasses ++= _.enclosingNestedClassesChain) for nestedClass <- allNestedClasses diff --git a/compiler/src/dotty/tools/backend/jvm/ClassfileWriters.scala b/compiler/src/dotty/tools/backend/jvm/ClassfileWriters.scala index 26531fbfe569..5a32363e5fda 100644 --- a/compiler/src/dotty/tools/backend/jvm/ClassfileWriters.scala +++ b/compiler/src/dotty/tools/backend/jvm/ClassfileWriters.scala @@ -272,8 +272,9 @@ class ClassfileWriters(frontendAccess: PostProcessorFrontendAccess) { else throw new FileConflictException(s"${base.path}/${path}: ${dir.path} is not a directory") val components = path.split('/') var dir = base - for (i <- 0 until components.length - 1) dir = ensureDirectory(dir) subdirectoryNamed components(i).toString - ensureDirectory(dir) fileNamed components.last.toString + for i <- 0 until components.length - 1 do + dir = ensureDirectory(dir).subdirectoryNamed(components(i).toString) + ensureDirectory(dir).fileNamed(components.last.toString) } private def writeBytes(outFile: AbstractFile, bytes: Array[Byte]): Unit = { diff --git a/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala b/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala index 262b5df43362..9348093533ca 100644 --- a/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala +++ b/compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala @@ -127,7 +127,7 @@ class DottyPrimitives(ictx: Context) { /** Add a primitive operation to the map */ def addPrimitive(s: Symbol, code: Int): Unit = { - assert(!(primitives contains s), "Duplicate primitive " + s) + assert(!primitives.contains(s), "Duplicate primitive " + s) primitives(s) = code } diff --git a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala index edaaca86ce67..67b1ece3a1a9 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala @@ -922,7 +922,7 @@ class JSCodeGen()(using genCtx: Context) { else irTpe0 if (isJSClass && f.isJSExposed) - fieldDefs += js.JSFieldDef(flags, genExpr(f.jsName)(f.sourcePos), irTpe) + fieldDefs += js.JSFieldDef(flags, genExpr(f.jsName)(using f.sourcePos), irTpe) else val fieldIdent = encodeFieldSym(f) val originalName = originalNameOfField(f) @@ -1082,7 +1082,7 @@ class JSCodeGen()(using genCtx: Context) { } yield { val sym = vparam.symbol val tpe = toIRType(sym.info) - js.VarDef(encodeLocalSym(sym), originalNameOfLocal(sym), tpe, mutable = true, jstpe.zeroOf(tpe))(vparam.span) + js.VarDef(encodeLocalSym(sym), originalNameOfLocal(sym), tpe, mutable = true, jstpe.zeroOf(tpe))(using vparam.span) } /* organize constructors in a called-by tree @@ -1222,10 +1222,10 @@ class JSCodeGen()(using genCtx: Context) { * +=: prepends to the ListBuffer in O(1) -- yes, it's a cryptic name. */ if (isStaticModule(currentClassSym)) - js.StoreModule()(jsSuperCall.get.pos) +=: postSuperStats + js.StoreModule()(using jsSuperCall.get.pos) +=: postSuperStats new PrimaryJSCtor(sym, genParamsAndInfo(sym, dd.paramss), - js.JSConstructorBody(preSuperStats.result(), jsSuperCall.get, postSuperStats.result())(dd.span)) + js.JSConstructorBody(preSuperStats.result(), jsSuperCall.get, postSuperStats.result())(using dd.span)) } private def genSecondaryJSClassCtor(dd: DefDef): SplitSecondaryJSCtor = { @@ -1433,7 +1433,7 @@ class JSCodeGen()(using genCtx: Context) { private def wrapJSCtorBody(before: List[js.Tree], body: js.JSConstructorBody, after: List[js.Tree]): js.JSConstructorBody = { js.JSConstructorBody(before ::: body.beforeSuper, body.superCall, - body.afterSuper ::: after)(body.pos) + body.afterSuper ::: after)(using body.pos) } private sealed trait JSCtor { @@ -2337,7 +2337,7 @@ class JSCodeGen()(using genCtx: Context) { } { jsClassVal => // Nested JS class if (cls.isAnonymousClass) - genNewAnonJSClass(cls, jsClassVal, genArgsAsClassCaptures)(fun.span) + genNewAnonJSClass(cls, jsClassVal, genArgsAsClassCaptures)(using fun.span) else if (atPhase(erasurePhase)(cls.is(ModuleClass))) // LambdaLift removes the ModuleClass flag of lifted classes js.JSNew(js.CreateJSClass(encodeClassName(cls), jsClassVal :: genArgsAsClassCaptures), Nil) else @@ -2422,7 +2422,7 @@ class JSCodeGen()(using genCtx: Context) { * class capture. It seems Scala 2 has the same vulnerability. How do we * avoid this? */ - val selfIdent = freshLocalIdent("this")(pos) + val selfIdent = freshLocalIdent("this")(using pos) def selfRef(implicit pos: ir.Position) = js.VarRef(selfIdent.name)(jstpe.AnyType) @@ -2530,7 +2530,7 @@ class JSCodeGen()(using genCtx: Context) { val afterSuper = new ir.Transformers.LocalScopeTransformer { override def transform(tree: js.Tree): js.Tree = tree match { case js.This() => - selfRef(tree.pos) + selfRef(using tree.pos) case tree => super.transform(tree) } @@ -3088,7 +3088,7 @@ class JSCodeGen()(using genCtx: Context) { genApplyStatic(sym, genActualArgs(sym, args)) } else if (sym.owner.isJSType) { if (!sym.owner.isNonNativeJSClass || sym.isJSExposed) - genApplyJSMethodGeneric(sym, genExprOrGlobalScope(receiver), genActualJSArgs(sym, args), isStat)(tree.sourcePos) + genApplyJSMethodGeneric(sym, genExprOrGlobalScope(receiver), genActualJSArgs(sym, args), isStat)(using tree.sourcePos) else genApplyJSClassMethod(genExpr(receiver), sym, genActualArgs(sym, args)) } else if (sym.hasAnnotation(jsdefn.JSNativeAnnot)) { @@ -3290,7 +3290,7 @@ class JSCodeGen()(using genCtx: Context) { Some(genLoadJSConstructor(currentClassSym.get.asClass.superClass)) } genApplyJSMethodGeneric(sym, MaybeGlobalScope.NotGlobalScope(genReceiver), - genJSArgs, isStat, jsSuperClassValue)(tree.sourcePos) + genJSArgs, isStat, jsSuperClassValue)(using tree.sourcePos) } } } @@ -3554,7 +3554,7 @@ class JSCodeGen()(using genCtx: Context) { val formalParam = js.ParamDef(freshLocalIdent(name), OriginalName(name.toString), formalTpe, mutable = false) val actualParam = - if (repeated) genJSArrayToVarArgs(formalParam.ref)(tree.sourcePos) + if (repeated) genJSArrayToVarArgs(formalParam.ref)(using tree.sourcePos) else unbox(formalParam.ref, tpe) (formalParam, actualParam) } @@ -3595,7 +3595,7 @@ class JSCodeGen()(using genCtx: Context) { js.Block( js.VarDef(thisParam.name, thisParam.originalName, thisParam.ptpe, mutable = false, - js.This()(thisParam.ptpe)(thisParam.pos))(thisParam.pos), + js.This()(thisParam.ptpe)(using thisParam.pos))(using thisParam.pos), genBody), actualCaptures) } else { @@ -4375,7 +4375,7 @@ class JSCodeGen()(using genCtx: Context) { val actualArgs = actualArgsAnyArray.elems.zip(formalParamTypesAndTypeRefs).map { (actualArgAny, formalParamTypeAndTypeRef) => val genActualArgAny = genExpr(actualArgAny) - genAsInstanceOf(genActualArgAny, formalParamTypeAndTypeRef._1)(genActualArgAny.pos) + genAsInstanceOf(genActualArgAny, formalParamTypeAndTypeRef._1)(using genActualArgAny.pos) } (formalParamTypesAndTypeRefs.map(pair => toParamOrResultTypeRef(pair._2)), actualArgs) @@ -4749,7 +4749,7 @@ class JSCodeGen()(using genCtx: Context) { case MaybeGlobalScope.NotGlobalScope(t) => t case MaybeGlobalScope.GlobalScope(pos) => - reportErrorLoadGlobalScope()(pos) + reportErrorLoadGlobalScope()(using pos) } } diff --git a/compiler/src/dotty/tools/backend/sjs/JSExportsGen.scala b/compiler/src/dotty/tools/backend/sjs/JSExportsGen.scala index 425710c6be9a..01fbf980fe12 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSExportsGen.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSExportsGen.scala @@ -318,7 +318,7 @@ final class JSExportsGen(jsCodeGen: JSCodeGen)(using Context) { em"Conflicting properties and methods for ${classSym.fullName}::$name.", firstAlt.srcPos) implicit val pos = firstAlt.span - js.JSPropertyDef(js.MemberFlags.empty, genExpr(name)(firstAlt.sourcePos), None, None)(Unversioned) + js.JSPropertyDef(js.MemberFlags.empty, genExpr(name)(using firstAlt.sourcePos), None, None)(Unversioned) } else { genMemberExportOrDispatcher(name, isProp, alts, static = false) } @@ -369,7 +369,7 @@ final class JSExportsGen(jsCodeGen: JSCodeGen)(using Context) { } } - js.JSPropertyDef(flags, genExpr(jsName)(alts.head.sourcePos), getterBody, setterArgAndBody)(Unversioned) + js.JSPropertyDef(flags, genExpr(jsName)(using alts.head.sourcePos), getterBody, setterArgAndBody)(Unversioned) } private def genExportMethod(alts0: List[Symbol], jsName: JSName, static: Boolean)(using Context): js.JSMethodDef = { @@ -974,10 +974,10 @@ final class JSExportsGen(jsCodeGen: JSCodeGen)(using Context) { class FormalArgsRegistry(val minArgc: Int, needsRestParam: Boolean) { private val fixedParamNames: scala.collection.immutable.IndexedSeq[jsNames.LocalName] = - (0 until minArgc).toIndexedSeq.map(_ => freshLocalIdent("arg")(NoPosition).name) + (0 until minArgc).toIndexedSeq.map(_ => freshLocalIdent("arg")(using NoPosition).name) private val restParamName: jsNames.LocalName = - if (needsRestParam) freshLocalIdent("rest")(NoPosition).name + if (needsRestParam) freshLocalIdent("rest")(using NoPosition).name else null def genFormalArgs()(implicit pos: Position): (List[js.ParamDef], Option[js.ParamDef]) = { diff --git a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala index 606916ca4b6e..ef594baf0af3 100644 --- a/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala +++ b/compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala @@ -90,7 +90,7 @@ class JSPrimitives(ictx: Context) extends DottyPrimitives(ictx) { // !!! Code duplicate with DottyPrimitives /** Add a primitive operation to the map */ def addPrimitive(s: Symbol, code: Int): Unit = { - assert(!(primitives contains s), "Duplicate primitive " + s) + assert(!primitives.contains(s), "Duplicate primitive " + s) primitives(s) = code } diff --git a/compiler/src/dotty/tools/dotc/Resident.scala b/compiler/src/dotty/tools/dotc/Resident.scala index 481d321773c6..5912825f712e 100644 --- a/compiler/src/dotty/tools/dotc/Resident.scala +++ b/compiler/src/dotty/tools/dotc/Resident.scala @@ -52,7 +52,7 @@ class Resident extends Driver { line = getLine() } if line.startsWith(quit) then ctx.reporter - else loop((line split "\\s+").asInstanceOf[Array[String]], nextCtx) + else loop((line.split("\\s+")).asInstanceOf[Array[String]], nextCtx) case None => prevCtx.reporter } diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index 225f12de67c6..ba7b9132e88a 100644 --- a/compiler/src/dotty/tools/dotc/ast/Desugar.scala +++ b/compiler/src/dotty/tools/dotc/ast/Desugar.scala @@ -150,25 +150,22 @@ object desugar { * accessor of a type parameter is a private type alias that cannot be accessed * from subclasses. */ - def derivedTree(sym: Symbol)(using Context): tpd.TypeTree = { - val relocate = new TypeMap { + def derivedTree(sym: Symbol)(using Context): tpd.TypeTree = + val relocate = new TypeMap: val originalOwner = sym.owner def apply(tp: Type) = tp match { case tp: NamedType if tp.symbol.exists && (tp.symbol.owner eq originalOwner) => val defctx = mapCtx.outersIterator.dropWhile(_.scope eq mapCtx.scope).next() var local = defctx.denotNamed(tp.name).suchThat(_.isParamOrAccessor).symbol - if (local.exists) (defctx.owner.thisType select local).dealiasKeepAnnots - else { + if local.exists then defctx.owner.thisType.select(local).dealiasKeepAnnots + else def msg = em"no matching symbol for ${tp.symbol.showLocated} in ${defctx.owner} / ${defctx.effectiveScope.toList}" ErrorType(msg).assertingErrorsReported(msg) - } case _ => mapOver(tp) } - } tpd.TypeTree(relocate(sym.info)) - } } /** A type definition copied from `tdef` with a rhs typetree derived from it */ diff --git a/compiler/src/dotty/tools/dotc/ast/Positioned.scala b/compiler/src/dotty/tools/dotc/ast/Positioned.scala index 5b57733eaeb1..5475935ba918 100644 --- a/compiler/src/dotty/tools/dotc/ast/Positioned.scala +++ b/compiler/src/dotty/tools/dotc/ast/Positioned.scala @@ -142,8 +142,8 @@ abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Src newpd } - def contains(that: Positioned): Boolean = { - def isParent(x: Any): Boolean = x match { + def contains(that: Positioned): Boolean = + def isParent(x: Any): Boolean = x match case x: Positioned => x.contains(that) case m: untpd.Modifiers => @@ -152,18 +152,18 @@ abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Src xs.exists(isParent) case _ => false - } - (this eq that) || - (this.span contains that.span) && { + + (this eq that) + || this.span.contains(that.span) + && { var n = productArity var found = false - while (!found && n > 0) { + while !found && n > 0 do n -= 1 found = isParent(productElement(n)) - } found - } - } + } + end contains private class LastPosRef: var positioned: Positioned | Null = null @@ -178,7 +178,7 @@ abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Src val last = LastPosRef() def check(p: Any): Unit = p match { case p: Positioned => - assert(span contains p.span, + assert(span.contains(p.span), i"""position error, parent span does not contain child span |parent = $this # $uniqueId, |parent span = $span, diff --git a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala index 94ef61c5d4bf..8c6303d07b9a 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeInfo.scala @@ -561,7 +561,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => | DefDef(_, _, _, _) => Pure case vdef @ ValDef(_, _, _) => - if (vdef.symbol.flags is Mutable) Impure else exprPurity(vdef.rhs) `min` Pure + if vdef.symbol.flags.is(Mutable) then Impure else exprPurity(vdef.rhs) `min` Pure case _ => Impure // TODO: It seem like this should be exprPurity(tree) @@ -849,7 +849,7 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => /** Decompose a template body into parameters and other statements */ def decomposeTemplateBody(body: List[Tree])(using Context): (List[Tree], List[Tree]) = body.partition { - case stat: TypeDef => stat.symbol is Flags.Param + case stat: TypeDef => stat.symbol.is(Flags.Param) case stat: ValOrDefDef => stat.symbol.is(Flags.ParamAccessor) && !stat.symbol.isSetter case _ => false @@ -954,8 +954,9 @@ trait TypedTreeInfo extends TreeInfo[Type] { self: Trees.Instance[Type] => private def isSimpleThrowable(tp: Type)(using Context): Boolean = tp match { case tp @ TypeRef(pre, _) => - (pre == NoPrefix || pre.typeSymbol.isStatic) && - (tp.symbol derivesFrom defn.ThrowableClass) && !tp.symbol.is(Trait) + (pre == NoPrefix || pre.typeSymbol.isStatic) + && tp.symbol.derivesFrom(defn.ThrowableClass) + && !tp.symbol.is(Trait) case _ => false } diff --git a/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala b/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala index 6dd85d730da8..dc8d9c700700 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeTypeMap.scala @@ -33,7 +33,7 @@ import Decorators.* */ class TreeTypeMap( val typeMap: Type => Type = IdentityTypeMap, - val treeMap: tpd.Tree => tpd.Tree = identity _, + val treeMap: tpd.Tree => tpd.Tree = identity, val oldOwners: List[Symbol] = Nil, val newOwners: List[Symbol] = Nil, val substFrom: List[Symbol] = Nil, @@ -103,8 +103,8 @@ class TreeTypeMap( constr = tmap.transformSub(constr), parents = impl.parents.mapconserve(transform), self = tmap.transformSub(self), - body = impl.body mapconserve - (tmap.transform(_)(using ctx.withOwner(mapOwner(impl.symbol.owner)))) + body = impl.body.mapconserve: + tmap.transform(_)(using ctx.withOwner(mapOwner(impl.symbol.owner))) ).withType(tmap.mapType(impl.tpe)) case tree1 => tree1.withType(mapType(tree1.tpe)) match { diff --git a/compiler/src/dotty/tools/dotc/ast/Trees.scala b/compiler/src/dotty/tools/dotc/ast/Trees.scala index d144703efeb7..ef64a025805a 100644 --- a/compiler/src/dotty/tools/dotc/ast/Trees.scala +++ b/compiler/src/dotty/tools/dotc/ast/Trees.scala @@ -125,7 +125,7 @@ object Trees { (if (myTpe == null || (myTpe.asInstanceOf[AnyRef] eq tpe.asInstanceOf[AnyRef])) this else cloneIn(source)).asInstanceOf[Tree[Type]] - tree overwriteType tpe + tree.overwriteType(tpe) tree.asInstanceOf[ThisTree[Type]] } @@ -1061,7 +1061,7 @@ object Trees { if (trees eq newTrees) this else - Thicket[U](newTrees)(source).asInstanceOf[this.type] + Thicket[U](newTrees)(using source).asInstanceOf[this.type] } override def foreachInThicket(op: Tree[T] => Unit): Unit = @@ -1080,13 +1080,13 @@ object Trees { mapElems(_.withSpan(span)).asInstanceOf[this.type] } - class EmptyTree[T <: Untyped] extends Thicket(Nil)(NoSource) { + class EmptyTree[T <: Untyped] extends Thicket(Nil)(using NoSource) { // assert(uniqueId != 1492) override def withSpan(span: Span) = throw AssertionError("Cannot change span of EmptyTree") } class EmptyValDef[T <: Untyped] extends ValDef[T]( - nme.WILDCARD, genericEmptyTree[T], genericEmptyTree[T])(NoSource) with WithoutTypeOrPos[T] { + nme.WILDCARD, genericEmptyTree[T], genericEmptyTree[T])(using NoSource) with WithoutTypeOrPos[T] { myTpe = NoType.asInstanceOf[T] setMods(untpd.Modifiers(PrivateLocal)) override def isEmpty: Boolean = true @@ -1270,7 +1270,7 @@ object Trees { def Ident(tree: Tree)(name: Name)(using Context): Ident = tree match { case tree: Ident if name == tree.name => tree - case _ => finalize(tree, untpd.Ident(name)(sourceFile(tree))) + case _ => finalize(tree, untpd.Ident(name)(using sourceFile(tree))) } def Select(tree: Tree)(qualifier: Tree, name: Name)(using Context): Select = tree match { case tree: Select if (qualifier eq tree.qualifier) && (name == tree.name) => tree @@ -1287,86 +1287,86 @@ object Trees { } def This(tree: Tree)(qual: untpd.Ident)(using Context): This = tree match { case tree: This if (qual eq tree.qual) => tree - case _ => finalize(tree, untpd.This(qual)(sourceFile(tree))) + case _ => finalize(tree, untpd.This(qual)(using sourceFile(tree))) } def Super(tree: Tree)(qual: Tree, mix: untpd.Ident)(using Context): Super = tree match { case tree: Super if (qual eq tree.qual) && (mix eq tree.mix) => tree - case _ => finalize(tree, untpd.Super(qual, mix)(sourceFile(tree))) + case _ => finalize(tree, untpd.Super(qual, mix)(using sourceFile(tree))) } def Apply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): Apply = tree match { case tree: Apply if (fun eq tree.fun) && (args eq tree.args) => tree - case _ => finalize(tree, untpd.Apply(fun, args)(sourceFile(tree))) + case _ => finalize(tree, untpd.Apply(fun, args)(using sourceFile(tree))) //.ensuring(res => res.uniqueId != 2213, s"source = $tree, ${tree.uniqueId}, ${tree.span}") } def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(using Context): TypeApply = tree match { case tree: TypeApply if (fun eq tree.fun) && (args eq tree.args) => tree - case _ => finalize(tree, untpd.TypeApply(fun, args)(sourceFile(tree))) + case _ => finalize(tree, untpd.TypeApply(fun, args)(using sourceFile(tree))) } def Literal(tree: Tree)(const: Constant)(using Context): Literal = tree match { case tree: Literal if const == tree.const => tree - case _ => finalize(tree, untpd.Literal(const)(sourceFile(tree))) + case _ => finalize(tree, untpd.Literal(const)(using sourceFile(tree))) } def New(tree: Tree)(tpt: Tree)(using Context): New = tree match { case tree: New if (tpt eq tree.tpt) => tree - case _ => finalize(tree, untpd.New(tpt)(sourceFile(tree))) + case _ => finalize(tree, untpd.New(tpt)(using sourceFile(tree))) } def Typed(tree: Tree)(expr: Tree, tpt: Tree)(using Context): Typed = tree match { case tree: Typed if (expr eq tree.expr) && (tpt eq tree.tpt) => tree - case tree => finalize(tree, untpd.Typed(expr, tpt)(sourceFile(tree))) + case tree => finalize(tree, untpd.Typed(expr, tpt)(using sourceFile(tree))) } def NamedArg(tree: Tree)(name: Name, arg: Tree)(using Context): NamedArg = tree match { case tree: NamedArg if (name == tree.name) && (arg eq tree.arg) => tree - case _ => finalize(tree, untpd.NamedArg(name, arg)(sourceFile(tree))) + case _ => finalize(tree, untpd.NamedArg(name, arg)(using sourceFile(tree))) } def Assign(tree: Tree)(lhs: Tree, rhs: Tree)(using Context): Assign = tree match { case tree: Assign if (lhs eq tree.lhs) && (rhs eq tree.rhs) => tree - case _ => finalize(tree, untpd.Assign(lhs, rhs)(sourceFile(tree))) + case _ => finalize(tree, untpd.Assign(lhs, rhs)(using sourceFile(tree))) } def Block(tree: Tree)(stats: List[Tree], expr: Tree)(using Context): Block = tree match { case tree: Block if (stats eq tree.stats) && (expr eq tree.expr) => tree - case _ => finalize(tree, untpd.Block(stats, expr)(sourceFile(tree))) + case _ => finalize(tree, untpd.Block(stats, expr)(using sourceFile(tree))) } def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(using Context): If = tree match { case tree: If if (cond eq tree.cond) && (thenp eq tree.thenp) && (elsep eq tree.elsep) => tree - case tree: InlineIf => finalize(tree, untpd.InlineIf(cond, thenp, elsep)(sourceFile(tree))) - case _ => finalize(tree, untpd.If(cond, thenp, elsep)(sourceFile(tree))) + case tree: InlineIf => finalize(tree, untpd.InlineIf(cond, thenp, elsep)(using sourceFile(tree))) + case _ => finalize(tree, untpd.If(cond, thenp, elsep)(using sourceFile(tree))) } def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(using Context): Closure = tree match { case tree: Closure if (env eq tree.env) && (meth eq tree.meth) && (tpt eq tree.tpt) => tree - case _ => finalize(tree, untpd.Closure(env, meth, tpt)(sourceFile(tree))) + case _ => finalize(tree, untpd.Closure(env, meth, tpt)(using sourceFile(tree))) } def Match(tree: Tree)(selector: Tree, cases: List[CaseDef])(using Context): Match = tree match { case tree: Match if (selector eq tree.selector) && (cases eq tree.cases) => tree - case tree: InlineMatch => finalize(tree, untpd.InlineMatch(selector, cases)(sourceFile(tree))) - case tree: SubMatch => finalize(tree, untpd.SubMatch(selector, cases)(sourceFile(tree))) - case _ => finalize(tree, untpd.Match(selector, cases)(sourceFile(tree))) + case tree: InlineMatch => finalize(tree, untpd.InlineMatch(selector, cases)(using sourceFile(tree))) + case tree: SubMatch => finalize(tree, untpd.SubMatch(selector, cases)(using sourceFile(tree))) + case _ => finalize(tree, untpd.Match(selector, cases)(using sourceFile(tree))) } def CaseDef(tree: Tree)(pat: Tree, guard: Tree, body: Tree)(using Context): CaseDef = tree match { case tree: CaseDef if (pat eq tree.pat) && (guard eq tree.guard) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.CaseDef(pat, guard, body)(sourceFile(tree))) + case _ => finalize(tree, untpd.CaseDef(pat, guard, body)(using sourceFile(tree))) } def Labeled(tree: Tree)(bind: Bind, expr: Tree)(using Context): Labeled = tree match { case tree: Labeled if (bind eq tree.bind) && (expr eq tree.expr) => tree - case _ => finalize(tree, untpd.Labeled(bind, expr)(sourceFile(tree))) + case _ => finalize(tree, untpd.Labeled(bind, expr)(using sourceFile(tree))) } def Return(tree: Tree)(expr: Tree, from: Tree)(using Context): Return = tree match { case tree: Return if (expr eq tree.expr) && (from eq tree.from) => tree - case _ => finalize(tree, untpd.Return(expr, from)(sourceFile(tree))) + case _ => finalize(tree, untpd.Return(expr, from)(using sourceFile(tree))) } def WhileDo(tree: Tree)(cond: Tree, body: Tree)(using Context): WhileDo = tree match { case tree: WhileDo if (cond eq tree.cond) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.WhileDo(cond, body)(sourceFile(tree))) + case _ => finalize(tree, untpd.WhileDo(cond, body)(using sourceFile(tree))) } def Try(tree: Tree)(expr: Tree, cases: List[CaseDef], finalizer: Tree)(using Context): Try = tree match { case tree: Try if (expr eq tree.expr) && (cases eq tree.cases) && (finalizer eq tree.finalizer) => tree - case _ => finalize(tree, untpd.Try(expr, cases, finalizer)(sourceFile(tree))) + case _ => finalize(tree, untpd.Try(expr, cases, finalizer)(using sourceFile(tree))) } def SeqLiteral(tree: Tree)(elems: List[Tree], elemtpt: Tree)(using Context): SeqLiteral = tree match { case tree: JavaSeqLiteral => if ((elems eq tree.elems) && (elemtpt eq tree.elemtpt)) tree else finalize(tree, untpd.JavaSeqLiteral(elems, elemtpt)) case tree: SeqLiteral if (elems eq tree.elems) && (elemtpt eq tree.elemtpt) => tree - case _ => finalize(tree, untpd.SeqLiteral(elems, elemtpt)(sourceFile(tree))) + case _ => finalize(tree, untpd.SeqLiteral(elems, elemtpt)(using sourceFile(tree))) } // Positions of trees are automatically pushed down except when we reach an Inlined tree. Therefore, we // make sure the new expansion has a position by copying the one of the original Inlined tree. @@ -1377,107 +1377,107 @@ object Trees { val expansionWithSpan = if expansion.span.exists then expansion else expansion.withSpan(tree.expansion.span) - finalize(tree, untpd.Inlined(call, bindings, expansionWithSpan)(sourceFile(tree))) + finalize(tree, untpd.Inlined(call, bindings, expansionWithSpan)(using sourceFile(tree))) def Quote(tree: Tree)(body: Tree, tags: List[Tree])(using Context): Quote = tree match { case tree: Quote if (body eq tree.body) && (tags eq tree.tags) => tree - case _ => finalize(tree, untpd.Quote(body, tags)(sourceFile(tree))) + case _ => finalize(tree, untpd.Quote(body, tags)(using sourceFile(tree))) } def Splice(tree: Tree)(expr: Tree)(using Context): Splice = tree match { case tree: Splice if (expr eq tree.expr) => tree - case _ => finalize(tree, untpd.Splice(expr)(sourceFile(tree))) + case _ => finalize(tree, untpd.Splice(expr)(using sourceFile(tree))) } def QuotePattern(tree: Tree)(bindings: List[Tree], body: Tree, quotes: Tree)(using Context): QuotePattern = tree match { case tree: QuotePattern if (bindings eq tree.bindings) && (body eq tree.body) && (quotes eq tree.quotes) => tree - case _ => finalize(tree, untpd.QuotePattern(bindings, body, quotes)(sourceFile(tree))) + case _ => finalize(tree, untpd.QuotePattern(bindings, body, quotes)(using sourceFile(tree))) } def SplicePattern(tree: Tree)(body: Tree, typeargs: List[Tree], args: List[Tree])(using Context): SplicePattern = tree match { case tree: SplicePattern if (body eq tree.body) && (typeargs eq tree.typeargs) & (args eq tree.args) => tree - case _ => finalize(tree, untpd.SplicePattern(body, typeargs, args)(sourceFile(tree))) + case _ => finalize(tree, untpd.SplicePattern(body, typeargs, args)(using sourceFile(tree))) } def SingletonTypeTree(tree: Tree)(ref: Tree)(using Context): SingletonTypeTree = tree match { case tree: SingletonTypeTree if (ref eq tree.ref) => tree - case _ => finalize(tree, untpd.SingletonTypeTree(ref)(sourceFile(tree))) + case _ => finalize(tree, untpd.SingletonTypeTree(ref)(using sourceFile(tree))) } def RefinedTypeTree(tree: Tree)(tpt: Tree, refinements: List[Tree])(using Context): RefinedTypeTree = tree match { case tree: RefinedTypeTree if (tpt eq tree.tpt) && (refinements eq tree.refinements) => tree - case _ => finalize(tree, untpd.RefinedTypeTree(tpt, refinements)(sourceFile(tree))) + case _ => finalize(tree, untpd.RefinedTypeTree(tpt, refinements)(using sourceFile(tree))) } def AppliedTypeTree(tree: Tree)(tpt: Tree, args: List[Tree])(using Context): AppliedTypeTree = tree match { case tree: AppliedTypeTree if (tpt eq tree.tpt) && (args eq tree.args) => tree - case _ => finalize(tree, untpd.AppliedTypeTree(tpt, args)(sourceFile(tree))) + case _ => finalize(tree, untpd.AppliedTypeTree(tpt, args)(using sourceFile(tree))) } def LambdaTypeTree(tree: Tree)(tparams: List[TypeDef], body: Tree)(using Context): LambdaTypeTree = tree match { case tree: LambdaTypeTree if (tparams eq tree.tparams) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.LambdaTypeTree(tparams, body)(sourceFile(tree))) + case _ => finalize(tree, untpd.LambdaTypeTree(tparams, body)(using sourceFile(tree))) } def TermLambdaTypeTree(tree: Tree)(params: List[ValDef], body: Tree)(using Context): TermLambdaTypeTree = tree match { case tree: TermLambdaTypeTree if (params eq tree.params) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.TermLambdaTypeTree(params, body)(sourceFile(tree))) + case _ => finalize(tree, untpd.TermLambdaTypeTree(params, body)(using sourceFile(tree))) } def MatchTypeTree(tree: Tree)(bound: Tree, selector: Tree, cases: List[CaseDef])(using Context): MatchTypeTree = tree match { case tree: MatchTypeTree if (bound eq tree.bound) && (selector eq tree.selector) && (cases eq tree.cases) => tree - case _ => finalize(tree, untpd.MatchTypeTree(bound, selector, cases)(sourceFile(tree))) + case _ => finalize(tree, untpd.MatchTypeTree(bound, selector, cases)(using sourceFile(tree))) } def ByNameTypeTree(tree: Tree)(result: Tree)(using Context): ByNameTypeTree = tree match { case tree: ByNameTypeTree if (result eq tree.result) => tree - case _ => finalize(tree, untpd.ByNameTypeTree(result)(sourceFile(tree))) + case _ => finalize(tree, untpd.ByNameTypeTree(result)(using sourceFile(tree))) } def TypeBoundsTree(tree: Tree)(lo: Tree, hi: Tree, alias: Tree)(using Context): TypeBoundsTree = tree match { case tree: TypeBoundsTree if (lo eq tree.lo) && (hi eq tree.hi) && (alias eq tree.alias) => tree - case _ => finalize(tree, untpd.TypeBoundsTree(lo, hi, alias)(sourceFile(tree))) + case _ => finalize(tree, untpd.TypeBoundsTree(lo, hi, alias)(using sourceFile(tree))) } def Bind(tree: Tree)(name: Name, body: Tree)(using Context): Bind = tree match { case tree: Bind if (name eq tree.name) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.Bind(name, body)(sourceFile(tree))) + case _ => finalize(tree, untpd.Bind(name, body)(using sourceFile(tree))) } def Alternative(tree: Tree)(trees: List[Tree])(using Context): Alternative = tree match { case tree: Alternative if (trees eq tree.trees) => tree - case _ => finalize(tree, untpd.Alternative(trees)(sourceFile(tree))) + case _ => finalize(tree, untpd.Alternative(trees)(using sourceFile(tree))) } def UnApply(tree: Tree)(fun: Tree, implicits: List[Tree], patterns: List[Tree])(using Context): UnApply = tree match { case tree: UnApply if (fun eq tree.fun) && (implicits eq tree.implicits) && (patterns eq tree.patterns) => tree - case _ => finalize(tree, untpd.UnApply(fun, implicits, patterns)(sourceFile(tree))) + case _ => finalize(tree, untpd.UnApply(fun, implicits, patterns)(using sourceFile(tree))) } def ValDef(tree: Tree)(name: TermName, tpt: Tree, rhs: LazyTree)(using Context): ValDef = tree match { case tree: ValDef if (name == tree.name) && (tpt eq tree.tpt) && (rhs eq tree.unforcedRhs) => tree - case _ => finalize(tree, untpd.ValDef(name, tpt, rhs)(sourceFile(tree))) + case _ => finalize(tree, untpd.ValDef(name, tpt, rhs)(using sourceFile(tree))) } def DefDef(tree: Tree)(name: TermName, paramss: List[ParamClause], tpt: Tree, rhs: LazyTree)(using Context): DefDef = tree match { case tree: DefDef if (name == tree.name) && (paramss eq tree.paramss) && (tpt eq tree.tpt) && (rhs eq tree.unforcedRhs) => tree - case _ => finalize(tree, untpd.DefDef(name, paramss, tpt, rhs)(sourceFile(tree))) + case _ => finalize(tree, untpd.DefDef(name, paramss, tpt, rhs)(using sourceFile(tree))) } def TypeDef(tree: Tree)(name: TypeName, rhs: Tree)(using Context): TypeDef = tree match { case tree: TypeDef if (name == tree.name) && (rhs eq tree.rhs) => tree - case _ => finalize(tree, untpd.TypeDef(name, rhs)(sourceFile(tree))) + case _ => finalize(tree, untpd.TypeDef(name, rhs)(using sourceFile(tree))) } def Template(tree: Tree)(constr: DefDef, parents: List[Tree], derived: List[untpd.Tree], self: ValDef, body: LazyTreeList)(using Context): Template = tree match { case tree: Template if (constr eq tree.constr) && (parents eq tree.parents) && (derived eq tree.derived) && (self eq tree.self) && (body eq tree.unforcedBody) => tree - case tree => finalize(tree, untpd.Template(constr, parents, derived, self, body)(sourceFile(tree))) + case tree => finalize(tree, untpd.Template(constr, parents, derived, self, body)(using sourceFile(tree))) } def Import(tree: Tree)(expr: Tree, selectors: List[untpd.ImportSelector])(using Context): Import = tree match { case tree: Import if (expr eq tree.expr) && (selectors eq tree.selectors) => tree - case _ => finalize(tree, untpd.Import(expr, selectors)(sourceFile(tree))) + case _ => finalize(tree, untpd.Import(expr, selectors)(using sourceFile(tree))) } def Export(tree: Tree)(expr: Tree, selectors: List[untpd.ImportSelector])(using Context): Export = tree match { case tree: Export if (expr eq tree.expr) && (selectors eq tree.selectors) => tree - case _ => finalize(tree, untpd.Export(expr, selectors)(sourceFile(tree))) + case _ => finalize(tree, untpd.Export(expr, selectors)(using sourceFile(tree))) } def PackageDef(tree: Tree)(pid: RefTree, stats: List[Tree])(using Context): PackageDef = tree match { case tree: PackageDef if (pid eq tree.pid) && (stats eq tree.stats) => tree - case _ => finalize(tree, untpd.PackageDef(pid, stats)(sourceFile(tree))) + case _ => finalize(tree, untpd.PackageDef(pid, stats)(using sourceFile(tree))) } def Annotated(tree: Tree)(arg: Tree, annot: Tree)(using Context): Annotated = tree match { case tree: Annotated if (arg eq tree.arg) && (annot eq tree.annot) => tree - case _ => finalize(tree, untpd.Annotated(arg, annot)(sourceFile(tree))) + case _ => finalize(tree, untpd.Annotated(arg, annot)(using sourceFile(tree))) } def Thicket(tree: Tree)(trees: List[Tree])(using Context): Thicket = tree match { case tree: Thicket if (trees eq tree.trees) => tree - case _ => finalize(tree, untpd.Thicket(trees)(sourceFile(tree))) + case _ => finalize(tree, untpd.Thicket(trees)(using sourceFile(tree))) } def Hole(tree: Tree)(isTerm: Boolean, idx: Int, args: List[Tree], content: Tree)(using Context): Hole = tree match { case tree: Hole if isTerm == tree.isTerm && idx == tree.idx && args.eq(tree.args) && content.eq(tree.content) && content.eq(tree.content) => tree - case _ => finalize(tree, untpd.Hole(isTerm, idx, args, content)(sourceFile(tree))) + case _ => finalize(tree, untpd.Hole(isTerm, idx, args, content)(using sourceFile(tree))) } // Copier methods with default arguments; these demand that the original tree diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index f7683e52c5fd..eddc0c675e9a 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -252,7 +252,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { sym) def DefDef(sym: TermSymbol, rhs: Tree = EmptyTree)(using Context): DefDef = - ta.assignType(DefDef(sym, Function.const(rhs) _), sym) + ta.assignType(DefDef(sym, Function.const(rhs)), sym) /** A DefDef with given method symbol `sym`. * @rhsFn A function from parameter references @@ -392,7 +392,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { termForwarders: List[(TermName, TermSymbol)], typeMembers: List[(TypeName, TypeBounds)], adaptVarargs: Boolean)(using Context): Block = { - AnonClass(termForwarders.head._2.owner, parents, termForwarders.map(_._2.span).reduceLeft(_ union _), adaptVarargs) { cls => + AnonClass(termForwarders.head._2.owner, parents, termForwarders.map(_._2.span).reduceLeft(_ `union` _), adaptVarargs) { cls => def forwarder(name: TermName, fn: TermSymbol) = { val fwdMeth = fn.copy(cls, name, Synthetic | Method | Final).entered.asTerm for overridden <- fwdMeth.allOverriddenSymbols do @@ -473,15 +473,15 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** A tree representing the same reference as the given type */ def ref(tp: NamedType, needLoad: Boolean = true)(using Context): Tree = - if (tp.isType) TypeTree(tp) - else if (prefixIsElidable(tp)) Ident(tp) - else if (tp.symbol.is(Module) && ctx.owner.isContainedIn(tp.symbol.moduleClass)) + if tp.isType then TypeTree(tp) + else if prefixIsElidable(tp) then Ident(tp) + else if tp.symbol.is(Module) && ctx.owner.isContainedIn(tp.symbol.moduleClass) then followOuterLinks(This(tp.symbol.moduleClass.asClass)) - else if (tp.symbol hasAnnotation defn.ScalaStaticAnnot) + else if tp.symbol.hasAnnotation(defn.ScalaStaticAnnot) then Ident(tp) else val pre = tp.prefix - if (pre.isSingleton) followOuterLinks(singleton(pre.dealias, needLoad)).select(tp) + if pre.isSingleton then followOuterLinks(singleton(pre.dealias, needLoad)).select(tp) else val res = Select(TypeTree(pre), tp) if needLoad && !res.symbol.isStatic then @@ -614,14 +614,14 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { def defaultValue(tpe: Type)(using Context): Tree = { val tpw = tpe.widen - if (tpw isRef defn.IntClass) Literal(Constant(0)) - else if (tpw isRef defn.LongClass) Literal(Constant(0L)) - else if (tpw isRef defn.BooleanClass) Literal(Constant(false)) - else if (tpw isRef defn.CharClass) Literal(Constant('\u0000')) - else if (tpw isRef defn.FloatClass) Literal(Constant(0f)) - else if (tpw isRef defn.DoubleClass) Literal(Constant(0d)) - else if (tpw isRef defn.ByteClass) Literal(Constant(0.toByte)) - else if (tpw isRef defn.ShortClass) Literal(Constant(0.toShort)) + if tpw.isRef(defn.IntClass) then Literal(Constant(0)) + else if tpw.isRef(defn.LongClass) then Literal(Constant(0L)) + else if tpw.isRef(defn.BooleanClass) then Literal(Constant(false)) + else if tpw.isRef(defn.CharClass) then Literal(Constant('\u0000')) + else if tpw.isRef(defn.FloatClass) then Literal(Constant(0f)) + else if tpw.isRef(defn.DoubleClass) then Literal(Constant(0d)) + else if tpw.isRef(defn.ByteClass) then Literal(Constant(0.toByte)) + else if tpw.isRef(defn.ShortClass) then Literal(Constant(0.toShort)) else nullLiteral.select(defn.Any_asInstanceOf).appliedToType(tpe) } @@ -1382,18 +1382,16 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { } // convert a numeric with a toXXX method - def primitiveConversion(tree: Tree, numericCls: Symbol)(using Context): Tree = { + def primitiveConversion(tree: Tree, numericCls: Symbol)(using Context): Tree = val mname = "to".concat(numericCls.name) - val conversion = tree.tpe member(mname) - if (conversion.symbol.exists) + val conversion = tree.tpe.member(mname) + if conversion.symbol.exists then tree.select(conversion.symbol.termRef).ensureApplied - else if (tree.tpe.widen isRef numericCls) + else if tree.tpe.widen.isRef(numericCls) then tree - else { + else report.warning(em"conversion from ${tree.tpe.widen} to ${numericCls.typeRef} will always fail at runtime.") Throw(New(defn.ClassCastExceptionClass.typeRef, Nil)).withSpan(tree.span) - } - } /** A tree that corresponds to `Predef.classOf[$tp]` in source */ def clsOf(tp: Type)(using Context): Tree = diff --git a/compiler/src/dotty/tools/dotc/ast/untpd.scala b/compiler/src/dotty/tools/dotc/ast/untpd.scala index a7e99ed2cdeb..17dbb5bff213 100644 --- a/compiler/src/dotty/tools/dotc/ast/untpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/untpd.scala @@ -166,7 +166,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { */ case class InLambdaTypeTree(isResult: Boolean, tpFun: (List[TypeSymbol], List[TermSymbol]) => Type)(implicit @constructorOnly src: SourceFile) extends Tree - @sharable object EmptyTypeIdent extends Ident(tpnme.EMPTY)(NoSource) with WithoutTypeOrPos[Untyped] { + @sharable object EmptyTypeIdent extends Ident(tpnme.EMPTY)(using NoSource), WithoutTypeOrPos[Untyped] { override def isEmpty: Boolean = true } @@ -640,19 +640,19 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { def ModuleDef(tree: Tree)(name: TermName, impl: Template)(using Context): ModuleDef = tree match { case tree: ModuleDef if (name eq tree.name) && (impl eq tree.impl) => tree - case _ => finalize(tree, untpd.ModuleDef(name, impl)(tree.source)) + case _ => finalize(tree, untpd.ModuleDef(name, impl)(using tree.source)) } def ParsedTry(tree: Tree)(expr: Tree, handler: Tree, finalizer: Tree)(using Context): TermTree = tree match { case tree: ParsedTry if (expr eq tree.expr) && (handler eq tree.handler) && (finalizer eq tree.finalizer) => tree - case _ => finalize(tree, untpd.ParsedTry(expr, handler, finalizer)(tree.source)) + case _ => finalize(tree, untpd.ParsedTry(expr, handler, finalizer)(using tree.source)) } def SymbolLit(tree: Tree)(str: String)(using Context): TermTree = tree match { case tree: SymbolLit if str == tree.str => tree - case _ => finalize(tree, untpd.SymbolLit(str)(tree.source)) + case _ => finalize(tree, untpd.SymbolLit(str)(using tree.source)) } def InterpolatedString(tree: Tree)(id: TermName, segments: List[Tree])(using Context): TermTree = tree match { case tree: InterpolatedString if (id eq tree.id) && (segments eq tree.segments) => tree - case _ => finalize(tree, untpd.InterpolatedString(id, segments)(tree.source)) + case _ => finalize(tree, untpd.InterpolatedString(id, segments)(using tree.source)) } def Function(tree: Tree)(args: List[Tree], body: Tree)(using Context): Tree = tree match { case tree: Function if (args eq tree.args) && (body eq tree.body) => tree @@ -664,65 +664,65 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { } def PolyFunction(tree: Tree)(targs: List[Tree], body: Tree)(using Context): Tree = tree match { case tree: PolyFunction if (targs eq tree.targs) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.PolyFunction(targs, body)(tree.source)) + case _ => finalize(tree, untpd.PolyFunction(targs, body)(using tree.source)) } def InfixOp(tree: Tree)(left: Tree, op: Ident, right: Tree)(using Context): Tree = tree match { case tree: InfixOp if (left eq tree.left) && (op eq tree.op) && (right eq tree.right) => tree - case _ => finalize(tree, untpd.InfixOp(left, op, right)(tree.source)) + case _ => finalize(tree, untpd.InfixOp(left, op, right)(using tree.source)) } def PostfixOp(tree: Tree)(od: Tree, op: Ident)(using Context): Tree = tree match { case tree: PostfixOp if (od eq tree.od) && (op eq tree.op) => tree - case _ => finalize(tree, untpd.PostfixOp(od, op)(tree.source)) + case _ => finalize(tree, untpd.PostfixOp(od, op)(using tree.source)) } def PrefixOp(tree: Tree)(op: Ident, od: Tree)(using Context): Tree = tree match { case tree: PrefixOp if (op eq tree.op) && (od eq tree.od) => tree - case _ => finalize(tree, untpd.PrefixOp(op, od)(tree.source)) + case _ => finalize(tree, untpd.PrefixOp(op, od)(using tree.source)) } def Parens(tree: Tree)(t: Tree)(using Context): ProxyTree = tree match { case tree: Parens if t eq tree.t => tree - case _ => finalize(tree, untpd.Parens(t)(tree.source)) + case _ => finalize(tree, untpd.Parens(t)(using tree.source)) } def Tuple(tree: Tree)(trees: List[Tree])(using Context): Tree = tree match { case tree: Tuple if trees eq tree.trees => tree - case _ => finalize(tree, untpd.Tuple(trees)(tree.source)) + case _ => finalize(tree, untpd.Tuple(trees)(using tree.source)) } def Throw(tree: Tree)(expr: Tree)(using Context): TermTree = tree match { case tree: Throw if expr eq tree.expr => tree - case _ => finalize(tree, untpd.Throw(expr)(tree.source)) + case _ => finalize(tree, untpd.Throw(expr)(using tree.source)) } def ForYield(tree: Tree)(enums: List[Tree], expr: Tree)(using Context): TermTree = tree match { case tree: ForYield if (enums eq tree.enums) && (expr eq tree.expr) => tree - case _ => finalize(tree, untpd.ForYield(enums, expr)(tree.source)) + case _ => finalize(tree, untpd.ForYield(enums, expr)(using tree.source)) } def ForDo(tree: Tree)(enums: List[Tree], body: Tree)(using Context): TermTree = tree match { case tree: ForDo if (enums eq tree.enums) && (body eq tree.body) => tree - case _ => finalize(tree, untpd.ForDo(enums, body)(tree.source)) + case _ => finalize(tree, untpd.ForDo(enums, body)(using tree.source)) } def GenFrom(tree: Tree)(pat: Tree, expr: Tree, checkMode: GenCheckMode)(using Context): Tree = tree match { case tree: GenFrom if (pat eq tree.pat) && (expr eq tree.expr) && (checkMode == tree.checkMode) => tree - case _ => finalize(tree, untpd.GenFrom(pat, expr, checkMode)(tree.source)) + case _ => finalize(tree, untpd.GenFrom(pat, expr, checkMode)(using tree.source)) } def GenAlias(tree: Tree)(pat: Tree, expr: Tree)(using Context): Tree = tree match { case tree: GenAlias if (pat eq tree.pat) && (expr eq tree.expr) => tree - case _ => finalize(tree, untpd.GenAlias(pat, expr)(tree.source)) + case _ => finalize(tree, untpd.GenAlias(pat, expr)(using tree.source)) } def ContextBounds(tree: Tree)(bounds: TypeBoundsTree, cxBounds: List[Tree])(using Context): TypTree = tree match { case tree: ContextBounds if (bounds eq tree.bounds) && (cxBounds eq tree.cxBounds) => tree - case _ => finalize(tree, untpd.ContextBounds(bounds, cxBounds)(tree.source)) + case _ => finalize(tree, untpd.ContextBounds(bounds, cxBounds)(using tree.source)) } def PatDef(tree: Tree)(mods: Modifiers, pats: List[Tree], tpt: Tree, rhs: Tree)(using Context): Tree = tree match { case tree: PatDef if (mods eq tree.mods) && (pats eq tree.pats) && (tpt eq tree.tpt) && (rhs eq tree.rhs) => tree - case _ => finalize(tree, untpd.PatDef(mods, pats, tpt, rhs)(tree.source)) + case _ => finalize(tree, untpd.PatDef(mods, pats, tpt, rhs)(using tree.source)) } def ExtMethods(tree: Tree)(paramss: List[ParamClause], methods: List[Tree])(using Context): Tree = tree match case tree: ExtMethods if (paramss eq tree.paramss) && (methods == tree.methods) => tree - case _ => finalize(tree, untpd.ExtMethods(paramss, methods)(tree.source)) + case _ => finalize(tree, untpd.ExtMethods(paramss, methods)(using tree.source)) def ContextBoundTypeTree(tree: Tree)(tycon: Tree, paramName: TypeName, ownName: TermName)(using Context): Tree = tree match case tree: ContextBoundTypeTree if (tycon eq tree.tycon) && paramName == tree.paramName && ownName == tree.ownName => tree - case _ => finalize(tree, untpd.ContextBoundTypeTree(tycon, paramName, ownName)(tree.source)) + case _ => finalize(tree, untpd.ContextBoundTypeTree(tycon, paramName, ownName)(using tree.source)) def ImportSelector(tree: Tree)(imported: Ident, renamed: Tree, bound: Tree)(using Context): Tree = tree match { case tree: ImportSelector if (imported eq tree.imported) && (renamed eq tree.renamed) && (bound eq tree.bound) => tree - case _ => finalize(tree, untpd.ImportSelector(imported, renamed, bound)(tree.source)) + case _ => finalize(tree, untpd.ImportSelector(imported, renamed, bound)(using tree.source)) } def Number(tree: Tree)(digits: String, kind: NumberKind)(using Context): Tree = tree match { case tree: Number if (digits == tree.digits) && (kind == tree.kind) => tree @@ -738,7 +738,7 @@ object untpd extends Trees.Instance[Untyped] with UntypedTreeInfo { } def MacroTree(tree: Tree)(expr: Tree)(using Context): Tree = tree match { case tree: MacroTree if expr `eq` tree.expr => tree - case _ => finalize(tree, untpd.MacroTree(expr)(tree.source)) + case _ => finalize(tree, untpd.MacroTree(expr)(using tree.source)) } } diff --git a/compiler/src/dotty/tools/dotc/cc/Capability.scala b/compiler/src/dotty/tools/dotc/cc/Capability.scala index fb12ff6c68b1..5a6fb7df5511 100644 --- a/compiler/src/dotty/tools/dotc/cc/Capability.scala +++ b/compiler/src/dotty/tools/dotc/cc/Capability.scala @@ -769,7 +769,7 @@ object Capabilities: case Maybe(x1) => x1.covers(y1) case _ => false case y: FreshCap => - y.hiddenSet.superCaps.exists(this covers _) + y.hiddenSet.superCaps.exists(this.covers(_)) case _ => false diff --git a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala index f434b365c3c9..d8a70186d3b0 100644 --- a/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala +++ b/compiler/src/dotty/tools/dotc/classpath/ClassPathFactory.scala @@ -23,10 +23,9 @@ class ClassPathFactory { * Creators for sub classpaths which preserve this context. */ def sourcesInPath(path: String)(using Context): List[ClassPath] = - for { + for file <- expandPath(path, expandStar = false) - dir <- Option(AbstractFile getDirectory file) - } + dir <- Option(AbstractFile.getDirectory(file)) yield createSourcePath(dir) @@ -48,7 +47,8 @@ class ClassPathFactory { def classesInPath(path: String)(using Context): List[ClassPath] = classesInPathImpl(path, expand = false) def classesInManifest(useManifestClassPath: Boolean)(using Context): List[ClassPath] = - if (useManifestClassPath) dotty.tools.io.ClassPath.manifests.map(url => newClassPath(AbstractFile getResources url)) + if useManifestClassPath + then dotty.tools.io.ClassPath.manifests.map(url => newClassPath(AbstractFile.getResources(url))) else Nil // Internal diff --git a/compiler/src/dotty/tools/dotc/config/CliCommand.scala b/compiler/src/dotty/tools/dotc/config/CliCommand.scala index 9c1b0871c144..7f6ea0cece5f 100644 --- a/compiler/src/dotty/tools/dotc/config/CliCommand.scala +++ b/compiler/src/dotty/tools/dotc/config/CliCommand.scala @@ -43,7 +43,7 @@ trait CliCommand: // expand out @filename to the contents of that filename def expandedArguments = args.toList flatMap { - case x if x startsWith "@" => CommandLineParser.expandArg(x) + case x if x.startsWith("@") => CommandLineParser.expandArg(x) case x => List(x) } diff --git a/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala b/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala index a6dbf696a575..80cb9f556867 100644 --- a/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala +++ b/compiler/src/dotty/tools/dotc/config/JavaPlatform.scala @@ -23,7 +23,7 @@ class JavaPlatform extends Platform { // The given symbol is a method with the right name and signature to be a runnable java program. def isMainMethod(sym: Symbol)(using Context): Boolean = (sym.name == nme.main) && (sym.info match { - case MethodTpe(_, defn.ArrayOf(el) :: Nil, restpe) => el =:= defn.StringType && (restpe isRef defn.UnitClass) + case MethodTpe(_, defn.ArrayOf(el) :: Nil, restpe) => el =:= defn.StringType && restpe.isRef(defn.UnitClass) case _ => false }) @@ -60,12 +60,12 @@ class JavaPlatform extends Platform { def isMaybeBoxed(sym: ClassSymbol)(using Context): Boolean = { val d = defn import d.* - (sym == ObjectClass) || - (sym == JavaSerializableClass) || - (sym == ComparableClass) || - (sym derivesFrom BoxedNumberClass) || - (sym derivesFrom BoxedCharClass) || - (sym derivesFrom BoxedBooleanClass) + sym == ObjectClass + || sym == JavaSerializableClass + || sym == ComparableClass + || sym.derivesFrom(BoxedNumberClass) + || sym.derivesFrom(BoxedCharClass) + || sym.derivesFrom(BoxedBooleanClass) } def shouldReceiveJavaSerializationMethods(sym: ClassSymbol)(using Context): Boolean = diff --git a/compiler/src/dotty/tools/dotc/config/OutputDirs.scala b/compiler/src/dotty/tools/dotc/config/OutputDirs.scala index ff0f59cb1309..39f25d2b0fa2 100644 --- a/compiler/src/dotty/tools/dotc/config/OutputDirs.scala +++ b/compiler/src/dotty/tools/dotc/config/OutputDirs.scala @@ -70,12 +70,11 @@ class OutputDirs { singleOutDir match { case Some(d) => d case None => - (outputs find (isBelow _).tupled) match { + outputs.find(isBelow(_, _)) match case Some((_, d)) => d case _ => - throw new FatalError("Could not find an output directory for " - + src.path + " in " + outputs) - } + throw new FatalError( + s"Could not find an output directory for ${src.path} in $outputs") } } @@ -107,7 +106,7 @@ class OutputDirs { case _ => List(d.lookupPathUnchecked(srcPath, false)) } case None => - (outputs filter (isBelow _).tupled) match { + outputs.filter(isBelow(_, _)) match { case Nil => Nil case matches => matches.map(_._1.lookupPathUnchecked(srcPath, false)) } diff --git a/compiler/src/dotty/tools/dotc/config/PathResolver.scala b/compiler/src/dotty/tools/dotc/config/PathResolver.scala index e21d452c4b76..f516aef18753 100644 --- a/compiler/src/dotty/tools/dotc/config/PathResolver.scala +++ b/compiler/src/dotty/tools/dotc/config/PathResolver.scala @@ -42,7 +42,7 @@ object PathResolver { // mutation of the System property map. stringPropertyNames internally uses the Enumeration interface, // rather than Iterator, and this disables the fail-fast ConcurrentModificationException. val propNames = props.stringPropertyNames() - propNames.asScala collectFirst { case k if k endsWith ".boot.class.path" => props.getProperty(k) } getOrElse "" + propNames.asScala collectFirst { case k if k.endsWith(".boot.class.path") => props.getProperty(k) } getOrElse "" } /** Environment variables which java pays attention to so it diff --git a/compiler/src/dotty/tools/dotc/config/Properties.scala b/compiler/src/dotty/tools/dotc/config/Properties.scala index 02e9bd2f53b9..b6da0a09af75 100644 --- a/compiler/src/dotty/tools/dotc/config/Properties.scala +++ b/compiler/src/dotty/tools/dotc/config/Properties.scala @@ -29,9 +29,9 @@ trait PropertiesTrait { /** The loaded properties */ @sharable protected lazy val scalaProps: java.util.Properties = { val props = new java.util.Properties - val stream = pickJarBasedOn getResourceAsStream propFilename + val stream = pickJarBasedOn.getResourceAsStream(propFilename) if (stream ne null) - quietlyDispose(props load stream, stream.close) + quietlyDispose(props.load(stream), stream.close) props } @@ -52,8 +52,8 @@ trait PropertiesTrait { def setProp(name: String, value: String): String = System.setProperty(name, value) def clearProp(name: String): String = System.clearProperty(name) - def envOrElse(name: String, alt: => String): String = Option(System getenv name) getOrElse alt - def envOrNone(name: String): Option[String] = Option(System getenv name) + def envOrElse(name: String, alt: => String): String = Option(System.getenv(name)).getOrElse(alt) + def envOrNone(name: String): Option[String] = Option(System.getenv(name)) // for values based on propFilename def scalaPropOrElse(name: String, alt: => String): String = scalaProps.getProperty(name, alt) @@ -122,8 +122,8 @@ trait PropertiesTrait { /** Some derived values. */ - def isWin: Boolean = osName startsWith "Windows" - def isMac: Boolean = javaVendor startsWith "Apple" + def isWin: Boolean = osName.startsWith("Windows") + def isMac: Boolean = javaVendor.startsWith("Apple") // This is looking for javac, tools.jar, etc. // Tries JDK_HOME first, then the more common but likely jre JAVA_HOME, diff --git a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala index cc89dd5f356a..41b8f8594401 100644 --- a/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala +++ b/compiler/src/dotty/tools/dotc/config/ScalaSettings.scala @@ -30,17 +30,17 @@ object ScalaSettings extends ScalaSettings // Kept as seperate type to avoid breaking backward compatibility abstract class ScalaSettings extends SettingGroup, AllScalaSettings: - val settingsByCategory: Map[SettingCategory, List[Setting[_]]] = + val settingsByCategory: Map[SettingCategory, List[Setting[?]]] = allSettings.groupBy(_.category) .view.mapValues(_.toList).toMap .withDefaultValue(Nil) def categories: List[SettingCategory] = settingsByCategory.keys.toList.sortBy(_.prefixLetter) - val rootSettings: List[Setting[_]] = settingsByCategory(RootSetting).sortBy(_.name) - val warningSettings: List[Setting[_]] = settingsByCategory(WarningSetting).sortBy(_.name) - val forkSettings: List[Setting[_]] = settingsByCategory(ForkSetting).sortBy(_.name) - val advancedSettings: List[Setting[_]] = settingsByCategory(AdvancedSetting).sortBy(_.name) - val verboseSettings: List[Setting[_]] = settingsByCategory(VerboseSetting).sortBy(_.name) - val settingsByAliases: Map[String, Setting[_]] = allSettings.flatMap(s => s.aliases.map(_ -> s)).toMap + val rootSettings: List[Setting[?]] = settingsByCategory(RootSetting).sortBy(_.name) + val warningSettings: List[Setting[?]] = settingsByCategory(WarningSetting).sortBy(_.name) + val forkSettings: List[Setting[?]] = settingsByCategory(ForkSetting).sortBy(_.name) + val advancedSettings: List[Setting[?]] = settingsByCategory(AdvancedSetting).sortBy(_.name) + val verboseSettings: List[Setting[?]] = settingsByCategory(VerboseSetting).sortBy(_.name) + val settingsByAliases: Map[String, Setting[?]] = allSettings.flatMap(s => s.aliases.map(_ -> s)).toMap trait AllScalaSettings extends CommonScalaSettings, PluginSettings, VerboseSettings, WarningSettings, XSettings, YSettings: @@ -370,7 +370,7 @@ private sealed trait XSettings: val XmacroSettings: Setting[List[String]] = MultiStringSetting(AdvancedSetting, "Xmacro-settings", "setting1,setting2,..settingN", "List of settings which exposed to the macros") @deprecated(message = "Superseded by -Wshadow, Scheduled for removal", since = "3.5.0") - val Xlint: Setting[_] = BooleanSetting(AdvancedSetting, "Xlint", "Enable or disable specific warnings", deprecation = Some(Deprecation("Use -Wshadow to enable shadowing lints. Scheduled for removal.")), ignoreInvalidArgs = true) + val Xlint: Setting[?] = BooleanSetting(AdvancedSetting, "Xlint", "Enable or disable specific warnings", deprecation = Some(Deprecation("Use -Wshadow to enable shadowing lints. Scheduled for removal.")), ignoreInvalidArgs = true) end XSettings diff --git a/compiler/src/dotty/tools/dotc/config/Settings.scala b/compiler/src/dotty/tools/dotc/config/Settings.scala index 7842113b5e48..b2cd2c893df4 100644 --- a/compiler/src/dotty/tools/dotc/config/Settings.scala +++ b/compiler/src/dotty/tools/dotc/config/Settings.scala @@ -359,7 +359,7 @@ object Settings: checkDependencies(stateWithArgs(skipped)) case "--" :: args => checkDependencies(stateWithArgs(skipped ++ args)) - case x :: _ if x startsWith "-" => + case x :: _ if x.startsWith("-") => @tailrec def loop(settings: List[Setting[?]]): ArgsSummary = settings match case setting :: settings1 => val state1 = setting.tryToSet(state) diff --git a/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala b/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala index 9f707c8bd2bb..bead5ac6e74e 100644 --- a/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala +++ b/compiler/src/dotty/tools/dotc/core/CheckRealizable.scala @@ -173,7 +173,7 @@ class CheckRealizable(using Context) { baseProblems.foldLeft( refinementProblems.foldLeft( memberProblems.foldLeft( - Realizable: Realizability)(_ andAlso _))(_ andAlso _))(_ andAlso _) + Realizable: Realizability)(_ `andAlso` _))(_ `andAlso` _))(_ `andAlso` _) } /** `Realizable` if all of `tp`'s non-strict fields have realizable types, diff --git a/compiler/src/dotty/tools/dotc/core/Comments.scala b/compiler/src/dotty/tools/dotc/core/Comments.scala index 886747041fa2..cafe09673684 100644 --- a/compiler/src/dotty/tools/dotc/core/Comments.scala +++ b/compiler/src/dotty/tools/dotc/core/Comments.scala @@ -100,11 +100,10 @@ object Comments { private def decomposeUseCase(body: String, span: Span, start: Int, end: Int)(using Context): UseCase = { def subPos(start: Int, end: Int) = if (span == NoSpan) NoSpan - else { + else val start1 = span.start + start val end1 = span.end + end - span withStart start1 withPoint start1 withEnd end1 - } + span.withStart(start1).withPoint(start1).withEnd(end1) val codeStart = skipWhitespace(body, start + "@usecase".length) val codeEnd = skipToEol(body, codeStart) @@ -360,7 +359,7 @@ object Comments { // necessary to document things like Symbol#decode def isEscaped = idx > 0 && str.charAt(idx - 1) == '\\' while (idx < str.length) - if ((str charAt idx) != '$' || isEscaped) + if str.charAt(idx) != '$' || isEscaped then idx += 1 else { val vstart = idx @@ -428,8 +427,8 @@ object Comments { else site.info.baseClasses searchList collectFirst { case x if defs(x) contains vble => defs(x)(vble) } match { - case Some(str) if str startsWith "$" => lookupVariable(str.tail, site) - case res => res `orElse` lookupVariable(vble, site.owner) + case Some(str) if str.startsWith("$") => lookupVariable(str.tail, site) + case res => res `orElse` lookupVariable(vble, site.owner) } } diff --git a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala index 04d55475ec60..5d6169cc6990 100644 --- a/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala +++ b/compiler/src/dotty/tools/dotc/core/ConstraintHandling.scala @@ -845,7 +845,7 @@ trait ConstraintHandling { val approx = new ApproximatingTypeMap { if (!fromBelow) variance = -1 def apply(t: Type): Type = t match { - case t @ TypeParamRef(tl: TypeLambda, n) if comparedTypeLambdas contains tl => + case t @ TypeParamRef(tl: TypeLambda, n) if comparedTypeLambdas.contains(tl) => val bounds = tl.paramInfos(n) range(bounds.lo, bounds.hi) case tl: TypeLambda => @@ -884,7 +884,7 @@ trait ConstraintHandling { val saved = canWidenAbstract canWidenAbstract = true try bound match - case bound: TypeParamRef if constraint contains bound => + case bound: TypeParamRef if constraint.contains(bound) => addParamBound(bound) case _ => val pbound = avoidLambdaParams(bound) diff --git a/compiler/src/dotty/tools/dotc/core/Contexts.scala b/compiler/src/dotty/tools/dotc/core/Contexts.scala index 171b98a8cdf4..c086491d9bb0 100644 --- a/compiler/src/dotty/tools/dotc/core/Contexts.scala +++ b/compiler/src/dotty/tools/dotc/core/Contexts.scala @@ -234,7 +234,7 @@ object Contexts { else Nil val outerImplicits = if (isImportContext && importInfo.nn.unimported.exists) - outer.implicits exclude importInfo.nn.unimported + outer.implicits.exclude(importInfo.nn.unimported) else outer.implicits if (implicitRefs.isEmpty) outerImplicits diff --git a/compiler/src/dotty/tools/dotc/core/Denotations.scala b/compiler/src/dotty/tools/dotc/core/Denotations.scala index b77209c675eb..834e6ae15dfe 100644 --- a/compiler/src/dotty/tools/dotc/core/Denotations.scala +++ b/compiler/src/dotty/tools/dotc/core/Denotations.scala @@ -811,7 +811,7 @@ object Denotations { var cur = this // search for containing period as long as nextInRun increases. var next = nextInRun - while next.validFor.code > valid.code && !(next.validFor contains currentPeriod) do + while next.validFor.code > valid.code && !next.validFor.contains(currentPeriod) do cur = next next = next.nextInRun if next.validFor.code > valid.code then @@ -857,7 +857,7 @@ object Denotations { // but to be defensive we check for infinite loop anyway var cur = this var cnt = 0 - while !(cur.validFor contains currentPeriod) do + while !cur.validFor.contains(currentPeriod) do //println(s"searching: $cur at $currentPeriod, valid for ${cur.validFor}") cur = cur.nextInRun // Note: One might be tempted to add a `prev` field to get to the new denotation @@ -1228,9 +1228,9 @@ object Denotations { def mapInherited(owndenot: PreDenotation, prevdenot: PreDenotation, pre: Type)(using Context): PreDenotation = derivedUnion(denot1.mapInherited(owndenot, prevdenot, pre), denot2.mapInherited(owndenot, prevdenot, pre)) def filterWithPredicate(p: SingleDenotation => Boolean): PreDenotation = - derivedUnion(denot1 filterWithPredicate p, denot2 filterWithPredicate p) + derivedUnion(denot1.filterWithPredicate(p), denot2.filterWithPredicate(p)) def filterDisjoint(denot: PreDenotation)(using Context): PreDenotation = - derivedUnion(denot1 filterDisjoint denot, denot2 filterDisjoint denot) + derivedUnion(denot1.filterDisjoint(denot), denot2.filterDisjoint(denot)) def filterWithFlags(required: FlagSet, excluded: FlagSet)(using Context): PreDenotation = derivedUnion(denot1.filterWithFlags(required, excluded), denot2.filterWithFlags(required, excluded)) def aggregate[T](f: SingleDenotation => T, g: (T, T) => T): T = @@ -1245,7 +1245,7 @@ object Denotations { def toDenot(pre: Type)(using Context): Denotation = denot1.toDenot(pre).meet(denot2.toDenot(pre), pre) def containsSym(sym: Symbol): Boolean = - (denot1 containsSym sym) || (denot2 containsSym sym) + denot1.containsSym(sym) || denot2.containsSym(sym) type AsSeenFromResult = PreDenotation def computeAsSeenFrom(pre: Type)(using Context): PreDenotation = derivedUnion(denot1.asSeenFrom(pre), denot2.asSeenFrom(pre)) diff --git a/compiler/src/dotty/tools/dotc/core/NameOps.scala b/compiler/src/dotty/tools/dotc/core/NameOps.scala index 766cf4abf8c4..f157da843f41 100644 --- a/compiler/src/dotty/tools/dotc/core/NameOps.scala +++ b/compiler/src/dotty/tools/dotc/core/NameOps.scala @@ -67,9 +67,9 @@ object NameOps { def isConstructorName: Boolean = name == CONSTRUCTOR || name == TRAIT_CONSTRUCTOR def isStaticConstructorName: Boolean = name == STATIC_CONSTRUCTOR - def isLocalDummyName: Boolean = name startsWith str.LOCALDUMMY_PREFIX - def isReplWrapperName: Boolean = name.toString contains str.REPL_SESSION_LINE - def isReplAssignName: Boolean = name.toString contains str.REPL_ASSIGN_SUFFIX + def isLocalDummyName: Boolean = name.startsWith(str.LOCALDUMMY_PREFIX) + def isReplWrapperName: Boolean = name.toString.contains(str.REPL_SESSION_LINE) + def isReplAssignName: Boolean = name.toString.contains(str.REPL_ASSIGN_SUFFIX) def isSetterName: Boolean = name.endsWith(str.SETTER_SUFFIX) || name.is(SyntheticSetterName) def isScala2LocalSuffix: Boolean = testSimple(_.endsWith(" ")) def isSelectorName: Boolean = testSimple(n => n.startsWith("_") && n.drop(1).forall(_.isDigit)) diff --git a/compiler/src/dotty/tools/dotc/core/Periods.scala b/compiler/src/dotty/tools/dotc/core/Periods.scala index 60226eb59fe0..30c10c0d170e 100644 --- a/compiler/src/dotty/tools/dotc/core/Periods.scala +++ b/compiler/src/dotty/tools/dotc/core/Periods.scala @@ -87,7 +87,7 @@ object Periods { /** The intersection of two periods */ def & (that: Period): Period = - if (this overlaps that) + if this `overlaps` that then Period( this.runId, this.firstPhaseId max that.firstPhaseId, diff --git a/compiler/src/dotty/tools/dotc/core/Signature.scala b/compiler/src/dotty/tools/dotc/core/Signature.scala index f62d594d639d..f8475a4cf314 100644 --- a/compiler/src/dotty/tools/dotc/core/Signature.scala +++ b/compiler/src/dotty/tools/dotc/core/Signature.scala @@ -189,7 +189,7 @@ object Signature { } def compare(x: Signature, y: Signature): Int = { import scala.math.Ordering.Implicits.seqOrdering - val paramsOrdering = seqOrdering(paramSigOrdering).compare(x.paramsSig, y.paramsSig) + val paramsOrdering = seqOrdering(using paramSigOrdering).compare(x.paramsSig, y.paramsSig) if (paramsOrdering != 0) paramsOrdering else summon[Ordering[Name]].compare(x.resSig, y.resSig) } diff --git a/compiler/src/dotty/tools/dotc/core/Substituters.scala b/compiler/src/dotty/tools/dotc/core/Substituters.scala index 425b6193f3cd..bedc6876adad 100644 --- a/compiler/src/dotty/tools/dotc/core/Substituters.scala +++ b/compiler/src/dotty/tools/dotc/core/Substituters.scala @@ -82,7 +82,7 @@ object Substituters: var ts = to while (fs.nonEmpty) { if (fs.head eq sym) - return substSym(tp.prefix, from, to, theMap) select ts.head + return substSym(tp.prefix, from, to, theMap).select(ts.head) fs = fs.tail ts = ts.tail } diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index 384531c135de..6dcf2a83ba5c 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -295,7 +295,7 @@ object SymDenotations { /** Remove annotation with given class from this denotation */ final def removeAnnotation(cls: Symbol)(using Context): Unit = - annotations = myAnnotations.filterNot(_ matches cls) + annotations = myAnnotations.filterNot(_.matches(cls)) /** Remove any annotations with same class as `annot`, and add `annot` */ final def updateAnnotation(annot: Annotation)(using Context): Unit = { @@ -309,7 +309,7 @@ object SymDenotations { @tailrec private def dropOtherAnnotations(anns: List[Annotation], cls: Symbol)(using Context): List[Annotation] = anns match { - case ann :: rest => if (ann matches cls) anns else dropOtherAnnotations(rest, cls) + case ann :: rest => if ann.matches(cls) then anns else dropOtherAnnotations(rest, cls) case Nil => Nil } @@ -2061,11 +2061,9 @@ object SymDenotations { } final override def derivesFrom(base: Symbol)(using Context): Boolean = - !isAbsent() && - base.isClass && - ( (symbol eq base) - || (baseClassSet contains base) - ) + !isAbsent() + && base.isClass + && ((symbol eq base) || baseClassSet.contains(base)) final override def isSubClass(base: Symbol)(using Context): Boolean = derivesFrom(base) @@ -3006,7 +3004,7 @@ object SymDenotations { else { locked = true val computed = - try clsd.computeMemberNames(keepOnly)(this, ctx) + try clsd.computeMemberNames(keepOnly)(using this, ctx) finally locked = false cache = cache.nn.updated(keepOnly, computed) computed @@ -3049,7 +3047,7 @@ object SymDenotations { locked = true provisional = false val computed = - try clsd.computeBaseData(this, ctx) + try clsd.computeBaseData(using this, ctx) finally locked = false if (!provisional) cache = computed else onBehalf.signalProvisional() diff --git a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala index 7b7eb2d2e5a9..9440920a31bb 100644 --- a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala +++ b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala @@ -304,9 +304,9 @@ object SymbolLoaders { } def doComplete(root: SymDenotation)(using Context): Unit = { - assert(root is PackageClass, root) + assert(root.is(PackageClass), root) val pre = root.owner.thisType - root.info = ClassInfo(pre, root.symbol.asClass, Nil, currentDecls, pre select sourceModule) + root.info = ClassInfo(pre, root.symbol.asClass, Nil, currentDecls, pre.select(sourceModule)) if (!sourceModule.isCompleted) sourceModule.completer.complete(sourceModule) diff --git a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala index 79f949b1c631..1d1c497b2196 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeComparer.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeComparer.scala @@ -814,21 +814,20 @@ class TypeComparer(@constructorOnly initctx: Context) extends ConstraintHandling case tp2: MethodType => def compareMethod = tp1 match { case tp1: MethodType => - (tp1.signature consistentParams tp2.signature) && - matchingMethodParams(tp1, tp2) && - (!tp2.isImplicitMethod || tp1.isImplicitMethod) && - isSubType(tp1.resultType, tp2.resultType.subst(tp2, tp1)) + tp1.signature.consistentParams(tp2.signature) + && matchingMethodParams(tp1, tp2) + && (!tp2.isImplicitMethod || tp1.isImplicitMethod) + && isSubType(tp1.resultType, tp2.resultType.subst(tp2, tp1)) case _ => false } compareMethod case tp2: PolyType => def comparePoly = tp1 match { case tp1: PolyType => - comparingTypeLambdas(tp1, tp2) { - (tp1.signature consistentParams tp2.signature) + comparingTypeLambdas(tp1, tp2): + tp1.signature.consistentParams(tp2.signature) && matchingPolyParams(tp1, tp2) && isSubType(tp1.resultType, tp2.resultType.subst(tp2, tp1)) - } case _ => false } comparePoly @@ -853,7 +852,7 @@ class TypeComparer(@constructorOnly initctx: Context) extends ConstraintHandling || (hi2 eq AnyKindType) || isSubType(hi1, hi2)) case tp1: ClassInfo => - tp2 contains tp1 + tp2.contains(tp1) case _ => false } @@ -2308,7 +2307,7 @@ class TypeComparer(@constructorOnly initctx: Context) extends ConstraintHandling /** Defer constraining type variables when compared against prototypes */ def isMatchedByProto(proto: ProtoType, tp: Type): Boolean = tp.stripTypeVar match { - case tp: TypeParamRef if constraint contains tp => true + case tp: TypeParamRef if constraint.contains(tp) => true case _ => proto.isMatchedBy(tp, keepConstraint = true) } @@ -2854,7 +2853,7 @@ class TypeComparer(@constructorOnly initctx: Context) extends ConstraintHandling case tp1: ClassInfo => tp2 match { case tp2: ClassInfo => - isSubTypeWhenFrozen(tp1.prefix, tp2.prefix) || (tp1.cls.owner derivesFrom tp2.cls.owner) + isSubTypeWhenFrozen(tp1.prefix, tp2.prefix) || tp1.cls.owner.derivesFrom(tp2.cls.owner) case _ => false } diff --git a/compiler/src/dotty/tools/dotc/core/TypeEval.scala b/compiler/src/dotty/tools/dotc/core/TypeEval.scala index b7995b1ffba2..98578f353b96 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeEval.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeEval.scala @@ -256,11 +256,11 @@ object TypeEval: else if owner == defn.CompiletimeOpsStringModuleClass then name match case tpnme.Plus => constantFold2(stringValue, _ + _) case tpnme.Length => constantFold1(stringValue, _.length) - case tpnme.Matches => constantFold2(stringValue, _ matches _) + case tpnme.Matches => constantFold2(stringValue, _.matches(_)) case tpnme.Substring => constantFold3(stringValue, intValue, intValue, (s, b, e) => s.substring(b, e)) case tpnme.CharAt => - constantFold2AB(stringValue, intValue, _ charAt _) + constantFold2AB(stringValue, intValue, _.charAt(_)) case _ => None else if owner == defn.CompiletimeOpsBooleanModuleClass then name match case tpnme.Not => constantFold1(boolValue, x => !x) diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index 4d0da65e430f..af449f323558 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -76,7 +76,7 @@ object TypeOps: * @param thiscls The prefix `C` of the `C.this` type. */ def toPrefix(pre: Type, cls: Symbol, thiscls: ClassSymbol): Type = /*>|>*/ trace.conditionally(track, s"toPrefix($pre, $cls, $thiscls)", show = true) /*<|<*/ { - if ((pre eq NoType) || (pre eq NoPrefix) || (cls is PackageClass)) + if ((pre eq NoType) || (pre eq NoPrefix) || cls.is(PackageClass)) tp else pre match { case pre: SuperType => toPrefix(pre.thistpe, cls, thiscls) @@ -242,7 +242,7 @@ object TypeOps: /** The minimal set of classes in `cs` which derive all other classes in `cs` */ def dominators(cs: List[ClassSymbol], accu: List[ClassSymbol]): List[ClassSymbol] = (cs: @unchecked) match { case c :: rest => - val accu1 = if (accu exists (_ derivesFrom c)) accu else c :: accu + val accu1 = if accu.exists(_.derivesFrom(c)) then accu else c :: accu if (cs == c.baseClasses) accu1 else dominators(rest, accu1) case Nil => // this case can happen because after erasure we do not have a top class anymore assert(ctx.erasedTypes || ctx.reporter.errorsReported) diff --git a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala index e2cb3fa79676..ea8a74d18192 100644 --- a/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala +++ b/compiler/src/dotty/tools/dotc/core/classfile/ClassfileParser.scala @@ -496,7 +496,7 @@ class ClassfileParser( * and make constructor type polymorphic in the type parameters of the class */ def normalizeConstructorInfo() = { - val rt = classRoot.typeRef appliedTo (classRoot.typeParams map (_.typeRef)) + val rt = classRoot.typeRef.appliedTo(classRoot.typeParams.map(_.typeRef)) def resultType(tpe: Type): Type = tpe match { case mt @ MethodType(paramNames) => mt.derivedLambdaType(paramNames, mt.paramInfos, rt) @@ -1122,7 +1122,7 @@ class ClassfileParser( def parseScalaSigBytes: Array[Byte] = { val tag = in.nextByte.toChar assert(tag == STRING_TAG, tag) - pool getBytes in.nextChar + pool.getBytes(in.nextChar) } def parseScalaLongSigBytes: Array[Byte] = { diff --git a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala index 7f560a53aae3..5087044f73e8 100644 --- a/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala +++ b/compiler/src/dotty/tools/dotc/core/unpickleScala2/Scala2Unpickler.scala @@ -579,7 +579,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas moduleClassRoot, rootClassUnpickler(start, moduleClassRoot.symbol, moduleClassRoot.sourceModule, infoRef), privateWithin) else { def completer(cls: Symbol) = { - val unpickler = new ClassUnpickler(infoRef) withDecls symScope(cls) + val unpickler = new ClassUnpickler(infoRef).withDecls(symScope(cls)) if (flags.is(ModuleClass)) unpickler.withSourceModule( cls.owner.info.decls.lookup(cls.name.sourceModuleName) @@ -592,7 +592,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas newSymbol(owner, name.asTermName, flags, localMemberUnpickler, privateWithin, coord = start) case MODULEsym => if (isModuleRoot) { - moduleRoot setFlag flags + moduleRoot.setFlag(flags) moduleRoot.symbol } else newSymbol(owner, name.asTermName, flags, new LocalUnpickler().withModuleClass( @@ -664,7 +664,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas assert(denot.is(ParamAccessor) || denot.symbol.isSuperAccessor, denot) def disambiguate(alt: Symbol) = // !!! DEBUG trace.onDebug(s"disambiguating ${denot.info} =:= ${denot.owner.thisType.memberInfo(alt)} ${denot.owner}") { - denot.info matches denot.owner.thisType.memberInfo(alt) + denot.info.matches(denot.owner.thisType.memberInfo(alt)) } val alias = readDisambiguatedSymbolRef(disambiguate).asTerm if alias.name == denot.name then denot.setFlag(SuperParamAlias) @@ -748,7 +748,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas case _ => super.foldOver(x, tp) def removeSingleton(tp: Type): Type = - if (tp isRef defn.SingletonClass) defn.AnyType else tp + if tp.isRef(defn.SingletonClass) then defn.AnyType else tp def mapArg(arg: Type) = arg match { case arg: TypeRef if isBound(arg) => arg.symbol.info case _ => arg @@ -1238,7 +1238,7 @@ class Scala2Unpickler(bytes: Array[Byte], classRoot: ClassDenotation, moduleClas val vparams = until(end, () => readValDefRef()) val applyType = MethodType(vparams map (_.name), vparams map (_.tpt.tpe), body.tpe) val applyMeth = newSymbol(symbol.owner, nme.apply, Method, applyType) - Closure(applyMeth, Function.const(body.changeOwner(symbol, applyMeth)) _) + Closure(applyMeth, Function.const(body.changeOwner(symbol, applyMeth))) case ASSIGNtree => val lhs = readTreeRef() diff --git a/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala b/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala index 6fe6d4ec22f7..338dd72f178e 100644 --- a/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala +++ b/compiler/src/dotty/tools/dotc/decompiler/DecompilationPrinter.scala @@ -27,7 +27,7 @@ class DecompilationPrinter extends Phase { var os: OutputStream|Null = null var ps: PrintStream|Null = null try { - os = File(outputDir.fileNamed("decompiled.scala").path)(Codec.UTF8).outputStream(append = true) + os = File(outputDir.fileNamed("decompiled.scala").path)(using Codec.UTF8).outputStream(append = true) ps = new PrintStream(os, /* autoFlush = */ false, StandardCharsets.UTF_8.name) printToOutput(ps) } diff --git a/compiler/src/dotty/tools/dotc/inlines/Inliner.scala b/compiler/src/dotty/tools/dotc/inlines/Inliner.scala index 17a98abfe667..356e5ad40fdd 100644 --- a/compiler/src/dotty/tools/dotc/inlines/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/inlines/Inliner.scala @@ -44,7 +44,7 @@ object Inliner: | DefDef(_, _, _, _) => true case vdef @ ValDef(_, _, _) => - if (vdef.symbol.flags is Mutable) false else apply(vdef.rhs) + if vdef.symbol.flags.is(Mutable) then false else apply(vdef.rhs) case _ => false } diff --git a/compiler/src/dotty/tools/dotc/inlines/Inlines.scala b/compiler/src/dotty/tools/dotc/inlines/Inlines.scala index f088480a7c71..83cdb5c1b26c 100644 --- a/compiler/src/dotty/tools/dotc/inlines/Inlines.scala +++ b/compiler/src/dotty/tools/dotc/inlines/Inlines.scala @@ -301,12 +301,12 @@ object Inlines: inContext(ctx.withSource(curSource)) { tree match - case tree: Ident => finalize(untpd.Ident(tree.name)(curSource)) - case tree: Literal => finalize(untpd.Literal(tree.const)(curSource)) - case tree: This => finalize(untpd.This(tree.qual)(curSource)) - case tree: JavaSeqLiteral => finalize(untpd.JavaSeqLiteral(transform(tree.elems), transform(tree.elemtpt))(curSource)) - case tree: SeqLiteral => finalize(untpd.SeqLiteral(transform(tree.elems), transform(tree.elemtpt))(curSource)) - case tree: Bind => finalize(untpd.Bind(tree.name, transform(tree.body))(curSource)) + case tree: Ident => finalize(untpd.Ident(tree.name)(using curSource)) + case tree: Literal => finalize(untpd.Literal(tree.const)(using curSource)) + case tree: This => finalize(untpd.This(tree.qual)(using curSource)) + case tree: JavaSeqLiteral => finalize(untpd.JavaSeqLiteral(transform(tree.elems), transform(tree.elemtpt))(using curSource)) + case tree: SeqLiteral => finalize(untpd.SeqLiteral(transform(tree.elems), transform(tree.elemtpt))(using curSource)) + case tree: Bind => finalize(untpd.Bind(tree.name, transform(tree.body))(using curSource)) case tree: TypeTree => finalize(tpd.TypeTree(tree.tpe)) case tree: DefTree => super.transform(tree).setDefTree case EmptyTree => tree diff --git a/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala b/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala index d1164d4742af..721c7a36acda 100644 --- a/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala @@ -509,7 +509,7 @@ object JavaParsers { if (isPackageAccess && !inInterface) thisPackageName else tpnme.EMPTY - return Modifiers(flags, privateWithin) withAnnotations annots.toList + return Modifiers(flags, privateWithin).withAnnotations(annots.toList) } assert(false, "should not be here") throw new RuntimeException @@ -646,7 +646,7 @@ object JavaParsers { atSpan(nameOffset) { New(Select(Select(scalaDot(nme.annotation), nme.internal), tpnme.AnnotationDefaultATTR), Nil) } - mods1 = mods1 withAddedAnnotation annot + mods1 = mods1.withAddedAnnotation(annot) val unimplemented = unimplementedExpr skipTo(SEMI) accept(SEMI) @@ -916,7 +916,7 @@ object JavaParsers { } else List(ObjectTpt()) - val permittedSubclasses = permittedSubclassesOpt(mods is Flags.Sealed) + val permittedSubclasses = permittedSubclassesOpt(mods.is(Flags.Sealed)) val (statics, body) = typeBody(INTERFACE, name) val iface = atSpan(start, nameOffset) { TypeDef( diff --git a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala index f4d3d14628df..a31152ddcc6f 100644 --- a/compiler/src/dotty/tools/dotc/parsing/Parsers.scala +++ b/compiler/src/dotty/tools/dotc/parsing/Parsers.scala @@ -3500,7 +3500,7 @@ object Parsers { } def annotsAsMods(skipNewLines: Boolean = false): Modifiers = - Modifiers() withAnnotations annotations(skipNewLines) + Modifiers().withAnnotations(annotations(skipNewLines)) def defAnnotsMods(allowed: BitSet): Modifiers = modifiers(allowed, annotsAsMods(skipNewLines = true)) diff --git a/compiler/src/dotty/tools/dotc/parsing/xml/MarkupParserCommon.scala b/compiler/src/dotty/tools/dotc/parsing/xml/MarkupParserCommon.scala index 803470fe85a5..671d26af4875 100644 --- a/compiler/src/dotty/tools/dotc/parsing/xml/MarkupParserCommon.scala +++ b/compiler/src/dotty/tools/dotc/parsing/xml/MarkupParserCommon.scala @@ -151,11 +151,11 @@ private[dotty] trait MarkupParserCommon { * see [66] */ def xCharRef(ch: () => Char, nextch: () => Unit): String = - Utility.parseCharRef(ch, nextch, reportSyntaxError _, truncatedError _) + Utility.parseCharRef(ch, nextch, reportSyntaxError(_), truncatedError(_)) def xCharRef(it: Iterator[Char]): String = { var c = it.next() - Utility.parseCharRef(() => c, () => { c = it.next() }, reportSyntaxError _, truncatedError _) + Utility.parseCharRef(() => c, () => { c = it.next() }, reportSyntaxError(_), truncatedError(_)) } def xCharRef: String = xCharRef(() => ch, () => nextch()) diff --git a/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala b/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala index d1f2875064d4..aa8532b1d969 100644 --- a/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala +++ b/compiler/src/dotty/tools/dotc/parsing/xml/SymbolicXMLBuilder.scala @@ -200,7 +200,7 @@ class SymbolicXMLBuilder(parser: Parser, preserveWS: Boolean)(using Context) { /** Extract all the namespaces from the attribute map. */ val namespaces: List[Tree] = - for (z <- attrMap.keys.toList ; if z startsWith "xmlns") yield { + for z <- attrMap.keys.toList if z.startsWith("xmlns") yield { val ns = splitPrefix(z) match { case (Some(_), rest) => rest case _ => null diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugin.scala b/compiler/src/dotty/tools/dotc/plugins/Plugin.scala index 5838f5df7e97..c0532944c9de 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugin.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugin.scala @@ -105,7 +105,7 @@ object Plugin { def load(classname: String, loader: ClassLoader): Try[AnyClass] = { import scala.util.control.NonFatal try - Success[AnyClass](loader loadClass classname) + Success[AnyClass](loader.loadClass(classname)) catch { case NonFatal(e) => Failure(new PluginLoadException(classname, s"Error: unable to load class $classname: ${e.getMessage}")) @@ -154,7 +154,10 @@ object Plugin { // List[(jar, Try(descriptor))] in dir def scan(d: Directory) = - d.files.toList sortBy (_.name) filter (Jar isJarOrZip _) map (j => (j, loadDescriptionFromJar(j))) + d.files.toList + .sortBy(_.name) + .filter(Jar.isJarOrZip(_)) + .map(j => (j, loadDescriptionFromJar(j))) type PDResults = List[Try[(String, ClassLoader)]] diff --git a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala index f3a58cde1a0c..6c162184f816 100644 --- a/compiler/src/dotty/tools/dotc/plugins/Plugins.scala +++ b/compiler/src/dotty/tools/dotc/plugins/Plugins.scala @@ -27,8 +27,10 @@ trait Plugins { * filtered from the final list of plugins. */ protected def loadRoughPluginsList(using Context): List[Plugin] = { - def asPath(p: String) = ClassPath split p - val paths = ctx.settings.plugin.value filter (_ != "") map (s => asPath(s) map Path.apply) + def asPath(p: String) = ClassPath.split(p) + val paths = ctx.settings.plugin.value + .filter (_ != "") + .map(s => asPath(s).map(Path.apply)) val dirs = { def injectDefault(s: String) = if (s.isEmpty) PathResolver.Defaults.scalaPluginPath else s asPath(ctx.settings.pluginsDir.value) map injectDefault map Path.apply @@ -87,11 +89,11 @@ trait Plugins { report.error(em"Missing required plugin: $req") // Verify no non-existent plugin given with -P - for { + for opt <- ctx.settings.pluginOptions.value - if !(plugs exists (opt startsWith _.name + ":")) - } - report.error(em"bad option: -P:$opt") + if !plugs.exists(plug => opt.startsWith(plug.name + ":")) + do + report.error(em"bad option: -P:$opt") plugs } @@ -115,10 +117,11 @@ trait Plugins { /** Add plugin phases to phase plan */ def addPluginPhases(plan: List[List[Phase]])(using Context): List[List[Phase]] = { - def options(plugin: Plugin): List[String] = { + def options(plugin: Plugin): List[String] = def namec = plugin.name + ":" - ctx.settings.pluginOptions.value filter (_ startsWith namec) map (_ stripPrefix namec) - } + ctx.settings.pluginOptions.value + .filter(_.startsWith(namec)) + .map(_.stripPrefix(namec)) // schedule plugins according to ordering constraints val pluginPhases = plugins.collect { case p: StandardPlugin => p }.flatMap { plug => plug.initialize(options(plug)) } diff --git a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala index 042a15f5ba0b..3a0611e74ec1 100644 --- a/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala +++ b/compiler/src/dotty/tools/dotc/printing/PlainPrinter.scala @@ -281,10 +281,10 @@ class PlainPrinter(_ctx: Context) extends Printer { def casesText = Text(cases.map(caseText), "\n") atPrec(InfixPrec) { toText(scrutinee) } ~ keywordStr(" match ") ~ "{" ~ casesText ~ "}" ~ - (" <: " ~ toText(bound) provided !bound.isAny) + (" <: " ~ toText(bound) `provided` !bound.isAny) }.close case tp @ CapturingType(parent, refs) => - val boxText: Text = Str("box ") provided tp.isBoxed && ccVerbose + val boxText: Text = Str("box ") `provided` tp.isBoxed && ccVerbose if elideCapabilityCaps && parent.derivesFromCapability && refs.containsTerminalCapability @@ -312,7 +312,7 @@ class PlainPrinter(_ctx: Context) extends Printer { ~ keywordText("implicit ").provided(tp.isImplicitMethod && !tp.isContextualMethod) ~ paramsText(tp) ~ ")" - ~ (Str(": ") provided !tp.resultType.isInstanceOf[MethodOrPoly]) + ~ (Str(": ") `provided` !tp.resultType.isInstanceOf[MethodOrPoly]) ~ CCState.inNewExistentialScope(tp)(toText(tp.resultType)) } case ExprType(restp) => @@ -331,7 +331,7 @@ class PlainPrinter(_ctx: Context) extends Printer { case tp: PolyType => changePrec(GlobalPrec) { "[" ~ paramsText(tp) ~ "]" ~ hashStr(tp) ~ - (Str(": ") provided !tp.resultType.isInstanceOf[MethodOrPoly]) ~ + (Str(": ") `provided` !tp.resultType.isInstanceOf[MethodOrPoly]) ~ toTextGlobal(tp.resultType) } case AnnotatedType(tpe, annot) => @@ -579,7 +579,7 @@ class PlainPrinter(_ctx: Context) extends Printer { (if (isParameter) ": => " else ": ") ~ toTextGlobal(tp.widenExpr) case tp: PolyType => "[" ~ paramsText(tp) ~ "]" - ~ (Str(": ") provided !tp.resultType.isInstanceOf[MethodOrPoly]) + ~ (Str(": ") `provided` !tp.resultType.isInstanceOf[MethodOrPoly]) ~ toTextGlobal(tp.resultType) case tp => ": " ~ toTextGlobal(tp) @@ -755,7 +755,7 @@ class PlainPrinter(_ctx: Context) extends Printer { else Text() - nodeName ~ "(" ~ elems ~ tpSuffix ~ ")" ~ (Str(tree.sourcePos.toString) provided printDebug) + nodeName ~ "(" ~ elems ~ tpSuffix ~ ")" ~ Str(tree.sourcePos.toString).provided(printDebug) }.close def toText(pos: SourcePosition): Text = diff --git a/compiler/src/dotty/tools/dotc/printing/Printer.scala b/compiler/src/dotty/tools/dotc/printing/Printer.scala index 761e6a6bb6ba..2d6e5d858736 100644 --- a/compiler/src/dotty/tools/dotc/printing/Printer.scala +++ b/compiler/src/dotty/tools/dotc/printing/Printer.scala @@ -189,7 +189,7 @@ abstract class Printer { /** Render elements alternating with `sep` string */ def toText(elems: Iterable[Showable], sep: String): Text = - Text(elems map (_ toText this), sep) + Text(elems.map(_.toText(this)), sep) /** Render elements within highest precedence */ def toTextLocal(elems: Iterable[Showable], sep: String): Text = diff --git a/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala b/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala index fd73dbe76477..3714878a42ee 100644 --- a/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala +++ b/compiler/src/dotty/tools/dotc/printing/RefinedPrinter.scala @@ -335,9 +335,11 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { case AnySelectionProto => "a type that can be selected or applied" case tp: SelectionProto => - "?{ " ~ toText(tp.name) ~ - (Str(" ") provided !tp.name.toSimpleName.last.isLetterOrDigit) ~ - ": " ~ toText(tp.memberProto) ~ " }" + "?{ " + ~ toText(tp.name) + ~ Str(" ").provided(!tp.name.toSimpleName.last.isLetterOrDigit) + ~ ": " ~ toText(tp.memberProto) + ~ " }" case tp: ViewProto => toText(tp.argType) ~ " ?=>? " ~ toText(tp.resultType) case tp @ FunProto(args, resultType) => @@ -348,7 +350,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { ~ toText(resultType) ~ "]" case IgnoredProto(ignored) => - "?" ~ (("(ignored: " ~ toText(ignored) ~ ")") provided printDebug) + "?" ~ ("(ignored: " ~ toText(ignored) ~ ")").provided(printDebug) case tp @ PolyProto(targs, resType) => "[applied to [" ~ toTextGlobal(targs, ", ") ~ "] returning " ~ toText(resType) case _ => @@ -389,7 +391,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { case _ => false } - def optDotPrefix(tree: This) = optText(tree.qual)(_ ~ ".") provided !isLocalThis(tree) + def optDotPrefix(tree: This) = optText(tree.qual)(_ ~ ".").provided(!isLocalThis(tree)) /** Should a binary operation with this operator be printed infix? */ def isInfix(op: Symbol) = @@ -481,7 +483,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { else txt case tree @ Select(qual, name) => if (qual.isType) toTextLocal(qual) ~ "#" ~ typeText(toText(name)) - else toTextLocal(qual) ~ ("." ~ nameIdText(tree) provided (name != nme.CONSTRUCTOR || printDebug)) + else toTextLocal(qual) ~ ("." ~ nameIdText(tree) `provided` (name != nme.CONSTRUCTOR || printDebug)) case tree: This => optDotPrefix(tree) ~ keywordStr("this") ~ idText(tree) case Super(qual: This, mix) => @@ -547,12 +549,13 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { val isInline = tree.isInstanceOf[Trees.InlineIf[?]] changePrec(GlobalPrec) { keywordStr(if (isInline) "inline if " else "if ") ~ - toText(cond) ~ (keywordText(" then") provided !cond.isInstanceOf[Parens]) ~~ + toText(cond) ~ keywordText(" then").provided(!cond.isInstanceOf[Parens]) ~~ toText(thenp) ~ optText(elsep)(keywordStr(" else ") ~ _) } case Closure(env, ref, target) => - "closure(" ~ (toTextGlobal(env, ", ") ~ " | " provided env.nonEmpty) ~ - toTextGlobal(ref) ~ (":" ~ toText(target) provided !target.isEmpty) ~ ")" + "closure(" + ~ (toTextGlobal(env, ", ") ~ " | " `provided` env.nonEmpty) + ~ toTextGlobal(ref) ~ (":" ~ toText(target) `provided` !target.isEmpty) ~ ")" case Match(sel, cases) => val isInline = tree.isInstanceOf[Trees.InlineMatch[?]] if (sel.isEmpty && !isInline) blockText(cases) @@ -635,7 +638,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { case MatchTypeTree(bound, sel, cases) => changePrec(GlobalPrec) { toText(sel) ~ keywordStr(" match ") ~ blockText(cases) ~ - (" <: " ~ toText(bound) provided !bound.isEmpty) + (" <: " ~ toText(bound) `provided` !bound.isEmpty) } case ImpureByNameTypeTree(tpt) => "=> " ~ toTextLocal(tpt) @@ -656,7 +659,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { } toTextLocal(extractor) ~ "(" ~ toTextGlobal(patterns, ", ") ~ ")" ~ - ("(" ~ toTextGlobal(implicits, ", ") ~ ")" provided implicits.nonEmpty) + ("(" ~ toTextGlobal(implicits, ", ") ~ ")" `provided` implicits.nonEmpty) case tree @ ValDef(_, _, _) => valDefToText(tree) case tree @ DefDef(_, _, _, _) => @@ -777,7 +780,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { case ForDo(enums, expr) => forText(enums, expr, keywordStr(" do ")) case GenFrom(pat, expr, checkMode) => - (Str("case ") provided checkMode == untpd.GenCheckMode.FilterAlways) ~ + (Str("case ") `provided` checkMode == untpd.GenCheckMode.FilterAlways) ~ toText(pat) ~ " <- " ~ toText(expr) case GenAlias(pat, expr) => toText(pat) ~ " = " ~ toText(expr) @@ -969,7 +972,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { else toText(tree.name) ~ idText(tree) private def toTextOwner(tree: Tree[?]) = - "[owner = " ~ tree.symbol.maybeOwner.show ~ "]" provided ctx.settings.YprintDebugOwners.value + "[owner = " ~ tree.symbol.maybeOwner.show ~ "]" `provided` ctx.settings.YprintDebugOwners.value protected def dclTextOr[T <: Untyped](tree: Tree[T])(treeText: => Text): Text = toTextOwner(tree) ~ { @@ -1069,7 +1072,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { protected def toTextTemplate(impl: Template, ofNew: Boolean = false): Text = { val Template(constr @ DefDef(_, paramss, _, _), _, self, _) = impl val tparamsTxt = withEnclosingDef(constr) { - paramsText(constr.leadingTypeParams) provided constr.leadingTypeParams.nonEmpty + paramsText(constr.leadingTypeParams) `provided` constr.leadingTypeParams.nonEmpty } val primaryConstrs = if (constr.rhs.isEmpty) Nil else constr :: Nil val prefix: Text = @@ -1180,7 +1183,7 @@ class RefinedPrinter(_ctx: Context) extends PlainPrinter(_ctx) { sym.annotationsUNSAFE.filterNot(ann => dropAnnotForModText(ann.symbol)).map(toText) else mods.annotations.filterNot(tree => dropAnnotForModText(tree.symbol)).map(annotText(NoSymbol, _)) - Text(annotTexts, " ") ~~ flagsText ~~ (Str(kw) provided !suppressKw) + Text(annotTexts, " ") ~~ flagsText ~~ (Str(kw) `provided` !suppressKw) } def optText(name: Name)(encl: Text => Text): Text = diff --git a/compiler/src/dotty/tools/dotc/printing/Texts.scala b/compiler/src/dotty/tools/dotc/printing/Texts.scala index a4b2e3305742..77670b074833 100644 --- a/compiler/src/dotty/tools/dotc/printing/Texts.scala +++ b/compiler/src/dotty/tools/dotc/printing/Texts.scala @@ -37,8 +37,8 @@ object Texts { case Fluid(Nil) => width case Fluid(last :: prevs) => - val r = last remaining width - if (r < 0) r else Fluid(prevs) remaining r + val r = last.remaining(width) + if (r < 0) r else Fluid(prevs).remaining(r) case Vertical(_) => -1 } @@ -51,13 +51,13 @@ object Texts { def appendToLastLine(that: Text): Text = that match { case Str(s2, lines1) => this match { - case Str(s1, lines2) => Str(s1 + s2, lines1 union lines2) - case Fluid(Str(s1, lines2) :: prev) => Fluid(Str(s1 + s2, lines1 union lines2) :: prev) + case Str(s1, lines2) => Str(s1 + s2, lines1 `union` lines2) + case Fluid(Str(s1, lines2) :: prev) => Fluid(Str(s1 + s2, lines1 `union` lines2) :: prev) case Fluid(relems) => Fluid(that :: relems) case Vertical(_) => throw new IllegalArgumentException("Unexpected Vertical.appendToLastLine") } case Fluid(relems) => - relems.reverse.foldLeft(this)(_ appendToLastLine _) + relems.reverse.foldLeft(this)(_.appendToLastLine(_)) case Vertical(_) => throw new IllegalArgumentException("Unexpected Text.appendToLastLine(Vertical(...))") } @@ -82,18 +82,18 @@ object Texts { case Fluid(relems) => relems.reverse.foldLeft(Str(""): Text)(_.append(width)(_)) case Vertical(relems) => - Vertical(relems map (_ layout width)) + Vertical(relems.map(_.layout(width))) } def map(f: String => String): Text = this match { case Str(s, lines) => Str(f(s), lines) - case Fluid(relems) => Fluid(relems map (_ map f)) - case Vertical(relems) => Vertical(relems map (_ map f)) + case Fluid(relems) => Fluid(relems.map(_.map(f))) + case Vertical(relems) => Vertical(relems.map(_.map(f))) } def stripPrefix(pre: String): Text = this match { case Str(s, _) => - if (s.startsWith(pre)) s drop pre.length else s + if (s.startsWith(pre)) s.drop(pre.length) else s case Fluid(relems) => val elems = relems.reverse val head = elems.head.stripPrefix(pre) From b5d20c85e3b77fc81147589d5c3e6f7f7f69d273 Mon Sep 17 00:00:00 2001 From: odersky Date: Mon, 22 Sep 2025 14:20:01 +0200 Subject: [PATCH 5/6] Remove warnings in Test infrastructure --- compiler/test/dotc/comptest.scala | 2 +- .../dotty/tools/dotc/CompilationTests.scala | 32 +++++++++---------- .../dotty/tools/dotc/IdempotencyTests.scala | 10 +++--- .../test/dotty/tools/dotc/SettingsTests.scala | 6 ++-- .../tools/dotc/TastyBootstrapTests.scala | 8 ++--- .../dotc/config/ScalaSettingsTests.scala | 10 +++--- .../dotc/core/tasty/CommentPicklingTest.scala | 2 +- .../tools/dotc/parsing/ScannerTest.scala | 4 +-- .../tools/dotc/sbt/ProgressCallbackTest.scala | 2 +- .../repl/AbstractFileClassLoaderTest.scala | 2 +- .../dotty/tools/vulpix/ParallelTesting.scala | 6 ++-- .../tools/vulpix/TestConfiguration.scala | 10 +++--- .../tools/tasty/TastyVersionFormatTest.scala | 20 ++++++------ 13 files changed, 57 insertions(+), 57 deletions(-) diff --git a/compiler/test/dotc/comptest.scala b/compiler/test/dotc/comptest.scala index fb53f561a94d..d79ebad4a00d 100644 --- a/compiler/test/dotc/comptest.scala +++ b/compiler/test/dotc/comptest.scala @@ -27,5 +27,5 @@ object comptest extends ParallelTesting { dotcDir + "tools/dotc/ast/Trees.scala" ), TestFlags("", Array("-Ylog:typer", "-Xprompt")) - )(TestGroup("comptest")) + )(using TestGroup("comptest")) } diff --git a/compiler/test/dotty/tools/dotc/CompilationTests.scala b/compiler/test/dotty/tools/dotc/CompilationTests.scala index 0a826e7089bb..baf1b4d66306 100644 --- a/compiler/test/dotty/tools/dotc/CompilationTests.scala +++ b/compiler/test/dotty/tools/dotc/CompilationTests.scala @@ -210,8 +210,8 @@ class CompilationTests { implicit val testGroup: TestGroup = TestGroup("explicitNullsNeg") aggregateTests( compileFilesInDir("tests/explicit-nulls/neg", explicitNullsOptions, FileFilter.exclude(TestSources.negExplicitNullsScala2LibraryTastyExcludelisted)), - compileFilesInDir("tests/explicit-nulls/flexible-types-common", explicitNullsOptions and "-Yno-flexible-types"), - compileFilesInDir("tests/explicit-nulls/unsafe-common", explicitNullsOptions and "-Yno-flexible-types", FileFilter.exclude(TestSources.negExplicitNullsScala2LibraryTastyExcludelisted)), + compileFilesInDir("tests/explicit-nulls/flexible-types-common", explicitNullsOptions `and` "-Yno-flexible-types"), + compileFilesInDir("tests/explicit-nulls/unsafe-common", explicitNullsOptions `and` "-Yno-flexible-types", FileFilter.exclude(TestSources.negExplicitNullsScala2LibraryTastyExcludelisted)), ).checkExpectedErrors() locally { @@ -231,12 +231,12 @@ class CompilationTests { aggregateTests( compileFilesInDir("tests/explicit-nulls/pos", explicitNullsOptions), compileFilesInDir("tests/explicit-nulls/flexible-types-common", explicitNullsOptions), - compileFilesInDir("tests/explicit-nulls/unsafe-common", explicitNullsOptions and "-language:unsafeNulls" and "-Yno-flexible-types"), + compileFilesInDir("tests/explicit-nulls/unsafe-common", explicitNullsOptions `and` "-language:unsafeNulls" `and` "-Yno-flexible-types"), ).checkCompile() locally { val tests = List( - compileFile("tests/explicit-nulls/flexible-unpickle/pos/Unsafe_1.scala", explicitNullsOptions without "-Yexplicit-nulls"), + compileFile("tests/explicit-nulls/flexible-unpickle/pos/Unsafe_1.scala", explicitNullsOptions `without` "-Yexplicit-nulls"), compileFile("tests/explicit-nulls/flexible-unpickle/pos/Flexible_2.scala", explicitNullsOptions.and("-Yflexify-tasty").withClasspath(defaultOutputDir + testGroup + "/Unsafe_1/pos/Unsafe_1")), ).map(_.keepOutput.checkCompile()) @@ -289,9 +289,9 @@ class CompilationTests { val outDir2 = defaultOutputDir + i12128Group + "/Macro_2/i12128/Macro_2" val tests = List( - compileFile("tests/init/special/i12128/Reflect_1.scala", i12128Options)(i12128Group), - compileFile("tests/init/special/i12128/Macro_2.scala", i12128Options.withClasspath(outDir1))(i12128Group), - compileFile("tests/init/special/i12128/Test_3.scala", options.withClasspath(outDir2))(i12128Group) + compileFile("tests/init/special/i12128/Reflect_1.scala", i12128Options)(using i12128Group), + compileFile("tests/init/special/i12128/Macro_2.scala", i12128Options.withClasspath(outDir1))(using i12128Group), + compileFile("tests/init/special/i12128/Test_3.scala", options.withClasspath(outDir2))(using i12128Group) ).map(_.keepOutput.checkCompile()) tests.foreach(_.delete()) @@ -310,12 +310,12 @@ class CompilationTests { val classB1 = defaultOutputDir + tastyErrorGroup + "/B/v1/B" val tests = List( - compileFile("tests/init/tasty-error/val-or-defdef/v1/A.scala", tastyErrorOptions)(tastyErrorGroup), - compileFile("tests/init/tasty-error/val-or-defdef/v1/B.scala", tastyErrorOptions.withClasspath(classA1))(tastyErrorGroup), - compileFile("tests/init/tasty-error/val-or-defdef/v0/A.scala", tastyErrorOptions)(tastyErrorGroup), + compileFile("tests/init/tasty-error/val-or-defdef/v1/A.scala", tastyErrorOptions)(using tastyErrorGroup), + compileFile("tests/init/tasty-error/val-or-defdef/v1/B.scala", tastyErrorOptions.withClasspath(classA1))(using tastyErrorGroup), + compileFile("tests/init/tasty-error/val-or-defdef/v0/A.scala", tastyErrorOptions)(using tastyErrorGroup), ).map(_.keepOutput.checkCompile()) - compileFile("tests/init/tasty-error/val-or-defdef/Main.scala", tastyErrorOptions.withClasspath(classA0).withClasspath(classB1))(tastyErrorGroup).checkExpectedErrors() + compileFile("tests/init/tasty-error/val-or-defdef/Main.scala", tastyErrorOptions.withClasspath(classA0).withClasspath(classB1))(using tastyErrorGroup).checkExpectedErrors() tests.foreach(_.delete()) } @@ -334,13 +334,13 @@ class CompilationTests { val classB1 = defaultOutputDir + tastyErrorGroup + "/B/v1/B" val tests = List( - compileFile("tests/init/tasty-error/typedef/C.scala", tastyErrorOptions)(tastyErrorGroup), - compileFile("tests/init/tasty-error/typedef/v1/A.scala", tastyErrorOptions.withClasspath(classC))(tastyErrorGroup), - compileFile("tests/init/tasty-error/typedef/v1/B.scala", tastyErrorOptions.withClasspath(classC).withClasspath(classA1))(tastyErrorGroup), - compileFile("tests/init/tasty-error/typedef/v0/A.scala", tastyErrorOptions.withClasspath(classC))(tastyErrorGroup), + compileFile("tests/init/tasty-error/typedef/C.scala", tastyErrorOptions)(using tastyErrorGroup), + compileFile("tests/init/tasty-error/typedef/v1/A.scala", tastyErrorOptions.withClasspath(classC))(using tastyErrorGroup), + compileFile("tests/init/tasty-error/typedef/v1/B.scala", tastyErrorOptions.withClasspath(classC).withClasspath(classA1))(using tastyErrorGroup), + compileFile("tests/init/tasty-error/typedef/v0/A.scala", tastyErrorOptions.withClasspath(classC))(using tastyErrorGroup), ).map(_.keepOutput.checkCompile()) - compileFile("tests/init/tasty-error/typedef/Main.scala", tastyErrorOptions.withClasspath(classC).withClasspath(classA0).withClasspath(classB1))(tastyErrorGroup).checkExpectedErrors() + compileFile("tests/init/tasty-error/typedef/Main.scala", tastyErrorOptions.withClasspath(classC).withClasspath(classA0).withClasspath(classB1))(using tastyErrorGroup).checkExpectedErrors() tests.foreach(_.delete()) } diff --git a/compiler/test/dotty/tools/dotc/IdempotencyTests.scala b/compiler/test/dotty/tools/dotc/IdempotencyTests.scala index 81dd7d7f4710..1b0f999c4f84 100644 --- a/compiler/test/dotty/tools/dotc/IdempotencyTests.scala +++ b/compiler/test/dotty/tools/dotc/IdempotencyTests.scala @@ -30,8 +30,8 @@ class IdempotencyTests { val opt = defaultOptions val posIdempotency = aggregateTests( - compileFilesInDir("tests/pos", opt, filter)(TestGroup("idempotency/posIdempotency1")), - compileFilesInDir("tests/pos", opt, filter)(TestGroup("idempotency/posIdempotency2")), + compileFilesInDir("tests/pos", opt, filter)(using TestGroup("idempotency/posIdempotency1")), + compileFilesInDir("tests/pos", opt, filter)(using TestGroup("idempotency/posIdempotency2")), ) val orderIdempotency = { @@ -41,8 +41,8 @@ class IdempotencyTests { } yield { val sources = TestSources.sources(testDir.toPath) aggregateTests( - compileList(testDir.getName, sources, opt)(TestGroup("idempotency/orderIdempotency1")), - compileList(testDir.getName, sources.reverse, opt)(TestGroup("idempotency/orderIdempotency2")) + compileList(testDir.getName, sources, opt)(using TestGroup("idempotency/orderIdempotency1")), + compileList(testDir.getName, sources.reverse, opt)(using TestGroup("idempotency/orderIdempotency2")) ) } aggregateTests(tests*) @@ -50,7 +50,7 @@ class IdempotencyTests { def check(name: String) = { val files = List(s"tests/idempotency/$name.scala", "tests/idempotency/IdempotencyCheck.scala") - compileList(name, files, defaultOptions)(TestGroup("idempotency/check")) + compileList(name, files, defaultOptions)(using TestGroup("idempotency/check")) } val allChecks = aggregateTests( check("CheckOrderIdempotency"), diff --git a/compiler/test/dotty/tools/dotc/SettingsTests.scala b/compiler/test/dotty/tools/dotc/SettingsTests.scala index 24549ade4d23..ac4e2341b2c2 100644 --- a/compiler/test/dotty/tools/dotc/SettingsTests.scala +++ b/compiler/test/dotty/tools/dotc/SettingsTests.scala @@ -218,7 +218,7 @@ class SettingsTests { assertNotEquals(fileStateBefore, String(Files.readAllBytes(file)), "Jar should have been overriden") - }(Files.deleteIfExists(_)) + }(using Files.deleteIfExists(_)) @Test def `Output setting is respecting previous setting`: Unit = val result = Using.resources( @@ -263,7 +263,7 @@ class SettingsTests { assertEquals(fileStateBefore, String(Files.readAllBytes(file))) - }(Files.deleteIfExists(_)) + }(using Files.deleteIfExists(_)) @Test def `Arguments of flags are correctly parsed with both ":" and " " separating`: Unit = object Settings extends SettingGroup: @@ -319,7 +319,7 @@ class SettingsTests { testValues(summary = summaryColon) testValues(summary = summaryWhitespace) - }(Files.deleteIfExists(_)) + }(using Files.deleteIfExists(_)) private def withProcessedArgs(summary: ArgsSummary)(f: SettingsState ?=> Unit) = f(using summary.sstate) diff --git a/compiler/test/dotty/tools/dotc/TastyBootstrapTests.scala b/compiler/test/dotty/tools/dotc/TastyBootstrapTests.scala index 046c8cf4754e..1d8f6597e4ff 100644 --- a/compiler/test/dotty/tools/dotc/TastyBootstrapTests.scala +++ b/compiler/test/dotty/tools/dotc/TastyBootstrapTests.scala @@ -61,18 +61,18 @@ class TastyBootstrapTests { compileList("lib", librarySources, defaultOptions.and("-Ycheck-reentrant", // "-source", "future", // TODO: re-enable once library uses updated syntax for vararg splices, wildcard imports, and import renaming - ))(libGroup) + ))(using libGroup) val tastyCoreSources = sources(Paths.get("tasty/src")) - val tastyCore = compileList("tastyCore", tastyCoreSources, opt)(tastyCoreGroup) + val tastyCore = compileList("tastyCore", tastyCoreSources, opt)(using tastyCoreGroup) val compilerSources = sources(Paths.get("compiler/src")) ++ sources(Paths.get("compiler/src-bootstrapped")) val compilerManagedSources = Properties.dottyCompilerManagedSources match case p if Files.isDirectory(p) => sources(p) case _ => Nil - val dotty1 = compileList("dotty1", compilerSources ++ compilerManagedSources, opt)(dotty1Group) - val dotty2 = compileList("dotty2", compilerSources ++ compilerManagedSources, opt)(dotty2Group) + val dotty1 = compileList("dotty1", compilerSources ++ compilerManagedSources, opt)(using dotty1Group) + val dotty2 = compileList("dotty2", compilerSources ++ compilerManagedSources, opt)(using dotty2Group) val tests = { lib.keepOutput :: tastyCore.keepOutput :: dotty1.keepOutput :: aggregateTests( diff --git a/compiler/test/dotty/tools/dotc/config/ScalaSettingsTests.scala b/compiler/test/dotty/tools/dotc/config/ScalaSettingsTests.scala index c7b030f0805c..b2d35f40bc8f 100644 --- a/compiler/test/dotty/tools/dotc/config/ScalaSettingsTests.scala +++ b/compiler/test/dotty/tools/dotc/config/ScalaSettingsTests.scala @@ -92,7 +92,7 @@ class ScalaSettingsTests: @nowarn("cat=deprecation") @Test def `Deprecated options are correctly mapped to their replacements`: Unit = - def createTestCase(oldSetting: Setting[_], newSetting: Setting[_], value: String = "") = + def createTestCase(oldSetting: Setting[?], newSetting: Setting[?], value: String = "") = s"${oldSetting.name}$value" -> newSetting val settings = ScalaSettings @@ -121,7 +121,7 @@ class ScalaSettingsTests: @nowarn("cat=deprecation") @Test def `Deprecated options should not be set if old option was incorrect`: Unit = - def createTestCase(oldSetting: Setting[_], newSetting: Setting[_], value: String = ":illegal") = + def createTestCase(oldSetting: Setting[?], newSetting: Setting[?], value: String = ":illegal") = s"${oldSetting.name}:$value" -> newSetting val settings = ScalaSettings @@ -161,7 +161,7 @@ class ScalaSettingsTests: @nowarn("cat=deprecation") @Test def `Deprecated options aliases are correctly mapped to their replacements`: Unit = - def createTestCase(oldSetting: Setting[_], newSetting: Setting[_], value: String = "") = + def createTestCase(oldSetting: Setting[?], newSetting: Setting[?], value: String = "") = oldSetting.aliases.map: alias => s"$alias$value" -> newSetting @@ -250,7 +250,7 @@ class ScalaSettingsTests: ) ) ) - }(Files.deleteIfExists(_)) + }(using Files.deleteIfExists(_)) assertEquals(result, Right(reporting.Action.Silent)) @Test def `WConf src filter doesn't silence warnings from a non-matching path for real file`: Unit = @@ -265,7 +265,7 @@ class ScalaSettingsTests: ) ) ) - }(Files.deleteIfExists(_)) + }(using Files.deleteIfExists(_)) assertEquals(result, Right(reporting.Action.Warning)) @Test def `WConf src filter reports an error on an invalid regex`: Unit = diff --git a/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala b/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala index 072944da1349..55b611310e39 100644 --- a/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala +++ b/compiler/test/dotty/tools/dotc/core/tasty/CommentPicklingTest.scala @@ -22,7 +22,7 @@ import dotty.tools.io.AbstractFile class CommentPicklingTest { - val compileOptions = TestConfiguration.defaultOptions and "-Ykeep-comments" and "-Yemit-tasty" + val compileOptions = TestConfiguration.defaultOptions `and` "-Ykeep-comments" `and` "-Yemit-tasty" val unpickleOptions = TestConfiguration.defaultOptions @Test def commentOnDef: Unit = { diff --git a/compiler/test/dotty/tools/dotc/parsing/ScannerTest.scala b/compiler/test/dotty/tools/dotc/parsing/ScannerTest.scala index 9f78d0778b41..d53d41103cba 100644 --- a/compiler/test/dotty/tools/dotc/parsing/ScannerTest.scala +++ b/compiler/test/dotty/tools/dotc/parsing/ScannerTest.scala @@ -33,12 +33,12 @@ class ScannerTest extends DottyTest { def scanDir(path: String): Unit = scanDir(Directory(path)) def scanDir(dir: Directory): Unit = { - if (excluded exists (dir.jpath.toString endsWith _)) + if excluded.exists(dir.jpath.toString.endsWith(_)) then println(s"excluded package: ${dir.toAbsolute.jpath}") else for (f <- dir.files) if (f.name.endsWith(".scala")) - if (excluded exists (f.jpath.toString endsWith _)) + if excluded.exists(f.jpath.toString.endsWith(_)) then println(s"excluded file: ${f.toAbsolute.jpath}") else scan(new PlainFile(f)) diff --git a/compiler/test/dotty/tools/dotc/sbt/ProgressCallbackTest.scala b/compiler/test/dotty/tools/dotc/sbt/ProgressCallbackTest.scala index 49fd3ee68d5f..a00e478c6ddf 100644 --- a/compiler/test/dotty/tools/dotc/sbt/ProgressCallbackTest.scala +++ b/compiler/test/dotty/tools/dotc/sbt/ProgressCallbackTest.scala @@ -149,7 +149,7 @@ final class ProgressCallbackTest extends DottyTest: assertEquals(s"Phase $recordedCurr was not expected", expectedCurr, recordedCurr) val (seenCurrPhases, seenNextPhases) = - val (currs0, nexts0) = progressCallback.progressPhasesFinal.unzip(Tuple.fromProductTyped) + val (currs0, nexts0) = progressCallback.progressPhasesFinal.unzip(using Tuple.fromProductTyped) (currs0.toSet, nexts0.toSet) val missingCurrPhases = expectedCurrPhases.diff(seenCurrPhases) diff --git a/compiler/test/dotty/tools/repl/AbstractFileClassLoaderTest.scala b/compiler/test/dotty/tools/repl/AbstractFileClassLoaderTest.scala index 44540629016e..b06c34950719 100644 --- a/compiler/test/dotty/tools/repl/AbstractFileClassLoaderTest.scala +++ b/compiler/test/dotty/tools/repl/AbstractFileClassLoaderTest.scala @@ -18,7 +18,7 @@ class AbstractFileClassLoaderTest: def closing[T <: Closeable, U](stream: T)(f: T => U): U = try f(stream) finally stream.close() extension (f: AbstractFile) def writeContent(s: String): Unit = closing(f.bufferedOutput)(_.write(s.getBytes(UTF8.charSet))) - def slurp(inputStream: => InputStream)(implicit codec: Codec): String = closing(Source.fromInputStream(inputStream)(codec))(_.mkString) + def slurp(inputStream: => InputStream)(implicit codec: Codec): String = closing(Source.fromInputStream(inputStream)(using codec))(_.mkString) def slurp(url: URL)(implicit codec: Codec): String = slurp(url.openStream()) extension (input: InputStream) def bytes: Array[Byte] = diff --git a/compiler/test/dotty/tools/vulpix/ParallelTesting.scala b/compiler/test/dotty/tools/vulpix/ParallelTesting.scala index ed8b69b90e4b..e84b721b0bb0 100644 --- a/compiler/test/dotty/tools/vulpix/ParallelTesting.scala +++ b/compiler/test/dotty/tools/vulpix/ParallelTesting.scala @@ -684,7 +684,7 @@ trait ParallelTesting extends RunnerOrchestration: protected def compileFromBestEffortTasty(flags0: TestFlags, targetDir: JFile): TestReporter = { val classes = flattenFiles(targetDir).filter(isBestEffortTastyFile).map(_.toString) - val flags = flags0 and "-from-tasty" and "-Ywith-best-effort-tasty" + val flags = flags0 `and` "-from-tasty" `and` "-Ywith-best-effort-tasty" val reporter = mkReporter val driver = new Driver @@ -710,7 +710,7 @@ trait ParallelTesting extends RunnerOrchestration: protected def compileFromTasty(flags0: TestFlags, targetDir: JFile): TestReporter = { val tastyOutput = new JFile(targetDir.getPath + "_from-tasty") tastyOutput.mkdir() - val flags = flags0 and ("-d", tastyOutput.getPath) and "-from-tasty" + val flags = flags0 `and` ("-d", tastyOutput.getPath) `and` "-from-tasty" val classes = flattenFiles(targetDir).filter(isTastyFile).map(_.toString) @@ -1566,7 +1566,7 @@ trait ParallelTesting extends RunnerOrchestration: def compileTastyInDir(f: String, flags0: TestFlags, fromTastyFilter: FileFilter)( implicit testGroup: TestGroup): TastyCompilationTest = { val outDir = defaultOutputDir + testGroup + JFile.separator - val flags = flags0 and "-Yretain-trees" + val flags = flags0 `and` "-Yretain-trees" val sourceDir = new JFile(f) checkRequirements(f, sourceDir, outDir) diff --git a/compiler/test/dotty/tools/vulpix/TestConfiguration.scala b/compiler/test/dotty/tools/vulpix/TestConfiguration.scala index 8304cec5bb24..ff589c953c23 100644 --- a/compiler/test/dotty/tools/vulpix/TestConfiguration.scala +++ b/compiler/test/dotty/tools/vulpix/TestConfiguration.scala @@ -62,7 +62,7 @@ object TestConfiguration { val commonOptions = Array("-indent") ++ checkOptions ++ noCheckOptions ++ yCheckOptions val noYcheckCommonOptions = Array("-indent") ++ checkOptions ++ noCheckOptions - val defaultOptions = TestFlags(basicClasspath, commonOptions) and "-Yno-stdlib-patches" + val defaultOptions = TestFlags(basicClasspath, commonOptions) `and` "-Yno-stdlib-patches" val noYcheckOptions = TestFlags(basicClasspath, noYcheckCommonOptions) val bestEffortBaselineOptions = TestFlags(basicClasspath, noCheckOptions) val unindentOptions = TestFlags(basicClasspath, Array("-no-indent") ++ checkOptions ++ noCheckOptions ++ yCheckOptions) @@ -74,9 +74,9 @@ object TestConfiguration { defaultOptions.withClasspath(withTastyInspectorClasspath).withRunClasspath(withTastyInspectorClasspath) lazy val scalaJSOptions = defaultOptions.and("-scalajs").withClasspath(scalaJSClasspath).withRunClasspath(scalaJSClasspath) - val allowDeepSubtypes = defaultOptions without "-Yno-deep-subtypes" - val allowDoubleBindings = defaultOptions without "-Yno-double-bindings" - val picklingOptions = defaultOptions and ( + val allowDeepSubtypes = defaultOptions `without` "-Yno-deep-subtypes" + val allowDoubleBindings = defaultOptions `without` "-Yno-double-bindings" + val picklingOptions = defaultOptions `and` ( "-Xprint-types", "-Ytest-pickler", "-Yprint-pos", @@ -85,7 +85,7 @@ object TestConfiguration { val picklingWithCompilerOptions = picklingOptions.withClasspath(withCompilerClasspath).withRunClasspath(withCompilerClasspath) - val explicitNullsOptions = defaultOptions and "-Yexplicit-nulls" + val explicitNullsOptions = defaultOptions `and` "-Yexplicit-nulls" /** Default target of the generated class files */ private def defaultTarget: String = { diff --git a/tasty/test/dotty/tools/tasty/TastyVersionFormatTest.scala b/tasty/test/dotty/tools/tasty/TastyVersionFormatTest.scala index 3e29c9baaf81..da61152e2a93 100644 --- a/tasty/test/dotty/tools/tasty/TastyVersionFormatTest.scala +++ b/tasty/test/dotty/tools/tasty/TastyVersionFormatTest.scala @@ -31,34 +31,34 @@ class TastyVersionFormatTest { /** these cases are unrelated because a final compiler can only read final tasty of <= minor version */ @Test def reject_FinalReadFinal_GTMinor: Unit = { - assert(file(28,2,Final) unrelatedTo compiler(28,1,Final)) // succeeding minor + assert(file(28,2,Final) `unrelatedTo` compiler(28,1,Final)) // succeeding minor } /** these cases are unrelated because a final compiler can not read experimental tasty */ @Test def reject_FinalReadExperimental: Unit = { - assert(file(28,0,Exp(1)) unrelatedTo compiler(28,1,Final)) // preceding minor - assert(file(28,1,Exp(1)) unrelatedTo compiler(28,1,Final)) // same minor - assert(file(28,2,Exp(1)) unrelatedTo compiler(28,1,Final)) // succeeding minor + assert(file(28,0,Exp(1)) `unrelatedTo` compiler(28,1,Final)) // preceding minor + assert(file(28,1,Exp(1)) `unrelatedTo` compiler(28,1,Final)) // same minor + assert(file(28,2,Exp(1)) `unrelatedTo` compiler(28,1,Final)) // succeeding minor } /** These cases are unrelated because an experimental compiler can only read final tasty of < minor version */ @Test def reject_ExperimentalReadFinal_GTEqualMinor: Unit = { - assert(file(28,2,Final) unrelatedTo compiler(28,1,Exp(1))) // succeeding minor - assert(file(28,1,Final) unrelatedTo compiler(28,1,Exp(1))) // equal minor + assert(file(28,2,Final) `unrelatedTo` compiler(28,1,Exp(1))) // succeeding minor + assert(file(28,1,Final) `unrelatedTo` compiler(28,1,Exp(1))) // equal minor } /**These cases are unrelated because both compiler and file are experimental, * and with unequal experimental part. */ @Test def reject_ExperimentalReadNEExperimental: Unit = { - assert(file(28,1,Exp(2)) unrelatedTo compiler(28,1,Exp(1))) // same minor version, succeeding experimental - assert(file(28,1,Exp(1)) unrelatedTo compiler(28,1,Exp(2))) // same minor version, preceding experimental + assert(file(28,1,Exp(2)) `unrelatedTo` compiler(28,1,Exp(1))) // same minor version, succeeding experimental + assert(file(28,1,Exp(1)) `unrelatedTo` compiler(28,1,Exp(2))) // same minor version, preceding experimental } /** these cases are unrelated because the major version must be identical */ @Test def reject_NEMajor: Unit = { - assert(file(27,0,Final) unrelatedTo compiler(28,0,Final)) // less than - assert(file(29,0,Final) unrelatedTo compiler(28,0,Final)) // greater than + assert(file(27,0,Final) `unrelatedTo` compiler(28,0,Final)) // less than + assert(file(29,0,Final) `unrelatedTo` compiler(28,0,Final)) // greater than } } From 4248321597d0b300156d9cbfa151626555b37971 Mon Sep 17 00:00:00 2001 From: odersky Date: Tue, 23 Sep 2025 13:40:19 +0200 Subject: [PATCH 6/6] Handle 2.13 specially for migration warnings and errors Move 2.13 back to its original place in front of future, but disable all migration warnings and errors for it. --- .../src/dotty/tools/dotc/config/SourceVersion.scala | 2 +- compiler/src/dotty/tools/dotc/report.scala | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/compiler/src/dotty/tools/dotc/config/SourceVersion.scala b/compiler/src/dotty/tools/dotc/config/SourceVersion.scala index 950a4bd8c677..59b958762042 100644 --- a/compiler/src/dotty/tools/dotc/config/SourceVersion.scala +++ b/compiler/src/dotty/tools/dotc/config/SourceVersion.scala @@ -8,7 +8,6 @@ import Feature.isPreviewEnabled import util.Property enum SourceVersion: - case `2.13` case `3.0-migration`, `3.0` case `3.1-migration`, `3.1` @@ -22,6 +21,7 @@ enum SourceVersion: case `3.9-migration`, `3.9` // Add 3.x-migration and 3.x here // !!! Keep in sync with scala.runtime.stdlibPatches.language !!! + case `2.13` case `future-migration`, `future` case `never` // needed for MigrationVersion.errorFrom if we never want to issue an error diff --git a/compiler/src/dotty/tools/dotc/report.scala b/compiler/src/dotty/tools/dotc/report.scala index ce46cb18c127..deb1c2023a28 100644 --- a/compiler/src/dotty/tools/dotc/report.scala +++ b/compiler/src/dotty/tools/dotc/report.scala @@ -98,10 +98,12 @@ object report: ctx.reporter.report(new Error(fullMsg, NoSourcePosition)) def errorOrMigrationWarning(msg: Message, pos: SrcPos, migrationVersion: MigrationVersion)(using Context): Unit = - if sourceVersion.isAtLeast(migrationVersion.errorFrom) then - if sourceVersion != migrationVersion.errorFrom.prevMigrating then error(msg, pos) - else if ctx.settings.rewrite.value.isEmpty then migrationWarning(msg, pos) - else if sourceVersion.isAtLeast(migrationVersion.warnFrom) then warning(msg, pos) + if sourceVersion != SourceVersion.`2.13` then + // ignore errors or warningsfor Scala 2 stdlib sources + if sourceVersion.isAtLeast(migrationVersion.errorFrom) then + if sourceVersion != migrationVersion.errorFrom.prevMigrating then error(msg, pos) + else if ctx.settings.rewrite.value.isEmpty then migrationWarning(msg, pos) + else if sourceVersion.isAtLeast(migrationVersion.warnFrom) then warning(msg, pos) def restrictionError(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = error(msg.mapMsg("Implementation restriction: " + _), pos)