KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > kawa > standard > constant_fold


1 package kawa.standard;
2 import kawa.lang.*;
3 import gnu.mapping.*;
4 import gnu.expr.*;
5
6 /** Implements the "constant-fold" transformer. */
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 JavaDoc 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 JavaDoc 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 JavaDoc func = checkConstant(aexp.getFunction(), tr);
36     if (! (func instanceof Procedure))
37       return exp;
38
39     // Not quite the same - checkConstant also looks up name in Environment,
40
// which seems a bit too dangerous for inlineIfConstant. FIXME.
41
// return aexp.inlineIfConstant((Procedure) func, tr.getMessages());
42

43     Expression[] args = aexp.getArgs();
44     int i = args.length;
45     Object JavaDoc[] vals = new Object JavaDoc[i];
46     while (--i >= 0)
47       {
48     Object JavaDoc 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 JavaDoc 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