1 package kawa.standard; 2 import kawa.lang.*; 3 import gnu.mapping.*; 4 import gnu.expr.*; 5 6 7 8 public class constant_fold extends Syntax 9 { 10 public static final constant_fold constant_fold = new constant_fold(); 11 static { constant_fold.setName("constant-fold"); } 12 13 static Object checkConstant(Expression exp, Translator tr) 14 { 15 if (exp instanceof QuoteExp) 16 return ((QuoteExp) exp).getValue(); 17 if (exp instanceof ReferenceExp) 18 { 19 ReferenceExp rexp = (ReferenceExp) exp; 20 Declaration decl = rexp.getBinding(); 21 if (decl == null || decl.getFlag(Declaration.IS_UNKNOWN)) 22 return Environment.user().get(rexp.getName(), null); 23 else 24 return Declaration.followAliases(decl).getConstantValue(); 25 } 26 return null; 27 } 28 29 public Expression rewrite (Object obj, Translator tr) 30 { 31 Expression exp = tr.rewrite(obj); 32 if (! (exp instanceof ApplyExp)) 33 return exp; 34 ApplyExp aexp = (ApplyExp) exp; 35 Object func = checkConstant(aexp.getFunction(), tr); 36 if (! (func instanceof Procedure)) 37 return exp; 38 39 43 Expression[] args = aexp.getArgs(); 44 int i = args.length; 45 Object [] vals = new Object [i]; 46 while (--i >= 0) 47 { 48 Object val = checkConstant(args[i], tr); 49 if (val == null) 50 return exp; 51 vals[i] = val; 52 } 53 try 54 { 55 return new QuoteExp(((Procedure) func).applyN(vals)); 56 } 57 catch (Throwable ex) 58 { 59 exp = tr.syntaxError("caught exception in constant-fold:"); 60 tr.syntaxError(ex.toString()); 61 return exp; 62 } 63 } 64 } 65 | Popular Tags |