From f7119b1dd3acb8c885c79baa504c2162a001af76 Mon Sep 17 00:00:00 2001 From: Ivy Date: Sat, 30 Jan 2021 18:09:05 +0100 Subject: [PATCH] Moved Enviroment into a separate file --- cherry-lisp.cabal | 3 ++- src/Enviroment.hs | 19 +++++++++++++++++++ src/Evaluator.hs | 16 +++++----------- src/ExprType.hs | 3 ++- src/Main.hs | 1 + 5 files changed, 29 insertions(+), 13 deletions(-) create mode 100644 src/Enviroment.hs diff --git a/cherry-lisp.cabal b/cherry-lisp.cabal index 4a7f7c0..eb0a693 100644 --- a/cherry-lisp.cabal +++ b/cherry-lisp.cabal @@ -22,7 +22,8 @@ executable cherry Parser, TokenType, Lexer, - Evaluator + Evaluator, + Enviroment build-depends: base >= 4.7 && < 5, containers, diff --git a/src/Enviroment.hs b/src/Enviroment.hs new file mode 100644 index 0000000..113b106 --- /dev/null +++ b/src/Enviroment.hs @@ -0,0 +1,19 @@ +module Enviroment where + +import qualified Data.Map as M +import ExprType +import Data.Maybe + +data Enviroment = Enviroment (M.Map String Expr) (Maybe Enviroment) + +base :: Enviroment +base = Enviroment (M.fromList [ + ("test-var", IntE 10) + ]) Nothing + +lookupVar :: Enviroment -> String -> Maybe Expr +lookupVar (Enviroment menv upperEnv) var = let mExpr = M.lookup var menv in + if isNothing mExpr then upperEnv >>= (`lookupVar` var) else mExpr + +insertVar :: Enviroment -> String -> Expr -> Enviroment +insertVar (Enviroment menv u) var expr = Enviroment (M.insert var expr menv) u diff --git a/src/Evaluator.hs b/src/Evaluator.hs index bf2ac62..007c3da 100644 --- a/src/Evaluator.hs +++ b/src/Evaluator.hs @@ -1,22 +1,16 @@ module Evaluator where -import qualified Data.Map as M import ExprType - -type Env = M.Map String Expr +import Enviroment +import Data.Maybe -- TODO: create a separated file for builtinProcs -- TODO: create a BuiltinProc or something like that in data Expr, and make + a builtin proc -base :: Env -base = M.fromList [ - ("test-var", IntE 10) - ] - -eval :: Env -> Expr -> (Env, Expr) +eval :: Enviroment -> Expr -> (Enviroment, Expr) eval env i@(IntE _) = (env, i) -eval env (VarE v) = eval env $ env M.! v -eval env (SetE v expr) = (M.insert v expr env, NilE) +eval env (VarE v) = eval env $ fromJust $ lookupVar env v +eval env (SetE v expr) = (insertVar env v expr, NilE) eval env (QuotedE e) = (env, e) eval env (ConsE car cdr) = (env, apply car cdr) eval env NilE = (env, NilE) diff --git a/src/ExprType.hs b/src/ExprType.hs index f4aaa21..73a4fde 100644 --- a/src/ExprType.hs +++ b/src/ExprType.hs @@ -5,7 +5,8 @@ data Expr = IntE Integer | SetE String Expr | ConsE Expr Expr | QuotedE Expr - | NilE deriving (Show) + | NilE + deriving (Show) -- instance Show Expr where -- show (IntE x) = show x diff --git a/src/Main.hs b/src/Main.hs index 7b77854..9487648 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -1,6 +1,7 @@ module Main where import Evaluator +import Enviroment import Parser import Control.Monad import Data.Maybe