diff --git a/app/Assembler.hs b/app/Assembler.hs new file mode 100644 index 0000000..da159f3 --- /dev/null +++ b/app/Assembler.hs @@ -0,0 +1,31 @@ +module Assembler where + +import Data.Int +import qualified Data.Binary as B +import qualified Data.Binary.Builder as Bu +import qualified Data.Binary.Put as P +import qualified Data.ByteString.Lazy as BL +import Compiler + +-- Binary (huffman) encoding of instructions +-- 0x00 reserver +-- 0x01 Const +-- 0x04 Add +-- 0x05 Sub +-- 0x06 Mult +-- 0x07 Div + + +type Bytecode = BL.ByteString + +toBinary :: Command -> P.Put +toBinary (Const i) = do + P.putWord8 0x0001 + P.putInt32be ((fromIntegral i)::Int32) +toBinary Add = P.putWord8 0x0004 +toBinary Sub = P.putWord8 0x0005 +toBinary Mult = P.putWord8 0x0006 +toBinary Div = P.putWord8 0x0007 + +assemble :: [Command] -> Bytecode +assemble cmds = Bu.toLazyByteString $ mconcat (map (P.execPut . toBinary) cmds) diff --git a/app/Main.hs b/app/Main.hs index 29032ec..bb6d056 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -4,10 +4,12 @@ import qualified Lexer import qualified Parser import qualified AbstractSyntaxTree as AST import qualified Compiler +import qualified Assembler +import qualified Data.ByteString.Lazy as BL main :: IO () main = do source <- readFile "arithmetic.txt" case Parser.parse $ Lexer.lex source of - Just source -> print $ Compiler.compile $ AST.createAST source + Just source -> BL.putStr $ Assembler.assemble $ Compiler.compile $ AST.createAST source _ -> putStr "Some error" diff --git a/simple-arithmetic-compiler.cabal b/simple-arithmetic-compiler.cabal index bb577fe..a425e38 100644 --- a/simple-arithmetic-compiler.cabal +++ b/simple-arithmetic-compiler.cabal @@ -52,13 +52,15 @@ executable simple-arithmetic-compiler main-is: Main.hs -- Modules included in this executable, other than Main. - other-modules: Lexer, Parser, AbstractSyntaxTree, Compiler + other-modules: Lexer, Parser, AbstractSyntaxTree, Compiler, Assembler -- LANGUAGE extensions used by modules in this package. -- other-extensions: -- Other library packages from which modules are imported. - build-depends: base ^>=4.16.4.0 + build-depends: base ^>=4.16.4.0, + binary ^>=0.8.9.2, + bytestring ^>=0.11.4.0 -- Directories containing source files. hs-source-dirs: app