简体   繁体   中英

C Parser using lex and yacc

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM