Parsing antlr lexer规则,几乎可以匹配任何内容
我在这里遇到了一个问题,我确信这是关于antlr是如何工作的,我做的都是错的,但我读了很多文档和教程,我仍然不完全理解它 我的症状是,当我添加(因为我需要)一个可能与它不应该匹配的lexer规则时,我的语法停止工作。它只能在正确的上下文中应用 我需要Parsing antlr lexer规则,几乎可以匹配任何内容,parsing,antlr,antlr3,Parsing,Antlr,Antlr3,我在这里遇到了一个问题,我确信这是关于antlr是如何工作的,我做的都是错的,但我读了很多文档和教程,我仍然不完全理解它 我的症状是,当我添加(因为我需要)一个可能与它不应该匹配的lexer规则时,我的语法停止工作。它只能在正确的上下文中应用 我需要ATTR规则,因为我需要description和其他规则来获取从该关键字到行尾的字符串。 这是相互冲突的规则: ATTR : (~('\r'| '\n'))* ; 它似乎匹配任何东西,所以它“吃掉”应该匹配不同标记的文本。这
ATTR
规则,因为我需要description
和其他规则来获取从该关键字到行尾的字符串。
这是相互冲突的规则:
ATTR
: (~('\r'| '\n'))*
;
它似乎匹配任何东西,所以它“吃掉”应该匹配不同标记的文本。这是有道理的,但我需要它,或者我需要另一个解决方案
这是我当前的示例输入:
; This is a comment
; Comment 2
audit-template this is the id {
description a description may include any char but {line break}
}
作为参考,这是我目前的完整语法:
grammar Grammar;
options {
superClass = AbstractTParser;
}
@header {
package antlrTest;
}
@lexer::header {
package antlrTest;
}
@lexer::members {
private void debug(String str) {
System.err.println("DEBUG(L) " + str);
}
}
@members {
private void debug(String str) {
System.err.println("DEBUG(P) " + str);
}
}
parse
: (template|'**TODO**') EOF { debug ("EOF"); }
;
template : 'audit-template' id=IDENTIFIER OB content=templateContent CB { debug("template id=" + $id.text); }
;
templateContent:
description?
;
description : 'description' ATTR
;
//
COMMENT
: ';' ~( '\r' | '\n' )* {$channel=HIDDEN; debug("COMMENT");}
;
SPACES : ( '\t' | '\f' | ' ' | '\n'| '\r' ) {$channel=HIDDEN;}
;
OB : '{' { debug("OB"); }
;
CB : '}' ('\r'| '\n')+ { debug("CB(lf)"); }
| '}' EOF { debug("CB(eof)"); }
;
IDENTIFIER
: ( 'a'..'z' | 'A'..'Z' | '_' )
( 'a'..'z' | 'A'..'Z' | '_' | '0'..'9' | '.' | ' ' | '\t')*
;
ATTR
: (~('\r'| '\n'))*
;
我得到了这个错误(错误处理有点调整):
解决方案?选择?谢谢。我刚刚有另一个相关的疑问。如果
IDENTIFIER
规则可能与审核模板匹配,这就是id
为什么我没有遇到相同的问题?另一种方法是使用此lexer规则并稍后在java中获取文本:DESCRIPTION:'DESCRIPTION'(~('\r'.'\n'))*
。这是个好主意吗?让它+不*然后看看会发生什么。你是对的@TheantlGuy。我明天试试。我终于引用了所有的字符串。一般来说,通过这种方式使用ANTLR和语法要容易得多。这样,lexer就知道字符串在没有上下文的情况下从何处开始和结束。
Line 4 char 0
at antlrTest.AbstractTParser.reportError(AbstractTParser.java:45)
at antlrTest.GrammarParser.parse(GrammarParser.java:106)
at antlrTest.TemplateParser.parseInput(TemplateParser.java:15)
at antlrTest.Main.testFile(Main.java:32)
at antlrTest.Main.main(Main.java:11)
Caused by: NoViableAltException(7@[])
at antlrTest.GrammarParser.parse(GrammarParser.java:71)
... 3 more