Purely functional byte code and class file generator written in Scala3
____ __
/ __ )__ __/ /______
/ __ / / / / __/ ___/
/ /_/ / /_/ / /_/ /__
/_____/\__, /\__/\___/
/____/
- The core class
CodeandClassFile.Operationare 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).
Passserves as the empty codeLoadIntelligently load various kinds of data typesStoreIntelligently store various kinds of data typesReturnIntelligently return with return typeInspectInspect intermediate code statePrintCodePrint codesNewCodeCustomize code as you likeNewnew instancesInvokeVirtualinvoke methods- ...
Definedefines a new classMainadds main methodMethodadds methodConstructoradds constructorDefaultConstructoradds 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
}