[antlr-interest] How to use an optional rule attribute in anaction?

Jim Idle jimi at temporal-wave.com
Tue Jun 26 13:25:03 PDT 2007


Hmm - I'll look at that, I think it probably SHOULD be initialized to
NULL, but perhaps I don't hae the label list or something (doubtful
though).

For now you could do this:

create_procedure 
@declarations
{
	ANTLR3_BOOLEAN haveNumber;
}
@init
{
	haveNumber = ANTLR3_FALSE;
}
:
          'CREATE' ('PROC' | 'PROCEDURE') procedure_name 
	( ';'number { $haveNumber = ANTLR3_TRUE; } )?
          {
              if ($haveNumber)
                  {
                      printf("Found number '%s'\n", $n.text->chars);
                      someFunction($n.text);
                  }
          }


But, now that I look at what you are doing, can't you do this:

    (';' n=number { someFunction($n.text->chars); })?

Jim

> -----Original Message-----
> From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-
> bounces at antlr.org] On Behalf Of troy runkel
> Sent: Tuesday, June 26, 2007 12:18 PM
> To: antlr-interest at antlr.org; trunkel at gmail.com
> Subject: Re: [antlr-interest] How to use an optional rule attribute in
> anaction?
> 
> > > -----Original Message-----
> > > From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-
> > > bounces at antlr.org] On Behalf Of troy runkel
> > > Sent: Tuesday, June 26, 2007 11:51 AM
> > > To: ANTLR mail-list
> > > Subject: [antlr-interest] How to use an optional rule attribute in
> an
> > > action?
> > >
> > > Greetings,
> > >
> > > I'm using ANTLR v3 with the C-target and have a situation like the
> > > following.  I have an optional rule called number and I want to
> access
> > > the text attribute of that rule if and only if the rule was
> applied.
> > > Using the C-target, $number is uninitialized if the rule wasn't
> > > applied.  Is there a way, in the action, to determine if
> $number.text
> > > is valid?
> > >
> >
> > create_procedure :
> >          'CREATE' ('PROC' | 'PROCEDURE') procedure_name ( ';'
> n=number
> > )?
> >          {
> >              if ($n != NULL)
> >                  {
> >                      printf("Found number '%s'\n", $n.text->chars);
> >                  someFunction($n.text);
> >                  }
> >          }
> >
> > Makes most sense to me.
> >
> > Jim
> 
> I tried that, but using the C-target the n variable will be
> uninitialized if the number rule was not applied.  Therefore, n will
> not be NULL but will instead be some random value.  In the Visual
> Studio 2005 debugger n is initialized to 0xcccccccc but that's not
> very helpful.  :-)
> 
> Troy Runkel


More information about the antlr-interest mailing list