[antlr-interest] ANTLR3 AST construction with optionsandalternatives

David Holroyd dave at badgers-in-foil.co.uk
Mon Nov 13 12:24:52 PST 2006


On Mon, Nov 13, 2006 at 06:40:05PM +0000, Foolish Ewe wrote:
> I'm not sure about what the ANTLR folks call these things so just
> to be clear, if we have a rule like the one I originally suggested,
> b and c+ are what I'll call atributes.  I'm guessing that Dave
> refers to the + suffix as the cardinality of the attribute.

Yes.  (I hope it's the right term.)

> I wasn't sure, it isn't clear to me what the + suffix implies for
> attributes, my gut reaction was that it was intended for attributes
> that occur a variable number of times.  If + means one or more repetitions,
> like it does for parsing and lexing, and if (from your the remainder of 
> your reply)
> we can use '?' for zero or one times, does that mean we can use other 
> cardinalities,
> i.e.  '*' for zero or more times as well?   Are empty/uninitialized 
> attributes (assuming * or ?
> cardinality) omitted from the tree if they are listed in the right hand 
> side of the ->
> operator in an AST rule?

I took my cues from this page,

  http://www.antlr.org/wiki/display/ANTLR3/Tree+construction


Where I saw stuff like,

  compilationUnit
    :   packageDefinition? importDefinition* typeDefinition+
        -> ^(UNIT packageDefinition? importDefinition* typeDefinition*)
    ;

  ['packageDefinition' has a '?' on the left and on the right;
  'typeDefinition' doesn't match - maybe a typo, or doesn't matter?]

and

  compoundStatement
      :   lc='{' statement* '}' -> ^(SLIST[$lc] statement*)
      ;

  ['statement' has a '*' on the left and the right]

Now, to be honest, I don't know *why* I'm doing this, but following the
established pattern seems to work :)

It is the case that in the above compoundStatement example, if there are
zero 'statement' matches, then the result tree will just be an SLIST
node with no children (i.e. the appearence of 'statement*' on the r.h.s.
doesn't add anything to the result tree if there's nothing to add).


does that help?
dave


More information about the antlr-interest mailing list