在Antlr中定义语法 [英] define a grammar in Antlr
问题描述
我定义了以下语法.
grammar Sample_1;
@header {
package a;
}
@lexer::header {
package a;
}
program
:
define*
implement*
;
define
: IDENT '=(' INTEGER',' INTEGER ')'
;
implement
:IDENT '=(' (IDENT ','?)* ')'
;
fragment LETTER : ('a'..'z' | 'A'..'Z') ;
fragment DIGIT : '0'..'9';
INTEGER : DIGIT+ ;
IDENT : LETTER (LETTER | DIGIT)*;
WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;};
COMMENT : '//' .* ('\n'|'\r') {$channel = HIDDEN;};
如何检查语法,以便在我有示例时
How to check in this grammar so that when I have the example
A=(1,1)
B=(1,2)
G=(A,B)
结果成功,但是如果我写
the result is successful but if I write
A=(1,1)
B=(1,2)
G=(A,E)
它给出一个错误,未定义E 谢谢
it gives an error that E is not defined thanks
结果: 我让它正常工作非常感谢:
the result: i got it working thanks a lot:
grammar Sample_1;
@members{
int level=0;
}
@header {
package a;
}
@lexer::header {
package a;
}
program
:
block
;
block
scope {
List symbols;
}
@init {
$block::symbols=new ArrayList();
level++;
}
@after {
System.err.println("Hello");
level--;
}
: (define* implement+)
;
define
: IDENT {$block::symbols.add($IDENT.text);} '=(' INTEGER',' INTEGER ')'
;
implement
:IDENT '=(' (a=IDENT
{if (!$block::symbols.contains($a.text)){
System.err.println("undefined");
}}','?)* ')'
;
fragment LETTER : ('a'..'z' | 'A'..'Z') ;
fragment DIGIT : '0'..'9';
INTEGER : DIGIT+ ;
IDENT : LETTER (LETTER | DIGIT)*;
WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;};
COMMENT : '//' .* ('\n'|'\r') {$channel = HIDDEN;};
推荐答案
Antlr支持 actions ,这是语法文件中嵌入的少量代码段.
Antlr supports actions, little snippets of code embedded in the grammar file.
一项分配动作可以存储到地图中.右侧IDENT的操作可能会尝试从映射中提取一个值,如果失败则抛出异常.
An action for an assignment could store into a map. An action for a right-hand-side IDENT could try to pull a value from the map, and throw an exception if it fails.
Terrence Parr的权威ANTLR参考"的第6章介绍了动作.
Chapter 6 in Terrence Parr's "The Definitive ANTLR Reference" covers actions.
这篇关于在Antlr中定义语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!