[antlr-interest] Parse rule to add multiple homogeneous branches under a root node?

Stefan Mätje Stefan.Maetje at esd-electronics.com
Tue May 8 06:47:27 PDT 2012


Am 08.05.2012 14:25, schrieb Peter Bosch:
> Okay, I've tried to boil it down to a simple test case that illustrates
> (probably in my parse rule) what I'm doing wrong. Target is C#.
:
:
>
> public parse
>
>      :  ( r=BRANCH )* EOF ->  ^(ROOT $r*)
>
>      ;
>
>
>
> BRANCH
>
>         :  'Branch' ('0'..'9')
>
>         ;

With that parse rule you will get only the last instance of the BRANCH 
token. You should collect it into a list and then reference the list in 
the rewrite rule. See below an excerpt of a grammar that builds two 
statement lists "tList" and "eList" and uses them in the rewrite rule:

/**	"IfStatement"
	*/
ifStat:
	'IF' cond=condRoot 'THEN' tList+=statement*
	('ELSE' eList+=statement*)? 'FIN'
		-> ^('IF' $cond SLIST $tList* ^('ELSE' SLIST $eList*)?)
	;

I think the following rule will do it for you (observe the '+' between 
"r" and "=BRANCH"):

public parse

      :  ( r+=BRANCH )* EOF ->  ^(ROOT $r*)
      ;


I hope that helps,

	Stefan Mätje


More information about the antlr-interest mailing list