Skip to content

Commit

Permalink
Improve the error message thrown when a companion object cannot be found
Browse files Browse the repository at this point in the history
Instead of letting the compiler fail with a NoSymbol error, try to catch
it during compilation and offer up a more informative error message.
  • Loading branch information
lloydmeta committed Feb 5, 2017
1 parent c93b0c5 commit 0b3eec4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
8 changes: 6 additions & 2 deletions enumeratum-core/src/test/scala/enumeratum/EnumSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -414,15 +414,19 @@ class EnumSpec extends FunSpec with Matchers {

describe("materializeEnum") {
import DummyEnum._
def findEnum[A <: EnumEntry: Enum](v: A) = implicitly[Enum[A]]

it("should return the proper Enum object") {
def findEnum[A <: EnumEntry: Enum](v: A) = implicitly[Enum[A]]

val hello: DummyEnum = Hello
val companion = findEnum(hello)
companion shouldBe DummyEnum
companion.values should contain(Hello)
}

it("should fail to compile when passed a singleton object") {
"""
| findEnum(Hello)
""" shouldNot compile
}
}
}
21 changes: 19 additions & 2 deletions macros/src/main/scala/enumeratum/EnumMacros.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package enumeratum

import ContextUtils.Context

import scala.collection.immutable._
import scala.util.control.NonFatal

Expand All @@ -22,8 +23,24 @@ object EnumMacros {
*/
def materializeEnumImpl[A: c.WeakTypeTag](c: Context) = {
import c.universe._
val symbol = weakTypeOf[A].typeSymbol
c.Expr[A](Ident(ContextUtils.companion(c)(symbol)))
val symbol = weakTypeOf[A].typeSymbol
val companionSymbol = ContextUtils.companion(c)(symbol)
if (companionSymbol == NoSymbol) {
c.abort(c.enclosingPosition,
s"""
|
| Could not find the companion object for type $symbol.
|
| If you're sure the companion object exists, you might be able to fix this error by annotating the
| value you're trying to find the companion object for with a parent type (e.g. Light.Red: Light).
|
| This error usually happens when trying to find the companion object of a hard-coded enum member, and
| is caused by Scala inferring the type to be the member's single type (e.g. Light.Red.type instead of
| Light).
""".stripMargin)
} else {
c.Expr[A](Ident(companionSymbol))
}
}

/**
Expand Down

0 comments on commit 0b3eec4

Please sign in to comment.