title: ANTLR4 book, calculator exercise
body: <p>I am stuck at a very fundamental level with antlr. Going through 'The Definitive ANTLR 4 Reference' by Dr. Parr. In section 4.2, 'Building a Calculator Using a Visitor' the following grammar is listed:</p>
  
  <pre><code>grammar LabeledExpr; // rename to distinguish from Expr.g4
  
  prog:   stat+ ;
  
  stat:   expr NEWLINE                # printExpr
      |   ID '=' expr NEWLINE         # assign
      |   NEWLINE                     # blank
      ;
  
  expr:   expr op=('*'|'/') expr      # MulDiv
      |   expr op=('+'|'-') expr      # AddSub
      |   INT                         # int
      |   ID                          # id
      |   '(' expr ')'                # parens
      ;
  
  MUL :   '*' ; // assigns token name to '*' used above in grammar
  DIV :   '/' ;
  ADD :   '+' ;
  SUB :   '-' ;
  ID  :   [a-zA-Z]+ ;      // match identifiers
  INT :   [0-9]+ ;         // match integers
  NEWLINE:'\r'? '\n' ;     // return newlines to parser (is end-statement signal)
  WS  :   [ \t]+ -&gt; skip ; // toss out whitespace
  </code></pre>
  
  <p>I'm trying to add <code>clear</code> statement to the above, from the book:</p>
  
  <p>Before moving on, you might take a moment to try to extend this expression language  by  adding  a <code>clear</code> statement.  The <code>clear</code> command should clear out the <code>memory</code> map, and you’ll need a new alternative in rule <code>stat</code> to recognize it. Label the alternative with <code># clear</code> and then run <code>ANTLR</code> on the grammar to get the  augmented  visitor  interface.</p>
  
  <p>This is my attempt:</p>
  
  <pre><code>grammar LabeledExpr;
  
  prog:   stat+ ;
  
  stat:   expr NEWLINE          # printExpr
      |   ID '=' expr NEWLINE   # assign
      |   clear NEWLINE         # clearMem
      |   NEWLINE               # blank
      ;
  
  expr:   expr op=('*'|'/') expr   # MulDiv
      |   expr op=('+'|'-') expr   # AddSub
      |   INT                   # int
      |   ID                    # id
      |   '(' expr ')'          # parens
      ;
  
  clear:  CLEAR               
      ;
  
  MUL:    '*' ;   // assigns token name to '*' used above in grammar
  DIV:    '/' ;
  ADD:    '+' ;
  SUB:    '-' ;
  
  ID  :   [a-zA-Z]+ ;
  INT :   [0-9]+ ;
  NEWLINE: '\r'?'\n' ;
  WS  :   [ \t]+ -&gt; skip ;
  CLEAR:  'clear';
  </code></pre>
  
  <p>However, <code>visitClearMem</code> never gets called:</p>
  
  <pre><code>@Override
  public Integer visitClearMem(LabeledExprParser.ClearMemContext ctx) {
      String text = ctx.getText();
      if (text.equalsIgnoreCase("clear")) {
          memory.clear();
      }
      return 0;
  }
  </code></pre>