1 package ro.infoiasi.donald.compiler.parser; 2 3 import ro.infoiasi.donald.compiler.cfg.*; 4 import java.io.*; 5 import java.util.*; 6 import java.lang.reflect.Constructor ; 7 import java.lang.reflect.InvocationTargetException ; 8 9 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, boolean addStartProduction) 39 throws IOException, SpecParseException { 40 this(ParserSpec.load(parserSpecPath), addStartProduction); 41 } 42 43 public AbstractParser(String parserSpecPath) 44 throws IOException, SpecParseException { 45 this(ParserSpec.load(parserSpecPath), false); 46 } 47 48 public CFG getGrammar() { 49 return g; 50 } 51 52 public Lexer getLexer() { 53 return lexer; 54 } 55 56 public void setLexer(String className, String fileName) 57 throws ClassNotFoundException , 58 FileNotFoundException, 59 ClassCastException , 60 NoSuchMethodException , 61 InstantiationException , 62 IllegalAccessException { 63 setLexer(Class.forName(className), fileName); 64 } 65 66 public void setLexer(Class lexerClass, String fileName) 67 throws ClassNotFoundException , 68 FileNotFoundException, 69 ClassCastException , 70 NoSuchMethodException , 71 InstantiationException , 72 IllegalAccessException { 73 FileReader fileReader = new FileReader(fileName); 74 if (lexerClass.isInterface()) { 75 throw new ClassCastException (lexerClass+" is an interface"); 76 } 77 if (!Lexer.class.isAssignableFrom(lexerClass)) { 78 throw new ClassCastException (lexerClass+" does not implement the Lexer interface"); 79 } 80 try { 81 Constructor ctor = lexerClass.getConstructor(new Class [] {Reader.class}); 82 lexer = (Lexer)ctor.newInstance(new Object [] {fileReader}); 83 } catch (InvocationTargetException e) { 84 throw new RuntimeException (e.getCause()); 86 } 87 lexer.setTerminals(t); 88 } 89 90 abstract public void precompute(); 91 abstract public List parse() throws IOException, SyntaxError; 92 } 93 | Popular Tags |