[antlr-interest] Newby - How to find rule context in the AST

Richard Clark rdclark at gmail.com
Sun May 27 09:48:35 PDT 2007


On 5/27/07, Harris, Tobin <tobin at tobinharris.com> wrote:


My top grammar rule looks a bit like this
>
> uriformat = scheme '://' credentials? host path? query?
> [snip]
>
> The problem is, I want to be able to interrogate the tree to find out if,
> for example, the [credentials] were parsed, and then loop through the
> sub-nodes (username, password etc).
>

It sounds like a tree is overkill for your problem. Trees are great if you
need to rearrange language elements after parsing (e.g. "1 + 2" needs to be
"(+ 1 2)"), but can get in the way for simple languages.

Assuming ANTLR v3, you could write something where the parse rules inject
their results into  a data structure (e.g. a hash table) and returns that
structure at the end.

(I'm not a C# programmer, some of the syntax may be off. The $xxx references
are ANTLR v3 syntax.)

urlformat returns [Hashtable parsedUrl ]
    scope { Hashtable url; } // declare a shared variable
    @init{ $urlformat::url = new Hashtable(); }
     : scheme '://' credentials? host path? query?
       { $parsedUrl = $urlformat::url; }
     ;

scheme
    scope urlformat;
    : ID { $urlformat::url.Add("scope", $ID.text); }
    ;

// and so on, having each parser rule stuff results into $urlformat::url...

ID: ('A'..'Z' | 'a..z')+;

// --- end of example ---

Does this help?

...Richard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20070527/63379853/attachment.html 


More information about the antlr-interest mailing list