3
votes

I was fiddling with the code for an ANSI C parser given here http://www.lysator.liu.se/c/ANSI-C-grammar-y.html and here http://www.lysator.liu.se/c/ANSI-C-grammar-l.html.

Unfortunately, the code isn't working - I modified it a bit to make it print a message upon successfully parsing an input program, but the message is never printed, even if the input program is in C with no syntax errors. I'd be glad if anyone can help me out here.

EDIT:

Just to clarify - I was only testing a publicly available lex + yacc program on a simple input C program that prints "Hello World!". The links are present above. Please just open them to see the code.

1
You might want to post some code, as it's pretty hard to tell what might be wrong without it. Also, take a look at How to Ask.jpw
Note that C parsers you can find on the net are typically not correct.user4815162342
Downvoters: Please give a reason for downvoting in the comments.Ricky
@jpw The lex program and the yacc program are there in the respective links. Please open the links.Ricky
With that grammar, you need to add symbol table handling to recognize type names properly.Chris Dodd

1 Answers

3
votes

It looks like the Yacc file just checks that your input program is correct (by printing an error if not), but it does nothing else.

Add some semantic actions (some code to execute when a rule has been matched), between curly braces just after the rules. See http://dinosaur.compilertools.net/bison/bison_4.html#SEC11

You can start by printing something when a rule is matched, but if you want to build a C compiler, you'll have to build an AST.

EDIT

You also need to add a main method which calls the parser. Just add

void main() {
    yyparse();
 }

at the end of the yacc file.

The parser will read the inputs from stdin. So, if you're using Linux or MacOSX, you can type

./parser < helloworld.c

or for Windows

parser < helloworld.c

Actually, the parser prints the input file if it is correct.