Iterate over list tokens in rule actions
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Tuesday, May 25, 2004 10:35 AM

Hi, coming from yacc, I'm unfamiliar with the CfG nature of ANTLR. I'm currently having a problem with the star syntax denoting zero or more token matches. How can I iterate over all individual matches? In the following example, I only get one matched element for i2... // A (possibly-qualified) java identifier. We start with the first IDENT // and expand its name by adding dots and following IDENTS identifier : i1:IDENT ( DOT^ i2:IDENT )* { System.out.println("i1= " + i1.getText() + "; i2= " + (i2!=null?i2.getText():"")); } ; Thanks in advance & Best regards, Pieter Van Gorp http://ww   More>>

Hi,
coming from yacc, I'm unfamiliar with the CfG nature of ANTLR. I'm currently having a problem with the star syntax denoting zero or more token matches.


How can I iterate over all individual matches?

In the following example, I only get one matched element for i2...

			
// A (possibly-qualified) java identifier. We start with the first IDENT
// and expand its name by adding dots and following IDENTS
identifier
: i1:IDENT ( DOT^ i2:IDENT )* {
System.out.println("i1= " + i1.getText() + "; i2= " + (i2!=null?i2.getText():""));
}
;


Thanks in advance & Best regards,
Pieter Van Gorp
http://www.pietervangorp.com/    <<Less

Re: Iterate over list tokens in rule actions

Posted By:   Shawn_Gens  
Posted On:   Thursday, May 27, 2004 12:56 PM

The reason you only seem to match two items in this example is because you aren't taking advantage of ANTLR's ability to do embeded actions. All LL(k) grammars allow you to place actions anywhere in the grammar as opposed to LR grammars (like the ones in yacc) where you can only do actions after you have matched the entire rule.



using your existing grammar you could do the following




identifier :
i1:IDENT
{System.out.print(""i1= "" + i1.getText());
( DOT^ i2:IDENT
{System.out.print(""i2= "" + i2.getText());}
)*
;


Note that you will match exactly 1 i1 and some number of i2's (0 if there is no i2).

About | Sitemap | Contact