diff --git a/compiler/src/dotty/tools/dotc/ast/Desugar.scala b/compiler/src/dotty/tools/dotc/ast/Desugar.scala index 5ab3d635677a..af6461eaf6d0 100644 --- a/compiler/src/dotty/tools/dotc/ast/Desugar.scala +++ b/compiler/src/dotty/tools/dotc/ast/Desugar.scala @@ -533,7 +533,7 @@ object desugar { appliedRef(enumClassRef) else { report.error(TypedCaseDoesNotExplicitlyExtendTypedEnum(enumClass, cdef) - , cdef.sourcePos.startPos) + , cdef.srcPos.startPos) appliedTypeTree(enumClassRef, constrTparams map (_ => anyRef)) } @@ -633,7 +633,7 @@ object desugar { .withSpan(cdef.span).toList if (companionDerived.nonEmpty) for (modClsDef @ TypeDef(_, _) <- mdefs) - modClsDef.putAttachment(DerivingCompanion, impl.sourcePos.startPos) + modClsDef.putAttachment(DerivingCompanion, impl.srcPos.startPos) mdefs } @@ -741,19 +741,19 @@ object desugar { if (!mods.isOneOf(GivenOrImplicit)) Nil else if (ctx.owner.is(Package)) { - report.error(TopLevelImplicitClass(cdef), cdef.sourcePos) + report.error(TopLevelImplicitClass(cdef), cdef.srcPos) Nil } else if (mods.is(Trait)) { - report.error(TypesAndTraitsCantBeImplicit(), cdef.sourcePos) + report.error(TypesAndTraitsCantBeImplicit(), cdef.srcPos) Nil } else if (isCaseClass) { - report.error(ImplicitCaseClass(cdef), cdef.sourcePos) + report.error(ImplicitCaseClass(cdef), cdef.srcPos) Nil } else if (arity != 1 && !mods.is(Given)) { - report.error(ImplicitClassPrimaryConstructorArity(), cdef.sourcePos) + report.error(ImplicitClassPrimaryConstructorArity(), cdef.srcPos) Nil } else { @@ -895,7 +895,7 @@ object desugar { .withSpan(mdef.span.startPos) val ValDef(selfName, selfTpt, _) = impl.self val selfMods = impl.self.mods - if (!selfTpt.isEmpty) report.error(ObjectMayNotHaveSelfType(mdef), impl.self.sourcePos) + if (!selfTpt.isEmpty) report.error(ObjectMayNotHaveSelfType(mdef), impl.self.srcPos) val clsSelf = ValDef(selfName, SingletonTypeTree(Ident(moduleName)), impl.self.rhs) .withMods(selfMods) .withSpan(impl.self.span.orElse(impl.span.startPos)) @@ -911,7 +911,7 @@ object desugar { for mdef <- ext.methods yield if mdef.tparams.nonEmpty then report.error("extension method cannot have type parameters here, all type parameters go after `extension`", - mdef.tparams.head.sourcePos) + mdef.tparams.head.srcPos) defDef( cpy.DefDef(mdef)( name = mdef.name.toExtensionName, @@ -1015,7 +1015,7 @@ object desugar { case Some(DefDef(name, _, (vparam :: _) :: _, _, _)) => s"extension_${name}_${inventTypeName(vparam.tpt)}" case _ => - report.error(AnonymousInstanceCannotBeEmpty(impl), impl.sourcePos) + report.error(AnonymousInstanceCannotBeEmpty(impl), impl.srcPos) nme.ERROR.toString else impl.parents.map(inventTypeName(_)).mkString("given_", "_", "") @@ -1189,7 +1189,7 @@ object desugar { var tested: MemberDef = tree def checkApplicable(flag: Flag, test: MemberDefTest): Unit = if (tested.mods.is(flag) && !test.applyOrElse(tree, (md: MemberDef) => false)) { - report.error(ModifierNotAllowedForDefinition(flag), tree.sourcePos) + report.error(ModifierNotAllowedForDefinition(flag), tree.srcPos) tested = tested.withMods(tested.mods.withoutFlags(flag)) } checkApplicable(Opaque, legalOpaque) @@ -1701,7 +1701,7 @@ object desugar { |This can be achieved by adding the import clause 'import scala.language.postfixOps' |or by setting the compiler option -language:postfixOps. |See the Scaladoc for value scala.language.postfixOps for a discussion - |why the feature needs to be explicitly enabled.""".stripMargin, t.sourcePos) + |why the feature needs to be explicitly enabled.""".stripMargin, t.srcPos) } Select(t, op.name) } @@ -1823,7 +1823,7 @@ object desugar { elems foreach collect case Alternative(trees) => for (tree <- trees; (vble, _) <- getVariables(tree)) - report.error(IllegalVariableInPatternAlternative(), vble.sourcePos) + report.error(IllegalVariableInPatternAlternative(), vble.srcPos) case Annotated(arg, _) => collect(arg) case InterpolatedString(_, segments) => @@ -1846,7 +1846,7 @@ object desugar { def traverse(tree: untpd.Tree)(using Context): Unit = tree match { case Splice(expr) => collect(expr) case TypSplice(expr) => - report.error(TypeSpliceInValPattern(expr), tree.sourcePos) + report.error(TypeSpliceInValPattern(expr), tree.srcPos) case _ => traverseChildren(tree) } }.traverse(expr) diff --git a/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala b/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala index 790c8d5ad710..9aa9ca1e38cf 100644 --- a/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala +++ b/compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala @@ -217,7 +217,7 @@ object DesugarEnums { case Ident(name) => val matches = tparamNames.contains(name) if (matches && (caseTypeParams.nonEmpty || vparamss.isEmpty)) - report.error(i"illegal reference to type parameter $name from enum case", tree.sourcePos) + report.error(i"illegal reference to type parameter $name from enum case", tree.srcPos) matches case LambdaTypeTree(lambdaParams, body) => underBinders(lambdaParams, foldOver(x, tree)) diff --git a/compiler/src/dotty/tools/dotc/ast/Positioned.scala b/compiler/src/dotty/tools/dotc/ast/Positioned.scala index 0629950e7b3b..1c57ce60425e 100644 --- a/compiler/src/dotty/tools/dotc/ast/Positioned.scala +++ b/compiler/src/dotty/tools/dotc/ast/Positioned.scala @@ -3,7 +3,7 @@ package dotc package ast import util.Spans._ -import util.{SourceFile, NoSource, SourcePosition} +import util.{SourceFile, NoSource, SourcePosition, SrcPos} import core.Contexts._ import core.Decorators._ import core.Flags.{JavaDefined, Extension} @@ -17,7 +17,7 @@ import java.io.{ PrintWriter } /** A base class for things that have positions (currently: modifiers and trees) */ -abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Product with Cloneable { +abstract class Positioned(implicit @constructorOnly src: SourceFile) extends SrcPos, Product, Cloneable { private var myUniqueId: Int = _ private var mySpan: Span = _ @@ -46,7 +46,12 @@ abstract class Positioned(implicit @constructorOnly src: SourceFile) extends Pro span = envelope(src) def source: SourceFile = SourceFile.fromId(uniqueId) - def sourcePos: SourcePosition = source.atSpan(span) + def sourcePos(using Context): SourcePosition = source.atSpan(span) + + /** This positioned item, widened to `SrcPos`. Used to make clear we only need the + * position, typically for error reporting. + */ + final def srcPos: SrcPos = this /** A positioned item like this one with given `span`. * If the positioned item is source-derived, a clone is returned. diff --git a/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala b/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala index ce782262ec24..3544a2a61df1 100644 --- a/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala +++ b/compiler/src/dotty/tools/dotc/ast/TreeMapWithImplicits.scala @@ -121,7 +121,7 @@ class TreeMapWithImplicits extends tpd.TreeMap { } catch { case ex: TypeError => - report.error(ex, tree.sourcePos) + report.error(ex, tree.srcPos) tree } } diff --git a/compiler/src/dotty/tools/dotc/ast/Trees.scala b/compiler/src/dotty/tools/dotc/ast/Trees.scala index ab876722d5c0..488a90ce37dc 100644 --- a/compiler/src/dotty/tools/dotc/ast/Trees.scala +++ b/compiler/src/dotty/tools/dotc/ast/Trees.scala @@ -10,7 +10,7 @@ import language.higherKinds import collection.mutable.ListBuffer import printing.Printer import printing.Texts.Text -import util.{Stats, Attachment, Property, SourceFile, NoSource, SourcePosition} +import util.{Stats, Attachment, Property, SourceFile, NoSource, SrcPos, SourcePosition} import config.Config import annotation.internal.sharable import annotation.unchecked.uncheckedVariance @@ -54,18 +54,10 @@ object Trees { * nodes. */ abstract class Tree[-T >: Untyped](implicit @constructorOnly src: SourceFile) - extends Positioned - with Product - with Attachment.Container - with printing.Showable { + extends Positioned, SrcPos, Product, Attachment.Container, printing.Showable { if (Stats.enabled) ntrees += 1 - /** This tree, widened to `Positioned`. Used to make clear we only need the - * position, typically for error reporting. - */ - final def posd: Positioned = this - /** The type constructor at the root of the tree */ type ThisTree[T >: Untyped] <: Tree[T] diff --git a/compiler/src/dotty/tools/dotc/config/Feature.scala b/compiler/src/dotty/tools/dotc/config/Feature.scala index dd513e32c81b..ed804ff4a7af 100644 --- a/compiler/src/dotty/tools/dotc/config/Feature.scala +++ b/compiler/src/dotty/tools/dotc/config/Feature.scala @@ -6,7 +6,7 @@ import core._ import Contexts._, Symbols._, Names._, NameOps._, Phases._ import StdNames.nme import Decorators.{given _} -import util.SourcePosition +import util.SrcPos import SourceVersion._ import reporting.Message @@ -76,7 +76,7 @@ object Feature: /** If current source migrates to `version`, issue given warning message * and return `true`, otherwise return `false`. */ - def warnOnMigration(msg: Message, pos: SourcePosition, + def warnOnMigration(msg: Message, pos: SrcPos, version: SourceVersion = defaultSourceVersion)(using Context): Boolean = if sourceVersion.isMigrating && sourceVersion.stable == version || version == `3.0` && migrateTo3 diff --git a/compiler/src/dotty/tools/dotc/core/Decorators.scala b/compiler/src/dotty/tools/dotc/core/Decorators.scala index a02cf7224019..afb356db2d52 100644 --- a/compiler/src/dotty/tools/dotc/core/Decorators.scala +++ b/compiler/src/dotty/tools/dotc/core/Decorators.scala @@ -5,7 +5,7 @@ package core import annotation.tailrec import Symbols._ import Contexts._, Names._, Phases._, printing.Texts._, printing.Printer -import util.Spans.Span, util.SourcePosition +import util.Spans.Span import collection.mutable.ListBuffer import dotty.tools.dotc.transform.MegaPhase import ast.tpd._ diff --git a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala index c7aae14d9df7..6b3e570cdc05 100644 --- a/compiler/src/dotty/tools/dotc/core/SymDenotations.scala +++ b/compiler/src/dotty/tools/dotc/core/SymDenotations.scala @@ -2508,7 +2508,7 @@ object SymDenotations { def complete(denot: SymDenotation)(using Context): Unit = { val sym = denot.symbol val errMsg = BadSymbolicReference(denot) - report.error(errMsg, sym.sourcePos) + report.error(errMsg, sym.srcPos) if (ctx.debug) throw new scala.Error() initializeToDefaults(denot, errMsg) } diff --git a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala index 8425f0228ae1..0d23f0df1d51 100644 --- a/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala +++ b/compiler/src/dotty/tools/dotc/core/SymbolLoaders.scala @@ -134,7 +134,7 @@ object SymbolLoaders { report.warning(i"""$what ${tree.name} is in the wrong directory. |It was declared to be in package ${path.reverse.mkString(".")} |But it is found in directory ${filePath.reverse.mkString(File.separator)}""", - tree.sourcePos.focus) + tree.srcPos.focus) ok } diff --git a/compiler/src/dotty/tools/dotc/core/Symbols.scala b/compiler/src/dotty/tools/dotc/core/Symbols.scala index f761f4f9c557..5f160a282041 100644 --- a/compiler/src/dotty/tools/dotc/core/Symbols.scala +++ b/compiler/src/dotty/tools/dotc/core/Symbols.scala @@ -30,7 +30,7 @@ import reporting.Message import collection.mutable import io.AbstractFile import language.implicitConversions -import util.{SourceFile, NoSource, Property, SourcePosition} +import util.{SourceFile, NoSource, Property, SourcePosition, SrcPos} import scala.collection.JavaConverters._ import scala.annotation.internal.sharable import config.Printers.typr @@ -47,7 +47,7 @@ object Symbols { * @param id A unique identifier of the symbol (unique per ContextBase) */ class Symbol private[Symbols] (private var myCoord: Coord, val id: Int) - extends Designator with ParamInfo with printing.Showable { + extends Designator, ParamInfo, SrcPos, printing.Showable { type ThisName <: Name @@ -321,6 +321,11 @@ object Symbols { (if (src.exists) src else ctx.source).atSpan(span) } + /** This positioned item, widened to `SrcPos`. Used to make clear we only need the + * position, typically for error reporting. + */ + final def srcPos: SrcPos = this + // ParamInfo types and methods def isTypeParam(using Context): Boolean = denot.is(TypeParam) def paramName(using Context): ThisName = name.asInstanceOf[ThisName] diff --git a/compiler/src/dotty/tools/dotc/core/TypeOps.scala b/compiler/src/dotty/tools/dotc/core/TypeOps.scala index 3eca986a973b..eee67820d5ed 100644 --- a/compiler/src/dotty/tools/dotc/core/TypeOps.scala +++ b/compiler/src/dotty/tools/dotc/core/TypeOps.scala @@ -6,7 +6,6 @@ import Contexts._, Types._, Symbols._, Names._, Flags._ import SymDenotations._ import util.Spans._ import util.Stats -import util.SourcePosition import NameKinds.DepParamName import Decorators._ import StdNames._ diff --git a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala index f60c4bdff191..bff0ec4d8792 100644 --- a/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala +++ b/compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala @@ -84,7 +84,7 @@ class TreePickler(pickler: TastyPickler) { // I believe it's a bug in typer: the type of an implicit argument refers // to a closure parameter outside the closure itself. TODO: track this down, so that we // can eliminate this case. - report.log(i"pickling reference to as yet undefined $sym in ${sym.owner}", sym.sourcePos) + report.log(i"pickling reference to as yet undefined $sym in ${sym.owner}", sym.srcPos) pickleForwardSymRef(sym) } @@ -622,7 +622,7 @@ class TreePickler(pickler: TastyPickler) { } catch { case ex: TypeError => - report.error(ex.toMessage, tree.sourcePos.focus) + report.error(ex.toMessage, tree.srcPos.focus) case ex: AssertionError => println(i"error when pickling tree $tree") throw ex @@ -734,7 +734,7 @@ class TreePickler(pickler: TastyPickler) { def pickle(trees: List[Tree])(using Context): Unit = { trees.foreach(tree => if (!tree.isEmpty) pickleTree(tree)) - def missing = forwardSymRefs.keysIterator.map(sym => sym.showLocated + "(line " + sym.sourcePos.line + ")").toList + def missing = forwardSymRefs.keysIterator.map(sym => sym.showLocated + "(line " + sym.srcPos.line + ")").toList assert(forwardSymRefs.isEmpty, i"unresolved symbols: $missing%, % when pickling ${ctx.source}") } diff --git a/compiler/src/dotty/tools/dotc/report.scala b/compiler/src/dotty/tools/dotc/report.scala index 54dc70caf41c..fe69b92a02a7 100644 --- a/compiler/src/dotty/tools/dotc/report.scala +++ b/compiler/src/dotty/tools/dotc/report.scala @@ -2,7 +2,7 @@ package dotty.tools.dotc import reporting._ import Diagnostic._ -import util.{SourcePosition, NoSourcePosition} +import util.{SourcePosition, NoSourcePosition, SrcPos} import core._ import Contexts._, Symbols._, Decorators._ import config.SourceVersion @@ -14,11 +14,11 @@ import java.lang.System.currentTimeMillis object report: /** For sending messages that are printed only if -verbose is set */ - def inform(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + def inform(msg: => String, pos: SrcPos = NoSourcePosition)(using Context): Unit = if ctx.settings.verbose.value then echo(msg, pos) - def echo(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - ctx.reporter.report(new Info(msg, pos)) + def echo(msg: => String, pos: SrcPos = NoSourcePosition)(using Context): Unit = + ctx.reporter.report(new Info(msg, pos.sourcePos)) private def issueWarning(warning: Warning)(using Context): Unit = if (!ctx.settings.silentWarnings.value) @@ -31,20 +31,20 @@ object report: } else ctx.reporter.report(warning) - def deprecationWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - issueWarning(new DeprecationWarning(msg, pos)) + def deprecationWarning(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = + issueWarning(new DeprecationWarning(msg, pos.sourcePos)) - def migrationWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - issueWarning(new MigrationWarning(msg, pos)) + def migrationWarning(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = + issueWarning(new MigrationWarning(msg, pos.sourcePos)) - def uncheckedWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - issueWarning(new UncheckedWarning(msg, pos)) + def uncheckedWarning(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = + issueWarning(new UncheckedWarning(msg, pos.sourcePos)) - def featureWarning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - issueWarning(new FeatureWarning(msg, pos)) + def featureWarning(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = + issueWarning(new FeatureWarning(msg, pos.sourcePos)) def featureWarning(feature: String, featureDescription: String, - featureUseSite: Symbol, required: Boolean, pos: SourcePosition)(using Context): Unit = { + featureUseSite: Symbol, required: Boolean, pos: SrcPos)(using Context): Unit = { val req = if (required) "needs to" else "should" val fqname = s"scala.language.$feature" @@ -60,38 +60,38 @@ object report: |by adding the import clause 'import $fqname' |or by setting the compiler option -language:$feature.$explain""".stripMargin if (required) error(msg, pos) - else issueWarning(new FeatureWarning(msg, pos)) + else issueWarning(new FeatureWarning(msg, pos.sourcePos)) } - def warning(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + def warning(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = issueWarning(new Warning(msg, addInlineds(pos))) - def error(msg: Message, pos: SourcePosition = NoSourcePosition, sticky: Boolean = false)(using Context): Unit = + def error(msg: Message, pos: SrcPos = NoSourcePosition, sticky: Boolean = false)(using Context): Unit = val fullPos = addInlineds(pos) ctx.reporter.report(if (sticky) new StickyError(msg, fullPos) else new Error(msg, fullPos)) if ctx.settings.YdebugError.value then Thread.dumpStack() - def error(ex: TypeError, pos: SourcePosition)(using Context): Unit = + def error(ex: TypeError, pos: SrcPos)(using Context): Unit = error(ex.toMessage, pos, sticky = true) if ctx.settings.YdebugTypeError.value then ex.printStackTrace() - def errorOrMigrationWarning(msg: Message, pos: SourcePosition = NoSourcePosition, + def errorOrMigrationWarning(msg: Message, pos: SrcPos = NoSourcePosition, from: SourceVersion = SourceVersion.defaultSourceVersion)(using Context): Unit = if sourceVersion.isAtLeast(from) then if sourceVersion.isMigrating then migrationWarning(msg, pos) else error(msg, pos) - def restrictionError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + def restrictionError(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = error(msg.mapMsg("Implementation restriction: " + _), pos) - def incompleteInputError(msg: Message, pos: SourcePosition = NoSourcePosition)(using Context): Unit = - ctx.reporter.incomplete(new Error(msg, pos)) + def incompleteInputError(msg: Message, pos: SrcPos = NoSourcePosition)(using Context): Unit = + ctx.reporter.incomplete(new Error(msg, pos.sourcePos)) /** Log msg if settings.log contains the current phase. * See [[config.CompilerCommand#explainAdvanced]] for the exact meaning of * "contains" here. */ - def log(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + def log(msg: => String, pos: SrcPos = NoSourcePosition)(using Context): Unit = if (ctx.settings.Ylog.value.containsPhase(ctx.phase)) echo(s"[log ${ctx.phase}] $msg", pos) @@ -111,13 +111,13 @@ object report: value } - def debugwarn(msg: => String, pos: SourcePosition = NoSourcePosition)(using Context): Unit = + def debugwarn(msg: => String, pos: SrcPos = NoSourcePosition)(using Context): Unit = if (ctx.settings.Ydebug.value) warning(msg, pos) - private def addInlineds(pos: SourcePosition)(using Context) = + private def addInlineds(pos: SrcPos)(using Context): SourcePosition = def recur(pos: SourcePosition, inlineds: List[Trees.Tree[?]]): SourcePosition = inlineds match case inlined :: inlineds1 => pos.withOuter(recur(inlined.sourcePos, inlineds1)) case Nil => pos - recur(pos, tpd.enclosingInlineds) + recur(pos.sourcePos, tpd.enclosingInlineds) end report \ No newline at end of file diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index 9885cba642c6..d875a930b063 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -2041,7 +2041,7 @@ import ast.tpd def symLocation(sym: Symbol) = { val lineDesc = if (sym.span.exists && sym.span != sym.owner.span) - s" at line ${sym.sourcePos.line + 1}" + s" at line ${sym.srcPos.line + 1}" else "" i"in ${sym.owner}${lineDesc}" } diff --git a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala index b1490bf4ff4a..31bfb9772bcb 100644 --- a/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala +++ b/compiler/src/dotty/tools/dotc/transform/AccessProxies.scala @@ -145,7 +145,7 @@ abstract class AccessProxies { def accessorIfNeeded(tree: Tree)(using Context): Tree = tree match { case tree: RefTree if needsAccessor(tree.symbol) => if (tree.symbol.isConstructor) { - report.error("Implementation restriction: cannot use private constructors in inlineable methods", tree.sourcePos) + report.error("Implementation restriction: cannot use private constructors in inlineable methods", tree.srcPos) tree // TODO: create a proper accessor for the private constructor } else useAccessor(tree) diff --git a/compiler/src/dotty/tools/dotc/transform/Bridges.scala b/compiler/src/dotty/tools/dotc/transform/Bridges.scala index ee6d9dc9e089..8ba39ea3ad8a 100644 --- a/compiler/src/dotty/tools/dotc/transform/Bridges.scala +++ b/compiler/src/dotty/tools/dotc/transform/Bridges.scala @@ -8,7 +8,7 @@ import DenotTransformers._ import ast.untpd import collection.{mutable, immutable} import util.Spans.Span -import util.SourcePosition +import util.SrcPos /** A helper class for generating bridge methods in class `root`. */ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { @@ -38,8 +38,8 @@ class Bridges(root: ClassSymbol, thisPhase: DenotTransformer)(using Context) { private val bridgesScope = newScope private val bridgeTarget = newMutableSymbolMap[Symbol] - def bridgePosFor(member: Symbol): SourcePosition = - (if (member.owner == root && member.span.exists) member else root).sourcePos + def bridgePosFor(member: Symbol): SrcPos = + (if (member.owner == root && member.span.exists) member else root).srcPos /** Add a bridge between `member` and `other`, where `member` overrides `other` * before erasure, if the following conditions are satisfied. diff --git a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala index 75e0fb824ece..ee6a41d86bd9 100644 --- a/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala +++ b/compiler/src/dotty/tools/dotc/transform/CheckStatic.scala @@ -35,24 +35,24 @@ class CheckStatic extends MiniPhase { for (defn <- defns) if (defn.symbol.isScalaStatic) { if (!ctx.owner.is(Module)) - report.error(StaticFieldsOnlyAllowedInObjects(defn.symbol), defn.sourcePos) + report.error(StaticFieldsOnlyAllowedInObjects(defn.symbol), defn.srcPos) if (defn.isInstanceOf[ValDef] && hadNonStaticField) - report.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol, defns), defn.sourcePos) + report.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol, defns), defn.srcPos) val companion = ctx.owner.companionClass def clashes = companion.asClass.membersNamed(defn.name) if (!companion.exists) - report.error(MissingCompanionForStatic(defn.symbol), defn.sourcePos) + report.error(MissingCompanionForStatic(defn.symbol), defn.srcPos) else if (clashes.exists) - report.error(MemberWithSameNameAsStatic(), defn.sourcePos) + report.error(MemberWithSameNameAsStatic(), defn.srcPos) else if (defn.symbol.is(Flags.Mutable) && companion.is(Flags.Trait)) - report.error(TraitCompanionWithMutableStatic(), defn.sourcePos) + report.error(TraitCompanionWithMutableStatic(), defn.srcPos) else if (defn.symbol.is(Flags.Lazy)) - report.error(LazyStaticField(), defn.sourcePos) + report.error(LazyStaticField(), defn.srcPos) else if (defn.symbol.allOverriddenSymbols.nonEmpty) - report.error(StaticOverridingNonStaticMembers(), defn.sourcePos) + report.error(StaticOverridingNonStaticMembers(), defn.srcPos) } else hadNonStaticField = hadNonStaticField || defn.isInstanceOf[ValDef] diff --git a/compiler/src/dotty/tools/dotc/transform/Constructors.scala b/compiler/src/dotty/tools/dotc/transform/Constructors.scala index a462cba7a000..1806340bc3cf 100644 --- a/compiler/src/dotty/tools/dotc/transform/Constructors.scala +++ b/compiler/src/dotty/tools/dotc/transform/Constructors.scala @@ -257,7 +257,7 @@ class Constructors extends MiniPhase with IdentityDenotTransformer { thisPhase = else { val param = acc.subst(accessors, paramSyms) if (param.hasAnnotation(defn.ConstructorOnlyAnnot)) - report.error(em"${acc.name} is marked `@constructorOnly` but it is retained as a field in ${acc.owner}", acc.sourcePos) + report.error(em"${acc.name} is marked `@constructorOnly` but it is retained as a field in ${acc.owner}", acc.srcPos) val target = if (acc.is(Method)) acc.field else acc if (!target.exists) Nil // this case arises when the parameter accessor is an alias else { diff --git a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala index b5a82b2ad44f..b49cacb19ecd 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimErasedValueType.scala @@ -103,7 +103,7 @@ class ElimErasedValueType extends MiniPhase with InfoTransformer { thisPhase => def bothSuperAccessors = sym1.name.is(SuperAccessorName) && sym2.name.is(SuperAccessorName) if (sym1.name != sym2.name && !bothSuperAccessors || !info1.matchesLoosely(info2) && !bothPolyApply) - report.error(DoubleDefinition(sym1, sym2, root), root.sourcePos) + report.error(DoubleDefinition(sym1, sym2, root), root.srcPos) } while (opc.hasNext) { val sym1 = opc.overriding diff --git a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala index a885518e66b6..9fc0b7b53c0e 100644 --- a/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala +++ b/compiler/src/dotty/tools/dotc/transform/ElimRepeated.scala @@ -291,7 +291,7 @@ class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase => if hasAnnotation then "@varargs" else if isBridge then "overriding a java varargs method" else "@varargs (on overriden method)" - report.error(s"$src produces a forwarder method that conflicts with ${conflict.showDcl}", original.sourcePos) + report.error(s"$src produces a forwarder method that conflicts with ${conflict.showDcl}", original.srcPos) case Nil => forwarder.enteredAfter(thisPhase) diff --git a/compiler/src/dotty/tools/dotc/transform/Erasure.scala b/compiler/src/dotty/tools/dotc/transform/Erasure.scala index 846dd2ce8c34..202747b5739e 100644 --- a/compiler/src/dotty/tools/dotc/transform/Erasure.scala +++ b/compiler/src/dotty/tools/dotc/transform/Erasure.scala @@ -543,19 +543,19 @@ object Erasure { if (sym is Flags.Package) || (sym.isAllOf(Flags.JavaModule) && !ctx.compilationUnit.isJava) then - report.error(JavaSymbolIsNotAValue(sym), tree.sourcePos) + report.error(JavaSymbolIsNotAValue(sym), tree.srcPos) private def checkNotErased(tree: Tree)(using Context): tree.type = { if (!ctx.mode.is(Mode.Type)) { if (isErased(tree)) - report.error(em"${tree.symbol} is declared as erased, but is in fact used", tree.sourcePos) + report.error(em"${tree.symbol} is declared as erased, but is in fact used", tree.srcPos) tree.symbol.getAnnotation(defn.CompileTimeOnlyAnnot) match { case Some(annot) => def defaultMsg = i"""Reference to ${tree.symbol.showLocated} should not have survived, |it should have been processed and eliminated during expansion of an enclosing macro or term erasure.""" val message = annot.argumentConstant(0).fold(defaultMsg)(_.stringValue) - report.error(message, tree.sourcePos) + report.error(message, tree.srcPos) case _ => // OK } } diff --git a/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala b/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala index 44524572a967..374d938e5523 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExpandSAMs.scala @@ -163,7 +163,7 @@ class ExpandSAMs extends MiniPhase { case _ => val found = tpe.baseType(defn.FunctionClass(1)) - report.error(TypeMismatch(found, tpe), tree.sourcePos) + report.error(TypeMismatch(found, tpe), tree.srcPos) tree } } @@ -171,7 +171,7 @@ class ExpandSAMs extends MiniPhase { private def checkRefinements(tpe: Type, tree: Tree)(using Context): Type = tpe.dealias match { case RefinedType(parent, name, _) => if (name.isTermName && tpe.member(name).symbol.ownersIterator.isEmpty) // if member defined in the refinement - report.error("Lambda does not define " + name, tree.sourcePos) + report.error("Lambda does not define " + name, tree.srcPos) checkRefinements(parent, tree) case tpe => tpe diff --git a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala index 877c964ed65c..3d351eb03a67 100644 --- a/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala +++ b/compiler/src/dotty/tools/dotc/transform/ExplicitOuter.scala @@ -115,7 +115,7 @@ class ExplicitOuter extends MiniPhase with InfoTransformer { thisPhase => if (tree.tpt ne EmptyTree) { val cls = tree.tpt.asInstanceOf[TypeTree].tpe.classSymbol if (cls.exists && hasOuter(cls.asClass)) - report.error("Not a single abstract method type, requires an outer pointer", tree.sourcePos) + report.error("Not a single abstract method type, requires an outer pointer", tree.srcPos) } tree } diff --git a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala index 719e298fe067..7e26308b9a88 100644 --- a/compiler/src/dotty/tools/dotc/transform/LazyVals.scala +++ b/compiler/src/dotty/tools/dotc/transform/LazyVals.scala @@ -88,7 +88,7 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { transformSyntheticModule(tree) else if (sym.isThreadUnsafe || ctx.settings.scalajs.value) if (sym.is(Module) && !ctx.settings.scalajs.value) { - report.error(em"@threadUnsafe is only supported on lazy vals", sym.sourcePos) + report.error(em"@threadUnsafe is only supported on lazy vals", sym.srcPos) transformMemberDefThreadSafe(tree) } else diff --git a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala index 7c670b4aed19..87a5ef67bf6b 100644 --- a/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala +++ b/compiler/src/dotty/tools/dotc/transform/MacroTransform.scala @@ -64,7 +64,7 @@ abstract class MacroTransform extends Phase { } catch { case ex: TypeError => - report.error(ex, tree.sourcePos) + report.error(ex, tree.srcPos) tree } diff --git a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala index c7f6ee252429..51cbe16a2e0a 100644 --- a/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala +++ b/compiler/src/dotty/tools/dotc/transform/MegaPhase.scala @@ -170,7 +170,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } catch { case ex: TypeError => - report.error(ex, tree.sourcePos) + report.error(ex, tree.srcPos) tree } def goUnnamed(tree: Tree, start: Int) = @@ -205,7 +205,7 @@ class MegaPhase(val miniPhases: Array[MiniPhase]) extends Phase { } catch { case ex: TypeError => - report.error(ex, tree.sourcePos) + report.error(ex, tree.srcPos) tree } if (tree.isInstanceOf[NameTree]) goNamed(tree, start) else goUnnamed(tree, start) diff --git a/compiler/src/dotty/tools/dotc/transform/Mixin.scala b/compiler/src/dotty/tools/dotc/transform/Mixin.scala index dbd53e09dc67..d9bcb5fcf544 100644 --- a/compiler/src/dotty/tools/dotc/transform/Mixin.scala +++ b/compiler/src/dotty/tools/dotc/transform/Mixin.scala @@ -248,7 +248,7 @@ class Mixin extends MiniPhase with SymTransformer { thisPhase => report.error( em"""parameterized $mixin is indirectly implemented, |needs to be implemented directly so that arguments can be passed""", - cls.sourcePos) + cls.srcPos) EmptyTree for (getter <- mixin.info.decls.toList if getter.isGetter && !wasOneOf(getter, Deferred)) yield { diff --git a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala index 4a691b363678..1653ef4acd3d 100644 --- a/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala +++ b/compiler/src/dotty/tools/dotc/transform/NonLocalReturns.scala @@ -91,7 +91,7 @@ class NonLocalReturns extends MiniPhase { override def transformReturn(tree: Return)(using Context): Tree = if isNonLocalReturn(tree) then if sourceVersion.isAtLeast(`3.1`) then - report.errorOrMigrationWarning("Non local returns are no longer supported; use scala.util.control.NonLocalReturns instead", tree.sourcePos) + report.errorOrMigrationWarning("Non local returns are no longer supported; use scala.util.control.NonLocalReturns instead", tree.srcPos) nonLocalReturnThrow(tree.expr, tree.from.symbol).withSpan(tree.span) else tree } diff --git a/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala b/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala index 1bedd2e6e261..c2e7b20fe14e 100644 --- a/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala +++ b/compiler/src/dotty/tools/dotc/transform/OverridingPairs.scala @@ -134,7 +134,7 @@ object OverridingPairs { case ex: TypeError => // See neg/i1750a for an example where a cyclic error can arise. // The root cause in this example is an illegal "override" of an inner trait - report.error(ex, base.sourcePos) + report.error(ex, base.srcPos) } else { curEntry = curEntry.prev diff --git a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala index 7f9b1fcbed2b..9afe86734f6d 100644 --- a/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala +++ b/compiler/src/dotty/tools/dotc/transform/PCPCheckAndHeal.scala @@ -14,7 +14,7 @@ import dotty.tools.dotc.core.StagingContext._ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.Types._ -import dotty.tools.dotc.util.SourcePosition +import dotty.tools.dotc.util.SrcPos import dotty.tools.dotc.util.Spans._ import dotty.tools.dotc.transform.SymUtils._ import dotty.tools.dotc.transform.TreeMapWithStages._ @@ -24,7 +24,6 @@ import dotty.tools.dotc.typer.Inliner import dotty.tools.dotc.core.Annotations._ import scala.collection.mutable -import dotty.tools.dotc.util.SourcePosition import dotty.tools.dotc.util.Property import scala.annotation.constructorOnly @@ -69,7 +68,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( else tree match { case _: TypeTree | _: RefTree if tree.isType => - val healedType = healType(tree.sourcePos)(tree.tpe) + val healedType = healType(tree.srcPos)(tree.tpe) if healedType == tree.tpe then tree else TypeTree(healedType).withSpan(tree.span) case _: AppliedTypeTree => @@ -80,7 +79,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( case tree1 => tree1 case _: Ident | _: This => - tree.withType(healTypeOfTerm(tree.sourcePos)(tree.tpe)) + tree.withType(healTypeOfTerm(tree.srcPos)(tree.tpe)) // Remove inline defs in quoted code. Already fully inlined. case tree: DefDef if tree.symbol.is(Inline) && level > 0 => @@ -88,11 +87,11 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( case tree: ValOrDefDef => checkAnnotations(tree) - healInfo(tree, tree.tpt.sourcePos) + healInfo(tree, tree.tpt.srcPos) super.transform(tree) case tree: Bind => checkAnnotations(tree) - healInfo(tree, tree.sourcePos) + healInfo(tree, tree.srcPos) super.transform(tree) case _ => @@ -104,7 +103,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( val taggedTypes = new PCPCheckAndHeal.QuoteTypeTags(quote.span) if (ctx.property(InAnnotation).isDefined) - report.error("Cannot have a quote in an annotation", quote.sourcePos) + report.error("Cannot have a quote in an annotation", quote.srcPos) val contextWithQuote = if level == 0 then contextWithQuoteTypeTags(taggedTypes)(using quoteContext) @@ -129,12 +128,12 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( case fun @ TypeApply(_, _ :: Nil) => // Type of the splice itsel must also be healed // internal.Quoted.expr[F[T]](... T ...) --> internal.Quoted.expr[F[$t]](... T ...) - val tp = healType(splice.sourcePos)(splice.tpe.widenTermRefExpr) + val tp = healType(splice.srcPos)(splice.tpe.widenTermRefExpr) cpy.Apply(splice)(cpy.TypeApply(fun)(fun.fun, tpd.TypeTree(tp) :: Nil), body1 :: Nil) case f @ Apply(fun @ TypeApply(_, _), qctx :: Nil) => // Type of the splice itsel must also be healed // internal.Quoted.expr[F[T]](... T ...) --> internal.Quoted.expr[F[$t]](... T ...) - val tp = healType(splice.sourcePos)(splice.tpe.widenTermRefExpr) + val tp = healType(splice.srcPos)(splice.tpe.widenTermRefExpr) cpy.Apply(splice)(cpy.Apply(f)(cpy.TypeApply(fun)(fun.fun, tpd.TypeTree(tp) :: Nil), qctx :: Nil), body1 :: Nil) } } @@ -156,7 +155,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( case _ => /** Heal types in the info of the given tree */ - private def healInfo(tree: Tree, pos: SourcePosition)(using Context): Unit = + private def healInfo(tree: Tree, pos: SrcPos)(using Context): Unit = tree.symbol.info = healType(pos)(tree.symbol.info) /** If the type refers to a locally defined symbol (either directly, or in a pickled type), @@ -170,7 +169,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( * The tag is generated by an instance of `QuoteTypeTags` directly if the splice is explicit * or indirectly by `tryHeal`. */ - private def healType(pos: SourcePosition)(using Context) = new TypeMap { + private def healType(pos: SrcPos)(using Context) = new TypeMap { def apply(tp: Type): Type = tp match case tp: TypeRef => @@ -202,7 +201,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( } /** Check phase consistency of terms and heal incosistent type references. */ - private def healTypeOfTerm(pos: SourcePosition)(using Context) = new TypeMap { + private def healTypeOfTerm(pos: SrcPos)(using Context) = new TypeMap { def apply(tp: Type): Type = tp match case tp @ TypeRef(NoPrefix, _) if level > levelOf(tp.symbol) => @@ -221,7 +220,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( * refercence to a type alias containing the equivalent of `${summon[quoted.Type[T]]}`. * Emits and error if `T` cannot be healed and returns `T`. */ - protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SourcePosition)(using Context): TypeRef = { + protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SrcPos)(using Context): TypeRef = { val reqType = defn.QuotedTypeClass.typeRef.appliedTo(tp) val tag = ctx.typer.inferImplicitArg(reqType, pos.span) tag.tpe match @@ -242,7 +241,7 @@ class PCPCheckAndHeal(@constructorOnly ictx: Context) extends TreeMapWithStages( tp } - private def levelError(sym: Symbol, tp: Type, pos: SourcePosition)(using Context): tp.type = { + private def levelError(sym: Symbol, tp: Type, pos: SrcPos)(using Context): tp.type = { def symStr = if (!tp.isInstanceOf[ThisType]) sym.show else if (sym.is(ModuleClass)) sym.sourceModule.show diff --git a/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala b/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala index 0e63cb898a09..dc1c26299c88 100644 --- a/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala +++ b/compiler/src/dotty/tools/dotc/transform/PatternMatcher.scala @@ -329,8 +329,8 @@ object PatternMatcher { .map(ref(unappResult).select(_)) matchArgsPlan(selectors, args, onSuccess) } - else if (isUnapplySeq && isProductSeqMatch(unapp.tpe.widen, args.length, unapp.sourcePos)) { - val arity = productArity(unapp.tpe.widen, unapp.sourcePos) + else if (isUnapplySeq && isProductSeqMatch(unapp.tpe.widen, args.length, unapp.srcPos)) { + val arity = productArity(unapp.tpe.widen, unapp.srcPos) unapplyProductSeqPlan(unappResult, args, arity) } else if (isUnapplySeq && unapplySeqTypeElemTp(unapp.tpe.widen.finalResultType).exists) { @@ -340,7 +340,7 @@ object PatternMatcher { assert(isGetMatch(unapp.tpe)) val argsPlan = { val get = ref(unappResult).select(nme.get, _.info.isParameterless) - val arity = productArity(get.tpe, unapp.sourcePos) + val arity = productArity(get.tpe, unapp.srcPos) if (isUnapplySeq) letAbstract(get) { getResult => if (arity > 0) unapplyProductSeqPlan(getResult, args, arity) @@ -988,7 +988,7 @@ object PatternMatcher { patmatch.println(i"original types: ${typesInCases(original.cases)}%, %") patmatch.println(i"switch types : ${typesInCases(resultCases)}%, %") patmatch.println(i"tree = $result") - report.warning(UnableToEmitSwitch(numTypes(original.cases) < MinSwitchCases), original.sourcePos) + report.warning(UnableToEmitSwitch(numTypes(original.cases) < MinSwitchCases), original.srcPos) } case _ => } diff --git a/compiler/src/dotty/tools/dotc/transform/PostTyper.scala b/compiler/src/dotty/tools/dotc/transform/PostTyper.scala index 92ae55663077..5837842164c7 100644 --- a/compiler/src/dotty/tools/dotc/transform/PostTyper.scala +++ b/compiler/src/dotty/tools/dotc/transform/PostTyper.scala @@ -153,7 +153,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase // This should be removed on Scala 3.1 && sym.owner != defn.ReflectPackageClass then - report.error("No Scala 3 implementation found for this Scala 2 macro.", tree.sourcePos) + report.error("No Scala 3 implementation found for this Scala 2 macro.", tree.srcPos) case _ => processMemberDef(tree) @@ -239,7 +239,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase } case tree @ Select(qual, name) => if (name.isTypeName) { - Checking.checkRealizable(qual.tpe, qual.posd) + Checking.checkRealizable(qual.tpe, qual.srcPos) withMode(Mode.Type)(super.transform(tree)) } else @@ -264,7 +264,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase case Select(nu: New, nme.CONSTRUCTOR) if isCheckable(nu) => // need to check instantiability here, because the type of the New itself // might be a type constructor. - Checking.checkInstantiable(tree.tpe, nu.posd) + Checking.checkInstantiable(tree.tpe, nu.srcPos) withNoCheckNews(nu :: Nil)(app1) case _ => app1 @@ -323,16 +323,16 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase case _ => processMemberDef(super.transform(tree)) case tree: New if isCheckable(tree) => - Checking.checkInstantiable(tree.tpe, tree.posd) + Checking.checkInstantiable(tree.tpe, tree.srcPos) super.transform(tree) case tree: Closure if !tree.tpt.isEmpty => - Checking.checkRealizable(tree.tpt.tpe, tree.posd, "SAM type") + Checking.checkRealizable(tree.tpt.tpe, tree.srcPos, "SAM type") super.transform(tree) case tree @ Annotated(annotated, annot) => cpy.Annotated(tree)(transform(annotated), transformAnnot(annot)) case tree: AppliedTypeTree => if (tree.tpt.symbol == defn.andType) - Checking.checkNonCyclicInherited(tree.tpe, tree.args.tpes, EmptyScope, tree.posd) + Checking.checkNonCyclicInherited(tree.tpe, tree.args.tpes, EmptyScope, tree.srcPos) // Ideally, this should be done by Typer, but we run into cyclic references // when trying to typecheck self types which are intersections. else if (tree.tpt.symbol == defn.orType) @@ -341,7 +341,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase Checking.checkAppliedType(tree) super.transform(tree) case SingletonTypeTree(ref) => - Checking.checkRealizable(ref.tpe, ref.posd) + Checking.checkRealizable(ref.tpe, ref.srcPos) super.transform(tree) case tree: TypeTree => tree.withType( @@ -358,9 +358,9 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase if !exprTpe.member(sel.name).exists && !exprTpe.member(sel.name.toTypeName).exists && !exprTpe.member(sel.name.toExtensionName).exists then - report.error(NotAMember(exprTpe, sel.name, "value"), sel.imported.sourcePos) + report.error(NotAMember(exprTpe, sel.name, "value"), sel.imported.srcPos) if seen.contains(sel.name) then - report.error(ImportRenamedTwice(sel.imported), sel.imported.sourcePos) + report.error(ImportRenamedTwice(sel.imported), sel.imported.srcPos) seen += sel.name for sel <- selectors do diff --git a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala index b7336c17f0ca..b02f2723de91 100644 --- a/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/ProtectedAccessors.scala @@ -58,7 +58,7 @@ class ProtectedAccessors extends MiniPhase { val curCls = ctx.owner.enclosingClass transforms.println(i"${curCls.ownersIterator.toList}%, %") report.error(i"illegal access to protected ${reference.symbol.showLocated} from $curCls", - reference.sourcePos) + reference.srcPos) reference } } diff --git a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala index 0964c67509da..ec0e0a7ff15d 100644 --- a/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala +++ b/compiler/src/dotty/tools/dotc/transform/ReifyQuotes.scala @@ -11,7 +11,6 @@ import Constants._ import ast.Trees._ import ast.{TreeTypeMap, untpd} import util.Spans._ -import util.SourcePosition import tasty.TreePickler.Hole import SymUtils._ import NameKinds._ @@ -25,7 +24,6 @@ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.quoted._ import dotty.tools.dotc.transform.TreeMapWithStages._ import dotty.tools.dotc.typer.Inliner -import dotty.tools.dotc.util.SourcePosition import scala.annotation.constructorOnly diff --git a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala index 7657ad21e31d..a89c71e29f3a 100644 --- a/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala +++ b/compiler/src/dotty/tools/dotc/transform/ResolveSuper.scala @@ -104,7 +104,7 @@ object ResolveSuper { val otherTp = other.asSeenFrom(base.typeRef).info val accTp = acc.asSeenFrom(base.typeRef).info if (!(otherTp.overrides(accTp, matchLoosely = true))) - report.error(IllegalSuperAccessor(base, memberName, acc, accTp, other.symbol, otherTp), base.sourcePos) + report.error(IllegalSuperAccessor(base, memberName, acc, accTp, other.symbol, otherTp), base.srcPos) bcs = bcs.tail } diff --git a/compiler/src/dotty/tools/dotc/transform/Splicer.scala b/compiler/src/dotty/tools/dotc/transform/Splicer.scala index fcf0a425d5d7..ed3a35ebaee7 100644 --- a/compiler/src/dotty/tools/dotc/transform/Splicer.scala +++ b/compiler/src/dotty/tools/dotc/transform/Splicer.scala @@ -21,7 +21,7 @@ import dotty.tools.dotc.core.Constants.Constant import dotty.tools.dotc.tastyreflect.ReflectionImpl import scala.util.control.NonFatal -import dotty.tools.dotc.util.SourcePosition +import dotty.tools.dotc.util.SrcPos import dotty.tools.repl.AbstractFileClassLoader import scala.reflect.ClassTag @@ -38,7 +38,7 @@ object Splicer { * * See: `Staging` */ - def splice(tree: Tree, pos: SourcePosition, classLoader: ClassLoader)(using Context): Tree = tree match { + def splice(tree: Tree, pos: SrcPos, classLoader: ClassLoader)(using Context): Tree = tree match { case Quoted(quotedTree) => quotedTree case _ => val macroOwner = newSymbol(ctx.owner, nme.MACROkw, Macro | Synthetic, defn.AnyType, coord = tree.span) @@ -95,7 +95,7 @@ object Splicer { tree match case tree: Ident if isEscapedVariable(tree.symbol) => val sym = tree.symbol - report.error(em"While expanding a macro, a reference to $sym was used outside the scope where it was defined", tree.sourcePos) + report.error(em"While expanding a macro, a reference to $sym was used outside the scope where it was defined", tree.srcPos) case Block(stats, _) => val last = locals stats.foreach(markDef) @@ -136,7 +136,7 @@ object Splicer { checkIfValidArgument(tree.rhs) summon[Env] + tree.symbol case _ => - report.error("Macro should not have statements", tree.sourcePos) + report.error("Macro should not have statements", tree.srcPos) summon[Env] } @@ -176,7 +176,7 @@ object Splicer { |Parameters may only be: | * Quoted parameters or fields | * Literal values of primitive types - |""".stripMargin, tree.sourcePos) + |""".stripMargin, tree.srcPos) } def checkIfValidStaticCall(tree: Tree)(using Env): Unit = tree match { @@ -195,7 +195,7 @@ object Splicer { fn.symbol.is(Module) || fn.symbol.isStatic || (fn.qualifier.symbol.is(Module) && fn.qualifier.symbol.isStatic) => if (fn.symbol.flags.is(Inline)) - report.error("Macro cannot be implemented with an `inline` method", fn.sourcePos) + report.error("Macro cannot be implemented with an `inline` method", fn.srcPos) args.flatten.foreach(checkIfValidArgument) case _ => @@ -203,14 +203,14 @@ object Splicer { """Malformed macro. | |Expected the splice ${...} to contain a single call to a static method. - |""".stripMargin, tree.sourcePos) + |""".stripMargin, tree.srcPos) } checkIfValidStaticCall(tree)(using Set.empty) } /** Tree interpreter that evaluates the tree */ - private class Interpreter(pos: SourcePosition, classLoader: ClassLoader)(using Context) { + private class Interpreter(pos: SrcPos, classLoader: ClassLoader)(using Context) { type Env = Map[Symbol, Object] @@ -345,7 +345,7 @@ object Splicer { } private def unexpectedTree(tree: Tree)(implicit env: Env): Object = - throw new StopInterpretation("Unexpected tree could not be interpreted: " + tree, tree.sourcePos) + throw new StopInterpretation("Unexpected tree could not be interpreted: " + tree, tree.srcPos) private def loadModule(sym: Symbol): Object = if (sym.owner.is(Package)) { @@ -491,7 +491,7 @@ object Splicer { /** Exception that stops interpretation if some issue is found */ - private class StopInterpretation(val msg: String, val pos: SourcePosition) extends Exception + private class StopInterpretation(val msg: String, val pos: SrcPos) extends Exception object Call { /** Matches an expression that is either a field access or an application diff --git a/compiler/src/dotty/tools/dotc/transform/Staging.scala b/compiler/src/dotty/tools/dotc/transform/Staging.scala index 3441c38c6409..efaa6b8059bf 100644 --- a/compiler/src/dotty/tools/dotc/transform/Staging.scala +++ b/compiler/src/dotty/tools/dotc/transform/Staging.scala @@ -15,14 +15,13 @@ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.tasty.TreePickler.Hole import dotty.tools.dotc.core.Types._ -import dotty.tools.dotc.util.{SourceFile, SourcePosition} +import dotty.tools.dotc.util.{SourceFile, SrcPos} import dotty.tools.dotc.transform.SymUtils._ import dotty.tools.dotc.transform.TreeMapWithStages._ import dotty.tools.dotc.typer.Implicits.SearchFailureType import dotty.tools.dotc.typer.Inliner import scala.collection.mutable -import dotty.tools.dotc.util.SourcePosition import scala.annotation.constructorOnly @@ -44,7 +43,7 @@ class Staging extends MacroTransform { tree match { case PackageDef(pid, _) if tree.symbol.owner == defn.RootClass => val checker = new PCPCheckAndHeal(freshStagingContext) { - override protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SourcePosition)(using Context): TypeRef = { + override protected def tryHeal(sym: Symbol, tp: TypeRef, pos: SrcPos)(using Context): TypeRef = { def symStr = if (sym.is(ModuleClass)) sym.sourceModule.show else i"${sym.name}.this" diff --git a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala index 03b87c1cf357..a2dd74ac9907 100644 --- a/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala +++ b/compiler/src/dotty/tools/dotc/transform/SuperAccessors.scala @@ -84,7 +84,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { if (!accDefs.contains(clazz)) report.error( s"Internal error: unable to store accessor definition in ${clazz}. clazz.hasPackageFlag=${clazz.is(Package)}. Accessor required for ${sel} (${sel.show})", - sel.sourcePos) + sel.srcPos) else accDefs(clazz) += DefDef(acc, EmptyTree).withSpan(accRange) acc } @@ -104,9 +104,9 @@ class SuperAccessors(thisPhase: DenotTransformer) { if (sym.isTerm && !sym.is(Method, butNot = Accessor) && !ctx.owner.isAllOf(ParamForwarder)) // ParamForwaders as installed ParamForwarding.scala do use super calls to vals - report.error(s"super may be not be used on ${sym.underlyingSymbol}", sel.sourcePos) + report.error(s"super may be not be used on ${sym.underlyingSymbol}", sel.srcPos) else if (isDisallowed(sym)) - report.error(s"super not allowed here: use this.${sel.name} instead", sel.sourcePos) + report.error(s"super not allowed here: use this.${sel.name} instead", sel.srcPos) else if (sym.is(Deferred)) { val member = sym.overridingSymbol(clazz.asClass) if (!mix.name.isEmpty || @@ -114,7 +114,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { !(member.is(AbsOverride) && member.isIncompleteIn(clazz))) report.error( i"${sym.showLocated} is accessed from super. It may not be abstract unless it is overridden by a member declared `abstract' and `override'", - sel.sourcePos) + sel.srcPos) else report.log(i"ok super $sel ${sym.showLocated} $member $clazz ${member.isIncompleteIn(clazz)}") } else { @@ -127,7 +127,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { if (overriding.is(Deferred, butNot = AbsOverride) && !overriding.owner.is(Trait)) report.error( s"${sym.showLocated} cannot be directly accessed from ${clazz} because ${overriding.owner} redeclares it as abstract", - sel.sourcePos) + sel.srcPos) } else { // scala/scala-dev#143: @@ -144,7 +144,7 @@ class SuperAccessors(thisPhase: DenotTransformer) { report.error( em"""Super call cannot be emitted: the selected $sym is declared in $owner, which is not the direct superclass of $clazz. |An unqualified super call (super.${sym.name}) would be allowed.""", - sel.sourcePos) + sel.srcPos) } } diff --git a/compiler/src/dotty/tools/dotc/transform/TailRec.scala b/compiler/src/dotty/tools/dotc/transform/TailRec.scala index 196fccf4c30e..f66944385893 100644 --- a/compiler/src/dotty/tools/dotc/transform/TailRec.scala +++ b/compiler/src/dotty/tools/dotc/transform/TailRec.scala @@ -124,7 +124,7 @@ class TailRec extends MiniPhase { // We don't report a new error if failures were reported // during the transformation. if (mandatory && !failureReported) - report.error(TailrecNotApplicable(method), method.sourcePos) + report.error(TailrecNotApplicable(method), method.srcPos) tree } @@ -197,7 +197,7 @@ class TailRec extends MiniPhase { } if isInfiniteRecCall(rhsFullyTransformed) then - report.warning("Infinite recursive call", tree.sourcePos) + report.warning("Infinite recursive call", tree.srcPos) cpy.DefDef(tree)(rhs = Block( @@ -304,7 +304,7 @@ class TailRec extends MiniPhase { def fail(reason: String) = { if (isMandatory) { failureReported = true - report.error(s"Cannot rewrite recursive call: $reason", tree.sourcePos) + report.error(s"Cannot rewrite recursive call: $reason", tree.srcPos) } else tailrec.println("Cannot rewrite recursive call at: " + tree.span + " because: " + reason) diff --git a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala index 10f48ad182ea..ed1232c0e213 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeChecker.scala @@ -210,7 +210,7 @@ class TreeChecker extends Phase with SymTransformer { assert( sym.isPatternBound, "patBoundSyms.contains(sym) => sym.isPatternBound is broken." + - i" Pattern bound symbol $sym has incorrect flags: " + sym.flagsString + ", line " + sym.sourcePos.line + i" Pattern bound symbol $sym has incorrect flags: " + sym.flagsString + ", line " + sym.srcPos.line ) } patBoundSyms ++= syms @@ -234,13 +234,13 @@ class TreeChecker extends Phase with SymTransformer { val sym = tree.symbol assert( nowDefinedSyms.contains(sym) || patBoundSyms.contains(sym), - i"undefined symbol ${sym} at line " + tree.sourcePos.line + i"undefined symbol ${sym} at line " + tree.srcPos.line ) if (!ctx.phase.patternTranslated) assert( !sym.isPatternBound || patBoundSyms.contains(sym), - i"sym.isPatternBound => patBoundSyms.contains(sym) is broken, sym = $sym, line " + tree.sourcePos.line + i"sym.isPatternBound => patBoundSyms.contains(sym) is broken, sym = $sym, line " + tree.srcPos.line ) } diff --git a/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala b/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala index 6020ca757643..5d7f76441d08 100644 --- a/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala +++ b/compiler/src/dotty/tools/dotc/transform/TreeMapWithStages.scala @@ -16,7 +16,7 @@ import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Symbols._ import dotty.tools.dotc.core.tasty.TreePickler.Hole import dotty.tools.dotc.util.Spans._ -import dotty.tools.dotc.util.{Property, SourcePosition} +import dotty.tools.dotc.util.Property import dotty.tools.dotc.transform.SymUtils._ import dotty.tools.dotc.typer.Implicits.SearchFailureType diff --git a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala index e0d69516fe16..124581c1db6e 100644 --- a/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala +++ b/compiler/src/dotty/tools/dotc/transform/TupleOptimizations.scala @@ -147,7 +147,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { val size = tpes.size val n = nTpe.value.intValue if (n < 0 || n >= size) { - report.error("index out of bounds: " + n, nTree.underlyingArgument.sourcePos) + report.error("index out of bounds: " + n, nTree.underlyingArgument.srcPos) tree } else if (size <= MaxTupleArity) @@ -157,7 +157,7 @@ class TupleOptimizations extends MiniPhase with IdentityDenotTransformer { // tup.asInstanceOf[TupleXXL].productElement(n) tup.asInstance(defn.TupleXXLClass.typeRef).select(nme.productElement).appliedTo(Literal(nTpe.value)) case (None, nTpe: ConstantType) if nTpe.value.intValue < 0 => - report.error("index out of bounds: " + nTpe.value.intValue, nTree.sourcePos) + report.error("index out of bounds: " + nTpe.value.intValue, nTree.srcPos) tree case _ => // No optimization, keep: diff --git a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala index 09bc9dad9f95..bc4c066fb065 100644 --- a/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala +++ b/compiler/src/dotty/tools/dotc/transform/TypeTestsCasts.scala @@ -198,8 +198,8 @@ object TypeTestsCasts { def unreachable(why: => String)(using Context): Boolean = { if (flagUnrelated) - if (inMatch) report.error(em"this case is unreachable since $why", expr.sourcePos) - else report.warning(em"this will always yield false since $why", expr.sourcePos) + if (inMatch) report.error(em"this case is unreachable since $why", expr.srcPos) + else report.warning(em"this will always yield false since $why", expr.srcPos) false } @@ -241,14 +241,14 @@ object TypeTestsCasts { val foundEffectiveClass = effectiveClass(expr.tpe.widen) if foundEffectiveClass.isPrimitiveValueClass && !testCls.isPrimitiveValueClass then - report.error(i"cannot test if value of $exprType is a reference of $testCls", tree.sourcePos) + report.error(i"cannot test if value of $exprType is a reference of $testCls", tree.srcPos) false else foundClasses.exists(check) end checkSensical if (expr.tpe <:< testType) if (expr.tpe.isNotNull) { - if (!inMatch) report.warning(TypeTestAlwaysSucceeds(expr.tpe, testType), tree.sourcePos) + if (!inMatch) report.warning(TypeTestAlwaysSucceeds(expr.tpe, testType), tree.srcPos) constant(expr, Literal(Constant(true))) } else expr.testNotNull @@ -349,7 +349,7 @@ object TypeTestsCasts { val argType = tree.args.head.tpe val isTrusted = tree.hasAttachment(PatternMatcher.TrustedTypeTestKey) if (!isTrusted && !checkable(expr.tpe, argType, tree.span)) - report.warning(i"the type test for $argType cannot be checked at runtime", tree.sourcePos) + report.warning(i"the type test for $argType cannot be checked at runtime", tree.srcPos) transformTypeTest(expr, tree.args.head.tpe, flagUnrelated = true) } else if (sym.isTypeCast) diff --git a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala index 6722701ad448..3f5da6bab7e7 100644 --- a/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala +++ b/compiler/src/dotty/tools/dotc/transform/YCheckPositions.scala @@ -8,7 +8,7 @@ import dotty.tools.dotc.core.Decorators._ import dotty.tools.dotc.core.Flags._ import dotty.tools.dotc.core.Phases.{Phase, postTyperPhase} import dotty.tools.dotc.core.Symbols._ -import dotty.tools.dotc.util.{SourceFile, SourcePosition} +import dotty.tools.dotc.util.SourceFile /** Ycheck inlined positions */ class YCheckPositions extends Phase { diff --git a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala index b38fb934e466..9e7735ff5da7 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Checking.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Checking.scala @@ -87,7 +87,7 @@ object Checking { else checkSecondaryConstructor(ctor) } else if (!cls.isOneOf(Flags.EffectivelyOpenFlags)) - report.warning("Inheriting non-open class may cause initialization errors", source.sourcePos) + report.warning("Inheriting non-open class may cause initialization errors", source.srcPos) } cls.paramAccessors.foreach { acc => diff --git a/compiler/src/dotty/tools/dotc/transform/init/Errors.scala b/compiler/src/dotty/tools/dotc/transform/init/Errors.scala index e2914b780031..94fc4832c7f1 100644 --- a/compiler/src/dotty/tools/dotc/transform/init/Errors.scala +++ b/compiler/src/dotty/tools/dotc/transform/init/Errors.scala @@ -8,7 +8,6 @@ import ast.tpd._ import core._ import Decorators._, printing.SyntaxHighlighting import Types._, Symbols._, Contexts._ -import util.SourcePosition import Effects._, Potentials._ @@ -25,7 +24,7 @@ object Errors { def show(using Context): String def issue(using Context): Unit = - report.warning(show + stacktrace, source.sourcePos) + report.warning(show + stacktrace, source.srcPos) def toErrors: Errors = Set(this) @@ -67,7 +66,7 @@ object Errors { "Access non-initialized field " + field.name.show + "." override def issue(using Context): Unit = - report.error(show + stacktrace, field.sourcePos) + report.error(show + stacktrace, field.srcPos) } /** Promote `this` under initialization to fully-initialized */ @@ -107,7 +106,7 @@ object Errors { assert(errors.nonEmpty) override def issue(using Context): Unit = - report.warning(show, source.sourcePos) + report.warning(show, source.srcPos) def show(using Context): String = { var index = 0 diff --git a/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala b/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala index 3a627751f5e7..4de45c371047 100644 --- a/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala +++ b/compiler/src/dotty/tools/dotc/transform/patmat/Space.scala @@ -20,7 +20,7 @@ import ProtoTypes._ import transform.SymUtils._ import reporting._ import config.Printers.{exhaustivity => debug} -import util.SourcePosition +import util.SrcPos import NullOpsDecorator._ /** Space logic for checking exhaustivity and unreachability of pattern matching @@ -291,7 +291,7 @@ object SpaceEngine { unappResult <:< ConstantType(Constant(true)) || (unapp.symbol.is(Synthetic) && unapp.symbol.owner.linkedClass.is(Case)) || // scala2 compatibility (patSize != -1 && productArity(unappResult) == patSize) || { - val isEmptyTp = extractorMemberType(unappResult, nme.isEmpty, unapp.sourcePos) + val isEmptyTp = extractorMemberType(unappResult, nme.isEmpty, unapp.srcPos) isEmptyTp <:< ConstantType(Constant(false)) } } @@ -306,7 +306,7 @@ object SpaceEngine { unapplySeqTypeElemTp(unappResult).exists || isProductSeqMatch(unappResult, patSize) || { - val isEmptyTp = extractorMemberType(unappResult, nme.isEmpty, unapp.sourcePos) + val isEmptyTp = extractorMemberType(unappResult, nme.isEmpty, unapp.srcPos) isEmptyTp <:< ConstantType(Constant(false)) } } @@ -387,7 +387,7 @@ class SpaceEngine(using Context) extends SpaceLogic { if (fun.symbol.owner == scalaSeqFactoryClass) projectSeq(pats) else { - val (arity, elemTp, resultTp) = unapplySeqInfo(fun.tpe.widen.finalResultType, fun.sourcePos) + val (arity, elemTp, resultTp) = unapplySeqInfo(fun.tpe.widen.finalResultType, fun.srcPos) if (elemTp.exists) Prod(erase(pat.tpe.stripAnnots), funRef, projectSeq(pats) :: Nil, isIrrefutableUnapplySeq(fun, pats.size)) else @@ -421,7 +421,7 @@ class SpaceEngine(using Context) extends SpaceLogic { case tp => Typ(tp, decomposed = true) } - private def unapplySeqInfo(resTp: Type, pos: SourcePosition)(using Context): (Int, Type, Type) = { + private def unapplySeqInfo(resTp: Type, pos: SrcPos)(using Context): (Int, Type, Type) = { var resultTp = resTp var elemTp = unapplySeqTypeElemTp(resultTp) var arity = productArity(resultTp, pos) @@ -559,21 +559,21 @@ class SpaceEngine(using Context) extends SpaceLogic { val isUnapplySeq = unappSym.name == nme.unapplySeq if (isUnapplySeq) { - val (arity, elemTp, resultTp) = unapplySeqInfo(resTp, unappSym.sourcePos) + val (arity, elemTp, resultTp) = unapplySeqInfo(resTp, unappSym.srcPos) if (elemTp.exists) scalaListType.appliedTo(elemTp) :: Nil else { - val sels = productSeqSelectors(resultTp, arity, unappSym.sourcePos) + val sels = productSeqSelectors(resultTp, arity, unappSym.srcPos) sels.init :+ scalaListType.appliedTo(sels.last) } } else { - val arity = productArity(resTp, unappSym.sourcePos) + val arity = productArity(resTp, unappSym.srcPos) if (arity > 0) - productSelectorTypes(resTp, unappSym.sourcePos) + productSelectorTypes(resTp, unappSym.srcPos) else { val getTp = resTp.select(nme.get).finalResultType.widen if (argLen == 1) getTp :: Nil - else productSelectorTypes(getTp, unappSym.sourcePos) + else productSelectorTypes(getTp, unappSym.srcPos) } } } @@ -835,7 +835,7 @@ class SpaceEngine(using Context) extends SpaceLogic { } if (uncovered.nonEmpty) - report.warning(PatternMatchExhaustivity(show(uncovered)), sel.sourcePos) + report.warning(PatternMatchExhaustivity(show(uncovered)), sel.srcPos) } private def redundancyCheckable(sel: Tree): Boolean = @@ -886,7 +886,7 @@ class SpaceEngine(using Context) extends SpaceLogic { if (covered == Empty && !isNullLit(pat)) covered = curr if (isSubspace(covered, prevs)) { - report.warning(MatchCaseUnreachable(), pat.sourcePos) + report.warning(MatchCaseUnreachable(), pat.srcPos) } // if last case is `_` and only matches `null`, produce a warning @@ -895,7 +895,7 @@ class SpaceEngine(using Context) extends SpaceLogic { if (!ctx.explicitNulls && i == cases.length - 1 && !isNullLit(pat) ) { simplify(minus(covered, prevs)) match { case Typ(`constantNullType`, _) => - report.warning(MatchCaseOnlyNullWarning(), pat.sourcePos) + report.warning(MatchCaseOnlyNullWarning(), pat.srcPos) case _ => } } diff --git a/compiler/src/dotty/tools/dotc/typer/Applications.scala b/compiler/src/dotty/tools/dotc/typer/Applications.scala index 5329c29ce0b3..a6e4168aebaf 100644 --- a/compiler/src/dotty/tools/dotc/typer/Applications.scala +++ b/compiler/src/dotty/tools/dotc/typer/Applications.scala @@ -6,7 +6,7 @@ import core._ import ast.{Trees, tpd, untpd, desugar} import util.Spans._ import util.Stats.record -import util.{SourcePosition, NoSourcePosition, SourceFile} +import util.{SrcPos, NoSourcePosition, SourceFile} import Trees.Untyped import Contexts._ import Flags._ @@ -42,7 +42,7 @@ object Applications { def extractorMember(tp: Type, name: Name)(using Context): SingleDenotation = tp.member(name).suchThat(sym => sym.info.isParameterless && sym.info.widenExpr.isValueType) - def extractorMemberType(tp: Type, name: Name, errorPos: SourcePosition)(using Context): Type = { + def extractorMemberType(tp: Type, name: Name, errorPos: SrcPos)(using Context): Type = { val ref = extractorMember(tp, name) if (ref.isOverloaded) errorType(i"Overloaded reference to $ref is not allowed in extractor", errorPos) @@ -53,7 +53,7 @@ object Applications { * for a pattern with `numArgs` subpatterns? * This is the case if `tp` has members `_1` to `_N` where `N == numArgs`. */ - def isProductMatch(tp: Type, numArgs: Int, errorPos: SourcePosition = NoSourcePosition)(using Context): Boolean = + def isProductMatch(tp: Type, numArgs: Int, errorPos: SrcPos = NoSourcePosition)(using Context): Boolean = numArgs > 0 && productArity(tp, errorPos) == numArgs /** Does `tp` fit the "product-seq match" conditions as an unapply result type @@ -61,7 +61,7 @@ object Applications { * This is the case if (1) `tp` has members `_1` to `_N` where `N <= numArgs + 1`. * (2) `tp._N` conforms to Seq match */ - def isProductSeqMatch(tp: Type, numArgs: Int, errorPos: SourcePosition = NoSourcePosition)(using Context): Boolean = { + def isProductSeqMatch(tp: Type, numArgs: Int, errorPos: SrcPos = NoSourcePosition)(using Context): Boolean = { val arity = productArity(tp, errorPos) arity > 0 && arity <= numArgs + 1 && unapplySeqTypeElemTp(productSelectorTypes(tp, errorPos).last).exists @@ -71,7 +71,7 @@ object Applications { * This is the case of `tp` has a `get` member as well as a * parameterless `isEmpty` member of result type `Boolean`. */ - def isGetMatch(tp: Type, errorPos: SourcePosition = NoSourcePosition)(using Context): Boolean = + def isGetMatch(tp: Type, errorPos: SrcPos = NoSourcePosition)(using Context): Boolean = extractorMemberType(tp, nme.isEmpty, errorPos).widenSingleton.isRef(defn.BooleanClass) && extractorMemberType(tp, nme.get, errorPos).exists @@ -108,7 +108,7 @@ object Applications { if (isValid) elemTp else NoType } - def productSelectorTypes(tp: Type, errorPos: SourcePosition)(using Context): List[Type] = { + def productSelectorTypes(tp: Type, errorPos: SrcPos)(using Context): List[Type] = { def tupleSelectors(n: Int, tp: Type): List[Type] = { val sel = extractorMemberType(tp, nme.selectorName(n), errorPos) // extractorMemberType will return NoType if this is the tail of tuple with an unknown tail @@ -124,7 +124,7 @@ object Applications { genTupleSelectors(0, tp) } - def productArity(tp: Type, errorPos: SourcePosition = NoSourcePosition)(using Context): Int = + def productArity(tp: Type, errorPos: SrcPos = NoSourcePosition)(using Context): Int = if (defn.isProductSubType(tp)) productSelectorTypes(tp, errorPos).size else -1 def productSelectors(tp: Type)(using Context): List[Symbol] = { @@ -133,7 +133,7 @@ object Applications { sels.takeWhile(_.exists).toList } - def getUnapplySelectors(tp: Type, args: List[untpd.Tree], pos: SourcePosition)(using Context): List[Type] = + def getUnapplySelectors(tp: Type, args: List[untpd.Tree], pos: SrcPos)(using Context): List[Type] = if (args.length > 1 && !(tp.derivesFrom(defn.SeqClass))) { val sels = productSelectorTypes(tp, pos) if (sels.length == args.length) sels @@ -141,14 +141,14 @@ object Applications { } else tp :: Nil - def productSeqSelectors(tp: Type, argsNum: Int, pos: SourcePosition)(using Context): List[Type] = { + def productSeqSelectors(tp: Type, argsNum: Int, pos: SrcPos)(using Context): List[Type] = { val selTps = productSelectorTypes(tp, pos) val arity = selTps.length val elemTp = unapplySeqTypeElemTp(selTps.last) (0 until argsNum).map(i => if (i < arity - 1) selTps(i) else elemTp).toList } - def unapplyArgs(unapplyResult: Type, unapplyFn: Tree, args: List[untpd.Tree], pos: SourcePosition)(using Context): List[Type] = { + def unapplyArgs(unapplyResult: Type, unapplyFn: Tree, args: List[untpd.Tree], pos: SrcPos)(using Context): List[Type] = { def getName(fn: Tree): Name = fn match case TypeApply(fn, _) => getName(fn) @@ -283,7 +283,7 @@ trait Applications extends Compatibility { /** Signal failure with given message at position of the application itself */ protected def fail(msg: Message): Unit - protected def appPos: SourcePosition + protected def appPos: SrcPos /** The current function part, which might be affected by lifting. */ @@ -662,7 +662,7 @@ trait Applications extends Compatibility { ok = false def fail(msg: Message): Unit = ok = false - def appPos: SourcePosition = NoSourcePosition + def appPos: SrcPos = NoSourcePosition @threadUnsafe lazy val normalizedFun: Tree = ref(methRef) init() } @@ -724,15 +724,15 @@ trait Applications extends Compatibility { def harmonizeArgs(args: List[TypedArg]): List[Tree] = harmonize(args) - override def appPos: SourcePosition = app.sourcePos + override def appPos: SrcPos = app.srcPos def fail(msg: Message, arg: Trees.Tree[T]): Unit = { - report.error(msg, arg.sourcePos) + report.error(msg, arg.srcPos) ok = false } def fail(msg: Message): Unit = { - report.error(msg, app.sourcePos) + report.error(msg, app.srcPos) ok = false } @@ -941,7 +941,7 @@ trait Applications extends Compatibility { case CaseDef(Bind(_, Typed(_: untpd.Ident, _)), _, _) => // OK case CaseDef(Ident(name), _, _) if name == nme.WILDCARD => // Ok case CaseDef(pat, _, _) => - report.error(UnexpectedPatternForSummonFrom(pat), pat.sourcePos) + report.error(UnexpectedPatternForSummonFrom(pat), pat.srcPos) } typed(untpd.InlineMatch(EmptyTree, cases).withSpan(arg.span), pt) case _ => @@ -1057,7 +1057,7 @@ trait Applications extends Compatibility { if (typedFn.symbol == defn.Predef_classOf && typedArgs.nonEmpty) { val arg = typedArgs.head if (!arg.symbol.is(Module)) // Allow `classOf[Foo.type]` if `Foo` is an object - checkClassType(arg.tpe, arg.sourcePos, traitReq = false, stablePrefixReq = false) + checkClassType(arg.tpe, arg.srcPos, traitReq = false, stablePrefixReq = false) } case _ => } @@ -1256,7 +1256,7 @@ trait Applications extends Compatibility { case Apply(Apply(unapply, `dummyArg` :: Nil), args2) => assert(args2.nonEmpty); res ++= args2 case Apply(unapply, `dummyArg` :: Nil) => case Inlined(u, _, _) => loop(u) - case DynamicUnapply(_) => report.error("Structural unapply is not supported", unapplyFn.sourcePos) + case DynamicUnapply(_) => report.error("Structural unapply is not supported", unapplyFn.srcPos) case Apply(fn, args) => assert(args.nonEmpty); loop(fn); res ++= args case _ => ().assertingErrorsReported } @@ -1264,7 +1264,7 @@ trait Applications extends Compatibility { res.result() } - var argTypes = unapplyArgs(unapplyApp.tpe, unapplyFn, args, tree.sourcePos) + var argTypes = unapplyArgs(unapplyApp.tpe, unapplyFn, args, tree.srcPos) for (argType <- argTypes) assert(!isBounds(argType), unapplyApp.tpe.show) val bunchedArgs = argTypes match { case argType :: Nil => @@ -1273,7 +1273,7 @@ trait Applications extends Compatibility { case _ => args } if (argTypes.length != bunchedArgs.length) { - report.error(UnapplyInvalidNumberOfArguments(qual, argTypes), tree.sourcePos) + report.error(UnapplyInvalidNumberOfArguments(qual, argTypes), tree.srcPos) argTypes = argTypes.take(args.length) ++ List.fill(argTypes.length - args.length)(WildcardType) } @@ -2109,7 +2109,7 @@ trait Applications extends Compatibility { case tree => tree.symbol.is(Extension) } if (!isExtension(app)) - report.error(em"not an extension method: $methodRef", receiver.sourcePos) + report.error(em"not an extension method: $methodRef", receiver.srcPos) app } } diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index 1e87a08b0fe0..09381b3af02c 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -20,7 +20,7 @@ import rewrites.Rewrites.patch import util.Spans.Span import Phases.refchecksPhase -import util.SourcePosition +import util.SrcPos import util.Spans.Span import rewrites.Rewrites.patch import transform.SymUtils._ @@ -73,7 +73,7 @@ object Checking { report.error( showInferred(DoesNotConformToBound(arg.tpe, which, bound), app, tpt), - arg.sourcePos.focus) + arg.srcPos.focus) /** Check that type arguments `args` conform to corresponding bounds in `tl` * Note: This does not check the bounds of AppliedTypeTrees. These @@ -115,7 +115,7 @@ object Checking { if (tycon.isLambdaSub && tp.hasWildcardArg) report.errorOrMigrationWarning( showInferred(UnreducibleApplication(tycon), tp, tpt), - tree.sourcePos) + tree.srcPos) case _ => } def checkValidIfApply(using Context): Unit = @@ -168,26 +168,26 @@ object Checking { /** Check that `tp` refers to a nonAbstract class * and that the instance conforms to the self type of the created class. */ - def checkInstantiable(tp: Type, posd: Positioned)(using Context): Unit = + def checkInstantiable(tp: Type, pos: SrcPos)(using Context): Unit = tp.underlyingClassRef(refinementOK = false) match case tref: TypeRef => val cls = tref.symbol if (cls.isOneOf(AbstractOrTrait)) - report.error(CantInstantiateAbstractClassOrTrait(cls, isTrait = cls.is(Trait)), posd.sourcePos) + report.error(CantInstantiateAbstractClassOrTrait(cls, isTrait = cls.is(Trait)), pos) if !cls.is(Module) then // Create a synthetic singleton type instance, and check whether // it conforms to the self type of the class as seen from that instance. val stp = SkolemType(tp) val selfType = cls.declaredSelfTypeAsSeenFrom(stp) if selfType.exists && !(stp <:< selfType) then - report.error(DoesNotConformToSelfTypeCantBeInstantiated(tp, selfType), posd.sourcePos) + report.error(DoesNotConformToSelfTypeCantBeInstantiated(tp, selfType), pos) case _ => /** Check that type `tp` is realizable. */ - def checkRealizable(tp: Type, posd: Positioned, what: String = "path")(using Context): Unit = { + def checkRealizable(tp: Type, pos: SrcPos, what: String = "path")(using Context): Unit = { val rstatus = realizability(tp) if (rstatus ne Realizable) - report.errorOrMigrationWarning(em"$tp is not a legal $what\nsince it${rstatus.msg}", posd.sourcePos) + report.errorOrMigrationWarning(em"$tp is not a legal $what\nsince it${rstatus.msg}", pos) } /** A type map which checks that the only cycles in a type are F-bounds @@ -320,7 +320,7 @@ object Checking { && !sym.is(Synthetic) && sourceVersion.isAtLeast(`3.1`) => report.deprecationWarning( - i"$sym has an operator name; it should come with an @alpha annotation", sym.sourcePos) + i"$sym has an operator name; it should come with an @alpha annotation", sym.srcPos) case _ => } @@ -335,7 +335,7 @@ object Checking { catch { case ex: CyclicReference => if (reportErrors) - errorType(IllegalCyclicTypeReference(sym, checker.where, checker.lastChecked), sym.sourcePos) + errorType(IllegalCyclicTypeReference(sym, checker.where, checker.lastChecked), sym.srcPos) else info } } @@ -352,7 +352,7 @@ object Checking { def checkRefinementNonCyclic(refinement: Tree, refineCls: ClassSymbol, seen: mutable.Set[Symbol]) (using Context): Unit = { def flag(what: String, tree: Tree) = - report.warning(i"$what reference in refinement is deprecated", tree.sourcePos) + report.warning(i"$what reference in refinement is deprecated", tree.srcPos) def forwardRef(tree: Tree) = flag("forward", tree) def selfRef(tree: Tree) = flag("self", tree) val checkTree = new TreeAccumulator[Unit] { @@ -396,7 +396,7 @@ object Checking { * unless a type with the same name already appears in `decls`. * @return true iff no cycles were detected */ - def checkNonCyclicInherited(joint: Type, parents: List[Type], decls: Scope, posd: Positioned)(using Context): Unit = { + def checkNonCyclicInherited(joint: Type, parents: List[Type], decls: Scope, pos: SrcPos)(using Context): Unit = { // If we don't have more than one parent, then there's nothing to check if (parents.lengthCompare(1) <= 0) return @@ -418,14 +418,14 @@ object Checking { } catch { case ex: RecursionOverflow => - report.error(em"cyclic reference involving type $name", posd.sourcePos) + report.error(em"cyclic reference involving type $name", pos) false } } /** Check that symbol's definition is well-formed. */ def checkWellFormed(sym: Symbol)(using Context): Unit = { - def fail(msg: Message) = report.error(msg, sym.sourcePos) + def fail(msg: Message) = report.error(msg, sym.srcPos) def checkWithDeferred(flag: FlagSet) = if (sym.isOneOf(flag)) @@ -580,7 +580,7 @@ object Checking { } val notPrivate = new NotPrivate val info = notPrivate(sym.info) - notPrivate.errors.foreach(error => report.errorOrMigrationWarning(error(), sym.sourcePos)) + notPrivate.errors.foreach(error => report.errorOrMigrationWarning(error(), sym.srcPos)) info } @@ -588,25 +588,25 @@ object Checking { def checkDerivedValueClass(clazz: Symbol, stats: List[Tree])(using Context): Unit = { def checkValueClassMember(stat: Tree) = stat match { case _: TypeDef if stat.symbol.isClass => - report.error(ValueClassesMayNotDefineInner(clazz, stat.symbol), stat.sourcePos) + report.error(ValueClassesMayNotDefineInner(clazz, stat.symbol), stat.srcPos) case _: ValDef if !stat.symbol.is(ParamAccessor) => - report.error(ValueClassesMayNotDefineNonParameterField(clazz, stat.symbol), stat.sourcePos) + report.error(ValueClassesMayNotDefineNonParameterField(clazz, stat.symbol), stat.srcPos) case _: DefDef if stat.symbol.isConstructor => - report.error(ValueClassesMayNotDefineASecondaryConstructor(clazz, stat.symbol), stat.sourcePos) + report.error(ValueClassesMayNotDefineASecondaryConstructor(clazz, stat.symbol), stat.srcPos) case _: MemberDef | _: Import | EmptyTree => // ok case _ => - report.error(ValueClassesMayNotContainInitalization(clazz), stat.sourcePos) + report.error(ValueClassesMayNotContainInitalization(clazz), stat.srcPos) } if (isDerivedValueClass(clazz)) { if (clazz.is(Trait)) - report.error(CannotExtendAnyVal(clazz), clazz.sourcePos) + report.error(CannotExtendAnyVal(clazz), clazz.srcPos) if (clazz.is(Abstract)) - report.error(ValueClassesMayNotBeAbstract(clazz), clazz.sourcePos) + report.error(ValueClassesMayNotBeAbstract(clazz), clazz.srcPos) if (!clazz.isStatic) - report.error(ValueClassesMayNotBeContainted(clazz), clazz.sourcePos) + report.error(ValueClassesMayNotBeContainted(clazz), clazz.srcPos) if (isCyclic(clazz.asClass)) - report.error(ValueClassesMayNotWrapItself(clazz), clazz.sourcePos) + report.error(ValueClassesMayNotWrapItself(clazz), clazz.srcPos) else { val clParamAccessors = clazz.asClass.paramAccessors.filter { param => param.isTerm && !param.is(Flags.Accessor) @@ -614,16 +614,16 @@ object Checking { clParamAccessors match { case param :: params => if (param.is(Mutable)) - report.error(ValueClassParameterMayNotBeAVar(clazz, param), param.sourcePos) + report.error(ValueClassParameterMayNotBeAVar(clazz, param), param.srcPos) if (param.info.isInstanceOf[ExprType]) - report.error(ValueClassParameterMayNotBeCallByName(clazz, param), param.sourcePos) + report.error(ValueClassParameterMayNotBeCallByName(clazz, param), param.srcPos) if (param.is(Erased)) - report.error("value class first parameter cannot be `erased`", param.sourcePos) + report.error("value class first parameter cannot be `erased`", param.srcPos) else for (p <- params if !p.is(Erased)) - report.error("value class can only have one non `erased` parameter", p.sourcePos) + report.error("value class can only have one non `erased` parameter", p.srcPos) case Nil => - report.error(ValueClassNeedsOneValParam(clazz), clazz.sourcePos) + report.error(ValueClassNeedsOneValParam(clazz), clazz.srcPos) } } stats.foreach(checkValueClassMember) @@ -639,7 +639,7 @@ object Checking { if enumCase.exists then val enumCls = enumCase.owner.linkedClass if !cls.info.parents.exists(_.typeSymbol == enumCls) then - report.error(i"enum case does not extend its enum $enumCls", enumCase.sourcePos) + report.error(i"enum case does not extend its enum $enumCls", enumCase.srcPos) /** Check the inline override methods only use inline parameters if they override an inline parameter. */ def checkInlineOverrideParameters(sym: Symbol)(using Context): Unit = @@ -652,7 +652,7 @@ object Checking { report.error( if p2.is(Inline) then "Cannot override inline parameter with a non-inline parameter" else "Cannot override non-inline parameter with an inline parameter", - p1.sourcePos) + p1.srcPos) } @@ -663,15 +663,15 @@ trait Checking { def checkNonCyclic(sym: Symbol, info: TypeBounds, reportErrors: Boolean)(using Context): Type = Checking.checkNonCyclic(sym, info, reportErrors) - def checkNonCyclicInherited(joint: Type, parents: List[Type], decls: Scope, posd: Positioned)(using Context): Unit = - Checking.checkNonCyclicInherited(joint, parents, decls, posd) + def checkNonCyclicInherited(joint: Type, parents: List[Type], decls: Scope, pos: SrcPos)(using Context): Unit = + Checking.checkNonCyclicInherited(joint, parents, decls, pos) /** Check that type `tp` is stable. */ - def checkStable(tp: Type, pos: SourcePosition, kind: String)(using Context): Unit = + def checkStable(tp: Type, pos: SrcPos, kind: String)(using Context): Unit = if !tp.isStable then report.error(NotAPath(tp, kind), pos) /** Check that all type members of `tp` have realizable bounds */ - def checkRealizableBounds(cls: Symbol, pos: SourcePosition)(using Context): Unit = { + def checkRealizableBounds(cls: Symbol, pos: SrcPos)(using Context): Unit = { val rstatus = boundsRealizability(cls.thisType) if (rstatus ne Realizable) report.error(ex"$cls cannot be instantiated since it${rstatus.msg}", pos) @@ -692,7 +692,7 @@ trait Checking { ex"""pattern's type ${pat.tpe} $problem the right hand side expression's type $reportedPt | |If the narrowing is intentional, this can be communicated by writing $fix the full pattern.${err.rewriteNotice}""", - pat.sourcePos) + pat.srcPos) false } @@ -708,7 +708,7 @@ trait Checking { case UnApply(fn, _, pats) => check(pat, pt) && (isIrrefutableUnapply(fn, pats.length) || fail(pat, pt)) && { - val argPts = unapplyArgs(fn.tpe.widen.finalResultType, fn, pats, pat.sourcePos) + val argPts = unapplyArgs(fn.tpe.widen.finalResultType, fn, pats, pat.srcPos) pats.corresponds(argPts)(recur) } case Alternative(pats) => @@ -727,8 +727,8 @@ trait Checking { /** Check that `path` is a legal prefix for an import or export clause */ def checkLegalImportPath(path: Tree)(using Context): Unit = { - checkStable(path.tpe, path.sourcePos, "import prefix") - if (!ctx.isAfterTyper) Checking.checkRealizable(path.tpe, path.posd) + checkStable(path.tpe, path.srcPos, "import prefix") + if (!ctx.isAfterTyper) Checking.checkRealizable(path.tpe, path.srcPos) } /** Check that `tp` is a class type. @@ -737,7 +737,7 @@ trait Checking { * check that class prefix is stable. * @return `tp` itself if it is a class or trait ref, ObjectType if not. */ - def checkClassType(tp: Type, pos: SourcePosition, traitReq: Boolean, stablePrefixReq: Boolean)(using Context): Type = + def checkClassType(tp: Type, pos: SrcPos, traitReq: Boolean, stablePrefixReq: Boolean)(using Context): Type = tp.underlyingClassRef(refinementOK = false) match { case tref: TypeRef => if (traitReq && !tref.symbol.is(Trait)) report.error(TraitIsExpected(tref.symbol), pos) @@ -757,7 +757,7 @@ trait Checking { nme.implicitConversions, i"Definition of implicit conversion $sym", ctx.owner.topLevelClass, - sym.sourcePos) + sym.srcPos) sym.info.stripPoly match { case mt @ MethodType(_ :: Nil) @@ -776,7 +776,7 @@ trait Checking { * - it is defined in Predef * - it is the scala.reflect.Selectable.reflectiveSelectable conversion */ - def checkImplicitConversionUseOK(sym: Symbol, posd: Positioned)(using Context): Unit = + def checkImplicitConversionUseOK(sym: Symbol, pos: SrcPos)(using Context): Unit = if (sym.exists) { val conv = if (sym.isOneOf(GivenOrImplicit) || sym.info.isErroneous) sym @@ -791,7 +791,7 @@ trait Checking { conv.name == nme.reflectiveSelectable && conv.maybeOwner.maybeOwner.maybeOwner == defn.ScalaPackageClass if (!conversionOK) checkFeature(nme.implicitConversions, - i"Use of implicit conversion ${conv.showLocated}", NoSymbol, posd.sourcePos) + i"Use of implicit conversion ${conv.showLocated}", NoSymbol, pos) } private def infixOKSinceFollowedBy(tree: untpd.Tree): Boolean = tree match { @@ -824,7 +824,7 @@ trait Checking { i"""Alphanumeric $kind $name is not declared @infix; it should not be used as infix operator. |The operation can be rewritten automatically to `$name` under -deprecation -rewrite. |Or rewrite to ${alternative(name)} manually.""", - tree.op.sourcePos) + tree.op.srcPos) if (ctx.settings.deprecation.value) { patch(Span(tree.op.span.start, tree.op.span.start), "`") patch(Span(tree.op.span.end, tree.op.span.end), "`") @@ -838,7 +838,7 @@ trait Checking { def checkFeature(name: TermName, description: => String, featureUseSite: Symbol, - pos: SourcePosition)(using Context): Unit = + pos: SrcPos)(using Context): Unit = if !enabled(name) then report.featureWarning(name.toString, description, featureUseSite, required = false, pos) @@ -846,7 +846,7 @@ trait Checking { * are feasible, i.e. that their lower bound conforms to their upper bound. If a type * argument is infeasible, issue and error and continue with upper bound. */ - def checkFeasibleParent(tp: Type, pos: SourcePosition, where: => String = "")(using Context): Type = { + def checkFeasibleParent(tp: Type, pos: SrcPos, where: => String = "")(using Context): Type = { def checkGoodBounds(tp: Type) = tp match { case tp @ TypeBounds(lo, hi) if !(lo <:< hi) => report.error(ex"no type exists between low bound $lo and high bound $hi$where", pos) @@ -873,9 +873,9 @@ trait Checking { tpt.tpe.widenTermRefExpr.dealias.normalized match case tp: ConstantType => if !(exprPurity(tree) >= Pure) then - report.error(em"inline value must be pure", tree.sourcePos) + report.error(em"inline value must be pure", tree.srcPos) case _ => - val pos = if tpt.span.isZeroExtent then tree.sourcePos else tpt.sourcePos + val pos = if tpt.span.isZeroExtent then tree.srcPos else tpt.srcPos report.error(em"inline value must have a literal constant type", pos) } @@ -898,12 +898,12 @@ trait Checking { if (decl.matches(other) && !javaFieldMethodPair) { def doubleDefError(decl: Symbol, other: Symbol): Unit = if (!decl.info.isErroneous && !other.info.isErroneous) - report.error(DoubleDefinition(decl, other, cls), decl.sourcePos) + report.error(DoubleDefinition(decl, other, cls), decl.srcPos) if (decl is Synthetic) 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.sourcePos) + report.error(em"two or more overloaded variants of $decl have default arguments", decl.srcPos) decl.resetFlag(HasDefaultParams) } if (!excludeFromDoubleDeclCheck(decl)) @@ -921,16 +921,16 @@ trait Checking { if (!ctx.isAfterTyper) { val called = call.tpe.classSymbol if (caller.is(Trait)) - report.error(i"$caller may not call constructor of $called", call.sourcePos) + report.error(i"$caller may not call constructor of $called", call.srcPos) else if (called.is(Trait) && !caller.mixins.contains(called)) report.error(i"""$called is already implemented by super${caller.superClass}, - |its constructor cannot be called again""", call.sourcePos) + |its constructor cannot be called again""", call.srcPos) if (caller.is(Module)) { val traverser = new TreeTraverser { def traverse(tree: Tree)(using Context) = tree match { case tree: RefTree if tree.isTerm && (tree.tpe.widen.classSymbol eq caller) => - report.error("super constructor cannot be passed a self reference", tree.sourcePos) + report.error("super constructor cannot be passed a self reference", tree.srcPos) case _ => traverseChildren(tree) } @@ -944,7 +944,7 @@ trait Checking { case Apply(fn, _) => checkLegalConstructorCall(fn, tree, "") case TypeApply(fn, _) => checkLegalConstructorCall(fn, tree, "type ") case Select(_, nme.CONSTRUCTOR) => // ok - case _ => report.error(s"too many ${kind}arguments in parent constructor", encl.sourcePos) + case _ => report.error(s"too many ${kind}arguments in parent constructor", encl.srcPos) } call match { case Apply(fn, _) => checkLegalConstructorCall(fn, call, "") @@ -963,7 +963,7 @@ trait Checking { /** Check that the signature of the class mamber does not return a repeated parameter type */ def checkSignatureRepeatedParam(sym: Symbol)(using Context): Unit = if (!sym.isOneOf(Synthetic | InlineProxy | Param) && sym.info.finalResultType.isRepeatedParam) - report.error(em"Cannot return repeated parameter type ${sym.info.finalResultType}", sym.sourcePos) + report.error(em"Cannot return repeated parameter type ${sym.info.finalResultType}", sym.srcPos) /** Verify classes extending AnyVal meet the requirements */ def checkDerivedValueClass(clazz: Symbol, stats: List[Tree])(using Context): Unit = @@ -980,7 +980,7 @@ trait Checking { * * The standard library relies on this idiom. */ - def checkTraitInheritance(parent: Symbol, cls: ClassSymbol, pos: SourcePosition)(using Context): Unit = + def checkTraitInheritance(parent: Symbol, cls: ClassSymbol, pos: SrcPos)(using Context): Unit = parent match { case parent: ClassSymbol if parent.is(Trait) => val psuper = parent.superClass @@ -995,7 +995,7 @@ trait Checking { /** Check that case classes are not inherited by case classes. */ - def checkCaseInheritance(parent: Symbol, caseCls: ClassSymbol, pos: SourcePosition)(using Context): Unit = + def checkCaseInheritance(parent: Symbol, caseCls: ClassSymbol, pos: SrcPos)(using Context): Unit = parent match { case parent: ClassSymbol => if (parent.is(Case)) @@ -1013,7 +1013,7 @@ trait Checking { val check = new TreeTraverser { def traverse(tree: Tree)(using Context) = tree match { case id: Ident if vparams.exists(_.symbol == id.symbol) => - report.error("illegal forward reference to method parameter", id.sourcePos) + report.error("illegal forward reference to method parameter", id.srcPos) case _ => traverseChildren(tree) } @@ -1029,7 +1029,7 @@ trait Checking { * of the self type, yet is no longer visible once the `this` has been replaced * by some other prefix. See neg/i3083.scala */ - def checkMembersOK(tp: Type, pos: SourcePosition)(using Context): Type = { + def checkMembersOK(tp: Type, pos: SrcPos)(using Context): Type = { var ok = true val check: Type => Unit = { case ref: NamedType => @@ -1056,7 +1056,7 @@ trait Checking { if (t.span.isSourceDerived && owner == badOwner) t match { case t: RefTree if allowed(t.name, checkedSym) => - case _ => report.error(i"illegal reference to $checkedSym from $where", t.sourcePos) + case _ => report.error(i"illegal reference to $checkedSym from $where", t.srcPos) } val sym = t.symbol t match { @@ -1083,12 +1083,12 @@ trait Checking { case _ => if tree.tpe.typeParams.nonEmpty then val what = if tree.symbol.exists then tree.symbol else i"type $tree" - report.error(em"$what takes type parameters", tree.sourcePos) + report.error(em"$what takes type parameters", tree.srcPos) /** Check that we are in an inline context (inside an inline method or in inline code) */ - def checkInInlineContext(what: String, posd: Positioned)(using Context): Unit = + def checkInInlineContext(what: String, pos: SrcPos)(using Context): Unit = if !Inliner.inInlineMethod && !ctx.isInlineContext then - report.error(em"$what can only be used in an inline method", posd.sourcePos) + report.error(em"$what can only be used in an inline method", pos) /** 1. Check that all case classes that extend `scala.Enum` are `enum` cases * 2. Check that case class `enum` cases do not extend java.lang.Enum. @@ -1101,7 +1101,7 @@ trait Checking { if (!isEnumAnonCls) if (cdef.mods.isEnumCase) { if (cls.derivesFrom(defn.JavaEnumClass)) - report.error(em"paramerized case is not allowed in an enum that extends java.lang.Enum", cdef.sourcePos) + report.error(em"paramerized case is not allowed in an enum that extends java.lang.Enum", cdef.srcPos) } else if (cls.is(Case) || firstParent.is(Enum)) // Since enums are classes and Namer checks that classes don't extend multiple classes, we only check the class @@ -1109,7 +1109,7 @@ trait Checking { // // Unlike firstParent.derivesFrom(defn.EnumClass), this test allows inheriting from `Enum` by hand; // see enum-List-control.scala. - report.error(ClassCannotExtendEnum(cls, firstParent), cdef.sourcePos) + report.error(ClassCannotExtendEnum(cls, firstParent), cdef.srcPos) } /** Check that all references coming from enum cases in an enum companion object @@ -1177,7 +1177,7 @@ trait Checking { def checkAnnotApplicable(annot: Tree, sym: Symbol)(using Context): Boolean = !ctx.reporter.reportsErrorsFor { val annotCls = Annotations.annotClass(annot) - val pos = annot.sourcePos + val pos = annot.srcPos if (annotCls == defn.MainAnnot) { if (!sym.isRealMethod) report.error(em"@main annotation cannot be applied to $sym", pos) @@ -1196,7 +1196,7 @@ trait Checking { if (ename != sym.name) { val preExisting = ctx.effectiveScope.lookup(ename) if (preExisting.exists || seen.contains(ename)) - report.error(em"@alpha annotation ${'"'}$ename${'"'} clashes with other definition is same scope", stat.sourcePos) + report.error(em"@alpha annotation ${'"'}$ename${'"'} clashes with other definition is same scope", stat.srcPos) if stat.isDef then seen += ename } } @@ -1215,22 +1215,22 @@ trait ReChecking extends Checking { trait NoChecking extends ReChecking { import tpd._ override def checkNonCyclic(sym: Symbol, info: TypeBounds, reportErrors: Boolean)(using Context): Type = info - override def checkNonCyclicInherited(joint: Type, parents: List[Type], decls: Scope, posd: Positioned)(using Context): Unit = () - override def checkStable(tp: Type, pos: SourcePosition, kind: String)(using Context): Unit = () - override def checkClassType(tp: Type, pos: SourcePosition, traitReq: Boolean, stablePrefixReq: Boolean)(using Context): Type = tp + override def checkNonCyclicInherited(joint: Type, parents: List[Type], decls: Scope, pos: SrcPos)(using Context): Unit = () + override def checkStable(tp: Type, pos: SrcPos, kind: String)(using Context): Unit = () + override def checkClassType(tp: Type, pos: SrcPos, traitReq: Boolean, stablePrefixReq: Boolean)(using Context): Type = tp override def checkImplicitConversionDefOK(sym: Symbol)(using Context): Unit = () - override def checkImplicitConversionUseOK(sym: Symbol, posd: Positioned)(using Context): Unit = () - override def checkFeasibleParent(tp: Type, pos: SourcePosition, where: => String = "")(using Context): Type = tp + override def checkImplicitConversionUseOK(sym: Symbol, pos: SrcPos)(using Context): Unit = () + override def checkFeasibleParent(tp: Type, pos: SrcPos, where: => String = "")(using Context): Type = tp override def checkInlineConformant(tpt: Tree, tree: Tree, sym: Symbol)(using Context): Unit = () override def checkNoAlphaConflict(stats: List[Tree])(using Context): Unit = () override def checkParentCall(call: Tree, caller: ClassSymbol)(using Context): Unit = () override def checkSimpleKinded(tpt: Tree)(using Context): Tree = tpt override def checkDerivedValueClass(clazz: Symbol, stats: List[Tree])(using Context): Unit = () - override def checkTraitInheritance(parentSym: Symbol, cls: ClassSymbol, pos: SourcePosition)(using Context): Unit = () - override def checkCaseInheritance(parentSym: Symbol, caseCls: ClassSymbol, pos: SourcePosition)(using Context): Unit = () + override def checkTraitInheritance(parentSym: Symbol, cls: ClassSymbol, pos: SrcPos)(using Context): Unit = () + override def checkCaseInheritance(parentSym: Symbol, caseCls: ClassSymbol, pos: SrcPos)(using Context): Unit = () override def checkNoForwardDependencies(vparams: List[ValDef])(using Context): Unit = () - override def checkMembersOK(tp: Type, pos: SourcePosition)(using Context): Type = tp - override def checkInInlineContext(what: String, posd: Positioned)(using Context): Unit = () + override def checkMembersOK(tp: Type, pos: SrcPos)(using Context): Type = tp + override def checkInInlineContext(what: String, pos: SrcPos)(using Context): Unit = () override def checkValidInfix(tree: untpd.InfixOp, meth: Symbol)(using Context): Unit = () - override def checkFeature(name: TermName, description: => String, featureUseSite: Symbol, pos: SourcePosition)(using Context): Unit = () + override def checkFeature(name: TermName, description: => String, featureUseSite: Symbol, pos: SrcPos)(using Context): Unit = () } diff --git a/compiler/src/dotty/tools/dotc/typer/Deriving.scala b/compiler/src/dotty/tools/dotc/typer/Deriving.scala index e0056f398d5f..969aa82f3af8 100644 --- a/compiler/src/dotty/tools/dotc/typer/Deriving.scala +++ b/compiler/src/dotty/tools/dotc/typer/Deriving.scala @@ -9,7 +9,7 @@ import StdNames._ import Contexts._, Symbols._, Types._, SymDenotations._, Names._, NameOps._, Flags._, Decorators._ import ProtoTypes._, ContextOps._ import util.Spans._ -import util.SourcePosition +import util.SrcPos import collection.mutable import Constants.Constant import config.Printers.derive @@ -28,7 +28,7 @@ trait Deriving { * synthesized infrastructure code that is not connected with a * `derives` instance. */ - class Deriver(cls: ClassSymbol, codePos: SourcePosition)(using Context) { + class Deriver(cls: ClassSymbol, codePos: SrcPos)(using Context) { /** A buffer for synthesized symbols for type class instances */ private var synthetics = new mutable.ListBuffer[Symbol] @@ -46,7 +46,7 @@ trait Deriving { * an instance with the same name does not exist already. * @param reportErrors Report an error if an instance with the same name exists already */ - private def addDerivedInstance(clsName: Name, info: Type, pos: SourcePosition): Unit = { + private def addDerivedInstance(clsName: Name, info: Type, pos: SrcPos): Unit = { val instanceName = s"derived$$$clsName".toTermName if (ctx.denotNamed(instanceName).exists) report.error(i"duplicate type class derivation for $clsName", pos) @@ -82,7 +82,7 @@ trait Deriving { */ private def processDerivedInstance(derived: untpd.Tree): Unit = { val originalTypeClassType = typedAheadType(derived, AnyTypeConstructorProto).tpe - val typeClassType = checkClassType(underlyingClassRef(originalTypeClassType), derived.sourcePos, traitReq = false, stablePrefixReq = true) + val typeClassType = checkClassType(underlyingClassRef(originalTypeClassType), derived.srcPos, traitReq = false, stablePrefixReq = true) val typeClass = typeClassType.classSymbol val typeClassParams = typeClass.typeParams val typeClassArity = typeClassParams.length @@ -91,7 +91,7 @@ trait Deriving { xs.corresponds(ys)((x, y) => x.paramInfo.hasSameKindAs(y.paramInfo)) def cannotBeUnified = - report.error(i"${cls.name} cannot be unified with the type argument of ${typeClass.name}", derived.sourcePos) + report.error(i"${cls.name} cannot be unified with the type argument of ${typeClass.name}", derived.srcPos) def addInstance(derivedParams: List[TypeSymbol], evidenceParamInfos: List[List[Type]], instanceTypes: List[Type]): Unit = { val resultType = typeClassType.appliedTo(instanceTypes) @@ -99,7 +99,7 @@ trait Deriving { if (evidenceParamInfos.isEmpty) ExprType(resultType) else ImplicitMethodType(evidenceParamInfos.map(typeClassType.appliedTo), resultType) val derivedInfo = if (derivedParams.isEmpty) methodOrExpr else PolyType.fromParams(derivedParams, methodOrExpr) - addDerivedInstance(originalTypeClassType.typeSymbol.name, derivedInfo, derived.sourcePos) + addDerivedInstance(originalTypeClassType.typeSymbol.name, derivedInfo, derived.srcPos) } def deriveSingleParameter: Unit = { @@ -251,7 +251,7 @@ trait Deriving { if (typeClassArity == 1) deriveSingleParameter else if (typeClass == defn.EqlClass) deriveEql else if (typeClassArity == 0) - report.error(i"type ${typeClass.name} in derives clause of ${cls.name} has no type parameters", derived.sourcePos) + report.error(i"type ${typeClass.name} in derives clause of ${cls.name} has no type parameters", derived.srcPos) else cannotBeUnified } diff --git a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala index 04ebd7e83eef..0026cf005fe5 100644 --- a/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala +++ b/compiler/src/dotty/tools/dotc/typer/ErrorReporting.scala @@ -7,7 +7,7 @@ import core._ import Types._, ProtoTypes._, Contexts._, Decorators._, Denotations._, Symbols._ import Implicits._, Flags._, Constants.Constant import util.Spans._ -import util.SourcePosition +import util.SrcPos import config.Feature import java.util.regex.Matcher.quoteReplacement import reporting._ @@ -16,26 +16,26 @@ object ErrorReporting { import tpd._ - def errorTree(tree: untpd.Tree, msg: Message, pos: SourcePosition)(using Context): tpd.Tree = + def errorTree(tree: untpd.Tree, msg: Message, pos: SrcPos)(using Context): tpd.Tree = tree.withType(errorType(msg, pos)) def errorTree(tree: untpd.Tree, msg: Message)(using Context): tpd.Tree = - errorTree(tree, msg, tree.sourcePos) + errorTree(tree, msg, tree.srcPos) - def errorTree(tree: untpd.Tree, msg: TypeError, pos: SourcePosition)(using Context): tpd.Tree = + def errorTree(tree: untpd.Tree, msg: TypeError, pos: SrcPos)(using Context): tpd.Tree = tree.withType(errorType(msg, pos)) - def errorType(msg: Message, pos: SourcePosition)(using Context): ErrorType = { + def errorType(msg: Message, pos: SrcPos)(using Context): ErrorType = { report.error(msg, pos) ErrorType(msg) } - def errorType(ex: TypeError, pos: SourcePosition)(using Context): ErrorType = { + def errorType(ex: TypeError, pos: SrcPos)(using Context): ErrorType = { report.error(ex, pos) ErrorType(ex.toMessage) } - def wrongNumberOfTypeArgs(fntpe: Type, expectedArgs: List[ParamInfo], actual: List[untpd.Tree], pos: SourcePosition)(using Context): ErrorType = + def wrongNumberOfTypeArgs(fntpe: Type, expectedArgs: List[ParamInfo], actual: List[untpd.Tree], pos: SrcPos)(using Context): ErrorType = errorType(WrongNumberOfTypeArgs(fntpe, expectedArgs, actual), pos) class Errors(using Context) { diff --git a/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala b/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala index 7fa03a78e25d..8f4e7ec29404 100644 --- a/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala +++ b/compiler/src/dotty/tools/dotc/typer/ImportSuggestions.scala @@ -189,7 +189,7 @@ trait ImportSuggestions: def run() = println(i"Cancelling test of $ref when making suggestions for error in ${ctx.source}") ctx.run.isCancelled = true - val span = ctx.owner.sourcePos.span + val span = ctx.owner.srcPos.span val (expectedType, argument, kind) = pt match case ViewProto(argType, resType) => (resType, diff --git a/compiler/src/dotty/tools/dotc/typer/Inliner.scala b/compiler/src/dotty/tools/dotc/typer/Inliner.scala index ccee284be953..e05bc4cd8421 100644 --- a/compiler/src/dotty/tools/dotc/typer/Inliner.scala +++ b/compiler/src/dotty/tools/dotc/typer/Inliner.scala @@ -22,14 +22,13 @@ import Inferencing.isFullyDefined import config.Printers.inlining import ErrorReporting.errorTree import dotty.tools.dotc.tastyreflect.ReflectionImpl -import dotty.tools.dotc.util.{SimpleIdentityMap, SimpleIdentitySet, SourceFile, SourcePosition} +import dotty.tools.dotc.util.{SimpleIdentityMap, SimpleIdentitySet, SourceFile, SourcePosition, SrcPos} import dotty.tools.dotc.parsing.Parsers.Parser import Nullables.{given _} import collection.mutable import reporting.trace import util.Spans.Span -import util.NoSourcePosition import dotty.tools.dotc.transform.{Splicer, TreeMapWithStages} object Inliner { @@ -124,7 +123,7 @@ object Inliner { cpy.Block(tree)(bindings.toList, inlineCall(tree1)) else if enclosingInlineds.length < ctx.settings.XmaxInlines.value && !reachedInlinedTreesLimit then val body = bodyToInline(tree.symbol) // can typecheck the tree and thereby produce errors - new Inliner(tree, body).inlined(tree.sourcePos) + new Inliner(tree, body).inlined(tree.srcPos) else val (reason, setting) = if reachedInlinedTreesLimit then ("inlined trees", ctx.settings.XmaxInlinedTrees) @@ -134,7 +133,7 @@ object Inliner { i"""|Maximal number of $reason (${setting.value}) exceeded, |Maybe this is caused by a recursive inline method? |You can use ${setting.name} to change the limit.""", - (tree :: enclosingInlineds).last.sourcePos + (tree :: enclosingInlineds).last.srcPos ) val endId = ctx.source.nextId @@ -306,7 +305,7 @@ object Inliner { res ++= typerErrors.map(e => ErrorKind.Typer -> e) res.toList case t => - report.error("argument to compileError must be a statically known String", underlyingCodeArg.sourcePos) + report.error("argument to compileError must be a statically known String", underlyingCodeArg.srcPos) Nil } @@ -443,7 +442,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { computeParamBindings(tp.resultType, Nil, argss) case tp: MethodType => if argss.isEmpty then - report.error(i"missing arguments for inline method $inlinedMethod", call.sourcePos) + report.error(i"missing arguments for inline method $inlinedMethod", call.srcPos) false else tp.paramNames.lazyZip(tp.paramInfos).lazyZip(argss.head).foreach { (name, paramtp, arg) => @@ -618,14 +617,14 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { } /** The Inlined node representing the inlined call */ - def inlined(sourcePos: SourcePosition): Tree = { + def inlined(sourcePos: SrcPos): Tree = { // Special handling of `constValue[T]` and `constValueOpt[T]` if (callTypeArgs.length == 1) if (inlinedMethod == defn.Compiletime_constValue) { val constVal = tryConstValue if (!constVal.isEmpty) return constVal - report.error(em"not a constant type: ${callTypeArgs.head}; cannot take constValue", call.sourcePos) + report.error(em"not a constant type: ${callTypeArgs.head}; cannot take constValue", call.srcPos) } else if (inlinedMethod == defn.Compiletime_constValueOpt) { val constVal = tryConstValue @@ -720,7 +719,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { val callToReport = if (enclosingInlineds.nonEmpty) enclosingInlineds.last else call val ctxToReport = ctx.outersIterator.dropWhile(enclosingInlineds(using _).nonEmpty).next inContext(ctxToReport) { - report.error(message, callToReport.sourcePos) + report.error(message, callToReport.srcPos) } case _ => } @@ -989,7 +988,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { val evidence = evTyper.inferImplicitArg(tpt.tpe, tpt.span)(using evCtx) evidence.tpe match { case fail: Implicits.AmbiguousImplicits => - report.error(evTyper.missingArgMsg(evidence, tpt.tpe, ""), tpt.sourcePos) + report.error(evTyper.missingArgMsg(evidence, tpt.tpe, ""), tpt.srcPos) true // hard error: return true to stop implicit search here case fail: Implicits.SearchFailureType => false @@ -1178,7 +1177,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { class InlineTyper(initialErrorCount: Int) extends ReTyper { import reducer._ - override def ensureAccessible(tpe: Type, superAccess: Boolean, pos: SourcePosition)(using Context): Type = { + override def ensureAccessible(tpe: Type, superAccess: Boolean, pos: SrcPos)(using Context): Type = { tpe match { case tpe: NamedType if tpe.symbol.exists && !tpe.symbol.isAccessibleFrom(tpe.prefix, superAccess) => tpe.info match { @@ -1203,7 +1202,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { typed(resMaybeReduced, pt) // redo typecheck if reduction changed something else val res = resMaybeReduced - ensureAccessible(res.tpe, tree.qualifier.isInstanceOf[untpd.Super], tree.sourcePos) + ensureAccessible(res.tpe, tree.qualifier.isInstanceOf[untpd.Super], tree.srcPos) res } @@ -1405,14 +1404,14 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) { if dependencies.nonEmpty && !ctx.reporter.errorsReported then for sym <- dependencies do if ctx.compilationUnit.source.file == sym.associatedFile then - report.error(em"Cannot call macro $sym defined in the same source file", call.sourcePos) + report.error(em"Cannot call macro $sym defined in the same source file", call.srcPos) if (suspendable && ctx.settings.XprintSuspension.value) - report.echo(i"suspension triggered by macro call to ${sym.showLocated} in ${sym.associatedFile}", call.sourcePos) + report.echo(i"suspension triggered by macro call to ${sym.showLocated} in ${sym.associatedFile}", call.srcPos) if suspendable then ctx.compilationUnit.suspend() // this throws a SuspendException val evaluatedSplice = inContext(tastyreflect.MacroExpansion.context(inlinedFrom)) { - Splicer.splice(body, inlinedFrom.sourcePos, MacroClassLoader.fromContext) + Splicer.splice(body, inlinedFrom.srcPos, MacroClassLoader.fromContext) } val inlinedNormailizer = new TreeMap { override def transform(tree: tpd.Tree)(using Context): tpd.Tree = tree match { diff --git a/compiler/src/dotty/tools/dotc/typer/Namer.scala b/compiler/src/dotty/tools/dotc/typer/Namer.scala index f488c417d049..0366636ec43d 100644 --- a/compiler/src/dotty/tools/dotc/typer/Namer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Namer.scala @@ -200,7 +200,7 @@ class Namer { typer: Typer => case tree: MemberDef => SymDenotations.canBeLocal(tree.name, flags) case _ => false if !ok then - report.error(i"modifier(s) `${flags.flagsString}` incompatible with $kind definition", tree.sourcePos) + report.error(i"modifier(s) `${flags.flagsString}` incompatible with $kind definition", tree.srcPos) if adapted.is(Private) && canBeLocal then adapted | Local else adapted } @@ -328,7 +328,7 @@ class Namer { typer: Typer => /** If there's already an existing type, then the package is a dup of this type */ val existingType = pkgOwner.info.decls.lookup(pid.name.toTypeName) if (existingType.exists) { - report.error(PkgDuplicateSymbol(existingType), pid.sourcePos) + report.error(PkgDuplicateSymbol(existingType), pid.srcPos) newCompletePackageSymbol(pkgOwner, (pid.name ++ "$_error_").toTermName).entered } else newCompletePackageSymbol(pkgOwner, pid.name.asTermName).entered @@ -491,8 +491,8 @@ class Namer { typer: Typer => body = fromTempl.body ++ modTempl.body)) if (fromTempl.derived.nonEmpty) { if (modTempl.derived.nonEmpty) - report.error(em"a class and its companion cannot both have `derives` clauses", mdef.sourcePos) - res.putAttachment(desugar.DerivingCompanion, fromTempl.sourcePos.startPos) + report.error(em"a class and its companion cannot both have `derives` clauses", mdef.srcPos) + res.putAttachment(desugar.DerivingCompanion, fromTempl.srcPos.startPos) } res } @@ -659,7 +659,7 @@ class Namer { typer: Typer => } def missingType(sym: Symbol, modifier: String)(using Context): Unit = { - report.error(s"${modifier}type of implicit definition needs to be given explicitly", sym.sourcePos) + report.error(s"${modifier}type of implicit definition needs to be given explicitly", sym.srcPos) sym.resetFlag(GivenOrImplicit) } @@ -724,7 +724,7 @@ class Namer { typer: Typer => for (annotTree <- original.mods.annotations) { val cls = typedAheadAnnotationClass(annotTree)(using annotCtx) if (cls eq sym) - report.error("An annotation class cannot be annotated with iself", annotTree.sourcePos) + report.error("An annotation class cannot be annotated with iself", annotTree.srcPos) else { val ann = Annotation.deferred(cls)(typedAheadAnnotation(annotTree)(using annotCtx)) sym.addAnnotation(ann) @@ -779,7 +779,7 @@ class Namer { typer: Typer => else report.error(em"""children of $parentCls were already queried before $sym was discovered. |As a remedy, you could move $sym on the same nesting level as $parentCls.""", - child.sourcePos) + child.srcPos) } if denot.isClass && !sym.isEnumAnonymClass && !sym.isRefinementClass then @@ -889,7 +889,7 @@ class Namer { typer: Typer => def opaqueToBounds(info: Type): Type = if sym.isOpaqueAlias && tparamSyms.isEmpty && info.typeParams.nonEmpty then - report.error(em"opaque type alias must be fully applied", rhs.sourcePos) + report.error(em"opaque type alias must be fully applied", rhs.srcPos) sym.opaqueToBounds(info, rhs1, tparamSyms) if (isDerived) sym.info = unsafeInfo @@ -1091,7 +1091,7 @@ class Namer { typer: Typer => // See issue #8073 for background report.error( i"""Implementation restriction: case classes cannot have dependencies between parameters""", - cls.sourcePos) + cls.srcPos) case _ => tempInfo = denot.asClass.classInfo.integrateOpaqueMembers.asInstanceOf[TempClassInfo] @@ -1138,7 +1138,7 @@ class Namer { typer: Typer => val ptype = parentType(parent)(using completerCtx.superCallContext).dealiasKeepAnnots if (cls.isRefinementClass) ptype else { - val pt = checkClassType(ptype, parent.sourcePos, + val pt = checkClassType(ptype, parent.srcPos, traitReq = parent ne parents.head, stablePrefixReq = true) if (pt.derivesFrom(cls)) { val addendum = parent match { @@ -1146,21 +1146,21 @@ class Namer { typer: Typer => "\n(Note that inheriting a class of the same name is no longer allowed)" case _ => "" } - report.error(CyclicInheritance(cls, addendum), parent.sourcePos) + report.error(CyclicInheritance(cls, addendum), parent.srcPos) defn.ObjectType } else { val pclazz = pt.typeSymbol if pclazz.is(Final) then - report.error(ExtendFinalClass(cls, pclazz), cls.sourcePos) + report.error(ExtendFinalClass(cls, pclazz), cls.srcPos) else if pclazz.isEffectivelySealed && pclazz.associatedFile != cls.associatedFile then if pclazz.is(Sealed) then - report.error(UnableToExtendSealedClass(pclazz), cls.sourcePos) + report.error(UnableToExtendSealedClass(pclazz), cls.srcPos) else if sourceVersion.isAtLeast(`3.1`) then checkFeature(nme.adhocExtensions, i"Unless $pclazz is declared 'open', its extension in a separate file", cls.topLevelClass, - parent.sourcePos) + parent.srcPos) pt } } @@ -1179,7 +1179,7 @@ class Namer { typer: Typer => if (impl.derived.nonEmpty) { val (derivingClass, derivePos) = original.removeAttachment(desugar.DerivingCompanion) match { case Some(pos) => (cls.companionClass.orElse(cls).asClass, pos) - case None => (cls, impl.sourcePos.startPos) + case None => (cls, impl.srcPos.startPos) } val deriver = new Deriver(derivingClass, derivePos)(using localCtx) deriver.enterDerived(impl.derived) @@ -1390,7 +1390,7 @@ class Namer { typer: Typer => case _: untpd.DerivedTypeTree => WildcardType case TypeTree() => - checkMembersOK(inferredType, mdef.sourcePos) + checkMembersOK(inferredType, mdef.srcPos) case DependentTypeTree(tpFun) => val tpe = tpFun(paramss.head) if (isFullyDefined(tpe, ForceDegree.none)) tpe @@ -1414,7 +1414,7 @@ class Namer { typer: Typer => val hygienicType = TypeOps.avoid(rhsType, paramss.flatten) if (!hygienicType.isValueType || !(hygienicType <:< tpt.tpe)) report.error(i"return type ${tpt.tpe} of lambda cannot be made hygienic;\n" + - i"it is not a supertype of the hygienic type $hygienicType", mdef.sourcePos) + i"it is not a supertype of the hygienic type $hygienicType", mdef.srcPos) //println(i"lifting $rhsType over $paramss -> $hygienicType = ${tpt.tpe}") //println(TypeComparer.explained { implicit ctx => hygienicType <:< tpt.tpe }) case _ => diff --git a/compiler/src/dotty/tools/dotc/typer/Nullables.scala b/compiler/src/dotty/tools/dotc/typer/Nullables.scala index a849dc469a96..dc6e47f55b3d 100644 --- a/compiler/src/dotty/tools/dotc/typer/Nullables.scala +++ b/compiler/src/dotty/tools/dotc/typer/Nullables.scala @@ -513,7 +513,7 @@ object Nullables: |Wrapping the argument in `byName(...)` fixes the problem by disabling the flow assumptions. | |`byName` needs to be imported from the `scala.compiletime` package.""", - arg.sourcePos) + arg.srcPos) arg else nestedCtx.typerState.commit() diff --git a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala index 73c14dc71838..b09669b0625b 100644 --- a/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala +++ b/compiler/src/dotty/tools/dotc/typer/PrepareInlineable.scala @@ -19,7 +19,7 @@ import NameOps._ import Annotations._ import transform.{AccessProxies, PCPCheckAndHeal, Splicer, TreeMapWithStages} import config.Printers.inlining -import util.{Property, SourcePosition} +import util.Property import dotty.tools.dotc.core.StagingContext._ import dotty.tools.dotc.transform.TreeMapWithStages._ @@ -78,7 +78,7 @@ object PrepareInlineable { def preTransform(tree: Tree)(using Context): Tree = tree match { case tree: RefTree if needsAccessor(tree.symbol) => if (tree.symbol.isConstructor) { - report.error("Implementation restriction: cannot use private constructors in inlineinline methods", tree.sourcePos) + report.error("Implementation restriction: cannot use private constructors in inlineinline methods", tree.srcPos) tree // TODO: create a proper accessor for the private constructor } else useAccessor(tree) @@ -251,16 +251,16 @@ object PrepareInlineable { def checkInlineMethod(inlined: Symbol, body: Tree)(using Context): body.type = { if (inlined.owner.isClass && inlined.owner.seesOpaques) - report.error(em"Implementation restriction: No inline methods allowed where opaque type aliases are in scope", inlined.sourcePos) + report.error(em"Implementation restriction: No inline methods allowed where opaque type aliases are in scope", inlined.srcPos) if Inliner.inInlineMethod(using ctx.outer) then - report.error(ex"Implementation restriction: nested inline methods are not supported", inlined.sourcePos) + report.error(ex"Implementation restriction: nested inline methods are not supported", inlined.srcPos) if (inlined.is(Macro) && !ctx.isAfterTyper) { def checkMacro(tree: Tree): Unit = tree match { case Spliced(code) => if (code.symbol.flags.is(Inline)) - report.error("Macro cannot be implemented with an `inline` method", code.sourcePos) + report.error("Macro cannot be implemented with an `inline` method", code.srcPos) Splicer.checkValidMacroBody(code) new PCPCheckAndHeal(freshStagingContext).transform(body) // Ignore output, only check PCP case Block(List(stat), Literal(Constants.Constant(()))) => checkMacro(stat) @@ -272,7 +272,7 @@ object PrepareInlineable { """Macros using a return type of the form `foo(): X ?=> Y` are not yet supported. | |Place the implicit as an argument (`foo()(using X): Y`) to overcome this limitation. - |""".stripMargin, tree.sourcePos) + |""".stripMargin, tree.srcPos) case _ => report.error( """Malformed macro. @@ -282,7 +282,7 @@ object PrepareInlineable { | | * The contents of the splice must call a static method | * All arguments must be quoted or inline - """.stripMargin, inlined.sourcePos) + """.stripMargin, inlined.srcPos) } checkMacro(body) } diff --git a/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala b/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala index 4156f8835125..5c573218da2c 100644 --- a/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala +++ b/compiler/src/dotty/tools/dotc/typer/QuotesAndSplices.scala @@ -42,9 +42,9 @@ trait QuotesAndSplices { record("typedQuote") tree.quoted match { case untpd.Splice(innerExpr) if tree.isTerm => - report.warning("Canceled splice directly inside a quote. '{ ${ XYZ } } is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled splice directly inside a quote. '{ ${ XYZ } } is equivalent to XYZ.", tree.srcPos) case untpd.TypSplice(innerType) if tree.isType => - report.warning("Canceled splice directly inside a quote. '[ ${ XYZ } ] is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled splice directly inside a quote. '[ ${ XYZ } ] is equivalent to XYZ.", tree.srcPos) case _ => } val qctx = inferImplicitArg(defn.QuoteContextClass.typeRef, tree.span) @@ -52,7 +52,7 @@ trait QuotesAndSplices { if qctx.tpe.isInstanceOf[SearchFailureType] then report.error(missingArgMsg(qctx, defn.QuoteContextClass.typeRef, ""), ctx.source.atSpan(tree.span)) else if !qctx.tpe.isStable then - report.error(em"Quotes require stable QuoteContext, but found non stable $qctx", qctx.sourcePos) + report.error(em"Quotes require stable QuoteContext, but found non stable $qctx", qctx.srcPos) val tree1 = if ctx.mode.is(Mode.Pattern) then @@ -70,7 +70,7 @@ trait QuotesAndSplices { checkSpliceOutsideQuote(tree) tree.expr match { case untpd.Quote(innerExpr) if innerExpr.isTerm => - report.warning("Canceled quote directly inside a splice. ${ '{ XYZ } } is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled quote directly inside a splice. ${ '{ XYZ } } is equivalent to XYZ.", tree.srcPos) case _ => } if (ctx.mode.is(Mode.QuotedPattern)) @@ -84,7 +84,7 @@ trait QuotesAndSplices { ref(defn.InternalQuoted_exprSplice).appliedToType(argType).appliedTo(pat) } else { - report.error(i"Type must be fully defined.\nConsider annotating the splice using a type ascription:\n ($tree: XYZ).", tree.expr.sourcePos) + report.error(i"Type must be fully defined.\nConsider annotating the splice using a type ascription:\n ($tree: XYZ).", tree.expr.srcPos) tree.withType(UnspecifiedErrorType) } else { @@ -120,7 +120,7 @@ trait QuotesAndSplices { assert(ctx.mode.is(Mode.QuotedPattern)) val untpd.Apply(splice: untpd.Splice, args) = tree if !isFullyDefined(pt, ForceDegree.flipBottom) then - report.error(i"Type must be fully defined.", splice.sourcePos) + report.error(i"Type must be fully defined.", splice.srcPos) tree.withType(UnspecifiedErrorType) else if splice.isInBraces then // ${x}(...) match an application val typedArgs = args.map(arg => typedExpr(arg)) @@ -132,11 +132,11 @@ trait QuotesAndSplices { case arg: untpd.Ident => typedExpr(arg) case arg => - report.error("Open patttern exprected an identifier", arg.sourcePos) + report.error("Open patttern exprected an identifier", arg.srcPos) EmptyTree } if args.isEmpty then - report.error("Missing arguments for open pattern", tree.sourcePos) + report.error("Missing arguments for open pattern", tree.srcPos) val argTypes = typedArgs.map(_.tpe.widenTermRefExpr) val typedPat = typedSplice(splice, defn.FunctionOf(argTypes, pt)) ref(defn.InternalQuotedMatcher_patternHigherOrderHole).appliedToType(pt).appliedTo(typedPat, SeqLiteral(typedArgs, TypeTree(defn.AnyType))) @@ -148,7 +148,7 @@ trait QuotesAndSplices { checkSpliceOutsideQuote(tree) tree.expr match { case untpd.Quote(innerType) if innerType.isType => - report.warning("Canceled quote directly inside a splice. ${ '[ XYZ ] } is equivalent to XYZ.", tree.sourcePos) + report.warning("Canceled quote directly inside a splice. ${ '[ XYZ ] } is equivalent to XYZ.", tree.srcPos) case _ => } @@ -158,7 +158,7 @@ trait QuotesAndSplices { val name = tree.expr match { case Ident(name) => ("$" + name).toTypeName case expr => - report.error("expected a name binding", expr.sourcePos) + report.error("expected a name binding", expr.srcPos) "$error".toTypeName } @@ -176,13 +176,13 @@ trait QuotesAndSplices { private def checkSpliceOutsideQuote(tree: untpd.Tree)(using Context): Unit = if (level == 0 && !ctx.owner.ownersIterator.exists(_.is(Inline))) - report.error("Splice ${...} outside quotes '{...} or inline method", tree.sourcePos) + report.error("Splice ${...} outside quotes '{...} or inline method", tree.srcPos) else if (level < 0) report.error( s"""Splice $${...} at level $level. | |Inline method may contain a splice at level 0 but the contents of this splice cannot have a splice. - |""".stripMargin, tree.sourcePos + |""".stripMargin, tree.srcPos ) /** Split a typed quoted pattern is split into its type bindings, pattern expression and inner patterns. @@ -265,7 +265,7 @@ trait QuotesAndSplices { transformTypeBindingTypeDef(tdef, typePatBuf) else if tdef.symbol.isClass then val kind = if tdef.symbol.is(Module) then "objects" else "classes" - report.error("Implementation restriction: cannot match " + kind, tree.sourcePos) + report.error("Implementation restriction: cannot match " + kind, tree.srcPos) EmptyTree else super.transform(tree) @@ -282,13 +282,13 @@ trait QuotesAndSplices { report.error("Names cannot start with $ quote pattern ", tree.namePos) super.transform(tree) case _: Match => - report.error("Implementation restriction: cannot match `match` expressions", tree.sourcePos) + report.error("Implementation restriction: cannot match `match` expressions", tree.srcPos) EmptyTree case _: Try => - report.error("Implementation restriction: cannot match `try` expressions", tree.sourcePos) + report.error("Implementation restriction: cannot match `try` expressions", tree.srcPos) EmptyTree case _: Return => - report.error("Implementation restriction: cannot match `return` statements", tree.sourcePos) + report.error("Implementation restriction: cannot match `return` statements", tree.srcPos) EmptyTree case _ => super.transform(tree) @@ -379,9 +379,9 @@ trait QuotesAndSplices { */ private def typedQuotePattern(tree: untpd.Quote, pt: Type, qctx: Tree)(using Context): Tree = { if tree.quoted.isTerm && !pt.derivesFrom(defn.QuotedExprClass) then - report.error("Quote pattern can only match scrutinees of type scala.quoted.Expr", tree.sourcePos) + report.error("Quote pattern can only match scrutinees of type scala.quoted.Expr", tree.srcPos) else if tree.quoted.isType && !pt.derivesFrom(defn.QuotedTypeClass) then - report.error("Quote pattern can only match scrutinees of type scala.quoted.Type", tree.sourcePos) + report.error("Quote pattern can only match scrutinees of type scala.quoted.Type", tree.srcPos) val quoted = tree.quoted val exprPt = pt.baseType(if quoted.isType then defn.QuotedTypeClass else defn.QuotedExprClass) diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index ba6302f335de..f0c5e9a1af6e 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -8,7 +8,7 @@ import StdNames._, Denotations._, SymUtils._, Phases._, SymDenotations._ import NameKinds.DefaultGetterName import Annotations._ import util.Spans._ -import util.{Store, SourcePosition} +import util.{Store, SrcPos} import scala.collection.{ mutable, immutable } import ast._ import MegaPhase._ @@ -62,7 +62,7 @@ object RefChecks { " define default arguments" + ( if (owners.forall(_ == clazz)) "." else ".\nThe members with defaults are defined in " + owners.map(_.showLocated).mkString("", " and ", ".")), - clazz.sourcePos) + clazz.srcPos) } } } @@ -71,7 +71,7 @@ object RefChecks { if (clazz derivesFrom defn.DynamicClass) for ((_, m1 :: m2 :: _) <- (clazz.info member nme.applyDynamic).alternatives groupBy (_.symbol.typeParams.length)) report.error("implementation restriction: applyDynamic cannot be overloaded except by methods with different numbers of type parameters, e.g. applyDynamic[T1](method: String)(arg: T1) and applyDynamic[T1, T2](method: String)(arg1: T1, arg2: T2)", - m1.symbol.sourcePos) + m1.symbol.srcPos) } /** The this-type of `cls` which should be used when looking at the types of @@ -100,7 +100,7 @@ object RefChecks { val otherSelf = other.declaredSelfTypeAsSeenFrom(cls.thisType) if otherSelf.exists && !(cinfo.selfType <:< otherSelf) then report.error(DoesNotConformToSelfType(category, cinfo.selfType, cls, otherSelf, relation, other.classSymbol), - cls.sourcePos) + cls.srcPos) } val parents = cinfo.classParents for (parent <- parents) @@ -128,7 +128,7 @@ object RefChecks { case TypeRef(ref: TermRef, _) => val paramRefs = ref.namedPartsWith(ntp => ntp.symbol.enclosingClass == cls) if (paramRefs.nonEmpty) - report.error(TraitParameterUsedAsParentPrefix(cls), parent.sourcePos) + report.error(TraitParameterUsedAsParentPrefix(cls), parent.srcPos) case _ => } @@ -143,7 +143,7 @@ object RefChecks { val others = cls.owner.linkedClass.info.decls.filter(clashes) others.foreach { other => - report.error(ClassAndCompanionNameClash(cls, other), cls.sourcePos) + report.error(ClassAndCompanionNameClash(cls, other), cls.srcPos) } } @@ -193,7 +193,7 @@ object RefChecks { mixinOverrideErrors.toList match { case Nil => case List(MixinOverrideError(_, msg)) => - report.error(msg, clazz.sourcePos) + report.error(msg, clazz.srcPos) case MixinOverrideError(member, msg) :: others => val others1 = others.map(_.member).filter(_.name != member.name).distinct def othersMsg = { @@ -203,7 +203,7 @@ object RefChecks { if (others1.isEmpty) "" else i";\nother members with override errors are:: $others1%, %" } - report.error(msg + othersMsg, clazz.sourcePos) + report.error(msg + othersMsg, clazz.srcPos) } def infoString(sym: Symbol) = infoString0(sym, sym.owner != clazz) @@ -254,7 +254,7 @@ object RefChecks { if (!(hasErrors && member.is(Synthetic) && member.is(Module))) { // suppress errors relating toi synthetic companion objects if other override // errors (e.g. relating to the companion class) have already been reported. - if (member.owner == clazz) report.error(fullmsg, member.sourcePos) + if (member.owner == clazz) report.error(fullmsg, member.srcPos) else mixinOverrideErrors += new MixinOverrideError(member, fullmsg) hasErrors = true } @@ -292,7 +292,7 @@ object RefChecks { memberTp.overrides(otherTp, member.matchNullaryLoosely || other.matchNullaryLoosely || warnOnMigration(overrideErrorMsg("no longer has compatible type"), - (if (member.owner == clazz) member else clazz).sourcePos)) + (if (member.owner == clazz) member else clazz).srcPos)) catch { case ex: MissingType => // can happen when called with upwardsSelf as qualifier of memberTp and otherTp, @@ -367,7 +367,7 @@ object RefChecks { // Also excluded under Scala2 mode are overrides of default methods of Java traits. if (autoOverride(member) || other.owner.isAllOf(JavaInterface) && - warnOnMigration("`override` modifier required when a Java 8 default method is re-implemented", member.sourcePos)) + warnOnMigration("`override` modifier required when a Java 8 default method is re-implemented", member.srcPos)) member.setFlag(Override) else if (member.isType && self.memberInfo(member) =:= self.memberInfo(other)) () // OK, don't complain about type aliases which are equal @@ -401,7 +401,7 @@ object RefChecks { else if (member.is(ModuleVal) && !other.isRealMethod && !other.isOneOf(Deferred | Lazy)) overrideError("may not override a concrete non-lazy value") else if (member.is(Lazy, butNot = Module) && !other.isRealMethod && !other.is(Lazy) && - !warnOnMigration(overrideErrorMsg("may not override a non-lazy value"), member.sourcePos)) + !warnOnMigration(overrideErrorMsg("may not override a non-lazy value"), member.srcPos)) overrideError("may not override a non-lazy value") else if (other.is(Lazy) && !other.isRealMethod && !member.is(Lazy)) overrideError("must be declared lazy to override a lazy value") @@ -674,7 +674,7 @@ object RefChecks { em"""${mbr.showLocated} is not a legal implementation of `$name` in $clazz | its type $mbrType | does not conform to ${mbrd.info}""", - (if (mbr.owner == clazz) mbr else clazz).sourcePos) + (if (mbr.owner == clazz) mbr else clazz).srcPos) } } @@ -687,13 +687,13 @@ object RefChecks { for (baseCls <- caseCls.info.baseClasses.tail) if (baseCls.typeParams.exists(_.paramVarianceSign != 0)) for (problem <- variantInheritanceProblems(baseCls, caseCls, "non-variant", "case ")) - report.errorOrMigrationWarning(problem(), clazz.sourcePos) + report.errorOrMigrationWarning(problem(), clazz.srcPos) checkNoAbstractMembers() if (abstractErrors.isEmpty) checkNoAbstractDecls(clazz) if (abstractErrors.nonEmpty) - report.error(abstractErrorMessage, clazz.sourcePos) + report.error(abstractErrorMessage, clazz.srcPos) checkMemberTypesOK() checkCaseClassInheritanceInvariant() @@ -707,7 +707,7 @@ object RefChecks { // override a concrete method in Object. The jvm, however, does not. val overridden = decl.matchingDecl(defn.ObjectClass, defn.ObjectType) if (overridden.is(Final)) - report.error(TraitRedefinedFinalMethodFromAnyRef(overridden), decl.sourcePos) + report.error(TraitRedefinedFinalMethodFromAnyRef(overridden), decl.srcPos) } if (!clazz.is(Trait)) { @@ -729,7 +729,7 @@ object RefChecks { if cls.paramAccessors.nonEmpty && !mixins.contains(cls) problem <- variantInheritanceProblems(cls, clazz.asClass.superClass, "parameterized", "super") } - report.error(problem(), clazz.sourcePos) + report.error(problem(), clazz.srcPos) } checkParameterizedTraitsOK() @@ -809,7 +809,7 @@ object RefChecks { val nonMatching = clazz.info.member(member.name).altsWith(alt => alt.owner != clazz) nonMatching match { case Nil => - report.error(OverridesNothing(member), member.sourcePos) + report.error(OverridesNothing(member), member.srcPos) case ms => // getClass in primitive value classes is defined in the standard library as: // override def getClass(): Class[Int] = ??? @@ -818,7 +818,7 @@ object RefChecks { // the standard library, we need to drop the override flag without reporting // an error. if (!(member.name == nme.getClass_ && clazz.isPrimitiveValueClass)) - report.error(OverridesNothingButNameExists(member, ms), member.sourcePos) + report.error(OverridesNothingButNameExists(member, ms), member.srcPos) } member.resetFlag(Override) member.resetFlag(AbsOverride) @@ -830,7 +830,7 @@ object RefChecks { // I assume that's a consequence of some code trying to avoid noise by suppressing // warnings after the first, but I think it'd be better if we didn't have to // arbitrarily choose one as more important than the other. - private def checkUndesiredProperties(sym: Symbol, pos: SourcePosition)(using Context): Unit = + private def checkUndesiredProperties(sym: Symbol, pos: SrcPos)(using Context): Unit = checkDeprecated(sym, pos) val xMigrationValue = ctx.settings.Xmigration.value @@ -841,19 +841,17 @@ object RefChecks { /** If @deprecated is present, and the point of reference is not enclosed * in either a deprecated member or a scala bridge method, issue a warning. */ - private def checkDeprecated(sym: Symbol, pos: SourcePosition)(using Context): Unit = - for - annot <- sym.getAnnotation(defn.DeprecatedAnnot) - if !ctx.owner.ownersIterator.exists(_.isDeprecated) - do - val msg = annot.argumentConstant(0).map(": " + _.stringValue).getOrElse("") - val since = annot.argumentConstant(1).map(" since " + _.stringValue).getOrElse("") - report.deprecationWarning(s"${sym.showLocated} is deprecated${since}${msg}", pos) + private def checkDeprecated(sym: Symbol, pos: SrcPos)(using Context): Unit = + for annot <- sym.getAnnotation(defn.DeprecatedAnnot) do + if !ctx.owner.ownersIterator.exists(_.isDeprecated) then + val msg = annot.argumentConstant(0).map(": " + _.stringValue).getOrElse("") + val since = annot.argumentConstant(1).map(" since " + _.stringValue).getOrElse("") + report.deprecationWarning(s"${sym.showLocated} is deprecated${since}${msg}", pos) /** If @migration is present (indicating that the symbol has changed semantics between versions), * emit a warning. */ - private def checkMigration(sym: Symbol, pos: SourcePosition, xMigrationValue: ScalaVersion)(using Context): Unit = + private def checkMigration(sym: Symbol, pos: SrcPos, xMigrationValue: ScalaVersion)(using Context): Unit = for annot <- sym.getAnnotation(defn.MigrationAnnot) do val migrationVersion = ScalaVersion.parse(annot.argumentConstant(1).get.stringValue) migrationVersion match @@ -877,7 +875,7 @@ object RefChecks { if (!concrOvers.isEmpty) report.deprecationWarning( symbol.toString + " overrides concrete, non-deprecated symbol(s):" + - concrOvers.map(_.name).mkString(" ", ", ", ""), tree.sourcePos) + concrOvers.map(_.name).mkString(" ", ", ", ""), tree.srcPos) } } @@ -902,7 +900,7 @@ object RefChecks { for bc <- cls.baseClasses.tail do val other = sym.matchingDecl(bc, cls.thisType) if other.exists then - report.error(i"private $sym cannot override ${other.showLocated}", sym.sourcePos) + report.error(i"private $sym cannot override ${other.showLocated}", sym.srcPos) end checkNoPrivateOverrides type LevelAndIndex = immutable.Map[Symbol, (LevelInfo, Int)] @@ -1067,7 +1065,7 @@ class RefChecks extends MiniPhase { thisPhase => val sym = tree.symbol if (sym.exists && sym.owner.isTerm) { tree.rhs match { - case Ident(nme.WILDCARD) => report.error(UnboundPlaceholderParameter(), sym.sourcePos) + case Ident(nme.WILDCARD) => report.error(UnboundPlaceholderParameter(), sym.srcPos) case _ => } if (!sym.is(Lazy)) @@ -1100,18 +1098,18 @@ class RefChecks extends MiniPhase { thisPhase => } catch { case ex: TypeError => - report.error(ex, tree.sourcePos) + report.error(ex, tree.srcPos) tree } override def transformIdent(tree: Ident)(using Context): Ident = { - checkUndesiredProperties(tree.symbol, tree.sourcePos) + checkUndesiredProperties(tree.symbol, tree.srcPos) currentLevel.enterReference(tree.symbol, tree.span) tree } override def transformSelect(tree: Select)(using Context): Select = { - checkUndesiredProperties(tree.symbol, tree.sourcePos) + checkUndesiredProperties(tree.symbol, tree.srcPos) tree } @@ -1132,7 +1130,7 @@ class RefChecks extends MiniPhase { thisPhase => override def transformNew(tree: New)(using Context): New = { val tpe = tree.tpe val sym = tpe.typeSymbol - checkUndesiredProperties(sym, tree.sourcePos) + checkUndesiredProperties(sym, tree.srcPos) currentLevel.enterReference(sym, tree.span) tpe.dealias.foreachPart { case TermRef(_, s: Symbol) => currentLevel.enterReference(s, tree.span) diff --git a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala index 43e731bbd791..28b3ddeb2fbf 100644 --- a/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala +++ b/compiler/src/dotty/tools/dotc/typer/TypeAssigner.scala @@ -7,7 +7,7 @@ import ast._ import Contexts._, Constants._, Types._, Symbols._, Names._, Flags._, Decorators._ import ErrorReporting._, Annotations._, Denotations._, SymDenotations._, StdNames._ import util.Spans._ -import util.SourcePosition +import util.SrcPos import config.Printers.typr import ast.Trees._ import NameOps._ @@ -34,7 +34,7 @@ trait TypeAssigner { case _ => report.error( if (qual.isEmpty) tree.show + " can be used only in a class, object, or template" - else qual.show + " is not an enclosing class", tree.sourcePos) + else qual.show + " is not an enclosing class", tree.srcPos) NoSymbol } } @@ -78,7 +78,7 @@ trait TypeAssigner { * (2) if the owner of the denotation is a package object, it is assured * that the package object shows up as the prefix. */ - def ensureAccessible(tpe: Type, superAccess: Boolean, pos: SourcePosition)(using Context): Type = { + def ensureAccessible(tpe: Type, superAccess: Boolean, pos: SrcPos)(using Context): Type = { def test(tpe: Type, firstTry: Boolean): Type = tpe match { case tpe: NamedType => val pre = tpe.prefix @@ -133,9 +133,9 @@ trait TypeAssigner { var qualType = qual1.tpe.widenIfUnstable if (!qualType.hasSimpleKind && tree.name != nme.CONSTRUCTOR) // constructors are selected on typeconstructor, type arguments are passed afterwards - qualType = errorType(em"$qualType takes type parameters", qual1.sourcePos) + qualType = errorType(em"$qualType takes type parameters", qual1.srcPos) else if (!qualType.isInstanceOf[TermType]) - qualType = errorType(em"$qualType is illegal as a selection prefix", qual1.sourcePos) + qualType = errorType(em"$qualType is illegal as a selection prefix", qual1.srcPos) val name = tree.name val pre = maybeSkolemizePrefix(qualType, name) @@ -157,11 +157,11 @@ trait TypeAssigner { else if (qualType.isErroneous || name.toTermName == nme.ERROR) UnspecifiedErrorType else if (name == nme.CONSTRUCTOR) - errorType(ex"$qualType does not have a constructor", tree.sourcePos) + errorType(ex"$qualType does not have a constructor", tree.srcPos) else { val kind = if (name.isTypeName) "type" else "value" def addendum = err.selectErrorAddendum(tree, qual1, qualType, importSuggestionAddendum) - errorType(NotAMember(qualType, name, kind, addendum), tree.sourcePos) + errorType(NotAMember(qualType, name, kind, addendum), tree.srcPos) } } @@ -173,7 +173,7 @@ trait TypeAssigner { def accessibleSelectionType(tree: untpd.RefTree, qual1: Tree)(using Context): Type = { val ownType = selectionType(tree, qual1) if (tree.hasAttachment(desugar.SuppressAccessCheck)) ownType - else ensureAccessible(ownType, qual1.isInstanceOf[Super], tree.sourcePos) + else ensureAccessible(ownType, qual1.isInstanceOf[Super], tree.srcPos) } /** Type assignment method. Each method takes as parameters @@ -190,7 +190,7 @@ trait TypeAssigner { qualType match { case JavaArrayType(elemtp) => elemtp case _ => - report.error("Expected Array but was " + qualType.show, tree.sourcePos) + report.error("Expected Array but was " + qualType.show, tree.srcPos) defn.NothingType } } @@ -236,7 +236,7 @@ trait TypeAssigner { val cls = qualifyingClass(tree, tree.qual.name, packageOK = false) tree.withType( if (cls.isClass) cls.thisType - else errorType("not a legal qualifying class for this", tree.sourcePos)) + else errorType("not a legal qualifying class for this", tree.srcPos)) } def assignType(tree: untpd.Super, qual: Tree, mixinClass: Symbol = NoSymbol)(using Context): Super = { @@ -249,9 +249,9 @@ trait TypeAssigner { case p :: Nil => p.typeConstructor case Nil => - errorType(SuperQualMustBeParent(mix, cls), tree.sourcePos) + errorType(SuperQualMustBeParent(mix, cls), tree.srcPos) case p :: q :: _ => - errorType("ambiguous parent class qualifier", tree.sourcePos) + errorType("ambiguous parent class qualifier", tree.srcPos) } val owntype = if (mixinClass.exists) mixinClass.appliedRef @@ -293,16 +293,16 @@ trait TypeAssigner { if (fntpe.isResultDependent) safeSubstParams(fntpe.resultType, fntpe.paramRefs, args.tpes) else fntpe.resultType else - errorType(i"wrong number of arguments at ${ctx.phase.prev} for $fntpe: ${fn.tpe}, expected: ${fntpe.paramInfos.length}, found: ${args.length}", tree.sourcePos) + errorType(i"wrong number of arguments at ${ctx.phase.prev} for $fntpe: ${fn.tpe}, expected: ${fntpe.paramInfos.length}, found: ${args.length}", tree.srcPos) case t => if (ctx.settings.Ydebug.value) new FatalError("").printStackTrace() - errorType(err.takesNoParamsStr(fn, ""), tree.sourcePos) + errorType(err.takesNoParamsStr(fn, ""), tree.srcPos) } ConstFold(tree.withType(ownType)) } def assignType(tree: untpd.TypeApply, fn: Tree, args: List[Tree])(using Context): TypeApply = { - def fail = tree.withType(errorType(err.takesNoParamsStr(fn, "type "), tree.sourcePos)) + def fail = tree.withType(errorType(err.takesNoParamsStr(fn, "type "), tree.srcPos)) ConstFold(fn.tpe.widen match { case pt: TypeLambda => tree.withType { @@ -314,9 +314,9 @@ trait TypeAssigner { val namedArgMap = new mutable.HashMap[Name, Type] for (NamedArg(name, arg) <- args) if (namedArgMap.contains(name)) - report.error(DuplicateNamedTypeParameter(name), arg.sourcePos) + report.error(DuplicateNamedTypeParameter(name), arg.srcPos) else if (!paramNames.contains(name)) - report.error(UndefinedNamedTypeParameter(name, paramNames), arg.sourcePos) + report.error(UndefinedNamedTypeParameter(name, paramNames), arg.srcPos) else namedArgMap(name) = arg.tpe @@ -353,7 +353,7 @@ trait TypeAssigner { else { val argTypes = args.tpes if (sameLength(argTypes, paramNames)) pt.instantiate(argTypes) - else wrongNumberOfTypeArgs(fn.tpe, pt.typeParams, args, tree.sourcePos) + else wrongNumberOfTypeArgs(fn.tpe, pt.typeParams, args, tree.srcPos) } } case err: ErrorType => @@ -462,7 +462,7 @@ trait TypeAssigner { if (tycon.symbol == defn.andType) AndType(args(0).tpe, args(1).tpe) else if (tycon.symbol == defn.orType) OrType(args(0).tpe, args(1).tpe) else tycon.tpe.appliedTo(args.tpes) - else wrongNumberOfTypeArgs(tycon.tpe, tparams, args, tree.sourcePos) + else wrongNumberOfTypeArgs(tycon.tpe, tparams, args, tree.srcPos) tree.withType(ownType) } diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index c93de84d2571..86e08442bc6b 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -28,7 +28,7 @@ import Inferencing._ import EtaExpansion.etaExpand import util.Spans._ import util.common._ -import util.Property +import util.{Property, SimpleIdentityMap, SrcPos} import Applications.{ExtMethodApply, IntegratedTypeArgs, productSelectorTypes, wrapDefs} import collection.mutable @@ -125,12 +125,12 @@ class Typer extends Namer * @param name the name of the identifier * @param pt the expected type * @param required flags the result's symbol must have - * @param posd indicates position to use for error reporting + * @param pos indicates position to use for error reporting */ - def findRef(name: Name, pt: Type, required: FlagSet, posd: Positioned)(using Context): Type = { + def findRef(name: Name, pt: Type, required: FlagSet, pos: SrcPos)(using Context): Type = { val refctx = ctx val noImports = ctx.mode.is(Mode.InPackageClauseName) - def fail(msg: Message) = report.error(msg, posd.sourcePos) + def fail(msg: Message) = report.error(msg, pos) /** A symbol qualifies if it really exists and is not a package class. * In addition, if we are in a constructor of a pattern, we ignore all definitions @@ -192,7 +192,7 @@ class Typer extends Namer def selection(imp: ImportInfo, name: Name, checkBounds: Boolean) = if imp.sym.isCompleting then - report.warning(i"cyclic ${imp.sym}, ignored", posd.sourcePos) + report.warning(i"cyclic ${imp.sym}, ignored", pos) NoType else if unimported.nonEmpty && unimported.contains(imp.site.termSymbol) then NoType @@ -326,9 +326,9 @@ class Typer extends Namer if !symsMatch then report.errorOrMigrationWarning( AmbiguousReference(name, Definition, Inheritance, prevCtx)(using outer), - posd.sourcePos) + pos) if migrateTo3 then - patch(Span(posd.span.start), + patch(Span(pos.span.start), if prevCtx.owner == refctx.owner.enclosingClass then "this." else s"${prevCtx.owner.name}.this.") else @@ -468,12 +468,12 @@ class Typer extends Namer unimported = Set.empty foundUnderScala2 = NoType try { - var found = findRef(name, pt, EmptyFlags, tree.posd) + var found = findRef(name, pt, EmptyFlags, tree.srcPos) if (foundUnderScala2.exists && !(foundUnderScala2 =:= found)) { report.migrationWarning( ex"""Name resolution will change. | currently selected : $foundUnderScala2 - | in the future, without -source 3.0-migration: $found""", tree.sourcePos) + | in the future, without -source 3.0-migration: $found""", tree.srcPos) found = foundUnderScala2 } found @@ -504,7 +504,7 @@ class Typer extends Namer errorTree(tree, MissingIdent(tree, kind, name)) if rawType.exists then - setType(ensureAccessible(rawType, superAccess = false, tree.sourcePos)) + setType(ensureAccessible(rawType, superAccess = false, tree.srcPos)) else if name == nme._scope then // gross hack to support current xml literals. // awaiting a better implicits based solution for library-supported xml @@ -526,7 +526,7 @@ class Typer extends Namer && !tree.tpe.isStable && !isWildcardArg(tree) then - report.error(StableIdentPattern(tree, pt), tree.sourcePos) + report.error(StableIdentPattern(tree, pt), tree.srcPos) def typedSelect(tree: untpd.Select, pt: Type, qual: Tree)(using Context): Tree = qual match { case qual @ IntegratedTypeArgs(app) => @@ -538,7 +538,7 @@ class Typer extends Namer val select = assignType(cpy.Select(tree)(qual, tree.name), qual) val select1 = toNotNullTermRef(select, pt) - if (tree.name.isTypeName) checkStable(qual.tpe, qual.sourcePos, "type prefix") + if (tree.name.isTypeName) checkStable(qual.tpe, qual.srcPos, "type prefix") if select1.tpe ne TryDynamicCallType then checkStableIdentPattern(select1, pt) @@ -589,7 +589,7 @@ class Typer extends Namer val qual1 = typed(tree.qual) val enclosingInlineable = ctx.owner.ownersIterator.findSymbol(_.isInlineMethod) if (enclosingInlineable.exists && !PrepareInlineable.isLocal(qual1.symbol, enclosingInlineable)) - report.error(SuperCallsNotAllowedInlineable(enclosingInlineable), tree.sourcePos) + report.error(SuperCallsNotAllowedInlineable(enclosingInlineable), tree.srcPos) pt match { case pt: SelectionProto if pt.name.isTypeName => qual1 // don't do super references for types; they are meaningless anyway @@ -660,7 +660,7 @@ class Typer extends Namer } catch { case ex: FromDigitsException => - report.error(ex.getMessage, tree.sourcePos) + report.error(ex.getMessage, tree.srcPos) tree.kind match { case Whole(_) => lit(0) case _ => lit(0.0) @@ -695,15 +695,15 @@ class Typer extends Namer typed(cpy.Block(tree)(clsDef :: Nil, New(Ident(x), Nil)), pt) case _ => var tpt1 = typedType(tree.tpt) - tpt1 = tpt1.withType(ensureAccessible(tpt1.tpe, superAccess = false, tpt1.sourcePos)) + tpt1 = tpt1.withType(ensureAccessible(tpt1.tpe, superAccess = false, tpt1.srcPos)) - if (checkClassType(typeOfNew(tpt1), tpt1.sourcePos, traitReq = false, stablePrefixReq = true) eq defn.ObjectType) + if (checkClassType(typeOfNew(tpt1), tpt1.srcPos, traitReq = false, stablePrefixReq = true) eq defn.ObjectType) tpt1 = TypeTree(defn.ObjectType).withSpan(tpt1.span) tpt1 match { case AppliedTypeTree(_, targs) => for case targ: TypeBoundsTree <- targs do - report.error(WildcardOnTypeArgumentNotAllowedOnNew(), targ.sourcePos) + report.error(WildcardOnTypeArgumentNotAllowedOnNew(), targ.srcPos) case _ => } @@ -874,7 +874,7 @@ class Typer extends Namer lhsCore match { case lhsCore: RefTree if setter.exists => val setterTypeRaw = pre.select(setterName, setter) - val setterType = ensureAccessible(setterTypeRaw, isSuperSelection(lhsCore), tree.sourcePos) + val setterType = ensureAccessible(setterTypeRaw, isSuperSelection(lhsCore), tree.srcPos) val lhs2 = untpd.rename(lhsCore, setterName).withType(setterType) typedUnadapted(untpd.Apply(untpd.TypedSplice(lhs2), tree.rhs :: Nil), WildcardType, locked) case _ => @@ -943,7 +943,7 @@ class Typer extends Namer } def typedIf(tree: untpd.If, pt: Type)(using Context): Tree = - if tree.isInline then checkInInlineContext("inline if", tree.posd) + if tree.isInline then checkInInlineContext("inline if", tree.srcPos) val cond1 = typed(tree.cond, defn.BooleanType) val result = @@ -995,7 +995,7 @@ class Typer extends Namer report.error( i"""Implementation restriction: Expected result type $pt1 |is a curried dependent context function type. Such types are not yet supported.""", - tree.sourcePos) + tree.srcPos) pt1 match { case pt1 if defn.isNonRefinedFunction(pt1) => // if expected parameter type(s) are wildcards, approximate from below. @@ -1049,7 +1049,7 @@ class Typer extends Namer val appDef = typed(appDef0).asInstanceOf[DefDef] val mt = appDef.symbol.info.asInstanceOf[MethodType] if (mt.isParamDependent) - report.error(i"$mt is an illegal function type because it has inter-parameter dependencies", tree.sourcePos) + report.error(i"$mt is an illegal function type because it has inter-parameter dependencies", tree.srcPos) val resTpt = TypeTree(mt.nonDependentResultApprox).withSpan(body.span) val typeArgs = appDef.vparamss.head.map(_.tpt) :+ resTpt val tycon = TypeTree(funCls.typeRef) @@ -1204,17 +1204,17 @@ class Typer extends Namer if target.exists then formal <:< target if isFullyDefined(formal, ForceDegree.flipBottom) then formal else if target.exists && isFullyDefined(target, ForceDegree.flipBottom) then target - else errorType(AnonymousFunctionMissingParamType(param, params, tree, formal), param.sourcePos) + else errorType(AnonymousFunctionMissingParamType(param, params, tree, formal), param.srcPos) def protoFormal(i: Int): Type = if (protoFormals.length == params.length) protoFormals(i) - else errorType(WrongNumberOfParameters(protoFormals.length), tree.sourcePos) + else errorType(WrongNumberOfParameters(protoFormals.length), tree.srcPos) /** Is `formal` a product type which is elementwise compatible with `params`? */ def ptIsCorrectProduct(formal: Type) = isFullyDefined(formal, ForceDegree.flipBottom) && (defn.isProductSubType(formal) || formal.derivesFrom(defn.PairClass)) && - productSelectorTypes(formal, tree.sourcePos).corresponds(params) { + productSelectorTypes(formal, tree.srcPos).corresponds(params) { (argType, param) => param.tpt.isEmpty || argType.widenExpr <:< typedAheadType(param.tpt).tpe } @@ -1260,11 +1260,11 @@ class Typer extends Namer // Replace the underspecified expected type by one based on the closure method type defn.PartialFunctionOf(mt.firstParamTypes.head, mt.resultType) else - report.error(ex"result type of lambda is an underspecified SAM type $pt", tree.sourcePos) + report.error(ex"result type of lambda is an underspecified SAM type $pt", tree.srcPos) pt if (pt.classSymbol.isOneOf(FinalOrSealed)) { val offendingFlag = pt.classSymbol.flags & FinalOrSealed - report.error(ex"lambda cannot implement $offendingFlag ${pt.classSymbol}", tree.sourcePos) + report.error(ex"lambda cannot implement $offendingFlag ${pt.classSymbol}", tree.srcPos) } TypeTree(targetTpe) case _ => @@ -1290,7 +1290,7 @@ class Typer extends Namer tree.selector match { case EmptyTree => if (tree.isInline) { - checkInInlineContext("summonFrom", tree.posd) + checkInInlineContext("summonFrom", tree.srcPos) val cases1 = tree.cases.mapconserve { case cdef @ CaseDef(pat @ Typed(Ident(nme.WILDCARD), _), _, _) => // case _ : T --> case evidence$n : T @@ -1307,7 +1307,7 @@ class Typer extends Namer typed(desugar.makeCaseLambda(tree.cases, checkMode, protoFormals.length).withSpan(tree.span), pt) } case _ => - if (tree.isInline) checkInInlineContext("inline match", tree.posd) + if (tree.isInline) checkInInlineContext("inline match", tree.srcPos) val sel1 = typedExpr(tree.selector) val selType = fullyDefinedType(sel1.tpe, "pattern selector", tree.span).widen @@ -1418,7 +1418,7 @@ class Typer extends Namer val sym = b.symbol if (sym.name != tpnme.WILDCARD) if (ctx.scope.lookup(b.name) == NoSymbol) ctx.enter(sym) - else report.error(new DuplicateBind(b, cdef), b.sourcePos) + else report.error(new DuplicateBind(b, cdef), b.srcPos) if (!ctx.isAfterTyper) { val bounds = ctx.gadt.fullBounds(sym) if (bounds != null) sym.info = bounds @@ -1479,7 +1479,7 @@ class Typer extends Namer var body1 = typedType(cdef.body, pt) if !body1.isType then assert(ctx.reporter.errorsReported) - body1 = TypeTree(errorType("", cdef.sourcePos)) + body1 = TypeTree(errorType("", cdef.srcPos)) assignType(cpy.CaseDef(cdef)(pat2, EmptyTree, body1), pat2, body1) } caseRest(using ctx.fresh.setFreshGADTBounds.setNewScope) @@ -1527,14 +1527,14 @@ class Typer extends Namer def enclMethInfo(cx: Context): (Tree, Type) = { val owner = cx.owner if (owner.isType) { - report.error(ReturnOutsideMethodDefinition(owner), tree.sourcePos) + report.error(ReturnOutsideMethodDefinition(owner), tree.srcPos) (EmptyTree, WildcardType) } else if (owner != cx.outer.owner && owner.isRealMethod) if (owner.isInlineMethod) - (EmptyTree, errorType(NoReturnFromInlineable(owner), tree.sourcePos)) + (EmptyTree, errorType(NoReturnFromInlineable(owner), tree.srcPos)) else if (!owner.isCompleted) - (EmptyTree, errorType(MissingReturnTypeWithReturnStatement(owner), tree.sourcePos)) + (EmptyTree, errorType(MissingReturnTypeWithReturnStatement(owner), tree.srcPos)) else { val from = Ident(TermRef(NoPrefix, owner.asTerm)) val proto = returnProto(owner) @@ -1646,12 +1646,12 @@ class Typer extends Namer tree.withType( if (isFullyDefined(pt, ForceDegree.flipBottom)) pt else if (ctx.reporter.errorsReported) UnspecifiedErrorType - else errorType(i"cannot infer type; expected type $pt is not fully defined", tree.sourcePos)) + else errorType(i"cannot infer type; expected type $pt is not fully defined", tree.srcPos)) } def typedSingletonTypeTree(tree: untpd.SingletonTypeTree)(using Context): SingletonTypeTree = { val ref1 = typedExpr(tree.ref) - checkStable(ref1.tpe, tree.sourcePos, "singleton type") + checkStable(ref1.tpe, tree.srcPos, "singleton type") assignType(cpy.SingletonTypeTree(tree)(ref1), ref1) } @@ -1670,11 +1670,11 @@ class Typer extends Namer val polymorphicRefinementAllowed = tpt1.tpe.typeSymbol == defn.PolyFunctionClass && rsym.name == nme.apply if (!polymorphicRefinementAllowed && rsym.info.isInstanceOf[PolyType] && rsym.allOverriddenSymbols.isEmpty) - report.error(PolymorphicMethodMissingTypeInParent(rsym, tpt1.symbol), refinement.sourcePos) + report.error(PolymorphicMethodMissingTypeInParent(rsym, tpt1.symbol), refinement.srcPos) val member = refineCls.info.member(rsym.name) if (member.isOverloaded) - report.error(OverloadInRefinement(rsym), refinement.sourcePos) + report.error(OverloadInRefinement(rsym), refinement.srcPos) } assignType(cpy.RefinedTypeTree(tree)(tpt1, refinements1), tpt1, refinements1, refineCls) } @@ -1693,14 +1693,14 @@ class Typer extends Namer } val tparams = tpt1.tpe.typeParams if (tparams.isEmpty) { - report.error(TypeDoesNotTakeParameters(tpt1.tpe, tree.args), tree.sourcePos) + report.error(TypeDoesNotTakeParameters(tpt1.tpe, tree.args), tree.srcPos) tpt1 } else { var args = tree.args val args1 = { if (args.length != tparams.length) { - wrongNumberOfTypeArgs(tpt1.tpe, tparams, args, tree.sourcePos) + wrongNumberOfTypeArgs(tpt1.tpe, tparams, args, tree.srcPos) args = args.take(tparams.length) } def typedArg(arg: untpd.Tree, tparam: ParamInfo) = { @@ -1811,7 +1811,7 @@ class Typer extends Namer if !alias1.isEmpty then val bounds = TypeBounds(lo2.tpe, hi2.tpe) if !bounds.contains(alias1.tpe) then - report.error(em"type ${alias1.tpe} outside bounds $bounds", tree.sourcePos) + report.error(em"type ${alias1.tpe} outside bounds $bounds", tree.srcPos) val tree1 = assignType(cpy.TypeBoundsTree(tree)(lo2, hi2, alias1), lo2, hi2, alias1) if (ctx.mode.is(Mode.Pattern)) @@ -1876,7 +1876,7 @@ class Typer extends Namer val sym = newPatternBoundSymbol(name, symTp, tree.span) if (pt == defn.ImplicitScrutineeTypeRef || tree.mods.is(Given)) sym.setFlag(Given) if (ctx.mode.is(Mode.InPatternAlternative)) - report.error(i"Illegal variable ${sym.name} in pattern alternative", tree.sourcePos) + report.error(i"Illegal variable ${sym.name} in pattern alternative", tree.srcPos) assignType(cpy.Bind(tree)(name, body1), sym) } } @@ -1984,7 +1984,7 @@ class Typer extends Namer if (sym.isConstructor && !sym.isPrimaryConstructor) { val ename = sym.erasedName if (ename != sym.name) - report.error(em"@alpha annotation ${'"'}$ename${'"'} may not be used on a constructor", ddef.sourcePos) + report.error(em"@alpha annotation ${'"'}$ename${'"'} may not be used on a constructor", ddef.srcPos) for (param <- tparams1 ::: vparamss1.flatten) checkRefsLegal(param, sym.owner, (name, sym) => sym.is(TypeParam), "secondary constructor") @@ -1992,7 +1992,7 @@ class Typer extends Namer def checkThisConstrCall(tree: Tree): Unit = tree match { case app: Apply if untpd.isSelfConstrCall(app) => if (sym.span.exists && app.symbol.span.exists && sym.span.start <= app.symbol.span.start) - report.error("secondary constructor must call a preceding constructor", app.sourcePos) + report.error("secondary constructor must call a preceding constructor", app.srcPos) case Block(call :: _, _) => checkThisConstrCall(call) case _ => } @@ -2042,7 +2042,7 @@ class Typer extends Namer case cinfo: MethodType => if (!ctx.erasedTypes) { // after constructors arguments are passed in super call. typr.println(i"constr type: $cinfo") - report.error(ParameterizedTypeLacksArguments(psym), ref.sourcePos) + report.error(ParameterizedTypeLacksArguments(psym), ref.srcPos) } ref case _ => @@ -2066,7 +2066,7 @@ class Typer extends Namer if (!tree.span.isSourceDerived) return EmptyTree - if (!ctx.isAfterTyper) report.error(i"$psym is extended twice", tree.sourcePos) + if (!ctx.isAfterTyper) report.error(i"$psym is extended twice", tree.srcPos) } else seenParents += psym if (tree.isType) { @@ -2075,8 +2075,8 @@ class Typer extends Namer result = maybeCall(result, psym, psym.primaryConstructor.info) } else checkParentCall(result, cls) - checkTraitInheritance(psym, cls, tree.sourcePos) - if (cls is Case) checkCaseInheritance(psym, cls, tree.sourcePos) + checkTraitInheritance(psym, cls, tree.srcPos) + if (cls is Case) checkCaseInheritance(psym, cls, tree.srcPos) result } @@ -2091,7 +2091,7 @@ class Typer extends Namer val other = memberInSelfButNotThis(decl) if (other.exists) { val msg = CannotHaveSameNameAs(decl, other, CannotHaveSameNameAs.DefinedInSelf(self)) - report.error(msg, decl.sourcePos) + report.error(msg, decl.srcPos) } foundRedef || other.exists } @@ -2130,10 +2130,10 @@ class Typer extends Namer !dynamicsEnabled if (reportDynamicInheritance) { val isRequired = parents1.exists(_.tpe.isRef(defn.DynamicClass)) - report.featureWarning(nme.dynamics.toString, "extension of type scala.Dynamic", cls, isRequired, cdef.sourcePos) + report.featureWarning(nme.dynamics.toString, "extension of type scala.Dynamic", cls, isRequired, cdef.srcPos) } - checkNonCyclicInherited(cls.thisType, cls.classParents, cls.info.decls, cdef.posd) + checkNonCyclicInherited(cls.thisType, cls.classParents, cls.info.decls, cdef.srcPos) // check value class constraints checkDerivedValueClass(cls, body1) @@ -2143,7 +2143,7 @@ class Typer extends Namer && !cls.isAllOf(PrivateLocal) && effectiveOwner.is(Trait) && !effectiveOwner.derivesFrom(defn.ObjectClass) - report.error(i"$cls cannot be defined in universal $effectiveOwner", cdef.sourcePos) + report.error(i"$cls cannot be defined in universal $effectiveOwner", cdef.srcPos) // Temporarily set the typed class def as root tree so that we have at least some // information in the IDE in case we never reach `SetRootTree`. @@ -2295,7 +2295,7 @@ class Typer extends Namer case closure(_, _, _) => case _ => val recovered = typed(qual)(using ctx.fresh.setExploreTyperState()) - report.errorOrMigrationWarning(OnlyFunctionsCanBeFollowedByUnderscore(recovered.tpe.widen), tree.sourcePos) + report.errorOrMigrationWarning(OnlyFunctionsCanBeFollowedByUnderscore(recovered.tpe.widen), tree.srcPos) if (migrateTo3) { // Under -rewrite, patch `x _` to `(() => x)` patch(Span(tree.span.start), "(() => ") @@ -2316,7 +2316,7 @@ class Typer extends Namer if ((prefix ++ suffix).isEmpty) "simply leave out the trailing ` _`" else s"use `$prefix$suffix` instead" report.errorOrMigrationWarning(i"""The syntax ` _` is no longer supported; - |you can $remedy""", tree.sourcePos, `3.1`) + |you can $remedy""", tree.srcPos, `3.1`) if sourceVersion.isMigrating then patch(Span(tree.span.start), prefix) patch(Span(qual.span.end, tree.span.end), suffix) @@ -2516,7 +2516,7 @@ class Typer extends Namer case xtree => typedUnnamed(xtree) simplify(result, pt, locked) - catch case ex: TypeError => errorTree(xtree, ex, xtree.sourcePos.focus) + catch case ex: TypeError => errorTree(xtree, ex, xtree.srcPos.focus) // use focussed sourcePos since tree might be a large definition // and a large error span would hide all errors in interior. // TODO: Not clear that hiding is what we want, actually @@ -2914,7 +2914,7 @@ class Typer extends Namer record("adapt") adapt1(tree, pt, locked, tryGadtHealing) } - catch case ex: TypeError => errorTree(tree, ex, tree.sourcePos.focus) + catch case ex: TypeError => errorTree(tree, ex, tree.srcPos.focus) final def adapt(tree: Tree, pt: Type)(using Context): Tree = adapt(tree, pt, ctx.typerState.ownedVars) @@ -2928,8 +2928,8 @@ class Typer extends Namer def missingArgs(mt: MethodType) = { val meth = methPart(tree).symbol - if (mt.paramNames.length == 0) report.error(MissingEmptyArgumentList(meth), tree.sourcePos) - else report.error(em"missing arguments for $meth", tree.sourcePos) + if (mt.paramNames.length == 0) report.error(MissingEmptyArgumentList(meth), tree.srcPos) + else report.error(em"missing arguments for $meth", tree.srcPos) tree.withType(mt.resultType) } @@ -3028,7 +3028,7 @@ class Typer extends Namer report.migrationWarning( em"""Context bounds will map to context parameters. |A `using` clause is needed to pass explicit arguments to them. - |This code can be rewritten automatically using -rewrite""", tree.sourcePos) + |This code can be rewritten automatically using -rewrite""", tree.srcPos) patch(Span(pt.args.head.span.start), "using ") tree else @@ -3108,7 +3108,7 @@ class Typer extends Namer case failure: SearchFailureType => report.error( missingArgMsg(arg, formal, implicitParamString(paramName, methodStr, tree)), - tree.sourcePos.endPos) + tree.srcPos.endPos) case _ => } } @@ -3189,7 +3189,7 @@ class Typer extends Namer def isAutoApplied(sym: Symbol): Boolean = sym.isConstructor || sym.matchNullaryLoosely - || warnOnMigration(MissingEmptyArgumentList(sym), tree.sourcePos) + || warnOnMigration(MissingEmptyArgumentList(sym), tree.srcPos) && { patch(tree.span.endPos, "()"); true } // Reasons NOT to eta expand: @@ -3205,7 +3205,7 @@ class Typer extends Namer if (!defn.isFunctionType(pt)) pt match { case SAMType(_) if !pt.classSymbol.hasAnnotation(defn.FunctionalInterfaceAnnot) => - report.warning(ex"${tree.symbol} is eta-expanded even though $pt does not have the @FunctionalInterface annotation.", tree.sourcePos) + report.warning(ex"${tree.symbol} is eta-expanded even though $pt does not have the @FunctionalInterface annotation.", tree.srcPos) case _ => } simplify(typed(etaExpand(tree, wtp, arity), pt), pt, locked) @@ -3271,7 +3271,7 @@ class Typer extends Namer tree.symbol != defn.StringContext_raw && tree.symbol != defn.StringContext_s) if (ctx.settings.XignoreScala2Macros.value) { - report.warning("Scala 2 macro cannot be used in Dotty, this call will crash at runtime. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html", tree.sourcePos.startPos) + report.warning("Scala 2 macro cannot be used in Dotty, this call will crash at runtime. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html", tree.srcPos.startPos) Throw(New(defn.MatchErrorClass.typeRef, Literal(Constant(s"Reached unexpanded Scala 2 macro call to ${tree.symbol.showFullName} compiled with -Xignore-scala2-macros.")) :: Nil)) .withType(tree.tpe) .withSpan(tree.span) @@ -3279,7 +3279,7 @@ class Typer extends Namer else { report.error( """Scala 2 macro cannot be used in Dotty. See https://dotty.epfl.ch/docs/reference/dropped-features/macros.html - |To turn this error into a warning, pass -Xignore-scala2-macros to the compiler""".stripMargin, tree.sourcePos.startPos) + |To turn this error into a warning, pass -Xignore-scala2-macros to the compiler""".stripMargin, tree.srcPos.startPos) tree } else if (tree.tpe.widenExpr <:< pt) { @@ -3466,13 +3466,13 @@ class Typer extends Namer case SelectionProto(name, mbrType, _, _) => def tryExtension(using Context): Tree = try - findRef(name.toExtensionName, WildcardType, ExtensionMethod, tree.posd) match { + findRef(name.toExtensionName, WildcardType, ExtensionMethod, tree.srcPos) match { case ref: TermRef => extMethodApply(untpd.ref(ref).withSpan(tree.span), tree, mbrType) case _ => EmptyTree } catch { - case ex: TypeError => errorTree(tree, ex, tree.sourcePos) + case ex: TypeError => errorTree(tree, ex, tree.srcPos) } val nestedCtx = ctx.fresh.setNewTyperState() val app = tryExtension(using nestedCtx) @@ -3494,12 +3494,12 @@ class Typer extends Namer if ctx.mode.is(Mode.ImplicitsEnabled) && tree.typeOpt.isValueType then if pt.isRef(defn.AnyValClass) || pt.isRef(defn.ObjectClass) then - report.error(em"the result of an implicit conversion must be more specific than $pt", tree.sourcePos) + report.error(em"the result of an implicit conversion must be more specific than $pt", tree.srcPos) inferView(tree, pt) match { case SearchSuccess(found: ExtMethodApply, _, _) => found // nothing to check or adapt for extension method applications case SearchSuccess(found, _, _) => - checkImplicitConversionUseOK(found.symbol, tree.posd) + checkImplicitConversionUseOK(found.symbol, tree.srcPos) withoutMode(Mode.ImplicitsEnabled)(readapt(found)) case failure: SearchFailure => if (pt.isInstanceOf[ProtoType] && !failure.isAmbiguous) then @@ -3541,7 +3541,7 @@ class Typer extends Namer * tree that went unreported. A scenario where this happens is i1802.scala. */ def ensureReported(tp: Type) = tp match { - case err: ErrorType if !ctx.reporter.errorsReported => report.error(err.msg, tree.sourcePos) + case err: ErrorType if !ctx.reporter.errorsReported => report.error(err.msg, tree.srcPos) case _ => } @@ -3629,7 +3629,7 @@ class Typer extends Namer private def checkStatementPurity(tree: tpd.Tree)(original: untpd.Tree, exprOwner: Symbol)(using Context): Unit = if (!tree.tpe.isErroneous && !ctx.isAfterTyper && isPureExpr(tree) && !tree.tpe.isRef(defn.UnitClass) && !isSelfOrSuperConstrCall(tree)) - report.warning(PureExpressionInStatementPosition(original, exprOwner), original.sourcePos) + report.warning(PureExpressionInStatementPosition(original, exprOwner), original.srcPos) /** Types the body Scala 2 macro declaration `def f = macro ` */ private def typedScala2MacroBody(call: untpd.Tree)(using Context): Tree = @@ -3658,7 +3658,7 @@ class Typer extends Namer |by making the implicit value scala.language.experimental.macros visible. |This can be achieved by adding the import clause 'import scala.language.experimental.macros' |or by setting the compiler option -language:experimental.macros. - """.stripMargin, call.sourcePos) + """.stripMargin, call.srcPos) call match case call: untpd.Ident => typedIdent(call, defn.AnyType) @@ -3673,7 +3673,7 @@ class Typer extends Namer typedTypeApply(call2, defn.AnyType) } case _ => - report.error("Invalid Scala 2 macro " + call.show, call.sourcePos) + report.error("Invalid Scala 2 macro " + call.show, call.srcPos) EmptyTree else typedExpr(call, defn.AnyType) diff --git a/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala b/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala index 2678799fdecc..96b4dd2632e7 100644 --- a/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala +++ b/compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala @@ -8,7 +8,7 @@ import Decorators._ import Variances._ import NameKinds._ import util.Spans._ -import util.SourcePosition +import util.SrcPos import config.Printers.variances import config.Feature.migrateTo3 import reporting.trace @@ -43,8 +43,8 @@ object VarianceChecker { } val pos = tree.tparams .find(_.name.toTermName == paramName) - .map(_.sourcePos) - .getOrElse(tree.sourcePos) + .map(_.srcPos) + .getOrElse(tree.srcPos) report.error(em"${paramVarianceStr}variant type parameter $paramName occurs in ${occursStr}variant position in ${tl.resType}", pos) } def apply(x: Boolean, t: Type) = x && { @@ -164,7 +164,7 @@ class VarianceChecker(using Context) { } private object Traverser extends TreeTraverser { - def checkVariance(sym: Symbol, pos: SourcePosition) = Validator.validateDefinition(sym) match { + def checkVariance(sym: Symbol, pos: SrcPos) = Validator.validateDefinition(sym) match { case Some(VarianceError(tvar, required)) => def msg = i"${varianceLabel(tvar.flags)} $tvar occurs in ${varianceLabel(required)} position in type ${sym.info} of $sym" if (migrateTo3 && @@ -191,21 +191,21 @@ class VarianceChecker(using Context) { case defn: MemberDef if skip => report.debuglog(s"Skipping variance check of ${sym.showDcl}") case tree: TypeDef => - checkVariance(sym, tree.sourcePos) + checkVariance(sym, tree.srcPos) tree.rhs match { case rhs: Template => traverseChildren(rhs) case _ => } case tree: ValDef => - checkVariance(sym, tree.sourcePos) + checkVariance(sym, tree.srcPos) case DefDef(_, tparams, vparamss, _, _) => - checkVariance(sym, tree.sourcePos) + checkVariance(sym, tree.srcPos) tparams foreach traverse vparamss foreach (_ foreach traverse) case _ => } catch { - case ex: TypeError => report.error(ex, tree.sourcePos.focus) + case ex: TypeError => report.error(ex, tree.srcPos.focus) } } } diff --git a/compiler/src/dotty/tools/dotc/util/SourcePosition.scala b/compiler/src/dotty/tools/dotc/util/SourcePosition.scala index 808e1c19065f..79919442a3b2 100644 --- a/compiler/src/dotty/tools/dotc/util/SourcePosition.scala +++ b/compiler/src/dotty/tools/dotc/util/SourcePosition.scala @@ -4,12 +4,15 @@ package util import printing.{Showable, Printer} import printing.Texts._ +import core.Contexts.Context import Spans.{Span, NoSpan} import scala.annotation.internal.sharable /** A source position is comprised of a span and a source file */ case class SourcePosition(source: SourceFile, span: Span, outer: SourcePosition = NoSourcePosition) -extends interfaces.SourcePosition with Showable { +extends SrcPos, interfaces.SourcePosition, Showable { + + def sourcePos(using Context) = this /** Is `that` a source position contained in this source position ? * `outer` is not taken into account. */ @@ -86,3 +89,12 @@ extends interfaces.SourcePosition with Showable { override def toString: String = "?" override def withOuter(outer: SourcePosition): SourcePosition = outer } + +/** Things that can produce a source position and a span */ +trait SrcPos: + def sourcePos(using ctx: Context): SourcePosition + def span: Span + def startPos(using ctx: Context): SourcePosition = sourcePos.startPos + def endPos(using ctx: Context): SourcePosition = sourcePos.endPos + def focus(using ctx: Context): SourcePosition = sourcePos.focus + def line(using ctx: Context): Int = sourcePos.line