编辑:问题部分解决,跳到底部进行更新。
我正在使用 haskell 编写一种小型语言,并且取得了很大进展,但是在实现使用块的语句时遇到了麻烦,例如“{ ... }”。我已经在我的解析器文件中实现了对 If 语句的支持:
stmt = skip +++ ifstmt +++ assignment +++ whilestmt
ifstmt = symbol "if" >>
parens expr >>= \c ->
stmt >>= \t ->
symbol "else" >>
stmt >>= \e ->
return $ If c t e
whilestmt = symbol "while" >>
parens expr >>= \c ->
symbol "\n" >>
symbol "{" >>
stmt >>= \t ->
symbol "}" >>
return $ While c t
expr = composite +++ atomic
在语法文件中:
class PP a where
pp :: Int -> a -> String
instance PP Stmt where
pp ind (If c t e) = indent ind ++
"if (" ++ show c ++ ") \n" ++
pp (ind + 2) t ++
indent ind ++ "else\n" ++
pp (ind + 2) e
pp ind (While c t) = indent ind ++
"while (" ++ show c ++") \n" ++
"{" ++ pp (ind + 2) t ++ "}" ++
indent ind
while 语句有问题,我不明白是什么。逻辑似乎是正确的,但是当我运行代码时,出现以下错误:
EDIT: Fixed the first problem based on the first reply, now it is not recognizing my while statment which I assume comes from this:
exec :: Env -> Stmt -> Env
exec env (If c t e) =
exec env ( if eval env c == BoolLit True then t else e )
exec env (While c t) =
exec env ( if eval env c == BoolLit True then t )
正在读取的文件如下所示:
x = 1; c = 0;
if (x < 2) c = c + 1; else ;
-- SEPARATE FILES FOR EACH
x = 1; c = 1;
while (x < 10)
{
c = c * x;
x = x + 1;
}
c
我试图理解错误报告,但我没有尝试解决问题。