[antlr-interest] Problems parsing real numbers

aliguori123 ajl13 at bellatlantic.net
Mon Jan 21 15:13:41 PST 2002


Hi,

I just started using ANTLR from using bison/flex.  I really like ANTLR
over these two tools but I am struggling when trying to parse real
numbers.  Specifically, floating point numbers that do not have an
explicit whole number portion (i.e. '.5', '.3').

The strange thing is that in attempting to figure out how to
accomplish this in ANTLR, I pulled in the grammars from the java,
pascal, and GNUC examples and they all seem to have the same problem. 
I've included a sample below that reproduces the problem.  From what I
can tell - and that doesn't mean much of course - it should do the
job, but the parser will bug out that '.' is an illegal character if
one of these numbers are inputted.  I am using ANTLR v2.7.1.

Otherwise, I am finding ANTLR to be incredibly useful.  I was able to
translate all the expression parsing stuff from lex/yacc to ANTLR with
no problems.  It actually turned out alot better because ANTLR handles
things a bit nicer than lex/yacc do.  ANTLR is really a great tool.

Thanks,
Anthony

<-- BEGIN SNIPPET -->

options {
    language="Cpp";
}

class NumberParser extends Parser;
options {
    buildAST = true;
}

expr: (NUM_INT | NUM_REAL) EOL! ;

class NumberLexer extends Lexer;
options {
k=4;
}

WS_	:	(' '
	|	'\t'
	|	'\r')
		{ _ttype = ANTLR_USE_NAMESPACE(antlr)Token::SKIP; }
	;

DOT: '.';
EOL: '\n';

NUM_INT
	{bool isDecimal=false; /* changed to bool for C++ */}
	:/*	".." {_ttype = DOTDOT;} 
        |*/   '.'  {_ttype = DOT;}
		(('0'..'9')+ (EXPONENT)? { _ttype = NUM_REAL; })?
	|	(	'0' {isDecimal = true;} 
                // special case for just '0'
		|	('1'..'9') ('0'..'9')*  {isDecimal=true;}		// non-zero decimal
		)
		(	{ LA(2)!='.' && LA(3)!='.' && isDecimal}?
			(	'.' ('0'..'9')* (EXPONENT)?
			|	EXPONENT
			)
			{ _ttype = NUM_REAL; }
		)?
	;

EXPONENT
	:	('e') ('+'|'-')? ('0'..'9')+
	;

class NumberTreeWalker extends TreeParser;
options {
	buildAST = true;
}

expr returns [double r]
{
	r=0.0;
}
	: ni:NUM_INT		{r=atoi(ni->getText().c_str());}
	| nf:NUM_REAL		{r=atof(nf->getText().c_str());}
	;

<-- END SNIPPET -->


 

Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ 



More information about the antlr-interest mailing list