[antlr-interest] AST tree print out.

rkevinburton at charter.net rkevinburton at charter.net
Mon Jul 21 15:26:30 PDT 2008


I have been reading the ANTLR book and thinking that I hade "learned" enough I decided to tackle modifying an exisiting grammar. I picked a JavaScript.g grammar that was on the ANTLR grammar page. In this grammar I find:

functionDeclaration
	: FUNCTION name=functionName formalParameterList functionBody
	-> ^( FUNCTION $name formalParameterList functionBody )
	;

functionExpression
	: FUNCTION name=functionName? formalParameterList functionBody
	-> ^( FUNCTION $name? formalParameterList functionBody )
	;

functionName
	: Identifier
	;

formalParameterList
	: LPAREN ( args+=Identifier (COLON types+=Identifier)? ( COMMA args+=Identifier (COLON types+=Identifier)? )* )? RPAREN
	-> ^( ARGS $args* $types*)
	;
	
functionBody
	: lb=LBRACE sourceElement* RBRACE
	-> ^( BLOCK[$lb, "BLOCK"] sourceElement* )
	;

// $>
	
// $<	Program (14)

program
	: (sourceElement { Console.WriteLine((CommonTree)$sourceElement.tree); })*
	;

/*
By setting k  to 1 for this rule and adding the semantical predicate ANTRL will generate code that will always prefer functionDeclararion over functionExpression
here and therefor remove the ambiguity between these to production.
This will result in the same behaviour that is described in the specification under 12.4 on the expressionStatement rule.
*/
sourceElement
options
{
	k = 1 ;
}
	: { input.LA(1) == FUNCTION }? functionDeclaration
	| statement
	;

Basically I modifed the grammar to allow the function to take types for the arguments to the function. I also made this generate CSharp code and print out the AST list. But it is not producing the output that I would expect. I only get a long list of the string 'function' on the output. I don't see any tree or the arguments to the function. Have I misplaced '^' somehow? I don't see where else I could go.

Thank you.

Kevin


More information about the antlr-interest mailing list