refactor: use LabelGenerator for RuntimeErrors
This commit is contained in:
46
src/main/wacc/backend/LabelGenerator.scala
Normal file
46
src/main/wacc/backend/LabelGenerator.scala
Normal 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)
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user