解析 if / else / if 语句
我试图复制一个简单的 if 语句的结构:
if (paren) { block } [else ({ block } | rec if (paren)) ]
对于 if (paren) 块,我创建一个 IfBlock AST 节点。否则,它递归地填充 IfElseBlock 节点。
我已经尝试了很多替代结构
let parse_if =
suffixparen .>>. suffixblock |>> IfBlock
//>>? attempt (str "else" >>. ifParser) |>> IfElseBlock
//<|> preturn IfBlock
// .>>? attempt (str "else" >>. ifParser) |>> IfElseBlock
// suffixparen .>>. suffixblock |>> IfBlock
// <|> ifParser |>> IfElseBlock
let inlineIf = str_ws "if" >>. parse_if
do ifParserR := inlineIf
建议?
I'm trying to replicate the structure of a simple if statement:
if (paren) { block } [else ({ block } | rec if (paren)) ]
for if (paren) block, I create a IfBlock AST node. Otherwise, it recursively fills a IfElseBlock node.
I've tried quite a few alternate constructions
let parse_if =
suffixparen .>>. suffixblock |>> IfBlock
//>>? attempt (str "else" >>. ifParser) |>> IfElseBlock
//<|> preturn IfBlock
// .>>? attempt (str "else" >>. ifParser) |>> IfElseBlock
// suffixparen .>>. suffixblock |>> IfBlock
// <|> ifParser |>> IfElseBlock
let inlineIf = str_ws "if" >>. parse_if
do ifParserR := inlineIf
Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你看过我的 GLSL 解析器(它是一种类似 C 的语言)吗?
http://laurent.le-brun.eu/fsharp/glsl_parse.fs
从代码示例中,这里是
if
语句的相关部分:我认为您的问题是您使用的是
attempt
而不是opt
。opt
表示else
部分是可选的(如果不存在,则为None
)。attempt
是完全不同的:当
attempt
中的解析器失败时,仍然会出现错误,但输入不会被消耗(与<|>
或choice 运算符)。
Have you had a look at my GLSL parser (it's a C-like language)?
http://laurent.le-brun.eu/fsharp/glsl_parse.fs
From the code example, here is the relevant part for the
if
statement:I think your problem is that you're using
attempt
instead ofopt
.opt
means theelse
part is optional (if it's not there, you getNone
).attempt
is quite different:When the parser in
attempt
fails, there's still an error but the input is not consumed (it's useful when combined with the<|>
orchoice
operators).