[antlr-interest] Manually failing a match

Mark Bednarczyk voytechs at yahoo.com
Wed Mar 14 08:56:09 PDT 2007

I need to manually fail a rule that has already been matched. 

Basically although the rule can match something that looks like an
identifier, a further manual check makes the final decision. Normally this
type of logic is in the Lexer and you would get Identifier token, but my
language syntax could not use this "standard" strategy as what is Identifier
and what is a Hex number is very "context" dependent.

I don't want to report an error, just fail the match on this rule in my
@finally, so that parser will go on to the next alternative in the "primary"
rule productions. So if input is "1", ids will match complexId will match
it, but the @finally statement should fail it, which should also fail the
ids, and then back in the "primary" rule move on to the next alternative
which is "address" which will not match, and lastly the "number" rule will

    :	  ids (identifierSuffix)? // Uses Hex combined with ParialIdentifier
    |   address 	// Also uses Hex token in various subrules
    |   number

	:	i1=complexId ('.' i2=complexId)*
		->	^(ID $i1 $i2*)

@init {
final StringBuilder b = new StringBuilder(); 
@finally {
	char c = b.charAt(0);
	if (c >= '0' && c <= '9') {
		failed=true; return retval; // How do I force a mismatch
	:	(
			(i=PartialIdentifier 	{b.append($i.text);})?
			(i=PartialIdentifier 	{b.append($i.text);})
		) {
			$i = new CommonToken(PartialIdentifier,
		-> $i

More information about the antlr-interest mailing list