mappings are derived from enums and bitfields

This commit is contained in:
Mark Canlas 2020-08-26 03:54:02 -04:00
parent 0a6379b9dd
commit 3f5f6e309d
3 changed files with 52 additions and 84 deletions

View File

@ -25,3 +25,51 @@ trait Mapping[A] {
*/
def comment(x: A): String
}
object Mapping {
implicit def mappingForBitField[A](implicit ev: BitField[A]): Mapping[A] =
new Mapping[A] {
private lazy val valueMap =
ev.all.toList
.zip(List.iterate(1, ev.all.size)(_ << 1))
.toMap
def definitionGroupComment: String =
ev.definitionGroupComment
def all: NonEmptyList[A] =
ev.all
def value(x: A): Int =
valueMap(x)
def label(x: A): String =
ev.label(x)
def comment(x: A): String =
"" // TODO
}
implicit def mappingForEnumAsm[A](implicit ev: EnumAsm[A]): Mapping[A] =
new Mapping[A] {
private lazy val valueMap =
ev.all.toList
.zip(List.iterate(0, ev.all.size)(_ + 1))
.toMap
def definitionGroupComment: String =
ev.comment
def all: NonEmptyList[A] =
ev.all
def value(x: A): Int =
valueMap(x)
def label(x: A): String =
ev.label(x)
def comment(x: A): String =
ev.comment(x)
}
}

View File

@ -25,47 +25,11 @@ trait AsmDocSyntax {
.push(g.toGroup(s))
}
def enum[A](implicit ctx: AsmDocumentContext, ev: EnumAsm[A]): Unit = {
val xs =
ev.all
.map(ev.label)
.toList
.zip(List.iterate(0, ev.all.size)(_ + 1))
def enum[A: EnumAsm: Mapping](implicit ctx: AsmDocumentContext): Unit =
mapping
val grp =
DefinitionGroup(
ev.comment,
xs
.map {
case (s, n) =>
Definition(s, n)
}
)
ctx
.push(grp)
}
def bitField[A](implicit ctx: AsmDocumentContext, ev: BitField[A]): Unit = {
val xs =
ev.all
.map(ev.label)
.toList
.zip(List.iterate(1, ev.all.size)(_ << 1))
val grp =
DefinitionGroup(
ev.definitionGroupComment,
xs
.map {
case (s, n) =>
Definition(s, n)
}
)
ctx
.push(grp)
}
def bitField[A: BitField: Mapping](implicit ctx: AsmDocumentContext): Unit =
mapping
def mapping[A](implicit ctx: AsmDocumentContext, ev: Mapping[A]): Unit = {
val xs =

View File

@ -68,27 +68,6 @@ class DslSpec extends AnyFlatSpec with should.Matchers {
)
}
"mapping" should "compile" in {
val doc =
asmDoc { implicit ctx =>
mapping[TestDirection]
}
doc shouldEqual AsmDocument(
List(
DefinitionGroup(
"foo as a mapping",
List(
Definition("up", 0x77),
Definition("down", 0x61),
Definition("left", 0x73),
Definition("right", 0x64)
)
)
)
)
}
"label" should "compile" in {
val doc =
asmDoc { implicit ctx =>
@ -151,27 +130,4 @@ object TestDirection {
def label(x: TestDirection): String =
x.toString.toLowerCase
}
implicit val mappingDirection: Mapping[TestDirection] =
new Mapping[TestDirection] {
def definitionGroupComment: String =
"foo as a mapping"
def all: NonEmptyList[TestDirection] =
NonEmptyList.of(Up, Down, Left, Right)
def value(x: TestDirection): Int =
x match {
case Up => 0x77
case Down => 0x61
case Left => 0x73
case Right => 0x64
}
def label(x: TestDirection): String =
x.toString.toLowerCase
def comment(x: TestDirection): String =
x.toString
}
}