1 package fri.patterns.interpreter.parsergenerator.semantics; 2 3 import java.lang.reflect.*; 4 import java.util.*; 5 import fri.patterns.interpreter.parsergenerator.syntax.Rule; 6 import fri.patterns.interpreter.parsergenerator.Semantic; 7 8 39 40 public abstract class ReflectSemantic implements Semantic 41 { 42 private List ranges; 43 44 51 public Object doSemantic(Rule rule, List inputTokens, List ranges) { 52 this.ranges = ranges; 53 54 String nonterminal = rule.getNonterminal(); 55 56 Class [] types = new Class [inputTokens.size()]; 57 for (int i = 0; i < types.length; i++) 58 types[i] = Object .class; 59 60 Method m = null; 61 try { 62 m = getClass().getMethod(nonterminal, types); 63 } 64 catch (Exception e) { 65 return fallback(rule, inputTokens, ranges); 67 } 68 69 Object [] args = new Object [inputTokens.size()]; 70 inputTokens.toArray(args); 71 72 if (m != null) { 73 try { 74 m.setAccessible(true); Object o = m.invoke(this, args); 76 return o; 77 } 78 catch (IllegalAccessException e) { 79 e.printStackTrace(); 80 } 81 catch (IllegalArgumentException e) { 82 e.printStackTrace(); 83 } 84 catch (InvocationTargetException e) { 85 e.printStackTrace(); 86 throw new RuntimeException ("ERROR in ReflectSemantic : "+e.getTargetException().toString()); 87 } 88 } 89 return null; 90 } 91 92 99 protected Object fallback(Rule rule, List inputTokens, List ranges) { 100 if (inputTokens.size() == 1) return inputTokens.get(0); 102 103 if (inputTokens.size() >= 2 && inputTokens.get(0) instanceof List && rule.getNonterminal().equals(rule.getRightSymbol(0))) { 105 List list = (List) inputTokens.get(0); 106 for (int i = 1; i < inputTokens.size(); i++) 107 list.add(inputTokens.get(i)); 108 109 return list; 110 } 111 112 return inputTokens; 113 } 114 115 116 117 protected List getRanges() { 118 return ranges; 119 } 120 121 } 122 | Popular Tags |