import
[org.ibex.xt.git] / src / org / ibex / xml / JSRewriter.java
1 package org.ibex.xml;
2 import org.ibex.js.*;
3 import org.ibex.util.*;
4 import org.ibex.io.*;
5 import java.io.*;
6 import java.net.*;
7 import java.util.*;
8
9 public class JSRewriter extends XML.Node.Stream {
10
11     private XML.Node.Stream in;
12     private JSScope scope;
13
14     public JSRewriter(XML.Node.Stream in) { this.in = in; this.scope = new JSScope(null); }
15     public JSRewriter(XML.Node.Stream in, JSScope scope) { this.in = in; this.scope = scope; }
16
17     public boolean _next(int level, XML.Node n) {
18         if (!in.next(level, n)) return false;
19         if (n.cdata != null) n.cdata = eval(n.cdata);
20         else for(int i=1; i<n.numattrs; i+=2) n.attrs[i] = eval(n.attrs[i]);
21         return true;
22     }
23
24     private String eval(String s) {
25         if (s == null) return null;
26         StringBuffer ret = new StringBuffer();
27         while(s.indexOf("$[") != -1) {
28             ret.append(s.substring(0, s.indexOf("$[")));
29             s = s.substring(s.indexOf("$[")+2);
30             String s2 = "return (" + s.substring(0, s.indexOf(']')) + ");\n";
31             System.err.println("evaluating " + s2);
32             try {
33                 JS js = JS.cloneWithNewParentScope(JS.fromReader("input", 0, new StringReader(s2)), scope);
34                 Object r = js.call(null, null, null, null, 0);
35                 System.err.println("output was " + r);
36                 ret.append(r == null ? "null" : r.toString());
37             } catch (Exception e) {
38                 e.printStackTrace();
39                 ret.append(e.toString());
40             }
41             s = s.substring(s.indexOf(']') + 1);
42         }
43         ret.append(s);
44         return ret.toString();
45     }
46 }
47
48