[antlr-interest] Example for Micheal (was: When does AST construction go through factory?)

Daniel Gackle gackle at shaw.ca
Fri Jan 17 22:48:35 PST 2003


Micheal,

> Hmm...this isn't right. Please post a repro-grammar and I'll fix it
> before Ter's planned 2.7.2 release party  ;-)

Ok, I modified calc.g that ships in the examples\csharp\calc folder of the
antlr-2.7.2rc2 distribution.  The modified grammar is copied below.  All I
did was:

(1) Added a tokens section with EXPR<AST=ExprNode> and STAR<AST=StarNode>;
(2) Defined the classes ExprNode and StarNode in an embedded code section;
(3) Added the following action to the expr rule: { ## = #(#[EXPR,"EXPR"],
##); }

On my machine this is enough to demonstrate both problems I wrote about:

(Problem 1) For STAR, which is a lexer token, the following code is
generated that does not compile:

tmp5_AST = (StarNode) astFactory.create(LT(1), "StarNode");

(Problem 2) For EXPR, which is an imaginary token, there is no code anywhere
that constructs an ExprNode or registers it with the factory.  The only
place that "ExprNode" appears in the parser code is its class declaration
mentioned in (2) above.

I hope this works for you.  Any other questions, feel free to e-mail me
privately.  (I get the digest, so my replies to the list are not always
prompt.)

Ciao,
Daniel

/////////////////////////////
// Start of modified Calc.g

options {
	language = "CSharp";
}

class CalcParser extends Parser;
options {
	buildAST = true;	// uses CommonAST by default
}

tokens {
	EXPR<AST=ExprNode>;
	STAR<AST=StarNode>;
}

{
	public class StarNode { }
	public class ExprNode { }
}

expr
	:	mexpr (PLUS^ mexpr)* SEMI!
		{ ## = #(#[EXPR,"EXPR"], ##); }
	;

mexpr
	:	atom (STAR^ atom)*
	;

atom:	INT
	;

class CalcLexer extends Lexer;

WS	:	(' '
	|	'\t'
	|	'\n'
	|	'\r')
		{ _ttype = Token.SKIP; }
	;

LPAREN:	'('
	;

RPAREN:	')'
	;

STAR:	'*'
	;

PLUS:	'+'
	;

SEMI:	';'
	;

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

INT	:	(DIGIT)+
	;

class CalcTreeWalker extends TreeParser;

expr returns [float r]
{
	float a,b;
	r=0;
}
	:	#(PLUS a=expr b=expr)	{r = a+b;}
	|	#(STAR a=expr b=expr)	{r = a*b;}
	|	i:INT			{r = Convert.ToSingle(i.getText());}
	;

// End of modified Calc.g
/////////////////////////////


 

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



More information about the antlr-interest mailing list