[antlr-interest] Easier way to do string literals?
Vaclav Barta
vbar at comp.cz
Mon Oct 15 00:18:32 PDT 2007
Gavin Lambert wrote:
> >I need to also run through the text and handle the escapes. This
> >seems like the wrong approach, since it means I'm writing parse
> >code in Java, which strikes me as underutilizing ANTLR.
> Well, you're always going to have to write your own escape-parsing code,
> since ANTLR can't make any guesses about what you want \n to mean.
> Maybe it's a newline; maybe it's a placeholder for "the contents of
> variable 'n'", maybe it's something even more esoteric.
Well, yes, _somebody_ has to write it...
> StringLiteral
> : '"' StringGuts '"' { setText(ParseEscapes($StringGuts.text)); }
> ;
...but as the OP says, they should use more ANTLR, i.e.
quotedString returns [ String value ]
@init {
StringBuffer sb;
} : {
sb = new StringBuffer();
}
DQUOTE (
EscapeSequence { sb.append($EscapeSequence.getText()); }
| BareString { sb.append($BareString.getText()); }
)* DQUOTE { $value = sb.toString(); }
;
EscapeSequence
: '\\' (
( ~ ( 'n' | 'r' | 't' ) ) =>
StringChar {
setText($StringChar.getText());
}
| 'n' { setText("\n"); }
| 'r' { setText("\r"); }
| 't' { setText("\t"); }
)
;
More information about the antlr-interest
mailing list