Skip to content

Commit b1d6de2

Browse files
committed
Fix hashCode method for value classes
Before this commit, we used the same implementation than for case classes. After this commit, we use the hashCode of the underlying type as defined in SIP-15.
1 parent ff8779e commit b1d6de2

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

src/dotty/tools/dotc/transform/SyntheticMethods.scala

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ class SyntheticMethods extends MiniPhaseTransform with IdentityDenotTransformer
7676
ref(defn.runtimeMethod("_" + sym.name.toString)).appliedToArgs(This(clazz) :: vrefss.head)
7777

7878
def syntheticRHS(implicit ctx: Context): List[List[Tree]] => Tree = synthetic.name match {
79-
case nme.hashCode_ => vrefss => hashCodeBody
79+
case nme.hashCode_ if isDerivedValueClass(clazz) => vrefss => valueHashCodeBody
80+
case nme.hashCode_ => vrefss => caseHashCodeBody
8081
case nme.toString_ => forwardToRuntime
8182
case nme.equals_ => vrefss => equalsBody(vrefss.head.head)
8283
case nme.canEqual_ => vrefss => canEqualBody(vrefss.head.head)
@@ -120,11 +121,24 @@ class SyntheticMethods extends MiniPhaseTransform with IdentityDenotTransformer
120121
}
121122
}
122123

124+
/** The class
125+
*
126+
* class C(x: T) extends AnyVal
127+
*
128+
* gets the hashCode method:
129+
*
130+
* def hashCode: Int = x.hashCode()
131+
*/
132+
def valueHashCodeBody(implicit ctx: Context): Tree = {
133+
assert(accessors.length == 1)
134+
ref(accessors.head).select(nme.hashCode_).ensureApplied
135+
}
136+
123137
/** The class
124138
*
125139
* case class C(x: T, y: T)
126140
*
127-
* get the hashCode method:
141+
* gets the hashCode method:
128142
*
129143
* def hashCode: Int = {
130144
* <synthetic> var acc: Int = 0xcafebabe;
@@ -133,7 +147,7 @@ class SyntheticMethods extends MiniPhaseTransform with IdentityDenotTransformer
133147
* Statics.finalizeHash(acc, 2)
134148
* }
135149
*/
136-
def hashCodeBody(implicit ctx: Context): Tree = {
150+
def caseHashCodeBody(implicit ctx: Context): Tree = {
137151
val acc = ctx.newSymbol(ctx.owner, "acc".toTermName, Mutable | Synthetic, defn.IntType, coord = ctx.owner.pos)
138152
val accDef = ValDef(acc, Literal(Constant(0xcafebabe)))
139153
val mixes = for (accessor <- accessors.toList) yield

0 commit comments

Comments
 (0)