



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




1.0 Initial release.
You will implement a lexer for MiniJava, a subset of the Java programming language you have already seen in MP3. After completing this MP, you should understand how to implement a practical lexer using a lexer generator tool such as ocamllex.
You should also gain a sense of appreciation for the availability of lexer generators, instead of having to code a lexer completely from scratch. Just look at “student.ml” after you finish the MP!
Collaboration in two-person groups is allowed, under the same terms as for MP3. You do not have to stay in the same group, however.
4.1 Overview of Lexical Analysis (Lexing)
Recall from lecture that the process of transforming raw program code (i.e., as ASCII or Unicode text) into an abstract syntax tree (AST) has two parts. First, the lexical analyzer (lexer) scans the text of the program and converts the text into a sequence of tokens, usually as values of a user-defined disjoint datatype. These tokens are then fed into the parser, which builds the AST.
Note that it is not the job of the lexer to check for correct syntax—this is done by the parser. In fact, our lexer will accept and correctly tokenize strings such as “if if == if if else”, which are not valid MiniJava programs.
4.2 Lexer Generators
The tokens of a programming language are specified using regular expressions, and thus the lexing process involves a great deal of regular-expression matching. It would be tedious to take the specification for the tokens of our language, convert the regular expressions to a DFA, and then implement the DFA in code to actually scan the text.
Instead, most languages come with tools that automate much of the process of implementing a lexer in those lan- guages. To implement a lexer with these tools, you simply need to define the lexing behavior in the tool’s specification language. The tool will then compile your specification into source code for an actual lexer that you can use.
In this MP, we will use a tool called ocamllex to build our lexer.
ocamllex is documented here:
http://caml.inria.fr/pub/docs/manual-ocaml/manual026.html
What follows below is only the short version. If something doesn’t make sense, or you need more details, consult the link above. You will need to become especially familiar with ocamllex’s regular expression syntax.
ocamllex’s lexer specification is slightly reminiscent of an OCaml match statement:
rule myrule = parse | regex1 { action1 } | regex2 { action2 } ...
where rule and parse are required words, but myrule can be any OCaml identifier (as long as it starts with a lower-case letter). By the way, even though ocamllex uses the word “parse,” it is a misnomer; ocamllex generates lexers, not parsers.
When this specification is compiled, it creates a function called myrule that does the lexing. Whenever myrule finds something that matches regex1, it consumes that part of the input and returns the result of evaluating the expression action1. In our code, the lexing function should return the token it finds. The token type is described in the problem description below, and will also be included in file mp4common.mli.
The syntax and meaning of regular expressions are given in the ocamllex manual, and were described in Lecture 6.
An “action” is any expression of type token, giving the token to be returned when the corresponding regular ex- pression is matched. For example, if the action is { LSHIFT }, the lexer will return the LSHIFT token. Within an action, you may refer to the variable lexbuf, which represents the part of the input remaining after the token is removed. Thus, if you simply want to ignore the token—as you might want to do, for example, with comments—the action would be myrule lexbuf, meaning scan the remaining input and return whatever token it returns.
To bind part of an expression to a variable which you can use in the action, use the as keyword. For example:
| ’+’ (_* as s) ’+’ { s }
recognizes strings surrounded by ’+’, and returns the characters inside.
Here is a quick example:
rule tokenize = parse | [’ ’ ’\t’ ’\n’] { tokenize lexbuf } | "<<" { LSHIFT } | ([’x’ ’y’ ’z’]+ as s) { IDENTIFIER s } | _ { failwith ("Illegal character") }
The function tokenize matches the following: (1) a single whitespace character; it ignores it and returns the token obtained from the remainder of the input, which may also begin with whitespace that will be ignored similarly; or (2) a left-shift operator; it returns the LSHIFT token; or (3) a sequence of one or more of the characters x, y, and z; it returns the IDENTIFIER token constructed from the matched sequence. In all other cases, it throws an exception.
You can also define multiple lexing functions—see the online documentation and lecture notes for more details (they are referred to as “entrypoints”). Then from the action of one rule, you can call a different lexing function. Think of the lexer on the whole as being a big state machine, where you can change lexing behaviors based on the state you
Table 1: MiniJava token constructors. Token Constructor abstract ABSTRACT boolean BOOLEAN break BREAK byte BYTE case CASE catch CATCH char CHAR class CLASS const CONST continue CONTINUE default DEFAULT do DO double DOUBLE else ELSE extends EXTENDS final FINAL finally FINALLY float FLOAT for FOR goto GOTO if IF implements IMPLEMENTS import IMPORT instanceof INSTANCEOF int INT interface INTERFACE long LONG native NATIVE new NEW public PUBLIC package PACKAGE private PRIVATE protected PROTECTED return RETURN short SHORT static STATIC strictfp STRICTFP switch SWITCH synchronized SYNCHRONIZED this THIS throw THROW throws THROWS transient TRANSIENT try TRY void VOID volatile VOLATILE while WHILE
Token Constructor null NULL LITERAL ( LPAREN ) RPAREN { LBRACE } RBRACE [ LBRACK ] RBRACK ; SEMICOLON , COMMA
. DOT = EQ > GT < LT ! NOT ˜ COMP ? QUESTION : COLON == EQEQ <= LTEQ >= GTEQ != NOTEQ && ANDAND || OROR ++ PLUSPLUS -- MINUSMINUS
There are token categories for integers, booleans, strings, and floats, specifically: INTEGER LITERAL of int, BOOLEAN LITERAL of boolean, STRING LITERAL of string, and FLOAT LITERAL of float. There is no token for comments—because comments don’t produce a token—but you will need to recognize and discard them, as we did with whitespace in the example above.
There is a token constructor FLOAT LITERAL that takes a float as an argument. (In real Java, the tokens we are describing are double literals, but in our version of Java we only have the float type, so we are omitting the “f” that is used in Java to make a float literal.) You may use float of string : string -> float to convert strings to floats.