From 62528a6d75df48ea9717967133161ce612b9fc50 Mon Sep 17 00:00:00 2001 From: Laborratte5 Date: Thu, 18 Jul 2024 18:04:36 +0200 Subject: [PATCH] Implement AbstractSyntaxTree --- app/AbstractSyntaxTree.hs | 36 ++++++++++++++++++++++++++++++++ app/Main.hs | 5 ++++- simple-arithmetic-compiler.cabal | 2 +- 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 app/AbstractSyntaxTree.hs diff --git a/app/AbstractSyntaxTree.hs b/app/AbstractSyntaxTree.hs new file mode 100644 index 0000000..009ccdc --- /dev/null +++ b/app/AbstractSyntaxTree.hs @@ -0,0 +1,36 @@ +module AbstractSyntaxTree where + +import qualified Parser + +type AST = Node + +data Node = Operation Opcode Node Node + | Scalar Int + deriving Show + +data Opcode = Add + | Sub + | Mult + | Div + deriving Show + +createAST :: Parser.CST -> AST +createAST = simplifyExpr + +simplifyExpr :: Parser.Expr -> Node +simplifyExpr expr = case expr of + Parser.Add term expr2 -> Operation Add (simplifyTerm term) (simplifyExpr expr2) + Parser.Sub term expr2 -> Operation Sub (simplifyTerm term) (simplifyExpr expr2) + Parser.ETerm term -> simplifyTerm term + +simplifyTerm :: Parser.Term -> Node +simplifyTerm term = case term of + Parser.Mult factor term2 -> Operation Mult (simplifyFactor factor) (simplifyTerm term2) + Parser.Div factor term2 -> Operation Div (simplifyFactor factor) (simplifyTerm term2) + Parser.TFactor factor -> simplifyFactor factor + +simplifyFactor :: Parser.Factor -> Node +simplifyFactor factor = case factor of + Parser.Integer i -> Scalar i + Parser.Parantheses expr -> simplifyExpr expr + Parser.NegFactor factor2 -> Operation Mult (Scalar (-1)) (simplifyFactor factor2) diff --git a/app/Main.hs b/app/Main.hs index 4eeddb7..7d519fa 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -2,8 +2,11 @@ module Main where import qualified Lexer import qualified Parser +import qualified AbstractSyntaxTree as AST main :: IO () main = do source <- readFile "arithmetic.txt" - putStr $ show (Parser.parse $ Lexer.lex source) + case Parser.parse $ Lexer.lex source of + Just source -> print $ AST.createAST source + _ -> putStr "Some error" diff --git a/simple-arithmetic-compiler.cabal b/simple-arithmetic-compiler.cabal index 629dee5..7f36a32 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 + other-modules: Lexer, Parser, AbstractSyntaxTree -- LANGUAGE extensions used by modules in this package. -- other-extensions: