Purely functional byte code and class file generator written in Scala3
____ __
/ __ )__ __/ /______
/ __ / / / / __/ ___/
/ /_/ / /_/ / /_/ /__
/_____/\__, /\__/\___/
/____/
- The core class
Code
andClassFile.Operation
are purely composable, which implementMonoid
. - No side effect until we have to write file (IO).
- Computation description and interpreter implementation properly seperated (Free monad is not necessary with Scala's implicits).
Pass
serves as the empty codeLoad
Intelligently load various kinds of data typesStore
Intelligently store various kinds of data typesReturn
Intelligently return with return typeInspect
Inspect intermediate code statePrintCode
Print codesNewCode
Customize code as you likeNew
new instancesInvokeVirtual
invoke methods- ...
Define
defines a new classMain
adds main methodMethod
adds methodConstructor
adds constructorDefaultConstructor
adds default constructor- ...
import bytc.*
import bytc.given
import Type.*
@main def main: Unit =
import Code.*
import ClassFile.Operation.*
val `class` =
Define("HelloWorld")
<< DefaultConstructor
<< Main(helloWorld)
`class`.create() match
case Left(err) => sys.error(err.msg)
case Right(cf) => cf.writeToFile("HelloWorld.class")
end main
def helloWorld: Code = {
import Code.*
Comment("Hello world example")
<< GetStatic("java.lang.System", "out", "Ljava/io/PrintStream;")
<< Load("Hello world!")
<< InvokeVirtual("java.io.PrintStream", "println", "(Ljava/lang/String;)V")
<< Return
}
def fact: Code = {
import Code.*
val label = Tool.getFreshLabel()
Comment("Define fact(n: Int): Int")
<< Load(Var(1))
<< Load(1)
<< If_ICmpGt(label)
<< Load(1)
<< Return
<< Label(label)
<< Load(Var(1))
<< Load(Var(0))
<< Load(Var(1))
<< Load(1)
<< ISUB
<< InvokeVirtual("HelloWorld", "fact", "(I)I")
<< IMUL
<< Return
}