Skip to content

Reject all explicitly written type references with bad bounds #15577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 9, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions compiler/src/dotty/tools/dotc/reporting/messages.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1446,9 +1446,18 @@ import transform.SymUtils._
}

class DoesNotConformToBound(tpe: Type, which: String, bound: Type)(using Context)
extends TypeMismatchMsg(tpe, bound)(DoesNotConformToBoundID) {
def msg = em"Type argument ${tpe} does not conform to $which bound $bound"
}
extends TypeMismatchMsg(
if which == "lower" then bound else tpe,
if which == "lower" then tpe else bound)(DoesNotConformToBoundID):
private def isBounds = tpe match
case TypeBounds(lo, hi) => lo ne hi
case _ => false
override def canExplain = !isBounds
def msg =
if isBounds then
em"Type argument ${tpe} does not overlap with $which bound $bound"
else
em"Type argument ${tpe} does not conform to $which bound $bound"

class DoesNotConformToSelfType(category: String, selfType: Type, cls: Symbol,
otherSelf: Type, relation: String, other: Symbol)(
Expand Down
26 changes: 14 additions & 12 deletions compiler/src/dotty/tools/dotc/transform/PostTyper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import ContextFunctionResults.annotateContextResults
import config.Printers.typr
import util.SrcPos
import reporting._
import NameKinds.WildcardParamName

object PostTyper {
val name: String = "posttyper"
Expand Down Expand Up @@ -345,12 +346,6 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase
val tree1 @ TypeApply(fn, args) = normalizeTypeArgs(tree)
for arg <- args do
checkInferredWellFormed(arg)
val isInferred = arg.isInstanceOf[InferredTypeTree] || arg.span.isSynthetic
if !isInferred then
// only check explicit type arguments. We rely on inferred type arguments
// to either have good bounds (if they come from a constraint), or be derived
// from values that recursively need to have good bounds.
Checking.checkGoodBounds(arg.tpe, arg.srcPos)
if (fn.symbol != defn.ChildAnnot.primaryConstructor)
// Make an exception for ChildAnnot, which should really have AnyKind bounds
Checking.checkBounds(args, fn.tpe.widen.asInstanceOf[PolyType])
Expand Down Expand Up @@ -403,13 +398,20 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase
val reference = ctx.settings.sourceroot.value
val relativePath = util.SourceFile.relativePath(ctx.compilationUnit.source, reference)
sym.addAnnotation(Annotation.makeSourceFile(relativePath))
else (tree.rhs, sym.info) match
case (rhs: LambdaTypeTree, bounds: TypeBounds) =>
VarianceChecker.checkLambda(rhs, bounds)
if sym.isOpaqueAlias then
VarianceChecker.checkLambda(rhs, TypeBounds.upper(sym.opaqueAlias))
case _ =>
else
if !sym.is(Param) && !sym.owner.isOneOf(AbstractOrTrait) then
Checking.checkGoodBounds(tree.symbol)
(tree.rhs, sym.info) match
case (rhs: LambdaTypeTree, bounds: TypeBounds) =>
VarianceChecker.checkLambda(rhs, bounds)
if sym.isOpaqueAlias then
VarianceChecker.checkLambda(rhs, TypeBounds.upper(sym.opaqueAlias))
case _ =>
processMemberDef(super.transform(tree))
case tree: Bind =>
if tree.symbol.isType && !tree.symbol.name.is(WildcardParamName) then
Checking.checkGoodBounds(tree.symbol)
super.transform(tree)
case tree: New if isCheckable(tree) =>
Checking.checkInstantiable(tree.tpe, tree.srcPos)
super.transform(tree)
Expand Down
33 changes: 17 additions & 16 deletions compiler/src/dotty/tools/dotc/typer/Checking.scala
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,10 @@ object Checking {
showInferred(MissingTypeParameterInTypeApp(arg.tpe), app, tpt))
}
for (arg, which, bound) <- TypeOps.boundsViolations(args, boundss, instantiate, app) do
if checkGoodBounds(arg.tpe, arg.srcPos.focus) then
report.error(
showInferred(DoesNotConformToBound(arg.tpe, which, bound),
app, tpt),
arg.srcPos.focus)
report.error(
showInferred(DoesNotConformToBound(arg.tpe, which, bound),
app, tpt),
arg.srcPos.focus)

/** Check that type arguments `args` conform to corresponding bounds in `tl`
* Note: This does not check the bounds of AppliedTypeTrees. These
Expand All @@ -86,17 +85,19 @@ object Checking {
def checkBounds(args: List[tpd.Tree], tl: TypeLambda)(using Context): Unit =
checkBounds(args, tl.paramInfos, _.substParams(tl, _))

def checkGoodBounds(tpe: Type, pos: SrcPos)(using Context): Boolean =
def recur(tp: Type) = tp.dealias match
case tp: TypeRef =>
checkGoodBounds(tp.info, pos)
case TypeBounds(lo, hi) if !(lo <:< hi) =>
val argStr = if tp eq tpe then "" else i" $tpe"
report.error(i"type argument$argStr has potentially unrealizable bounds $tp", pos)
false
case _ =>
true
recur(tpe)
def checkGoodBounds(sym: Symbol)(using Context): Boolean =
val bad = findBadBounds(sym.typeRef)
if bad.exists then
report.error(em"$sym has possibly conflicting bounds $bad", sym.srcPos)
!bad.exists

/** If `tp` dealiases to a typebounds L..H where not L <:< H
* return the potentially conflicting bounds, otherwise return NoType.
*/
private def findBadBounds(tp: Type)(using Context): Type = tp.dealias match
case tp: TypeRef => findBadBounds(tp.info)
case tp @ TypeBounds(lo, hi) if !(lo <:< hi) => tp
case _ => NoType

/** Check applied type trees for well-formedness. This means
* - all arguments are within their corresponding bounds
Expand Down
1 change: 1 addition & 0 deletions compiler/test/dotty/tools/dotc/CompilationTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ class CompilationTests {
compileFile("tests/neg-custom-args/i12650.scala", allowDeepSubtypes),
compileFile("tests/neg-custom-args/i9517.scala", defaultOptions.and("-Xprint-types")),
compileFile("tests/neg-custom-args/i11637.scala", defaultOptions.and("-explain")),
compileFile("tests/neg-custom-args/i15575.scala", defaultOptions.and("-explain")),
compileFile("tests/neg-custom-args/interop-polytypes.scala", allowDeepSubtypes.and("-Yexplicit-nulls")),
compileFile("tests/neg-custom-args/conditionalWarnings.scala", allowDeepSubtypes.and("-deprecation").and("-Xfatal-warnings")),
compileFilesInDir("tests/neg-custom-args/isInstanceOf", allowDeepSubtypes and "-Xfatal-warnings"),
Expand Down
2 changes: 1 addition & 1 deletion tests/init/neg/i11572.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class A {
trait Bounded {
type T >: Cov[Int] <: Cov[String]
}
val t: Bounded = new Bounded { // error
val t: Bounded = new Bounded { // error
// Note: using this instead of t produces an error (as expected)
override type T >: t.T <: t.T
}
Expand Down
2 changes: 1 addition & 1 deletion tests/init/neg/i5854.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class B {
val a: String = (((1: Any): b.A): Nothing): String
val b: { type A >: Any <: Nothing } = loop() // error
val b: { type A >: Any <: Nothing } = loop() // error
def loop(): Nothing = loop()
}
5 changes: 0 additions & 5 deletions tests/neg-custom-args/fatal-warnings/i13820.scala

This file was deleted.

40 changes: 40 additions & 0 deletions tests/neg-custom-args/i15575.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
-- [E057] Type Mismatch Error: tests/neg-custom-args/i15575.scala:3:27 -------------------------------------------------
3 | def bar[T]: Unit = foo[T & Any] // error
| ^
| Type argument T & Any does not conform to lower bound Any
|---------------------------------------------------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| I tried to show that
| Any
| conforms to
| T & Any
| but the comparison trace ended with `false`:
|
| ==> Any <: T & Any
| ==> Any <: T
| <== Any <: T = false
| <== Any <: T & Any = false
|
| The tests were made under the empty constraint
---------------------------------------------------------------------------------------------------------------------
-- [E057] Type Mismatch Error: tests/neg-custom-args/i15575.scala:7:14 -------------------------------------------------
7 | val _ = foo[String] // error
| ^
| Type argument String does not conform to lower bound CharSequence
|---------------------------------------------------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| I tried to show that
| CharSequence
| conforms to
| String
| but the comparison trace ended with `false`:
|
| ==> CharSequence <: String
| ==> CharSequence <: String
| <== CharSequence <: String = false
| <== CharSequence <: String = false
|
| The tests were made under the empty constraint
---------------------------------------------------------------------------------------------------------------------
7 changes: 7 additions & 0 deletions tests/neg-custom-args/i15575.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
object Test1:
def foo[T >: Any]: Unit = ()
def bar[T]: Unit = foo[T & Any] // error

object Test2:
def foo[T >: CharSequence]: Unit = ()
val _ = foo[String] // error
4 changes: 2 additions & 2 deletions tests/neg/i15568.check
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
-- Error: tests/neg/i15568.scala:3:15 ----------------------------------------------------------------------------------
-- [E057] Type Mismatch Error: tests/neg/i15568.scala:3:15 -------------------------------------------------------------
3 |type Bar = Foo[? >: Int <: String] // error
| ^
| type argument has potentially unrealizable bounds >: Int <: String
| Type argument >: Int <: String does not overlap with upper bound String
38 changes: 34 additions & 4 deletions tests/neg/i15569.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,42 @@ def andThenSub[A, B, C](f: A <:< B, g: B <:< C): A <:< C =
f.andThen(g)

@main def Test = (None: Option[Foo[?]]) match {
case _: Option[Foo[t]] =>
val unsound: Any <:< Nothing = andThenSub[Any, t, Nothing](summon, summon) // error
case _: Option[Foo[t]] => // error
val unsound: Any <:< Nothing = andThenSub[Any, t, Nothing](summon, summon)
unsound("hi :)")
}
@main def Test2 =
type t >: Any <: Nothing
val unsound: Any <:< Nothing = andThenSub[Any, t, Nothing](summon, summon) // error
type t >: Any <: Nothing // error
val unsound: Any <:< Nothing = andThenSub[Any, t, Nothing](summon, summon)
unsound("hi :)")

@main def Test3 = (None: Option[Foo[?]]) match {
case _: Option[Foo[t]] => // error
val unsound: Nothing = (5 : Any) : t
(unsound : Unit => Unit).apply(())
}

@main def Test3ok = (None: Option[Foo[?]]) match {
case _: Option[Foo[_]] => // ok
}

@main def Test4 =
type t >: Any <: Nothing // error
val unsound: Nothing = (5 : Any) : t
(unsound : Unit => Unit).apply(())

@main def Test5 =
type t >: Any <: Nothing // error
val unsound: List[Nothing] = List(5 : Any) : List[t]
(unsound.head : Unit => Unit).apply(())

@main def Test6 =
type t[X] >: Any <: Nothing // error
val unsound: List[Nothing] = List(5 : Any) : List[t[String]]
(unsound.head : Unit => Unit).apply(())

@main def Test7 =
trait A:
type t >: Any <: Nothing
val unsound: List[Nothing] = List(5 : Any) : List[A#t] // error
(unsound.head : Unit => Unit).apply(())
2 changes: 1 addition & 1 deletion tests/pos/i13820.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ trait Expr { type T }

def foo[A](e: Expr { type T = A }) = e match
case e1: Expr { type T <: Int } =>
val i: Int = ??? : e1.T
val i: Int = ??? : e1.T
6 changes: 1 addition & 5 deletions tests/semanticdb/expect/i5854.expect.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package i5854

class B/*<-i5854::B#*/ {
// Known issue: Can't lookup the symbol of `b.A`
// we have to register the symbol of `b { type A }` to the refinementSymtab first
// then resolve, or assign same semanticdb symbol for both
// fake symbol for b.A, and real symbol of A in b
val a/*<-i5854::B#a.*/: String/*->scala::Predef.String#*/ = (((1: Any/*->scala::Any#*/): b/*->i5854::B#b.*/.A): Nothing/*->scala::Nothing#*/): String/*->scala::Predef.String#*/
val b/*<-i5854::B#b.*/: { type A/*<-local0*/ >: Any/*->scala::Any#*/ <: Nothing/*->scala::Nothing#*/ } = loop/*->i5854::B#loop().*/() // error
val b/*<-i5854::B#b.*/: { type A/*<-local0*/ >: Any/*->scala::Any#*/ <: Nothing/*->scala::Nothing#*/ } = loop/*->i5854::B#loop().*/() // error
def loop/*<-i5854::B#loop().*/(): Nothing/*->scala::Nothing#*/ = loop/*->i5854::B#loop().*/()
}
6 changes: 1 addition & 5 deletions tests/semanticdb/expect/i5854.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package i5854

class B {
// Known issue: Can't lookup the symbol of `b.A`
// we have to register the symbol of `b { type A }` to the refinementSymtab first
// then resolve, or assign same semanticdb symbol for both
// fake symbol for b.A, and real symbol of A in b
val a: String = (((1: Any): b.A): Nothing): String
val b: { type A >: Any <: Nothing } = loop() // error
val b: { type A >: Any <: Nothing } = loop() // error
def loop(): Nothing = loop()
}
28 changes: 14 additions & 14 deletions tests/semanticdb/metac.expect
Original file line number Diff line number Diff line change
Expand Up @@ -3945,20 +3945,20 @@ local0 => type A >: Any <: Nothing
Occurrences:
[0:8..0:13): i5854 <- i5854/
[2:6..2:7): B <- i5854/B#
[7:6..7:7): a <- i5854/B#a.
[7:9..7:15): String -> scala/Predef.String#
[7:24..7:27): Any -> scala/Any#
[7:30..7:31): b -> i5854/B#b.
[7:36..7:43): Nothing -> scala/Nothing#
[7:46..7:52): String -> scala/Predef.String#
[8:6..8:7): b <- i5854/B#b.
[8:16..8:17): A <- local0
[8:21..8:24): Any -> scala/Any#
[8:28..8:35): Nothing -> scala/Nothing#
[8:40..8:44): loop -> i5854/B#loop().
[9:6..9:10): loop <- i5854/B#loop().
[9:14..9:21): Nothing -> scala/Nothing#
[9:24..9:28): loop -> i5854/B#loop().
[3:6..3:7): a <- i5854/B#a.
[3:9..3:15): String -> scala/Predef.String#
[3:24..3:27): Any -> scala/Any#
[3:30..3:31): b -> i5854/B#b.
[3:36..3:43): Nothing -> scala/Nothing#
[3:46..3:52): String -> scala/Predef.String#
[4:6..4:7): b <- i5854/B#b.
[4:16..4:17): A <- local0
[4:21..4:24): Any -> scala/Any#
[4:28..4:35): Nothing -> scala/Nothing#
[4:40..4:44): loop -> i5854/B#loop().
[5:6..5:10): loop <- i5854/B#loop().
[5:14..5:21): Nothing -> scala/Nothing#
[5:24..5:28): loop -> i5854/B#loop().

expect/i9727.scala
------------------
Expand Down