6502-opcodes/firepower-demo/src/main/scala/com/htmlism/firepower/demo/asm/AsmBlock.scala

57 lines
1.6 KiB
Scala

package com.htmlism.firepower.demo.asm
sealed trait AsmBlock
case class CommentBlock(xs: List[String]) extends AsmBlock
case class NamedCodeBlock(name: String, comment: Option[String], intents: List[AsmBlock.Intent]) extends AsmBlock
case class AnonymousCodeBlock(intents: List[AsmBlock.Intent]) extends AsmBlock
object AsmBlock:
def interFlatMap[A, B](xs: List[A])(x: List[B], f: A => List[B]): List[B] =
xs match
case head :: tail =>
f(head) ::: tail.flatMap(a => x ::: f(a))
case Nil =>
Nil
def toComment(s: String): String =
"; " + s
def withIndent(s: String): String =
" " + s
def toLines(xs: AsmBlock): List[String] =
xs match
case CommentBlock(ys) =>
ys.map(toComment)
case NamedCodeBlock(label, oComment, intents) =>
val headerParagraph =
List(label + ":") ++ oComment.map(toComment).map(withIndent).toList
val intentParagraphs =
interFlatMap(intents)(List(""), Intent.toLines)
headerParagraph ::: intentParagraphs
case AnonymousCodeBlock(intents) =>
interFlatMap(intents)(List(""), Intent.toLines)
case class Intent(label: Option[String], instructions: List[Intent.Instruction])
object Intent:
case class Instruction(code: String, comment: Option[String])
def toLines(x: Intent): List[String] =
x.label.map(toComment).map(withIndent).toList ++ x
.instructions
.map(i => i.code + i.comment.map(toComment).map(" " + _).getOrElse(" "))
.map(withIndent)
object CommentBlock:
def fromMultiline(s: String): CommentBlock =
CommentBlock(s.split("\\n").toList)