[antlr-interest] Simple way to get the text that matched

Rick Morgan r.morgan at verizonbusiness.com
Wed Nov 1 05:32:34 PST 2006


Could someone reply with the simplist way to return the text matched by any
parser rule?  I was told previously that I need to know what kind of things
are returned by the lower level rules, but honestly, I don't know what they
return other than a "Token" from the lexer, and once they get into the
parser I don't know what they turn into, and I don't see a straight-forward
example in the docs.  I just want everything to be a string buffer or
something like that so that I can get the text that matched. A 3-level
example like this is what I'm asking for.
parserRule1 : t1:("keyword1" parserRule2)
              {printf( "parserRule1 got a %s from parserRule2\n",
                       t1.getText());}
            ;
parserRule2 : t2:("keyword2" LEXER_RULE_1)
              {printf( "parserRule2 got a %s from the lexer\n", 
                       t2.getText());}
            ;
LEXER_RULE_1 : "sometoken";

The problem I'm having is that t1 and t2 never get declared and I'm told
it's my responsibility to declare them somehow in a returns statement. It
doesn't seem to me they are a "Token" anymore once they get back to the
parser, since the parser is matching several tokens.

BTW, I tried putting a [returns char* x] on one of my lower rules and then
the Eclipse plugin complained that in a higher rule that used the lower
rule, "classSpec returns a value" (classSpec was the rule name.) That
implies that I need to use an assignment instead of the label:rule notation,
defeating the purpose of the notation I think.  Maybe the label notation
applies only to the lexer, but the docs don't read that way.

Sorry for such a beginner question, but I'm stumped.
Rick




More information about the antlr-interest mailing list