title: Using Antlr to get identifiers and function names
body: <p>I'm trying to use and understand AntLR, this is new to me. My purpose is to read a source code file written in C and extract from it the identifiers (variables and function names).</p>
  
  <p>In my C grammar (file <strong>C.g4</strong>) consider:</p>
  
  <pre><code>identifierList
      :   Identifier
      |   identifierList Comma Identifier
      ;
  Identifier
      :   IdentifierNondigit
          (   IdentifierNondigit
          |   Digit
          )*
      ;
  </code></pre>
  
  <p>After generation of parser and listener I create my own listener to the identifierList.</p>
  
  <p>Note that MyCListener class extends CBaseListener:</p>
  
  <pre><code>public class MyCListener extends CBaseListener {
  
  
  @Override
  public void enterIdentifierList(CParser.IdentifierListContext ctx) {
      List&lt;ParseTree&gt; children = ctx.children;
      for (ParseTree parseTree : children) {
          System.out.println(parseTree.getText());
      }
  
  }
  </code></pre>
  
  <p>Then I have this in main class:</p>
  
  <pre><code> String fileurl = "C:/example.c";
  
   CLexer lexer;
   try {
         lexer = new CLexer(new ANTLRFileStream(fileurl));
         CommonTokenStream tokens = new CommonTokenStream(lexer);
         CParser parser = new CParser(tokens);
  
         CParser.IdentifierListContext identifierContext = parser.identifierList();
         ParseTreeWalker walker = new ParseTreeWalker();
         MyCListener listener = new MyCListener();
         walker.walk(listener, identifierContext);
  
   } catch (IOException ex) {
         Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
   }
  </code></pre>
  
  <p>Where example.c is:</p>
  
  <pre><code>int main() {
  
  // this is C
  
   int i=0; // i is int
   /* double j=0.0;
      C
   */
  }
  </code></pre>
  
  <p>What am I doing wrong? 
  Maybe I didn't write MyCListener properly, or identifierList is not what I need to listen... Really don't know. I'm sorry, but I didn't even understand my output, why is there a lexical error?:</p>
  
  <pre><code>line 3:4 mismatched input '(' expecting {&lt;EOF&gt;, ','}
  main
  (
  )
  {
  int
  i
  =
  0
  ;
  }
  </code></pre>
  
  <p>As you see, I'm very confused about this. Can somebody help me ? Please...</p>