Compilers Principles, Techniques, & Tools (purple dragon book) second edition exercise answers

Exercises for Section 3.5


Describe how to make the following modifications to the Lex program of Fig. 3.23:

  1. Add the keyword while.
  2. Change the comparison operators to be the C operators of that kind.
  3. Allow the underscore ( _ ) as an additional letter.
  4. ! Add a new pattern with token STRING. The pattern consists of a double­ quote ( " ) , any string of characters and a final double-quote. However, if a double-quote appears in the string, it must be escaped by preceding it with a backslash () , and therefore a backslash in the string must be represented by two backslashes. The lexical value, which is the string without the surrounding double-quotes, and with backslashes used to es.,. cape a character removed. Strings are to be installed in a table of strings.



Write a Lex program that copies a file, replacing each non­ empty sequence of white space by a single blank


Write a Lex program that copies a C program, replacing each instance of the keyword f loat by double.。

3.5.4 !

Write a Lex program that converts a file to "Pig latin." Specifically, assume the file is a sequence of words (groups . of letters) separated by whitespace. Every time you encounter a word:

  1. If the first letter is a consonant, move it to the end of the word and then add ay!
  2. If the first letter is a vowel, just add ay to the end of the word.

All nonletters are copied int act to the output.


3.5.5 !

In SQL, keywords and identifiers are case-insensitive. Write a Lex program that recognizes the keywords SELECT, FROM, and WHERE (in any combination of capital and lower-case letters) , and token ID, which for the purposes of this exercise you may take to be any sequence of letters and digits, beginning with a letter. You need not install identifiers in a symbol table, but tell how the "install" function would differ from that described for case-sensitive identifiers as in Fig. 3.23.