user3107659
user3107659

Reputation: 35

ANTLR: Testing the equivalence of tagname in start and endtag

I have a problem building a grammar with ANTLR v3 using antlrworks-1.5.2-complete.
I am looking for a grammar rule representing an XML-element. The equivalence of the tagnames in start- and endtag must be tested (well-formedness).

In the article Parsing XML a solution of the Problem is given,
but I would prefer a simpler way as e.g. possible with Perl (RecDescent) or yacc/bison.

With the Perl module Parse::RecDescent the problem can be solved by a rule

element:  '<' name attributes '>' content '</' "$item[2]" '>'

the $item[2] carries the string, found by the symbol name (2. part of the production).

Does such a simple reference as $item[2] or $2 (in yacc) exist in ANTLR too?

Upvotes: 1

Views: 91

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170158

Does such a simple reference as $item[2] or $2 (in yacc) exist in ANTLR too?

No.

In ANTLR, one would validate this when walking the (parse) tree, or inside the grammar using a predicate:

element
 : '<' open=NAME attributes '>' content '</' close=NAME '>'
   {$open.text.equals($close.text)}?
 ;

attributes
 : (NAME '=' STRING)+
 ;

content
 : ...
 ;

NAME
 : 'a'..'z'+ // not complete, of course!
 ;

Upvotes: 1

Related Questions