refactor: use LabelGenerator for RuntimeErrors

This commit is contained in:
2025-02-28 14:07:00 +00:00
parent 967a6fe58b
commit fb5799dbfd
4 changed files with 91 additions and 86 deletions

View File

@@ -0,0 +1,46 @@
package wacc
import scala.collection.mutable
import cats.data.Chain
private class LabelGenerator {
import assemblyIR._
import microWacc.{CallTarget, Ident, Builtin}
import asmGenerator.escaped
private val strings = mutable.HashMap[String, String]()
private var labelVal = -1
/** Get an arbitrary label. */
def getLabel(): String = {
labelVal += 1
s".L$labelVal"
}
/** Get a named label for a function. */
def getLabel(target: CallTarget): String = target match {
case Ident(v, _) => s"wacc_$v"
case Builtin(name) => s"_$name"
}
/** Get a named label for an error. */
def getLabel(target: RuntimeError): String =
s".L.${target.name}"
/** Get an arbitrary label for a string. */
def getLabel(str: String): String =
strings.getOrElseUpdate(str, s".L.str${strings.size}")
/** Get a named label for a string. */
def getLabel(src: String, name: String): String =
strings.getOrElseUpdate(src, s".L.$name.str${strings.size}")
/** Generate the assembly labels for constants that were labelled using the LabelGenerator. */
def generateConstants: Chain[AsmLine] =
strings.foldLeft(Chain.empty) { case (acc, (str, label)) =>
acc ++ Chain(
LabelDef(label),
Directive.Asciz(str.escaped)
)
}
}