Implement AbstractSyntaxTree

This commit is contained in:
Laborratte 5 2024-07-18 18:04:36 +02:00
parent 7c19a6e890
commit 62528a6d75
Signed by: Laborratte5
GPG key ID: 3A30072E35202C02
3 changed files with 41 additions and 2 deletions

36
app/AbstractSyntaxTree.hs Normal file
View file

@ -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)

View file

@ -2,8 +2,11 @@ module Main where
import qualified Lexer import qualified Lexer
import qualified Parser import qualified Parser
import qualified AbstractSyntaxTree as AST
main :: IO () main :: IO ()
main = do main = do
source <- readFile "arithmetic.txt" 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"

View file

@ -52,7 +52,7 @@ executable simple-arithmetic-compiler
main-is: Main.hs main-is: Main.hs
-- Modules included in this executable, other than Main. -- 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. -- LANGUAGE extensions used by modules in this package.
-- other-extensions: -- other-extensions: