简体   繁体   English

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

[英]Problem with treetop grammar, not matching all options

I am writing a small, really simple lisp parser in ruby with the treetop gem just to experiment with it. 我正在用树顶宝石在Ruby中编写一个很小的,非常简单的Lisp解析器,以进行实验。 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. 但是,当我在atomic规则中切换顺序时,例如将其更改为bool / number / symbol,它仍然与前两个匹配,但与最后一个不匹配。 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. 同样,诸如“(3)”之类的东西仍然无法解析。

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

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). 定义规则numbersymbol始终匹配的方式(因为*表示“零个或多个”,并且您始终可以找到零个)。 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. 这意味着,如果您尝试解析“ 42”,则解析器首先会成功地将规则symbol与开头的空字符串进行匹配,然后再期望没有进一步的输入。

To fix this simply replace * with + . 要解决此问题,只需将*替换为+

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

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