checkpoint
[sbp.git] / src / edu / berkeley / sbp / meta / MetaGrammar.java
1 package edu.berkeley.sbp.meta;
2 import edu.berkeley.sbp.util.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.misc.*;
6 import edu.berkeley.sbp.bind.*;
7 import java.util.*;
8 import java.lang.annotation.*;
9 import java.lang.reflect.*;
10 import java.io.*;
11
12 public class MetaGrammar {
13     
14     public static void main(String[] args) throws Exception {
15         if (args.length != 2) {
16             System.err.println("usage: java " + MetaGrammar.class.getName() + " grammarfile.g com.yourdomain.package.ClassName");
17             System.exit(-1);
18         }
19         String className   = args[1].substring(args[1].lastIndexOf('.')+1);
20         String packageName = args[1].substring(0, args[1].lastIndexOf('.'));
21         String fileName    = packageName.replace('.', '/') + "/" + className + ".java";
22
23         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
24         StringBuffer out = new StringBuffer();
25
26         boolean skip = false;
27         for(String s = br.readLine(); s != null; s = br.readLine()) {
28             if (s.indexOf("DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) skip = true;
29             if (s.indexOf("DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED") != -1 && s.indexOf("\"")==-1) break;
30             if (!skip) out.append(s+"\n");
31         }
32
33         out.append("\n        // DO NOT EDIT STUFF BELOW: IT IS AUTOMATICALLY GENERATED\n");
34
35         Tree t = MetaGrammarTree.meta;
36         Union u = MetaGrammar.make(t, "s");
37
38         System.err.println();
39         System.err.println("== parsing with parsed grammar =================================================================================");
40         t = new CharParser((Union)u).parse(new FileInputStream(args[0])).expand1();
41         System.out.println(t.toPrettyString());
42
43         t.toJava(out);
44         out.append("\n        // DO NOT EDIT STUFF ABOVE: IT IS AUTOMATICALLY GENERATED\n");
45
46         for(String s = br.readLine(); s != null; s = br.readLine()) out.append(s+"\n");
47         br.close();
48
49         OutputStream os = new FileOutputStream(fileName);
50         PrintWriter p = new PrintWriter(new OutputStreamWriter(os));
51         p.println(out.toString());
52         p.flush();
53         os.close();
54     }
55    
56     public static class TreeBindable {
57
58         private Bindable _bindable;
59         public TreeBindable(Object o) { this(Bindable.create(o)); }
60         public TreeBindable(Bindable b) { this._bindable = b; }
61
62         private int[] buildSequence(Production p) {
63             Annotation[][] annotations = _bindable.getArgAnnotations();
64             Class[]        types       = _bindable.getArgTypes();
65             String[]       names       = _bindable.getArgNames();
66             String name                = _bindable.getSimpleName();
67             int len                    = annotations.length;
68             int ofs                    = 0;
69             bind.arg[] argtags  = new bind.arg[len];
70             for(int i=0; i<names.length; i++)
71                 for(Annotation a : annotations[i+ofs])
72                     if (a instanceof bind.arg)
73                         argtags[i+ofs] = (bind.arg)a;
74             return TreeBindable.this.buildSequence(p, names, argtags, types);
75         }
76
77         public String  getName()   { return _bindable.getSimpleName(); }
78         public bind    getBind()   { return (bind)_bindable.getAnnotation(bind.class); }
79         public bind.as getBindAs() { return (bind.as)_bindable.getAnnotation(bind.as.class); }
80         public String  toString()  { return _bindable.getSimpleName(); }
81         public boolean isRaw()     { return _bindable.isAnnotationPresent(bind.raw.class); }
82
83         public boolean isCompatible(Production p) {
84             bind.as t = getBindAs();
85             bind b = getBind();
86
87             if (t != null &&
88                 (t.value().equals(p.tag)))
89                 return buildSequence(p)!=null;
90
91             if (t != null &&
92                 ((t.value().equals("") && getName().equals(p.tag))))
93                 return buildSequence(p)!=null;
94             if (b != null && getName().equals(p.tag))
95                 return buildSequence(p)!=null;
96
97             if (t != null &&
98                 (t.value().equals(p.tag)))
99                 return buildSequence(p)!=null;
100             if (t != null &&
101                 ((t.value().equals("") && getName().equals(p.tag))))
102                 return buildSequence(p)!=null;
103             if (b != null && getName().equals(p.tag))
104                 return buildSequence(p)!=null;
105
106             return false;
107         }
108
109         private int[] buildSequence(Production p, String[] names, bind.arg[] argtags, Class[] types) {
110             int argTagged = 0;
111             boolean hasloc = types.length>0 && types[0]==Input.Region.class;
112             for(int i=0; i<argtags.length; i++) {
113                 if (i==0 && types[0]==Input.Region.class) continue;
114                 if (argtags[i] != null)
115                     argTagged++;
116             }
117             int numNames = names.length;
118             if (hasloc) numNames--;
119
120             // FIXME: can be smarter here
121             if (argTagged==p.count) {
122                 int[] ret = new int[argtags.length];
123                 int j = 0;
124                 for(int i=0; i<argtags.length; i++) {
125                     if (i==0 && types[0]==Input.Region.class) continue;
126                     if (argtags[i]==null) continue;
127                     if (argtags[i].value().equals(""))
128                         ret[i] = j++;
129                     else {
130                         ret[i] = -1;
131                         for(int k=0; k<names.length; k++)
132                             if (argtags[i].value().equals(names[k])){
133                                 ret[i] = k;
134                                 break;
135                             }
136                         if (ret[i]==-1) return null;
137                     }
138                 }
139                 return ret;
140             } else if (numNames==p.count) {
141                 int[] ret = new int[p.count];
142                 for(int i=0; i<p.count; i++) ret[i] = i+(hasloc?1:0);
143                 return ret;
144             } else {
145                 return null;
146             }
147         }
148         public Sequence makeSequence(final Production p) {
149
150             if (_bindable.getArgTypes().length > 0 &&
151                 _bindable.getArgTypes()[0] == Input.Region.class) {
152                 Functor<Input.Region,Object> func = new Functor<Input.Region,Object>() {
153                     public Object invoke(final Input.Region region) {
154                         return 
155                         new TreeBindableReducer(buildSequence(p),
156                                                 _bindable,
157                                                 isRaw()) {
158                             public Object invoke(Iterable<Tree<Object>> t) {
159                                 if (_israw) return _bindable.impose(new Object[] { t });
160                                 ArrayList ret = new ArrayList();
161                                 ret.add(region);
162                                 for(Tree tc : t) {
163                                     if (tc.head() != null && tc.head() instanceof Functor)
164                                         ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
165                                     else if (tc.numChildren() == 0)
166                                         ret.add(tc.head());
167                                     else {
168                                         System.err.println("FIXME: don't know what to do about " + tc);
169                                         ret.add(null);
170                                     }
171                                 }
172                                 Object[] o = (Object[])ret.toArray(new Object[0]);
173                                 int max = 0;
174                                 for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
175                                 Object[] o2 = new Object[max+2];
176                                 for(int i=0; i<o.length; i++) o2[map[i]+1] = o[i];
177                                 o2[0] = region;
178                                 return _bindable.impose(o2);
179                             }
180                         };
181                     }
182                 };
183                 return Sequence.regionRewritingSequence(func,
184                                                         p.elements,
185                                                         p.drops);
186             }
187
188             return Sequence.rewritingSequence(new TreeBindableReducer(buildSequence(p),
189                                                                       _bindable,
190                                                                       isRaw()),
191                                               p.elements,
192                                               p.drops);
193         }
194
195     }
196
197     public static class TreeBindableReducer implements Tree.TreeFunctor<Object,Object>, ToJava {
198          int[] map;
199          Bindable _bindable;
200          boolean _israw;
201
202         public void toJava(StringBuffer sb) {
203             sb.append("new MetaGrammar.TreeBindableReducer(new int[] {");
204             for(int i=0; i<map.length; i++) sb.append((i+"")+(i<map.length-1 ? "," : ""));
205             sb.append("}, ");
206             _bindable.toJava(sb);
207             sb.append(", ");
208             sb.append(_israw ? "true" : "false");
209             sb.append(")");
210         }
211         
212         public TreeBindableReducer(int[] map, Bindable b, boolean raw) {
213             this.map = map;
214             this._bindable = b;
215             this._israw = raw;
216         }
217         public String toString() { return "reducer-"+_bindable.toString(); }
218         public Object invoke(Iterable<Tree<Object>> t) {
219             if (_israw) return _bindable.impose(new Object[] { t });
220             ArrayList ret = new ArrayList();
221             for(Tree tc : t) {
222                 if (tc.head() != null && tc.head() instanceof Functor)
223                     ret.add(((Tree.TreeFunctor<Object,Object>)tc.head()).invoke(tc.children()));
224                 else if (tc.numChildren() == 0)
225                     ret.add(tc.head());
226                 else {
227                     System.err.println("FIXME: don't know what to do about " + tc);
228                     ret.add(null);
229                 }
230             }
231             Object[] o = (Object[])ret.toArray(new Object[0]);
232             int max = 0;
233             for(int i=0; i<map.length; i++) max = Math.max(map[i], max);
234             Object[] o2 = new Object[max+1];
235             for(int i=0; i<o.length; i++) o2[map[i]] = o[i];
236             return _bindable.impose(o2);
237         }
238     }
239
240
241     public static Union make() { return make(MetaGrammarTree.meta, "s"); }
242     public static Union make(Tree t, String s) { return make(t, s, new AnnotationGrammarBindingResolver(MetaGrammarBindings.class)); }
243     public static Union make(Tree t, String s, GrammarBindingResolver rm) {
244         Tree.TreeFunctor<Object,Object> red = (Tree.TreeFunctor<Object,Object>)t.head();
245         MetaGrammarBindings.GrammarNode g = (MetaGrammarBindings.GrammarNode)red.invoke(t.children());
246         return g.build(s, rm);
247     }
248
249 }