Skip to content

Commit 1c81ccc

Browse files
committed
Constant fold based on atoms
1 parent bef520f commit 1c81ccc

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

compiler/src/dotty/tools/dotc/core/Types.scala

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3154,6 +3154,21 @@ object Types extends TypeUtils {
31543154
}
31553155
}
31563156

3157+
/** Extractor that matches a type that contains a single atom and returns that
3158+
* atom.
3159+
*
3160+
* See also [[Atoms]].
3161+
*/
3162+
object SingleAtom:
3163+
def unapply(tp: Type)(using Context): Option[Type] =
3164+
tp.atoms match
3165+
case Atoms.Range(lo, hi) =>
3166+
if lo.size == 1 then Some(lo.head)
3167+
else if hi.size == 1 then Some(hi.head)
3168+
else None
3169+
case _ =>
3170+
None
3171+
31573172
// `refFn` can be null only if `computed` is true.
31583173
case class LazyRef(private var refFn: (Context => (Type | Null)) | Null) extends UncachedProxyType with ValueType {
31593174
private var myRef: Type | Null = null

compiler/src/dotty/tools/dotc/typer/ConstFold.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ object ConstFold:
6969
case Literal(c) if c.tag == Constants.NullTag => Some(c)
7070
case _ =>
7171
tree.tpe.widenTermRefExpr.normalized.simplified match
72-
case ConstantType(c) => Some(c)
72+
case SingleAtom(ConstantType(c)) => Some(c)
7373
case _ => None
7474

7575
extension [T <: Tree](tree: T)(using Context)

tests/pos/constfold-atoms.scala

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class annot() extends scala.annotation.StaticAnnotation
2+
class refiningAnnot() extends scala.annotation.RefiningAnnotation
3+
4+
type Foo = 4
5+
6+
@main def main =
7+
val v1: 4 = 2 + 2
8+
val v2: 8 = v1 + v1
9+
10+
val v3: 4 | v1.type = 4
11+
val v4: 8 = v3 + v3
12+
13+
val v5: 4 & v1.type = 4
14+
val v6: 8 = v5 + v5
15+
16+
val v7: 4 @annot = 4
17+
val v8: 8 = v7 + v7
18+
19+
val v9: 4 @refiningAnnot = ???
20+
val v10: 8 = v9 + v9
21+
22+
val v11: Foo = 4
23+
val v12: 8 = v11 + v11

0 commit comments

Comments
 (0)