├── .gitignore ├── src ├── test │ └── scala │ │ └── example │ │ ├── package.scala │ │ ├── NumericSuite.scala │ │ └── ReflectionSuite.scala └── main │ └── scala │ └── enumextensions │ ├── EnumMirror.scala │ ├── numeric │ ├── Macros.scala │ └── NumericOps.scala │ └── Macros.scala ├── project.scala ├── .scalafmt.conf ├── publish-conf.scala ├── .github └── workflows │ └── ci.yml ├── _docs └── index.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | .DS_Store 4 | .scala-build 5 | .metals 6 | .vscode 7 | .bsp 8 | -------------------------------------------------------------------------------- /src/test/scala/example/package.scala: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | extension [T](inline expr: T) inline def endLocally: T = expr 4 | -------------------------------------------------------------------------------- /project.scala: -------------------------------------------------------------------------------- 1 | //> using scala 3.3.1 2 | //> using jvm 8 3 | //> using test.dep org.scalameta::munit:1.0.0-M10 4 | //> using option -Xcheck-macros 5 | //> using options -siteroot ${.} 6 | //> using options -project enum-extensions 7 | -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version = "3.7.14" 2 | runner.dialect = scala3 3 | align.preset = more 4 | maxColumn = 100 5 | indent.fewerBraces = never 6 | rewrite.scala3.convertToNewSyntax = true 7 | rewrite.scala3.removeOptionalBraces = yes 8 | rewrite.scala3.insertEndMarkerMinLines = 5 9 | verticalMultiline.atDefnSite = true 10 | newlines.usingParamListModifierPrefer = before 11 | -------------------------------------------------------------------------------- /publish-conf.scala: -------------------------------------------------------------------------------- 1 | //> using publish.organization "io.github.bishabosha" 2 | //> using publish.name "enum-extensions" 3 | //> using publish.computeVersion "git:tag" 4 | //> using publish.repository "central-s01" 5 | //> using publish.license "Apache-2.0" 6 | //> using publish.url "https://github.com/bishabosha/enum-extensions" 7 | //> using publish.versionControl "github:bishabosha/enum-extensions" 8 | //> using publish.developer "bishabosha|Jamie Thompson|https://github.com/bishabosha" 9 | //> using publish.ci.computeVersion "git:tag" 10 | //> using publish.ci.repository "central-s01" 11 | //> using publish.ci.user "env:PUBLISH_USER" 12 | //> using publish.ci.password "env:PUBLISH_PASSWORD" 13 | //> using publish.ci.secretKey "env:PUBLISH_SECRET_KEY" 14 | //> using publish.ci.secretKeyPassword "env:GPG_PASSWORD" 15 | //> using publish.ci.publicKey "env:PUBLISH_PUBLIC_KEY" 16 | -------------------------------------------------------------------------------- /src/main/scala/enumextensions/EnumMirror.scala: -------------------------------------------------------------------------------- 1 | package enumextensions 2 | 3 | trait EnumMirror[E]: 4 | 5 | def mirroredName: String 6 | def size: Int 7 | def values: IArray[E] 8 | def declaresOrdinal(ordinal: Int): Boolean 9 | def declaresName(name: String): Boolean 10 | def valueOfUnsafe(name: String): E 11 | def fromOrdinalUnsafe(ordinal: Int): E 12 | def valueOf(name: String): Option[E] = 13 | if declaresName(name) then Some(valueOfUnsafe(name)) else None 14 | def fromOrdinal(ordinal: Int): Option[E] = 15 | if declaresOrdinal(ordinal) then Some(fromOrdinalUnsafe(ordinal)) else None 16 | 17 | extension (e: E) 18 | def ordinal: Int 19 | def name: String 20 | 21 | end EnumMirror 22 | 23 | object EnumMirror: 24 | 25 | inline def apply[E](using mirror: EnumMirror[E]): mirror.type = mirror 26 | 27 | transparent inline def derived[E]: EnumMirror[E] = ${ 28 | Macros.derivedEnumMirror[E] 29 | } 30 | 31 | end EnumMirror 32 | -------------------------------------------------------------------------------- /src/main/scala/enumextensions/numeric/Macros.scala: -------------------------------------------------------------------------------- 1 | package enumextensions.numeric 2 | 3 | import enumextensions.EnumMirror 4 | 5 | import scala.quoted.* 6 | 7 | object Macros: 8 | 9 | def derivedNumericOps[T: Type](mirror: Expr[EnumMirror[T]])(using Quotes): Expr[NumericOps[T]] = 10 | import quotes.reflect.* 11 | 12 | val tpe = TypeRepr.of[T] 13 | 14 | val sym = tpe.classSymbol match 15 | case Some(sym) => sym 16 | case _ => report.errorAndAbort(s"${tpe.show} is not a class type") 17 | 18 | if sym.children.length > 1 then 19 | '{ 20 | new NumericOps(using $mirror) with NumericOps.Modular[T]: 21 | override final val zero = EnumMirror[T].fromOrdinalUnsafe(0) 22 | override final val one = EnumMirror[T].fromOrdinalUnsafe(1) 23 | } 24 | else 25 | '{ 26 | new NumericOps(using $mirror) with NumericOps.Singleton[T]: 27 | override final val zero = EnumMirror[T].fromOrdinalUnsafe(0) 28 | } 29 | end if 30 | end derivedNumericOps 31 | 32 | end Macros 33 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: 5 | - main 6 | tags: 7 | - "v*" 8 | pull_request: 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3 15 | with: 16 | fetch-depth: 0 17 | - uses: coursier/cache-action@v6.4 18 | - uses: VirtusLab/scala-cli-setup@v1.0 19 | with: 20 | power: true 21 | 22 | - name: Check formatting 23 | run: scala-cli fmt . --check 24 | 25 | - name: Run unit tests 26 | run: scala-cli test . --cross 27 | 28 | publish: 29 | needs: test 30 | if: github.event_name == 'push' 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v3 34 | with: 35 | fetch-depth: 0 36 | - uses: coursier/cache-action@v6.4 37 | - uses: VirtusLab/scala-cli-setup@v1.0 38 | with: 39 | power: true 40 | - name: Publish 41 | run: scala-cli publish . --cross 42 | env: 43 | PUBLISH_USER: ${{ secrets.PUBLISH_USER }} 44 | PUBLISH_PASSWORD: ${{ secrets.PUBLISH_PASSWORD }} 45 | PUBLISH_SECRET_KEY: ${{ secrets.PUBLISH_SECRET_KEY }} 46 | PUBLISH_SECRET_KEY_PASSWORD: ${{ secrets.PUBLISH_SECRET_KEY_PASSWORD }} 47 | GPG_PASSWORD: ${{ secrets.GPG_PASSWORD }} 48 | -------------------------------------------------------------------------------- /src/test/scala/example/NumericSuite.scala: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import NumericSuite.* 4 | import Rank.* 5 | import Suit.* 6 | 7 | import enumextensions.EnumMirror 8 | import enumextensions.numeric.NumericOps 9 | 10 | import scala.collection.immutable.NumericRange 11 | 12 | object NumericSuite: 13 | 14 | enum Single derives EnumMirror, NumericOps: 15 | case One 16 | 17 | enum Rank derives EnumMirror, NumericOps: 18 | case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, 19 | King, Ace 20 | 21 | enum Suit derives EnumMirror, NumericOps: 22 | case Clubs, Diamonds, Hearts, Spades 23 | 24 | case class Card(suit: Suit, rank: Rank) 25 | end NumericSuite 26 | 27 | class NumericSuite extends munit.FunSuite: 28 | 29 | test("make deck of cards"): 30 | val deck = 31 | for 32 | suit <- Clubs to Spades 33 | rank <- Two to Ace 34 | yield Card(suit, rank) 35 | 36 | val deck2 = 37 | for 38 | suit <- EnumMirror[Suit].values 39 | rank <- EnumMirror[Rank].values 40 | yield Card(suit, rank) 41 | 42 | assertEquals( 43 | deck, 44 | deck2.toIndexedSeq 45 | ) 46 | .endLocally 47 | 48 | test("test is numeric"): 49 | def rangeTo[E: Integral](from: E, to: E): NumericRange[E] = 50 | NumericRange.inclusive(from, to, summon[Numeric[E]].one) 51 | assertEquals( 52 | rangeTo(Clubs, Spades).toIndexedSeq, 53 | EnumMirror[Suit].values.toIndexedSeq 54 | ) 55 | .endLocally 56 | 57 | end NumericSuite 58 | -------------------------------------------------------------------------------- /src/test/scala/example/ReflectionSuite.scala: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import enumextensions.EnumMirror 4 | 5 | import ReflectionSuite.* 6 | 7 | object ReflectionSuite: 8 | enum Color derives EnumMirror: 9 | case Red, Green, Blue 10 | 11 | class ReflectionSuite extends munit.FunSuite: 12 | 13 | test("EnumMirror Color"): 14 | import Color.{Red, Green, Blue} 15 | 16 | def testName[E: EnumMirror](e: E, expected: String)(using munit.Location) = 17 | assertEquals(e.name, expected) 18 | 19 | def testOrdinal[E: EnumMirror](e: E, expected: Int)(using munit.Location) = 20 | assertEquals(e.ordinal, expected) 21 | 22 | def testValueOf[E: EnumMirror](name: String, expected: E)(using munit.Location) = 23 | assertEquals(EnumMirror[E].valueOfUnsafe(name), expected) 24 | 25 | def testFromOrdinal[E: EnumMirror](ordinal: Int, expected: E)(using munit.Location) = 26 | assertEquals(EnumMirror[E].fromOrdinalUnsafe(ordinal), expected) 27 | 28 | def testDeclaresName[E: EnumMirror](name: String)(using munit.Location) = 29 | assertEquals(EnumMirror[E].declaresName(name), true) 30 | 31 | def testDeclaresOrdinal[E: EnumMirror](ordinal: Int)(using munit.Location) = 32 | assertEquals(EnumMirror[E].declaresOrdinal(ordinal), true) 33 | 34 | assertEquals( 35 | EnumMirror[Color].mirroredName, 36 | "example.ReflectionSuite$.Color" 37 | ) 38 | assertEquals(EnumMirror[Color].size, 3) 39 | assertEquals(EnumMirror[Color].values.toSeq, Seq(Red, Green, Blue)) 40 | testValueOf("Red", Red) 41 | testValueOf("Green", Green) 42 | testValueOf("Blue", Blue) 43 | testDeclaresName[Color]("Red") 44 | testDeclaresName[Color]("Green") 45 | testDeclaresName[Color]("Blue") 46 | testDeclaresOrdinal[Color](0) 47 | testDeclaresOrdinal[Color](1) 48 | testDeclaresOrdinal[Color](2) 49 | testFromOrdinal(0, Red) 50 | testFromOrdinal(1, Green) 51 | testFromOrdinal(2, Blue) 52 | testName(Red, "Red") 53 | testName(Green, "Green") 54 | testName(Blue, "Blue") 55 | testOrdinal(Red, 0) 56 | testOrdinal(Green, 1) 57 | testOrdinal(Blue, 2) 58 | .endLocally 59 | end ReflectionSuite 60 | -------------------------------------------------------------------------------- /src/main/scala/enumextensions/numeric/NumericOps.scala: -------------------------------------------------------------------------------- 1 | package enumextensions.numeric 2 | 3 | import enumextensions.EnumMirror 4 | 5 | import scala.collection.immutable.NumericRange 6 | import scala.util.Try 7 | import scala.quoted.* 8 | 9 | trait NumericOps[T](using final val mirror: EnumMirror[T]) extends Numeric[T] with Integral[T]: 10 | self => 11 | 12 | final def parseString(str: String): Option[T] = EnumMirror[T].valueOf(str) 13 | 14 | extension (t: T) 15 | def to(u: T): NumericRange[T] = NumericRange.inclusive(t, u, one)(self) 16 | def until(u: T): NumericRange[T] = NumericRange(t, u, one)(self) 17 | end NumericOps 18 | 19 | object NumericOps: 20 | 21 | trait Singleton[T] extends NumericOps[T]: 22 | 23 | final def compare(l: T, r: T): Int = 0 24 | 25 | override final def one = zero 26 | 27 | final def fromInt(x: Int): T = zero 28 | 29 | final def minus(x: T, y: T): T = x 30 | final def plus(x: T, y: T): T = x 31 | final def times(x: T, y: T): T = x 32 | final def quot(x: T, y: T): T = x 33 | final def rem(x: T, y: T): T = x 34 | final def negate(x: T): T = x 35 | 36 | final def toDouble(x: T): Double = 0 37 | final def toFloat(x: T): Float = 0 38 | final def toInt(x: T): Int = 0 39 | final def toLong(x: T): Long = 0 40 | end Singleton 41 | 42 | trait Modular[T] extends NumericOps[T]: 43 | import mirror.size 44 | 45 | final def compare(l: T, r: T): Int = l.ordinal compare r.ordinal 46 | 47 | final def minus(x: T, y: T): T = 48 | EnumMirror[T].fromOrdinalUnsafe((size + 1 + x.ordinal - y.ordinal) % size) 49 | final def plus(x: T, y: T): T = 50 | EnumMirror[T].fromOrdinalUnsafe((x.ordinal + y.ordinal) % size) 51 | final def times(x: T, y: T): T = 52 | EnumMirror[T].fromOrdinalUnsafe((x.ordinal * y.ordinal) % size) 53 | final def quot(x: T, y: T): T = 54 | EnumMirror[T].fromOrdinalUnsafe((x.ordinal / y.ordinal) % size) 55 | final def rem(x: T, y: T): T = 56 | EnumMirror[T].fromOrdinalUnsafe((x.ordinal % y.ordinal) % size) 57 | final def negate(x: T): T = 58 | EnumMirror[T].fromOrdinalUnsafe((size - x.ordinal) % size) 59 | 60 | final def fromInt(x: Int): T = 61 | EnumMirror[T].fromOrdinalUnsafe((x + size) % size) 62 | 63 | final def toDouble(x: T): Double = x.ordinal.toDouble 64 | final def toFloat(x: T): Float = x.ordinal.toFloat 65 | final def toInt(x: T): Int = x.ordinal 66 | final def toLong(x: T): Long = x.ordinal.toLong 67 | end Modular 68 | 69 | transparent inline def derived[T](using inline mirror: EnumMirror[T]): NumericOps[T] = 70 | ${ Macros.derivedNumericOps[T]('mirror) } 71 | end NumericOps 72 | -------------------------------------------------------------------------------- /_docs/index.md: -------------------------------------------------------------------------------- 1 | # Enum Extensions 2 | The Enum Extensions library provides type classes to work generically with enumerations in Scala 3 3 | 4 | ## Usage 5 | 6 | Type classes are provided in the `enumextensions` package. 7 | 8 | ### Enum Mirror 9 | 10 | `EnumMirror[E]` is a type class that provides reflection over an enumeration type `E`. It provides several capabilities: 11 | - cached `values` as an `IArray[E]` 12 | - reflection of `name` (`String`) or `ordinal` (`Int`) for any individual case. 13 | - safe lookup individual cases by `name` or `ordinal`, 14 | - unsafe (efficient) lookup of individual cases by `name` or `ordinal`. 15 | 16 | See the above use cases in action below: 17 | 18 | ```scala 19 | import enumextensions.EnumMirror 20 | 21 | def enumName[E: EnumMirror]: String = 22 | EnumMirror[E].mirroredName // e.g. example.Color 23 | 24 | def sortedCases[E: EnumMirror]: IArray[E] = 25 | EnumMirror[E].values // cached IArray 26 | 27 | def nameOrdinalPairs[E: EnumMirror]: Map[String, Int] = 28 | Map.from( // ┌ NAME ┌ ORDINAL 29 | for e <- sortedCases[E] yield e.name -> e.ordinal 30 | ) 31 | 32 | // Lookups returning `Option[E]` 33 | def safeLookup[E: EnumMirror](name: String): Option[E] = 34 | EnumMirror[E].valueOf(name) 35 | def safeLookup[E: EnumMirror](ordinal: Int): Option[E] = 36 | EnumMirror[E].fromOrdinal(ordinal) 37 | 38 | // assert that name/ordinal exists for convenience 39 | def unsafeLookup[E: EnumMirror](name: String): E = 40 | EnumMirror[E].valueOfUnsafe(name) 41 | def unsafeLookup[E: EnumMirror](ordinal: Int): E = 42 | EnumMirror[E].fromOrdinalUnsafe(ordinal) 43 | ``` 44 | 45 | `given` instances of `EnumMirror` are not provided automatically, you must explicitly opt in as follows: 46 | 47 | ```scala sc:nocompile 48 | enum Color derives EnumMirror: 49 | case Red, Green, Blue 50 | ``` 51 | 52 | ### Numeric 53 | 54 | In the `enumextensions.numeric` package we provide `NumericOps`, which extends types with a given `EnumMirror[E]` into a given `scala.math.Integral[E]`, as well as providing standard numeric operations over the enum, it is simple to create sub-ranges of values. 55 | 56 | Let's define a `WeekDays` enumeration, opting into numeric derivation by `derives NumericOps`, and declare ranges for both the `daysOfWeek` and `weekend`: 57 | 58 | ```scala sc:nocompile 59 | import enumextensions.EnumMirror 60 | import enumextensions.numeric.NumericOps 61 | 62 | enum WeekDays derives EnumMirror, NumericOps: 63 | case Monday, Tuesday, Wednesday, Thursday, Friday 64 | case Saturday, Sunday 65 | 66 | object WeekDays: 67 | val daysOfWeek = Monday to Friday 68 | val weekend = Saturday to Sunday 69 | ``` 70 | 71 | here is a demonstration of using the numeric operators, e.g. 72 | ```scala sc:nocompile 73 | scala> -(-Wednesday) == Wednesday 74 | true 75 | ``` 76 | 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Enum Extensions 2 | ![CI status](https://github.com/bishabosha/enum-extensions/actions/workflows/ci.yml/badge.svg) 3 | [![javadoc](https://javadoc.io/badge2/io.github.bishabosha/enum-extensions_3/latest_documentation.svg)](https://javadoc.io/doc/io.github.bishabosha/enum-extensions_3) 4 | 5 | The Enum Extensions library provides type classes to work generically with enumerations in Scala 3 6 | 7 | ## Usage 8 | 9 | Type classes are provided in the `enumextensions` package. 10 | 11 | ### Enum Mirror 12 | 13 | `EnumMirror[E]` is a type class that provides reflection over an enumeration type `E`. It provides several capabilities: 14 | - cached `values` as an `IArray[E]` 15 | - reflection of `name` (`String`) or `ordinal` (`Int`) for any individual case. 16 | - safe lookup individual cases by `name` or `ordinal`, 17 | - unsafe (efficient) lookup of individual cases by `name` or `ordinal`. 18 | 19 | See the above use cases in action below: 20 | 21 | ```scala 22 | import enumextensions.EnumMirror 23 | 24 | def enumName[E: EnumMirror]: String = 25 | EnumMirror[E].mirroredName // e.g. example.Color 26 | 27 | def sortedCases[E: EnumMirror]: IArray[E] = 28 | EnumMirror[E].values // cached IArray 29 | 30 | def nameOrdinalPairs[E: EnumMirror]: Map[String, Int] = 31 | Map.from( // ┌ NAME ┌ ORDINAL 32 | for e <- sortedCases[E] yield e.name -> e.ordinal 33 | ) 34 | 35 | // Lookups returning `Option[E]` 36 | def safeLookup[E: EnumMirror](name: String): Option[E] = 37 | EnumMirror[E].valueOf(name) 38 | def safeLookup[E: EnumMirror](ordinal: Int): Option[E] = 39 | EnumMirror[E].fromOrdinal(ordinal) 40 | 41 | // assert that name/ordinal exists for convenience 42 | def unsafeLookup[E: EnumMirror](name: String): E = 43 | EnumMirror[E].valueOfUnsafe(name) 44 | def unsafeLookup[E: EnumMirror](ordinal: Int): E = 45 | EnumMirror[E].fromOrdinalUnsafe(ordinal) 46 | ``` 47 | 48 | `given` instances of `EnumMirror` are not provided automatically, you must explicitly opt in as follows: 49 | 50 | ```scala 51 | enum Color derives EnumMirror: 52 | case Red, Green, Blue 53 | ``` 54 | 55 | ### Numeric 56 | 57 | In the `enumextensions.numeric` package we provide `NumericOps`, which extends types with a given `EnumMirror[E]` into a given `scala.math.Integral[E]`, as well as providing standard numeric operations over the enum, it is simple to create sub-ranges of values. 58 | 59 | Let's define a `WeekDays` enumeration, opting into numeric derivation by `derives NumericOps`, and declare ranges for both the `daysOfWeek` and `weekend`: 60 | 61 | ```scala 62 | import enumextensions.EnumMirror 63 | import enumextensions.numeric.NumericOps 64 | 65 | enum WeekDays derives EnumMirror, NumericOps: 66 | case Monday, Tuesday, Wednesday, Thursday, Friday 67 | case Saturday, Sunday 68 | 69 | object WeekDays: 70 | val daysOfWeek = Monday to Friday 71 | val weekend = Saturday to Sunday 72 | ``` 73 | 74 | here is a demonstration of using the numeric operators, e.g. 75 | ```scala 76 | scala> -(-Wednesday) == Wednesday 77 | true 78 | ``` 79 | 80 | -------------------------------------------------------------------------------- /src/main/scala/enumextensions/Macros.scala: -------------------------------------------------------------------------------- 1 | package enumextensions 2 | 3 | import scala.quoted.* 4 | import scala.collection.SeqView 5 | import scala.deriving.Mirror 6 | 7 | object Macros: 8 | 9 | def string[T: Type](using Quotes): Expr[String] = 10 | import quotes.reflect.* 11 | val ConstantType(StringConstant(str)) = TypeRepr.of[T]: @unchecked 12 | Expr(str) 13 | end string 14 | 15 | def names[T: Type](using Quotes): List[Expr[String]] = Type.of[T] match 16 | case '[EmptyTuple] => Nil 17 | case '[t *: ts] => string[t] :: names[ts] 18 | 19 | def derivedEnumMirror[E: Type](using Quotes): Expr[EnumMirror[E]] = 20 | import quotes.reflect.* 21 | 22 | val tpe = TypeRepr.of[E] 23 | 24 | val sym = tpe.classSymbol match 25 | case Some(sym) if sym.flags.is(Flags.Enum) && !sym.flags.is(Flags.JavaDefined) => 26 | sym 27 | case _ => 28 | report.errorAndAbort(s"${tpe.show} is not an enum type") 29 | 30 | val M = Expr.summon[Mirror.SumOf[E]] match 31 | case Some(mirror) => mirror 32 | case None => 33 | report.errorAndAbort(s"Could not summon a Mirror.SumOf[${tpe.show}]") 34 | 35 | val reifiedNames: Expr[Set[String]] = M match 36 | case '{ $m: Mirror.SumOf[E] { type MirroredElemLabels = elemLabels } } => 37 | '{ Set(${ Varargs(names[elemLabels]) }*) } 38 | 39 | val E = sym.companionModule 40 | 41 | val valuesRef = 42 | Select.unique(Ref(E), "values").asExprOf[Array[E & reflect.Enum]] 43 | 44 | def reifyValueOf(name: Expr[String]) = 45 | Select 46 | .overloaded(Ref(E), "valueOf", Nil, name.asTerm :: Nil) 47 | .asExprOf[E & reflect.Enum] 48 | 49 | def reifyFromOrdinal(ordinal: Expr[Int]) = 50 | Select 51 | .overloaded(Ref(E), "fromOrdinal", Nil, ordinal.asTerm :: Nil) 52 | .asExprOf[E & reflect.Enum] 53 | 54 | val sizeExpr = Expr(sym.children.length) 55 | 56 | val mirroredNameExpr = Expr(sym.fullName) 57 | 58 | '{ 59 | 60 | new EnumMirror[E]: 61 | 62 | private val _values: IArray[E & reflect.Enum] = 63 | IArray.unsafeFromArray($valuesRef) 64 | private val _ordinals = _values.indices 65 | private val _names = $reifiedNames 66 | 67 | locally: 68 | assert(_values.length == $sizeExpr) 69 | assert( 70 | (_values: IndexedSeq[E & reflect.Enum]) 71 | .map(_.ordinal) 72 | .corresponds(_ordinals)(_ == _) 73 | ) 74 | 75 | final def mirroredName: String = $mirroredNameExpr 76 | final def size: Int = $sizeExpr 77 | final def values: IArray[E] = _values 78 | final def declaresOrdinal(ordinal: Int): Boolean = 79 | _ordinals.contains(ordinal) 80 | final def declaresName(name: String): Boolean = _names.contains(name) 81 | final def valueOfUnsafe(name: String): E = ${ reifyValueOf('name) } 82 | final def fromOrdinalUnsafe(ordinal: Int): E = ${ 83 | reifyFromOrdinal('ordinal) 84 | } 85 | 86 | extension (e: E & scala.reflect.Enum) 87 | final def ordinal: Int = e.ordinal 88 | final def name: String = e.productPrefix 89 | 90 | end new 91 | 92 | } 93 | 94 | end derivedEnumMirror 95 | 96 | end Macros 97 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------