简体   繁体   English

Haskell - 解析器组合子关键字

[英]Haskell — parser combinators keywords

I am working on building a parser in Haskell using parser combinators. 我正在使用解析器组合器在Haskell中构建解析器。 I have an issue with parsing keywords such as "while", "true", "if" etc 我在解析诸如“while”,“true”,“if”等关键字时遇到问题

So the issue I am facing is that after a keyword there is a requirement that there is a separator or whitespace, for example in the statement if cond then stat1 else stat2 fi;x = 1 with this statement all keywords have either a space in front of them or a semi colon. 所以我面临的问题是在关键字之后需要有一个分隔符或空格,例如在语句中if cond then stat1 else stat2 fi;x = 1这个语句所有关键字都有一个空格在前面他们或半结肠。 However in different situations there can be different separators. 但是在不同的情况下可以有不同的分隔符。

Currently I have implemented it as follows: 目前我已经实现如下:

keyword :: String -> Parser String
keyword k = do
  kword <- leadingWS (string k)
  check (== ';') <|> check isSpace <|> check (== ',') <|> check (== ']')
  junk
  return word

however the problem with this keyword parser is that it will allow programs which have statements like if; 但是这个关键字解析器的问题在于它允许具有if语句的程序; cond then stat1 else stat2 fi cond然后stat1 else stat2 fi

We tried passing in a (Char -> Bool) to keyword, which would then be passed to check. 我们尝试将(Char - > Bool)传递给关键字,然后将其传递给检查。 But this wouldn't work because where we parse the keyword we don't know what kind of separator is allowed. 但这不起作用,因为在我们解析关键字时,我们不知道允许哪种分隔符。

I was wondering if I could have some help with this issue? 我想知道我是否能对这个问题有所帮助?

Don't try to handle the separators in keyword but you need to ensure that keyword "if" will not be confused with an identifier "iffy" (see comment by sepp2k). 不要尝试在keyword处理分隔符,但是您需要确保keyword "if"不会与标识符“iffy”混淆(请参阅sepp2k的评论)。

keyword :: String -> Parser String
keyword k = leadingWS $ try (do string k
                                notFollowedBy alphanum)

Handling separators for statements would go like this: 处理语句的分隔符将如下所示:

statements = statement `sepBy` semi
statement  = ifStatement <|> assignmentStatement <|> ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM