Antlr左因子语法 [英] Antlr Left-Factoring Grammar

查看:119
本文介绍了Antlr左因子语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Antlr的新手.我正在使用Antlr 3为我的公司定义语法.

I am new to Antlr. I am defining a grammar for my company using Antlr 3.

下面是我的语法:

grammar Grammar;

@header {
package com.grammar;
}

true        : 'true';
false       : 'false';
null        : 'null';
value       : true | false | null | STRING | NUMBER;
query           : (STATEMENT+) | STATEMENT?;
INSERT      : 'INSERT INTO' TABLE 'VALUES' '('ELEMENTS')'';';
STATEMENT   : INSERT;
STRING      : ('a'..'z'|'A'..'Z')+;
INTEGER     : '0'..'9'+;
ELEMENTS    : value | value ',' ELEMENTS;

当我尝试使用ANTLRWorks生成代码时,出现以下异常:

When I try to generate the code using ANTLRWorks, I get the following Exception:

error (211): Grammar.g.1:8: [fatal] rule Tokens has non-LL(*) decision due to recursive rule  invocations reacable from alts 18,24. Resolve by left-factoring or using syntactic predicates or using backtrack=true option

我浏览了以下网站:

http://www.antlr.org/wiki/display/ANTLR3/How+to+remove+global+backtracking+from+your+语法

任何建议可以做什么?我在网上找不到很多东西.

Any suggestions what can be done? I couldn't find much online.

当我添加以下内容时:

 grammar Grammar;

@options {
  backtrack=true;
}

我只有一个例外:

    error(100): Grammar.g:3:2: syntax error: antlr: NoViableAltException(55@[])
   [12:03:20] error(100): Grammar.g:3:2: syntax error: antlr: MissingTokenException (inserted [@-1,0:0='<missing ACTION>',<50>,3:1] at options {)
   [12:03:20] error(100): Grammar.g:3:2: syntax error: antlr:    org.antlr.runtime.EarlyExitException
 [12:03:20] error(150):  grammar file Grammar.g has no rules
  [12:03:20] error(100): Grammar.g:0:1: syntax error: assign.types:   MismatchedTreeNodeException(0!=3)

我拥有增值和要素.在ANTLRWorks中的图形内部使用ELEMENTS时,无法看到该值.我只能看到:

I have added value and ELEMENTS. When using ELEMENTS inside the graph in ANTLRWorks, the value cannot be seen. I can only see:

',' ELEMENTS

代替:

value | value ',' ELEMENTS

这可能是令牌异常问题的原因吗?这是真的允许吗?解决办法是什么?

Could this be the cause of the problem for the Tokens Exception? Is this actually allowed? What is the solution?

推荐答案

尝试

query           : (STATEMENT)*;

一些建议:

  • 避免使用

  • avoid rules like

value | value ',' ELEMENTS

其中两种选择都以相同的术语开头.将该词移到方括号中:

where both alternative starts with the same term. Move that term "out of brackets":

   value (','  value ) * 

  • 必须定义所有术语(语法中未定义NUMBER)

    • all terms must be defined (NUMBER is not defined in your grammar)

      只有一个规则可以定义未被其他规则引用的术语

      only one rule can define term which is not referenced from other rules

      这篇关于Antlr左因子语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆