[antlr-interest] Parser rule writing question

Alexey Demakov demakov at ispras.ru
Sun Sep 11 23:44:32 PDT 2005


Parser rule writing questionHi,

You can use LT(k) for k-th next token and LA(k) for type of k-th next token:

relationalOperator  returns [String rel=null]
    : { rel = LT(1).getText(); }
      ( ASSIGNEQUAL | NOTEQUAL1 | NOTEQUAL2 )
    ; 

Regards,
Alexey

-----
Alexey Demakov
TreeDL: Tree Description Language: http://treedl.sourceforge.net
RedVerst Group: http://www.unitesk.com


  ----- Original Message ----- 
  From: Nagesh, Harsha 
  To: 'antlr-interest at antlr.org' 
  Sent: Saturday, September 10, 2005 10:38 PM
  Subject: [antlr-interest] Parser rule writing question




  Hi, 

     I am trying to write some transformer for which I have a rule as below 

  mainRule 
     : 
     expr relationalOperator expr 

  relationalOperator 
      : 
        ASSIGNEQUAL | NOTEQUAL1 | NOTEQUAL2 
      ; 

  where ASSIGNEQUAL, NOTEQUAL1 and NOTEQUAL2 are defined as lexical tokens in the lexers 

  ASSIGNEQUAL : '=' ; 
  NOTEQUAL1 : "<>" ; 
  NOTEQUAL2 : "!=" ; 

  I want to change the relationalOperator to return back a string to the calling rule MainRule 
  where I want to append the operator to a string that I am constructing. One way that I could achieve 
  this was by changing the rule as 

  relationalOperator1 returns [string rl=""] 
      : 
        rel1:ASSIGNEQUAL { rl = (rel1.getText());} | rel2:NOTEQUAL1 { rl = (rel2.getText());} 
        | rel3:NOTEQUAL2 { rl = (rel3.getText());} 
      ; 

  But this is quite dirty. When I inspected the generated code by antlr, I am thinking that there should 
  Be a way to specify something on the lines 
    
  relationalOperator1 returns [string rl=""] 
      : 
        rel:ASSIGNEQUAL | rel:NOTEQUAL1 | rel:NOTEQUAL2 
        { rl = (rel.getText());} 
      ; 

  Can anybody tell me if this is possible as this is much more elegant than having to write rules for 
  Every terminal in a rule ? My intuition says this can be done, but I could not get it to work as 
  Antlr complained of rel already ebing used, etc. The generated code has this in different parts of the 
  switch case, so I am not sure why this is a problem. 

  The second issue is 
  - If I turn the buildAST=true and generate Csharp code, the generated code has an unreachable 
  Statement (related to the AST). How can I fix it ? 

  Thanks, 
  Harsha 





  ==============================================================================
  Please access the attached hyperlink for an important electronic communications disclaimer: 

  http://www.csfb.com/legal_terms/disclaimer_external_email.shtml

  ==============================================================================

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


More information about the antlr-interest mailing list