06.01.2015 Views

Manual

Manual

Manual

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

28 Bison 2.3<br />

#include <br />

/* Called by yyparse on error. */<br />

void<br />

yyerror (char const *s)<br />

{<br />

fprintf (stderr, "%s\n", s);<br />

}<br />

After yyerror returns, the Bison parser may recover from the error and continue parsing<br />

if the grammar contains a suitable error rule (see Chapter 6 [Error Recovery], page 83).<br />

Otherwise, yyparse returns nonzero. We have not written any error rules in this example,<br />

so any invalid input will cause the calculator program to exit. This is not clean behavior<br />

for a real calculator, but it is adequate for the first example.<br />

2.1.6 Running Bison to Make the Parser<br />

Before running Bison to produce a parser, we need to decide how to arrange all the source<br />

code in one or more source files. For such a simple example, the easiest thing is to put<br />

everything in one file. The definitions of yylex, yyerror and main go at the end, in the<br />

epilogue of the file (see Section 1.9 [The Overall Layout of a Bison Grammar], page 22).<br />

For a large project, you would probably have several source files, and use make to arrange<br />

to recompile them.<br />

With all the source in a single file, you use the following command to convert it into a<br />

parser file:<br />

bison file.y<br />

In this example the file was called ‘rpcalc.y’ (for “Reverse Polish calculator”). Bison<br />

produces a file named ‘file.tab.c’, removing the ‘.y’ from the original file name. The<br />

file output by Bison contains the source code for yyparse. The additional functions in the<br />

input file (yylex, yyerror and main) are copied verbatim to the output.<br />

2.1.7 Compiling the Parser File<br />

Here is how to compile and run the parser file:<br />

# List files in current directory.<br />

$ ls<br />

rpcalc.tab.c rpcalc.y<br />

# Compile the Bison parser.<br />

# ‘-lm’ tells compiler to search math library for pow.<br />

$ cc -lm -o rpcalc rpcalc.tab.c<br />

# List files again.<br />

$ ls<br />

rpcalc rpcalc.tab.c rpcalc.y<br />

The file ‘rpcalc’ now contains the executable code. Here is an example session using<br />

rpcalc.<br />

$ rpcalc

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!