Question

I am trying to parse a very simple C file using the antlr v4 grammar found at https://github.com/antlr/grammars-v4. The file looks like this:

#include <stdio.h>
int main()
{
  printf("hello world!");
  return 0;
}

I am trying to parse the file like this:

public void parse(FileInputStream myFile) throws IOException {
  ANTLRInputStream source = new ANTLRInputStream(myFile);
  CLexer lexer = new CLexer(source);
  CommonTokenStream stream = new CommonTokenStream(lexer);
  CParser parser = new CParser(stream);
  ParseTree tree = parser.primaryExpression();
  ParseTreeWalker.DEFAULT.walk(new MyParseListener(), tree);
}

As i am trying to parse it i will get the error.

line 1:0 token recognition error at: '#i'

Is there another step i need to do to handle preprocessing? Is the C grammar incomplete?

Was it helpful?

Solution

The grammar provided does not support #include directives as far as I can see in the current committed version.

In fact the #include directive is not part of the C grammar as such, and therefor it is not treated typically by a compiler but by a preprocessor

Definition of the C preprocessor

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top