[antlr-interest] problem parsing numbers

isabelle_muszynski isabelle_muszynski at yahoo.com
Mon Jan 26 05:33:10 PST 2004


Hi everyone,

A typical newbie question: the following grammar won't parse numbers 
correctly (for ex. give 123.456). I have simplified the grammar to 
the extreme to show only the number problem.

class ExpressionLexer extends Lexer;
options {
    k = 2; // needed for newline stuff
    filter = true; 
    charVocabulary='\3'..'\177';  // allow ASCII
}

tokens {
    LONG;
}
 
PLUS   : '+' ;
MINUS  : '-' ;

protected
DIGIT
	:	'0'..'9'
	;

protected
EXPONENT
	:	('e' | 'E') ('+' | '-')? (DIGIT)+
	;

NUMBER
    :   ( (DIGIT)+ ('.' | 'e' | 'E') )=> (DIGIT)+ ( '.' (DIGIT)* 
(EXPONENT)? | EXPONENT	)
	|	'.'	(DIGIT)+ (EXPONENT)?
	|	'0' ('0'..'7')* {_ttype = LONG;}
	|	'1'..'9' (DIGIT)* {_ttype = LONG;}
	|	'0' ('x' | 'X') ('a'..'f' | 'A'..'F' | DIGIT)+ 
{_ttype = LONG;}
	;

// Whitespace -- ignored
WS	:	(	' '
		|	'\t'
		|	'\f'
			// handle newlines
		|	(	options {generateAmbigWarnings=false;}
			:	"\r\n"  // Evil DOS
			|	'\r'    // Macintosh
			|	'\n'    // Unix (the right way)
			)
			{ newline(); }
		)+
		{ _ttype = Token.SKIP; }
	;

{import java.lang.Math;}
class ExpressionParser extends Parser;
options 
{ 
    buildAST=false; 
	exportVocab=Eval;
}

statement returns [double r = 0]
    : r=constant
    ;

constant returns [double r = 0]
	:	n:NUMBER {r=Double.parseDouble(n.getText());}
	|	l:LONG {r=Long.parseLong(l.getText());}
	;





 

Yahoo! Groups Links

To visit your group on the web, go to:
 http://groups.yahoo.com/group/antlr-interest/

To unsubscribe from this group, send an email to:
 antlr-interest-unsubscribe at yahoogroups.com

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




More information about the antlr-interest mailing list