树顶语法有问题,不匹配所有选项

发布于 2024-09-19 07:50:44 字数 646 浏览 2 评论 0原文

我正在用 ruby​​ 和 treetop gem 编写一个小型的、非常简单的 lisp 解析器,只是为了进行实验。然而,它并没有真正按照我想要的方式工作,而且文档非常差,所以很难理解我做错了什么。目前,该语法可以匹配符号和布尔值,但不能匹配数字。但是,当我切换原子规则中的顺序时,例如切换为布尔/数字/符号,它仍然匹配前两个,但不匹配最后一个。树顶宝石是否存在限制,意味着您在一条规则中只能有两个选项?另外,像“(3)”这样的东西仍然无法解析。

我的语法如下:

grammar Lisp
 rule expression
   atom / list
 end

 rule atom
   symbol / bool / number
 end

 rule number
   [0-9]*
 end

 rule bool
   'T' / 'F'
 end

 rule symbol
  [a-zA-Z]*
 end

 rule list
   '(' expression* ')'
 end    
end

我正在按照教程中所示的方式对其进行测试,其中:

parser = LispParser.new
if parser.parse('T')
  puts "Success"
else
  puts "Fail"
end

I am writing a small, really simple lisp parser in ruby with the treetop gem just to experiment with it. However, it is not really working out how I want it to, and the documentation is pretty poor so it's hard to understand what I am doing wrong. Currently, the grammar can match both a symbol and a boolean, but not a number. However, when I switch the order in the atom rule, for example to bool / number / symbol, it still matches for the first two, but not the last one. Is there a limitation in the treetop gem that means you can only have two options in a rule? Also, something like '(3)' still does not parse.

My grammar is as follows:

grammar Lisp
 rule expression
   atom / list
 end

 rule atom
   symbol / bool / number
 end

 rule number
   [0-9]*
 end

 rule bool
   'T' / 'F'
 end

 rule symbol
  [a-zA-Z]*
 end

 rule list
   '(' expression* ')'
 end    
end

I am testing it as they showed in the tutorial, with:

parser = LispParser.new
if parser.parse('T')
  puts "Success"
else
  puts "Fail"
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风情万种。 2024-09-26 07:50:44

您定义规则 numbersymbol 的方式它们始终匹配(因为 * 表示“零个或多个”,并且您始终可以找到某些内容中的零个) )。这意味着,如果您尝试解析“42”,解析器首先成功地将规则 symbol 与开头的空字符串进行匹配,然后期望不再输入。

要解决此问题,只需将 * 替换为 + 即可。

The way you defined the rules number and symbol they always match (because * means "zero or more" and you can always find zero of something). This means that if you try to parse "42", the parser first successfully matches the rule symbol against the empty string at the beginning and then expect no further input.

To fix this simply replace * with +.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文