问题描述
我正在尝试通过ANTLR(ANTLRWorks-3.5.2)解析语言.目的是输入完整的输入,但Antlr给出语法中已定义部分的分析树,而忽略其余输入,例如,这是我的语法:
I'm trying to parse a language by ANTLR (ANTLRWorks-3.5.2). The goal is to enter complete input but Antlr gives a parse tree of defined parts in grammar and ignore the rest of inputs, for example this is my grammar :
grammar asap;
project : '/begin PROJECT' name module+ '/end PROJECT';
module : '/begin MODULE'name '/end MODULE';
name : IDENT ;
IDENT : ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'.'|':'|'-')*;
输入:
/begin PROJECT HybridSailboat_2
/begin MODULE engine
/begin A2ML
/include XCP_common_v1_0.aml
"XCP" struct {
taggedstruct Common_Parameters ;
};
/end A2ML
/end MODULE
/end PROJECT
关于此输入,我只希望解析树包含项目和模块,而不是A2ML部分.在antlr中是否可能忽略输入的某些部分?我可以在语法中指定不重要部分的起点和终点吗?
regarding to this input I just want the parse tree contains project and module and not A2ML part.Is it possible in antlr that it ignore some part of inputs?Can I specify start and end points of unimportant parts in grammar?
推荐答案
在词法分析器中将A2ML
部分作为单个标记进行简单匹配,并将其skip()
进行匹配:
Simply match the A2ML
part as a single token in the lexer and skip()
it:
grammar asap;
project
: BEGIN_PROJECT name module* END_PROJECT EOF
;
module
: BEGIN_MODULE name END_MODULE
;
name
: IDENT
;
IDENT
: ('a'..'z'|'A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'.'|':'|'-')*
;
BEGIN_PROJECT
: '/begin' S 'PROJECT'
;
END_PROJECT
: '/end' S 'PROJECT'
;
BEGIN_MODULE
: '/begin' S 'MODULE'
;
END_MODULE
: '/end' S 'MODULE'
;
A2ML
: '/begin' S 'A2ML' .* '/end' S 'A2ML' {skip();}
;
SPACES
: S {skip();}
;
fragment S
: (' ' | '\t' | '\r' | '\n')+
;
这篇关于使用ANTLR解析时忽略输入的某些部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!