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.

Chapter 11: Frequently Asked Questions 113<br />

}<br />

char *snd = (yylex (), yylval);<br />

printf ("\"%s\", \"%s\"\n", fst, snd);<br />

return 0;<br />

If you compile and run this code, you get:<br />

$ flex -osplit-lines.c split-lines.l<br />

$ gcc -osplit-lines split-lines.c -ll<br />

$ printf ’one\ntwo\n’ | ./split-lines<br />

"one<br />

two", "two"<br />

this is because yytext is a buffer provided for reading in the action, but if you want to<br />

keep it, you have to duplicate it (e.g., using strdup). Note that the output may depend<br />

on how your implementation of Lex handles yytext. For instance, when given the Lex<br />

compatibility option ‘-l’ (which triggers the option ‘%array’) Flex generates a different<br />

behavior:<br />

$ flex -l -osplit-lines.c split-lines.l<br />

$ gcc -osplit-lines split-lines.c -ll<br />

$ printf ’one\ntwo\n’ | ./split-lines<br />

"two", "two"<br />

11.4 Implementing Gotos/Loops<br />

My simple calculator supports variables, assignments, and functions,<br />

but how can I implement gotos, or loops<br />

Although very pedagogical, the examples included in the document blur the distinction<br />

to make between the parser—whose job is to recover the structure of a text and to transmit<br />

it to subsequent modules of the program—and the processing (such as the execution) of this<br />

structure. This works well with so called straight line programs, i.e., precisely those that<br />

have a straightforward execution model: execute simple instructions one after the others.<br />

If you want a richer model, you will probably need to use the parser to construct a tree<br />

that does represent the structure it has recovered; this tree is usually called the abstract<br />

syntax tree, or AST for short. Then, walking through this tree, traversing it in various<br />

ways, will enable treatments such as its execution or its translation, which will result in an<br />

interpreter or a compiler.<br />

This topic is way beyond the scope of this manual, and the reader is invited to consult<br />

the dedicated literature.<br />

11.5 Multiple start-symbols<br />

I have several closely related grammars, and I would like to share their<br />

implementations. In fact, I could use a single grammar but with<br />

multiple entry points.<br />

Bison does not support multiple start-symbols, but there is a very simple means to<br />

simulate them. If foo and bar are the two pseudo start-symbols, then introduce two new<br />

tokens, say START_FOO and START_BAR, and use them as switches from the real start-symbol:

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

Saved successfully!

Ooh no, something went wrong!