Upload
bibin-raj-b-s
View
218
Download
0
Embed Size (px)
DESCRIPTION
A super file
Citation preview
Computer Science 332
Compiler Construction
Parser Generators(Supercedes 4.9)
Parser Generators A.k.a. parser compilers, compiler compilers
Uses LALR method to convert grammar to parser saves us a lot of work!
Basic idea:
LALRGrammar Parser GeneratorParsing Program(in C or Java)
Detect and reportconflicts(shift/reduce, reduce/reduce)
Build sets of LR(1)items
Build DFABuild parse table
Parser Generators Basic idea: Annotate RHS of rules with method calls typically, code that builds parse tree
Classic version is yacc (Yet Another Compiler Compiler), which outputs C.
Modern version is bison. We'll use (J)CUP: Java-Based Constructor of Useful Parsers:
http://www.cs.princeton.edu/~appel/modern/java/CUP
CUP : Grammar E.g, expression grammar
expr expr + expr | expr * expr | ( expr ) | number
In CUP format:import java_cup.runtime.*;
terminal PLUS, TIMES, LPAR, RPARterminal Integer NUMBER
non terminal Integer expr
expr ::= expr PLUS expr | expr TIMES expr | LPAR expr RPAR | NUMBER
CUP: Parse Actions
expr ::= expr:e1 PLUS expr:e2 {: RESULT = new Integer(e1.intValue()+ e2.intValue(); :}
| expr:e1 TIMES expr:e2 {: RESULT = new Integer(e1.intValue() * e2.intValue(); :}
| LPAR expr:e RPAR {: RESULT = e; :} | NUMBER:n {: RESULT = n; :}
CUP: Precedenceimport java_cup.runtime.*;
terminal PLUS, TIMES, LPAR, RPAR;terminal Integer NUMBER
non terminal Integer expr;
precedence left PLUS;precedence left TIMES;
expr ::= expr PLUS expr | expr TIMES expr | LPAR expr RPAR | NUMBER;
CUP: Working with Jflex, main()
.cup grammar JCup
parser.javasym.java
javac javac
sym.class parser.class
public static final int PLUS = 9;public static final int LPAR = 2;// etc.
public parser(Scanner s) { // ...}
CUP: Working with Jflex, main()
.flex file JFlex
Yylex.java
javac
Yylex.class
class Yylex implements Scanner { // ...}
"+" {return(sym.PLUS); }"(" {return(sym.LPAR); }
CUP: Working with Jflex, main()public class ExprParser {
public ExprParser(String filename) {
java.io.InputStream inp;
try {inp=new java.io.FileInputStream(filename);
} catch (java.io.FileNotFoundException e) { throw new Error("File not found: " + filename);
} parser parser_obj = new parser(new Yylex(inp));
try { parser_obj.parse(); } catch // blah blah blah }}