From 8e5fba32f6d85ff2651787a3dd38cdf08cb911d5 Mon Sep 17 00:00:00 2001 From: Laborratte5 Date: Sat, 20 Jul 2024 09:23:21 +0200 Subject: [PATCH] Implement Compiler --- app/Compiler.hs | 19 +++++++++++++++++++ app/Main.hs | 3 ++- simple-arithmetic-compiler.cabal | 2 +- 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 app/Compiler.hs diff --git a/app/Compiler.hs b/app/Compiler.hs new file mode 100644 index 0000000..8c7aee6 --- /dev/null +++ b/app/Compiler.hs @@ -0,0 +1,19 @@ +module Compiler where + +import qualified AbstractSyntaxTree as AST + +data Command = Const Int -- Load integer const + | Add + | Sub + | Mult + | Div + deriving Show + +compile :: AST.AST -> [Command] +compile = reverse . compile' + where compile' ast = case ast of + AST.Scalar i -> [Const i] + AST.Operation AST.Add left right -> Add : compile' left ++ compile' right + AST.Operation AST.Sub left right -> Sub : compile' left ++ compile' right + AST.Operation AST.Mult left right -> Mult : compile' left ++ compile' right + AST.Operation AST.Div left right -> Div : compile' left ++ compile' right diff --git a/app/Main.hs b/app/Main.hs index 7d519fa..29032ec 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -3,10 +3,11 @@ module Main where import qualified Lexer import qualified Parser import qualified AbstractSyntaxTree as AST +import qualified Compiler main :: IO () main = do source <- readFile "arithmetic.txt" case Parser.parse $ Lexer.lex source of - Just source -> print $ AST.createAST source + Just source -> print $ Compiler.compile $ AST.createAST source _ -> putStr "Some error" diff --git a/simple-arithmetic-compiler.cabal b/simple-arithmetic-compiler.cabal index 7f36a32..bb577fe 100644 --- a/simple-arithmetic-compiler.cabal +++ b/simple-arithmetic-compiler.cabal @@ -52,7 +52,7 @@ executable simple-arithmetic-compiler main-is: Main.hs -- Modules included in this executable, other than Main. - other-modules: Lexer, Parser, AbstractSyntaxTree + other-modules: Lexer, Parser, AbstractSyntaxTree, Compiler -- LANGUAGE extensions used by modules in this package. -- other-extensions: