next up previous contents
Next: 3 Parsing Up: 2 Lexical Analysis Previous: 2.3 Converting a Regular   Contents

2.4 Case Study: The Calculator Scanner

As a running example for this and the subsequent sections, we will use a simple interpreter for a calculator written in Scala.

Scala requires the Java runtime engine. If you don't have Java on your PC, you need to download Java SE 7 JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html. Then, you can install Scala from http://www.scala-lang.org/download/.

On a Unix or OS X system, you do:

  1. download the file http://lambda.uta.edu/cse5317/calc.tgz
  2. open a command shell and execute tar xfz calc.tgz to extract the files
  3. execute: cd calc; ./build
  4. run the calculator using ./run
On Windows, you do:
  1. download and unzip the file http://lambda.uta.edu/cse5317/calc.zip
  2. on the Windows Command Prompt, go to the calc directory and execute build to compile the programs
  3. execute run to run the calculator.
Using the calculator, you can calculate arithmetic expressions, such as 2*(3+8);, you can assign values to variables, such as x:=3+4;, you can reference variables by name, such as x+3;, you can define recursive functions interactively, such as:

define f(n) = if n=0 then 1 else n*f(n-1);

and you can call them using f(5);, etc. You exit using quit;.

The source files of the calculator example are given in http://lambda.uta.edu/cse5317/calc/src/edu/uta/calc/. Each of these files will be explained in detail later, but now we are ready to look at the scanner only, given in calc.lex. The tokens, such as sym.INT, are imported from calc.cup and will be explained in the next section. For now, just assume that these are different constants (integers). The order of lines is important in some cases: if we put the rule for {ID} before the keywords, then the keywords will never be recognized (this is the consequence of the rule priority law). The lexical constructs that need to be skipped, such as comments and whitespaces, should never return (we must return only when we find a complete token).


next up previous contents
Next: 3 Parsing Up: 2 Lexical Analysis Previous: 2.3 Converting a Regular   Contents
2015-01-20