Skip to content

Fix #300: Make literals have the same constants as their types. #301

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 4 commits into from
Dec 17, 2014
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions src/dotty/tools/dotc/transform/Literalize.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ import core.Flags._
import core.Decorators._
import core.StdNames.nme
import ast.Trees._
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Constants._

/** This phase rewrites idempotent expressions with constant types to Literals.
* The constant types are eliminated by erasure, so we need to keep
* the info about constantness in the trees.
*
* The phase also makes sure that the constant of a literal is the same as the constant
* in the type of the literal.
*/
class Literalize extends MiniPhaseTransform { thisTransform =>
import ast.tpd._
Expand Down Expand Up @@ -62,4 +67,25 @@ class Literalize extends MiniPhaseTransform { thisTransform =>

override def transformTypeApply(tree: TypeApply)(implicit ctx: Context, info: TransformerInfo): Tree =
literalize(tree)

override def transformLiteral(tree: Literal)(implicit ctx: Context, info: TransformerInfo): Tree = tree.tpe match {
case ConstantType(const) if tree.const.value != const.value || (tree.const.tag != const.tag) => Literal(const)
case _ => tree
}

/** Check that all literals have types match underlying constants
*/
override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = {
tree match {
case Literal(c @ Constant(treeValue)) =>
tree.tpe match {
case ConstantType(c2 @ Constant(typeValue)) =>
assert(treeValue == typeValue && c2.tag == c.tag,
i"Type of Literal $tree is inconsistent with underlying constant")
case tpe =>
assert(c.tpe =:= tpe, i"Type of Literal $tree is inconsistent with underlying constant type ${c.tpe}")
}
case _ =>
}
}
}
6 changes: 6 additions & 0 deletions tests/pos/constants.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
object Test {

val x: Double = 2
val y: Byte = 3

}