01: package ro.infoiasi.donald.compiler.parser;
02:
03: import ro.infoiasi.donald.compiler.cfg.*;
04: import java.io.*;
05: import java.util.*;
06: import java.lang.reflect.Constructor;
07: import java.lang.reflect.InvocationTargetException;
08:
09: public abstract class AbstractParser implements Parser {
10: protected ParserSpec spec;
11: protected CFG g;
12: protected NonTerminals v;
13: protected Terminals t;
14: protected NonTerminal s;
15: protected Productions p;
16: protected Production sp;
17:
18: protected Lexer lexer;
19:
20: protected boolean DEBUG = false;
21:
22: public AbstractParser(ParserSpec spec, boolean addStartProduction) {
23: this .spec = spec;
24: g = spec.getGrammar();
25: if (addStartProduction) {
26: sp = g.addStartProduction();
27: }
28: v = g.getNonTerminals();
29: t = g.getTerminals();
30: s = g.getStartSymbol();
31: p = g.getProductions();
32: }
33:
34: public AbstractParser(ParserSpec spec) {
35: this (spec, false);
36: }
37:
38: public AbstractParser(String parserSpecPath,
39: boolean addStartProduction) throws IOException,
40: SpecParseException {
41: this (ParserSpec.load(parserSpecPath), addStartProduction);
42: }
43:
44: public AbstractParser(String parserSpecPath) throws IOException,
45: SpecParseException {
46: this (ParserSpec.load(parserSpecPath), false);
47: }
48:
49: public CFG getGrammar() {
50: return g;
51: }
52:
53: public Lexer getLexer() {
54: return lexer;
55: }
56:
57: public void setLexer(String className, String fileName)
58: throws ClassNotFoundException, FileNotFoundException,
59: ClassCastException, NoSuchMethodException,
60: InstantiationException, IllegalAccessException {
61: setLexer(Class.forName(className), fileName);
62: }
63:
64: public void setLexer(Class lexerClass, String fileName)
65: throws ClassNotFoundException, FileNotFoundException,
66: ClassCastException, NoSuchMethodException,
67: InstantiationException, IllegalAccessException {
68: FileReader fileReader = new FileReader(fileName);
69: if (lexerClass.isInterface()) {
70: throw new ClassCastException(lexerClass
71: + " is an interface");
72: }
73: if (!Lexer.class.isAssignableFrom(lexerClass)) {
74: throw new ClassCastException(lexerClass
75: + " does not implement the Lexer interface");
76: }
77: try {
78: Constructor ctor = lexerClass
79: .getConstructor(new Class[] { Reader.class });
80: lexer = (Lexer) ctor
81: .newInstance(new Object[] { fileReader });
82: } catch (InvocationTargetException e) {
83: // the constructor has thrown an exception, tha was wraped as a Invoc...
84: throw new RuntimeException(e.getCause());
85: }
86: lexer.setTerminals(t);
87: }
88:
89: abstract public void precompute();
90:
91: abstract public List parse() throws IOException, SyntaxError;
92: }
|