From 641de5e4f68385da3b53bfc532c2d6585a6d958d Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Sun, 14 Aug 2022 19:19:26 +0100 Subject: Limit lambdas to only use local variables Dynamic allocation (and hence closures) is not supported. --- src/Ast.hs | 4 ++-- src/Compiler.hs | 6 ++++-- src/Parser.hs | 10 +++++----- 3 files changed, 11 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/Ast.hs b/src/Ast.hs index c2bae9e..aa6a5c8 100644 --- a/src/Ast.hs +++ b/src/Ast.hs @@ -23,8 +23,8 @@ data Expr = Num Integer SourcePos | BinOp Op Expr Expr | Var Ident SourcePos - | -- fn [params] return body private pos - Func Ident [FuncParam] (Maybe Type) [Expr] Bool SourcePos + | -- fn [params] return body private anomyous pos + Func Ident [FuncParam] (Maybe Type) [Expr] Bool Bool SourcePos | Call Expr [Expr] SourcePos | Return (Maybe Expr) SourcePos | Module String SourcePos diff --git a/src/Compiler.hs b/src/Compiler.hs index f9c0eed..0d90143 100644 --- a/src/Compiler.hs +++ b/src/Compiler.hs @@ -86,7 +86,7 @@ compile x = do l <- compile a r <- compile b return $ l -- TODO: placeholder - (A.Func ident params ret body priv pos) -> do + (A.Func ident params ret body priv anon pos) -> do -- current env (ev, errs) <- get -- updated with the function @@ -94,8 +94,10 @@ compile x = do return $ case addSymUniq ev (ident, ftype, pos) of Left err -> (ev, err : errs) Right ev -> (ev, errs) + -- lambdas can only access local variables (closures aren't supported) + fev <- return $ if anon then emptyEnv else ev -- with parameters - (nev, errs) <- return $ foldlEither addSymUniq (addEnv ev, errs) params + (nev, errs) <- return $ foldlEither addSymUniq (addEnv fev, errs) params -- helper for return nev <- return $ addSym nev ("$fn$", ftype, pos) put (nev, errs) diff --git a/src/Parser.hs b/src/Parser.hs index 1c21700..851b4c0 100644 --- a/src/Parser.hs +++ b/src/Parser.hs @@ -59,8 +59,8 @@ arg = do t <- type' "type" return $ (i, t, pos) -fdef :: Ident -> Bool -> SourcePos -> Parser Expr -fdef ident priv pos = do +fdef :: Ident -> Bool -> Bool -> SourcePos -> Parser Expr +fdef ident priv anon pos = do args <- parens $ commaSep arg rtyp <- optionMaybe @@ -70,7 +70,7 @@ fdef ident priv pos = do return $ rtyp ) body <- braces $ many statement - return $ Func ident args rtyp body priv pos + return $ Func ident args rtyp body priv anon pos function :: Parser Expr function = do @@ -78,7 +78,7 @@ function = do priv <- optionMaybe $ reserved "private" reserved "def" ident <- identifier - fdef ident (isJust priv) pos + fdef ident (isJust priv) False pos lambdaId :: SourcePos -> Ident lambdaId s = @@ -87,7 +87,7 @@ lambdaId s = lambda :: Parser Expr lambda = do pos <- getPosition - fdef (lambdaId pos) True pos + fdef (lambdaId pos) True True pos return' :: Parser Expr return' = do -- cgit v1.2.3