From 19f9ae72bb74c2e2575981aba5704302aa8d1612 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Sat, 12 Jun 2021 16:05:29 +0200 Subject: [PATCH 1/2] Use `==` for instance tests against string constants We used `eq` before, as for other objetc singletons. But this means we are subject to the vagaries of string hashing. Fixes #12796 --- compiler/src/dotty/tools/dotc/ast/tpd.scala | 4 +++- tests/run/i12796/A_1.scala | 4 ++++ tests/run/i12796/Test_2.scala | 3 +++ 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 tests/run/i12796/A_1.scala create mode 100644 tests/run/i12796/Test_2.scala diff --git a/compiler/src/dotty/tools/dotc/ast/tpd.scala b/compiler/src/dotty/tools/dotc/ast/tpd.scala index 990bbf4155e9..6555e2b3b1fb 100644 --- a/compiler/src/dotty/tools/dotc/ast/tpd.scala +++ b/compiler/src/dotty/tools/dotc/ast/tpd.scala @@ -963,8 +963,10 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo { /** `tree.isInstanceOf[tp]`, with special treatment of singleton types */ def isInstance(tp: Type)(using Context): Tree = tp.dealias match { + case ConstantType(c) if c.tag == StringTag => + singleton(tp).equal(tree) case tp: SingletonType => - if (tp.widen.derivesFrom(defn.ObjectClass)) + if tp.widen.derivesFrom(defn.ObjectClass) then tree.ensureConforms(defn.ObjectType).select(defn.Object_eq).appliedTo(singleton(tp)) else singleton(tp).equal(tree) diff --git a/tests/run/i12796/A_1.scala b/tests/run/i12796/A_1.scala new file mode 100644 index 000000000000..46290e942335 --- /dev/null +++ b/tests/run/i12796/A_1.scala @@ -0,0 +1,4 @@ +object A: + type Timeframe = "1m" | "2m" | "1H" + + def test(input: String) = input.isInstanceOf[Timeframe] diff --git a/tests/run/i12796/Test_2.scala b/tests/run/i12796/Test_2.scala new file mode 100644 index 000000000000..8274f8804063 --- /dev/null +++ b/tests/run/i12796/Test_2.scala @@ -0,0 +1,3 @@ +@main def Test = + val x = "1" + assert(A.test(x + "m")) From 82b94e98d4cfabd8c318055f65806bba1b3c4824 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Sat, 12 Jun 2021 17:24:38 +0200 Subject: [PATCH 2/2] Additional fixed issue test --- tests/run/i6996.check | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/run/i6996.check b/tests/run/i6996.check index a4387987de57..3e37e529877c 100644 --- a/tests/run/i6996.check +++ b/tests/run/i6996.check @@ -1,3 +1,3 @@ an `a` -false -not `a` +true +an `a`