[antlr-interest] StringTemplate question
Gabriel Miro
gsmiro at gmail.com
Thu Sep 15 10:12:17 PDT 2011
Hello all,
I'm writing a translator to add tab characters before specific elements of a
string, e.g.:
Input : (FIELD1 + FIELD2) > 'VALUE' OR FIELD3 like ('%somevalue%')
output:
\t(\tFIELD1\t+\tFIELD2)\t>\t'VALUE'\tOR\tFIELD3\tlike\t(\t'%somevalue%'\t)
and I'm thinking about the best way to do that. I already wrote the parser
and I'm working on the translator/emitter.
For instance, in the grammar below I find that the template from 'expr' gets
overriden with the template of the last matched sub rule. Is there a way to
merge the subrule templates into the main rule one? Also, does the template
declaration need to be in the first rule?
grammar Test;
options{
output=template;
}
rule : e+=expr+ -> template(exps={$e}) "<exps>";
expr : (B_OP WS?)* lside WS* C_OP WS* STRING
-> template(bop={$B_OP.text},ls={lside.text},
op={$C_OP.text},val={$STRING.text}) " <bop> <ls>
<op> <val>";
lside :
FIELD
-> template(f={$FIELD.text}) " <f>"
|
LPAREN WS* alside WS* A_OP WS* arside WS* RPAREN
-> template(ls={$alside.text},op={$A_OP.text},rs={$arside.text})
" ( <ls> <op> <rs> )";
alside : FIELD;
arside : FIELD;
FIELD : 'A'..'Z'+;
RPAREN : ')';
LPAREN : '(';
A_OP : '+'|'-';
C_OP : '<>'|'='|'<'|'>'|'<='|'>=';
B_OP : 'AND'|'OR';
LIKE : 'like' LPAREN STRING* RPAREN;
WS : ( ' '
| '\t'
) {$channel=HIDDEN;}
;
STRING
: '\'' ( ESC_SEQ | ~('\\'|'\'') )* '\''
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment
ESC_SEQ
: '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
| UNICODE_ESC
| OCTAL_ESC
;
fragment
OCTAL_ESC
: '\\' ('0'..'3') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
More information about the antlr-interest
mailing list