|
Write a parser for the programming language J0! Your parser should only check for
syntactic correctness of the input. It is not yet necessary to construct an abstract
syntax tree. However, it is a good idea, to write your parser in a way such that
the return types of the parsing methods are always Tree . You can return
the value null for now. This makes it easier to add the tree construction
later. Here is a simple framework you can use for implementing your parser:
import java.io.*;
class Parser extends Scanner {
public Parser(InputStream in) {
super(in);
nextToken();
}
// accept a token or print an error, if another token was found
void accept(int token) {
if (this.token == token)
nextToken();
else {
error(tokenClass(token) + " expected, but " + tokenClass(this.token) + " found");
}
}
// ModuleDeclaration = "module" ident "{" { Declaration } "}"
Tree moduleDeclaration() {
accept(MODULE);
accept(IDENT);
accept(LBRACE);
while ((token != RBRACE) && (token != EOF))
declaration();
accept(RBRACE);
return null;
}
// Declaration = "void" ident "(" [ Formals ] ")" Block
// | Type ident ( ";" | "(" [ Formals ] ")" Block )
Tree declaration() {
// something is missing here
return null;
}
// some methods are missing here
}
abstract class Tree {} // please ignore this class
class ParserTest implements Tokens {
static public void main(String[] args) {
try {
Parser parser = new Parser(new FileInputStream(args[0]));
parser.moduleDeclaration();
System.out.println("no syntax errors in " + args[0]);
parser.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
|
|