Skip to content

Commit 4c246c4

Browse files
Enums valuesOf exception type conforms to that of Java enums
1 parent 27d4ac6 commit 4c246c4

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

compiler/src/dotty/tools/dotc/ast/DesugarEnums.scala

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,12 @@ object DesugarEnums {
8686
/** The following lists of definitions for an enum type E:
8787
*
8888
* private val $values = new EnumValues[E]
89-
* def valueOf = $values.fromName
89+
* def valueOf(name: String) =
90+
* try $values.fromName(name) catch
91+
* {
92+
* case ex$:NoSuchElementException =>
93+
* throw new IllegalArgumentException("key not found: ".concat(name))
94+
* }
9095
* def values = $values.values.toArray
9196
*/
9297
private def enumScaffolding(implicit ctx: Context): List[Tree] = {
@@ -95,9 +100,22 @@ object DesugarEnums {
95100
val privateValuesDef =
96101
ValDef(nme.DOLLAR_VALUES, TypeTree(),
97102
New(TypeTree(defn.EnumValuesType.appliedTo(enumClass.typeRef :: Nil)), ListOfNil))
98-
.withFlags(Private)
103+
.withFlags(Private)
104+
105+
val valuesOfExnMessage = Apply(
106+
Select(Literal(Constant("key not found: ")), "concat".toTermName)
107+
, Ident(nme.name) :: Nil)
108+
val valuesOfBody = Try(
109+
expr = Apply(valuesDot("fromName"), Ident(nme.name) :: Nil)
110+
, cases = CaseDef(
111+
pat = Typed(Ident(nme.DEFAULT_EXCEPTION_NAME), TypeTree(defn.NoSuchElementExceptionType))
112+
, guard = EmptyTree
113+
, body = Throw(New(TypeTree(defn.IllegalArgumentExceptionType), List(valuesOfExnMessage :: Nil)))
114+
) :: Nil
115+
, finalizer = EmptyTree
116+
)
99117
val valueOfDef = DefDef(nme.valueOf, Nil, List(param(nme.name, defn.StringType) :: Nil),
100-
TypeTree(), Apply(valuesDot("fromName"), Ident(nme.name) :: Nil))
118+
TypeTree(), valuesOfBody)
101119

102120
valuesDef ::
103121
privateValuesDef ::

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,11 @@ class Definitions {
605605
lazy val SystemClass: ClassSymbol = ctx.requiredClass("java.lang.System")
606606
lazy val SystemModule: Symbol = SystemClass.linkedClass
607607

608+
lazy val NoSuchElementExceptionClass = ctx.requiredClass("java.util.NoSuchElementException")
609+
def NoSuchElementExceptionType = NoSuchElementExceptionClass.typeRef
610+
lazy val IllegalArgumentExceptionClass = ctx.requiredClass("java.lang.IllegalArgumentException")
611+
def IllegalArgumentExceptionType = IllegalArgumentExceptionClass.typeRef
612+
608613
// in scalac modified to have Any as parent
609614

610615
lazy val ThrowableType: TypeRef = ctx.requiredClassRef("java.lang.Throwable")

0 commit comments

Comments
 (0)