Skip to content

Commit 0470a2c

Browse files
compareTo implemented for enums
1 parent a4e5911 commit 0470a2c

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

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

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,6 @@ class SyntheticMethods(thisPhase: DenotTransformer) {
8282

8383
def removeColors(msg: String): String = msg.replaceAll("\u001b\\[.*?m", "")
8484
def syntheticDef(sym: Symbol): Tree = {
85-
// if (removeColors(sym.show) == "method getDeclaringClass")
86-
// println(s"Sym ${sym.show} info ${sym.denot.info.show} asf ${clazz.info.parents.head.show}: " +
87-
// s"${sym.denot.asSeenFrom(clazz.info.parents.head).info.show}")
8885
val synthetic = sym
8986
.copy(
9087
owner = clazz,
@@ -112,13 +109,35 @@ class SyntheticMethods(thisPhase: DenotTransformer) {
112109
// Enum Methods
113110
case nme.name => _ => Literal(Constant("Hello World"))
114111
case nme.ordinal => _ => Literal(Constant(0))
115-
case nme.compareTo => _ => Literal(Constant(0))
112+
case nme.compareTo => vrefss => compareToBody(vrefss.head.head)
116113
case nme.getDeclaringClass => _ => Literal(Constant(null))
117114
}
118115
ctx.log(s"adding $synthetic to $clazz at ${ctx.phase}")
119116
DefDef(synthetic, syntheticRHS(ctx.withOwner(synthetic))).withSpan(ctx.owner.span.focus)
120117
}
121118

119+
/** An enum case `X` in
120+
*
121+
* ```
122+
* enum Foo { case X }
123+
* ```
124+
*
125+
* gets the `compareTo` method:
126+
*
127+
* ```
128+
* def compareTo(other: Foo): Int =
129+
* new Integer(this).ordinal.compareTo(new Integer(other.ordinal))
130+
* ```
131+
*/
132+
def compareToBody(other: Tree): Tree = {
133+
val thisOrdinal = This(clazz).select(defn.Enum_ordinal)
134+
val thisOrdinalBoxed = New(defn.BoxedIntType, thisOrdinal :: Nil)
135+
val otherOrdinal = other.select(defn.Enum_ordinal)
136+
val otherOrdinalBoxed = New(defn.BoxedIntType, otherOrdinal :: Nil)
137+
val thisOrdinalCompareTo = thisOrdinalBoxed.select(defn.Comparable_compareTo)
138+
Apply(thisOrdinalCompareTo, otherOrdinalBoxed :: Nil)
139+
}
140+
122141
/** The class
123142
*
124143
* ```

0 commit comments

Comments
 (0)