rename slipway=>fpga
[fleet.git] / src / edu / berkeley / fleet / assembler / Parser.java
1 package edu.berkeley.fleet.assembler;
2 import edu.berkeley.fleet.api.*;
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.misc.*;
6 import edu.berkeley.sbp.meta.*;
7 import edu.berkeley.sbp.util.*;
8 import java.util.*;
9 import java.io.*;
10
11 /**
12  *  @author Adam Megacz <megacz@cs.berkeley.edu>
13  */
14 public class Parser {
15
16     Parser(Fleet fleet) {
17         expect = new ArrayList<Long>();
18         this.fleet = fleet;
19     }
20
21     //////////////////////////////////////////////////////////////////////////////
22
23     private Fleet fleet;
24     private ArrayList<String> imports = new ArrayList<String>();
25
26     private HashMap<String,Ship> shipMap = new HashMap<String,Ship>();
27
28     // codebags in numerical order
29     private ArrayList<CodeBag> codeBags = new ArrayList<CodeBag>();
30     private HashMap<String,CodeBag> codeBagsByName = new HashMap<String,CodeBag>();
31     
32     private CodeBag getCodeBag(String name) {
33         CodeBag cb = codeBagsByName.get(name);
34         if (cb!=null) return cb;
35         return new CodeBag(name);
36     }
37
38     private static Union grammar;
39     private static synchronized Union getGrammar() throws Exception {
40         if (grammar != null) return grammar;
41         InputStream grammarStream =
42             Parser.class.getClassLoader().getResourceAsStream("edu/berkeley/fleet/assembler/fleet.g");
43         CharParser metaGrammarParser   = new CharParser(MetaGrammar.newInstance());
44         Tree<String> parsedGrammar     = metaGrammarParser.parse(new CharInput(grammarStream)).expand1();
45         grammar                        = GrammarAST.buildFromAST(parsedGrammar, "s", new File[0]);
46         return grammar;
47     }
48
49     Tree<String> parse(Reader r) throws Exception {
50         return new CharParser(getGrammar()).parse(new CharInput(r)).expand1();
51     }
52
53     public void parse(Reader r, OutputStream out) throws Exception {
54         // this needs to be "code bag zero"
55         CodeBag baseCodeBag = new CodeBag();
56         CodeBag rootCodeBag = new CodeBag();
57         skip = false;
58         baseCodeBag.add(new Instruction.Literal.CodeBagDescriptor(null, rootCodeBag.getFakeAddress(), 1));
59         walk((Tree<String>)parse(r), rootCodeBag);
60         if (fleet instanceof edu.berkeley.fleet.fpga.Slipway)
61             ((edu.berkeley.fleet.fpga.Slipway)fleet).dumpFabric(true);
62
63         // map from arbitrary identifiers to actual addresses
64         int[] codeBagMap = new int[codeBags.size()];
65         ByteArrayOutputStream baos = new ByteArrayOutputStream();
66         DataOutputStream dos       = new DataOutputStream(baos);
67         int count = 0;
68         for(int i=0; i<codeBags.size(); i++) {
69             CodeBag c = codeBags.get(i);
70             dos.flush();
71             codeBagMap[i] = count;
72             for(Instruction inst : c) {
73                 fleet.writeInstruction(dos, inst);
74                 count++;
75             }
76         }
77
78         // now write for real
79         dos = new DataOutputStream(out);
80         count = 0;
81         for(int i=0; i<codeBags.size(); i++) {
82             CodeBag c = codeBags.get(i);
83             dos.flush();
84             for(Instruction inst : c) {
85                 if (inst instanceof Instruction.Literal.CodeBagDescriptor) {
86                     dos.flush();
87                     Instruction.Literal.CodeBagDescriptor old = (Instruction.Literal.CodeBagDescriptor)inst;
88                     int offset = codeBagMap[(int)old.offset] - count;
89                     inst = new Instruction.Literal.CodeBagDescriptor(old.dest,
90                                                                      offset,
91                                                                      codeBags.get((int)old.offset).size());
92                 }
93                 fleet.writeInstruction(dos, inst);
94                 count++;
95             }
96         }
97         dos.flush();
98         out.flush();
99         out.close();
100     }
101
102     /** in the first pass, codebags are assigned "addresses" in arbitrary order */
103     void walk(Tree<String> t, CodeBag cb) {
104
105         String head = t.head();
106         if (head==null) {
107         } else if (head.equals("Program")) {
108             for(Tree<String> tc : t.child(0))
109                 walk(tc, cb);
110             if (t.size()>1)
111                 for(Tree<String> statement : t.child(1))
112                     fillCodeBag(statement, cb);
113    
114         } else if (head.equals("Import")) {
115             // ignored
116
117         } else if (head.equals("Ship")) {
118             String name = name(t.child(0));
119             String type = string(t.child(1));
120             Ship ship = null;
121
122             if (fleet instanceof Fleet.WithDynamicShips) {
123                 Fleet.WithDynamicShips dyn = ((Fleet.WithDynamicShips)fleet);
124                 ship = dyn.createShip(type, name);
125                 if (ship==null)
126                     throw new RuntimeException("couldn't find a ship called \""+type+"\"");
127             } else {
128                 ship = allocateShip(type);
129             }
130             shipMap.put(name, ship);
131
132         } else if (head.equals("Include")) {
133             try {
134                 walk(parse(new InputStreamReader(new FileInputStream(string(t.child(0))))), cb);
135             } catch (Exception e) {
136                 throw new RuntimeException(e);
137             }
138             
139         } else if (head.equals("Expect")) {
140             expect.add(Long.parseLong(string(t.child(0))));
141         } else if (head.equals("Skip")) {
142             skip = true;
143
144         }
145     }
146
147     String string(Tree<String> t) {
148         String ret = "";
149         if (t.head() != null) ret += t.head();
150         for(Tree<String> c : t)
151             ret += string(c);
152         return ret;
153     }
154
155     String name(Tree<String> t) {
156         return string(t.child(0))+string(t.child(1));
157     }
158
159     Destination portReference(Tree<String> t) {
160         if (!"Port".equals(t.head()) && !"SubPort".equals(t.head()) && !"ShipSpecificLiteral".equals(t.head())) return null;
161         String shipName = name(t.child(0));
162         String portName = name(t.child(1));
163         String subPort = t.size()<3 ? null : name(t.child(2));
164         Ship ship = shipMap.get(shipName);
165         if (ship==null) throw new RuntimeException("no such ship \""+shipName+"\"");
166         Destination ret = null;
167         BenkoBox bb = null;
168         for(BenkoBox b : ship.getBenkoBoxes())
169             if (b.getName().equals(portName)) {
170                 bb = b;
171             }
172         if (bb==null)
173             throw new RuntimeException("no such benkobox \""+portName+"\"");
174         if (subPort==null) subPort="";
175         for(Destination d : bb.getDestinations())
176             if (d.getDestinationName().equals(subPort))
177                 return d;
178         if (ret==null)
179             throw new RuntimeException("no such benkobox \""+portName+"\" on ships of type \""+ship.getType()+"\"");
180         return ret;
181     }
182
183     BenkoBox benkoBox(Tree<String> t) {
184         if (!"Port".equals(t.head()) && !"SubPort".equals(t.head()) && !"ShipSpecificLiteral".equals(t.head())) return null;
185         String shipName = name(t.child(0));
186         String portName = name(t.child(1));
187         Ship ship = shipMap.get(shipName);
188         if (ship==null) throw new RuntimeException("no such ship \""+shipName+"\"");
189         BenkoBox bb = null;
190         for(BenkoBox b : ship.getBenkoBoxes())
191             if (b.getName().equals(portName))
192                 return b;
193         throw new RuntimeException("no such benkobox \""+portName+"\"");
194     }
195
196     private HashMap<String,Integer> numAllocated = new HashMap<String,Integer>();
197
198     Ship allocateShip(String shipType) {
199         int allocated = 0;
200         if (numAllocated.get(shipType) != null)
201             allocated = numAllocated.get(shipType);
202         numAllocated.put(shipType, allocated+1);
203         for(Iterator<Ship> it = fleet.iterator();
204             it.hasNext();
205             ) {
206             Ship s = it.next();
207             if (s.getType().equals(shipType)) {
208                 if (allocated == 0) return s;
209                 allocated--;
210             }
211         }
212         throw new RuntimeException("no more ships of type \""+shipType+"\"");
213     }
214
215     void fillCodeBag(Tree<String> t, CodeBag cb) {
216         if (t.head()==null) return;
217         else if (t.head().equals("NamedCodeBag")) {
218             CodeBag cb2 = getCodeBag(name(t.child(0)));
219             for(Tree<String> statement : t.child(1))
220                 fillCodeBag(statement, cb2);
221
222         } else if (t.head().equals("ShipSpecificLiteral")) {
223             String shipType = name(t.child(0).child(0));
224             String portName = name(t.child(0).child(1));
225             Ship chosenship = null;
226             for(Ship ship : fleet) {
227                 if (ship.getType().equals(shipType)) {
228                     chosenship = ship;
229                     break;
230                 }
231             }
232             long literal = chosenship.resolveLiteral(portName);
233             cb.add(new Instruction.Literal.Absolute(portReference(t.child(1)), literal));
234
235         } else if (t.head().equals("Literal")) {
236             long literal = Long.parseLong(string(t.child(0)));
237             cb.add(new Instruction.Literal.Absolute(portReference(t.child(1)), literal));
238
239         } else if (t.head().equals("CodeBagDescriptor")) {
240             String refname = name(t.child(0).child(0));
241             CodeBag cb2 = getCodeBag(refname);
242             cb.add(new Instruction.Literal.CodeBagDescriptor(portReference(t.child(1)), cb2.getFakeAddress(), 0));
243
244         } else if (t.head().equals("Fiber")) {
245             BenkoBox benkobox = (BenkoBox)benkoBox(t.child(0));
246             
247             OUTER: for(Tree tt : t.child(1)) {
248                 int count = 1;
249                 Tree ttx = null;
250                 boolean recycle = false;
251                 ttx = tt.child(1);
252                 if (tt.size() > 1 && tt.child(0).size()>0) {
253                     tt = tt.child(0).child(0);
254                     if (tt.head().equals("BrackStar")) {
255                         count = 0;
256                         recycle = false;
257                     } else if (tt.head().equals("ParenStar")) {
258                         count = 0;
259                         recycle = true;
260                     } else if (tt.head().equals("Brack")) {
261                         count = Integer.parseInt(string(tt.child(0)));
262                         recycle = false;
263                     } else if (tt.head().equals("Paren")) {
264                         count = Integer.parseInt(string(tt.child(0)));
265                         recycle = true;
266                     }
267                 }
268                 boolean tokenIn = false;
269                 boolean dataIn = false;
270                 boolean latch = false;
271                 boolean dataOut = false;
272                 boolean tokenOut = false;
273                 Destination dest = null;
274                 for(int i=0; i<ttx.size(); i++) {
275                     Tree ttt = ttx.child(i);
276                     if      ("Wait".equals(ttt.head()))    { tokenIn = true; }
277                     else if ("Nop".equals(ttt.head()))     { }
278                     else if ("KillStar".equals(ttt.head()))    {
279                         cb.add(new Instruction.Kill(benkobox, count, true));
280                         continue OUTER;
281                     } else if ("Kill".equals(ttt.head()))    {
282                         cb.add(new Instruction.Kill(benkobox, count, false));
283                         continue OUTER;
284                     }
285                     else if ("Discard".equals(ttt.head())) { dataIn = true; latch = false; }
286                     else if ("Take".equals(ttt.head()))    { dataIn = true; latch = true; }
287                     else if ("SendTo".equals(ttt.head()))  { dataOut = true; dest = portReference(ttt.child(0)); }
288                     else if ("Deliver".equals(ttt.head())) { dataOut = true;  }
289                     else if ("Ack".equals(ttt.head()))     { tokenOut = true; dest = portReference(ttt.child(0)); }
290                 }
291                 cb.add(new Instruction.Executable(benkobox,
292                                                   dest, count, tokenIn, dataIn,
293                                                   latch, dataOut, tokenOut, recycle));
294             }
295         }
296     }
297
298     private class CodeBag extends ArrayList<Instruction> {
299         public long address = -1;
300         public CodeBag() { codeBags.add(this); }
301         public CodeBag(String name) { this(); codeBagsByName.put(name, this); }
302         public long getFakeAddress() { return codeBags.indexOf(this); }
303         public boolean equals(Object o) { return this==o; }
304     }
305
306     // hideous hack
307     public static ArrayList<Long> expect;
308     public static boolean         skip;
309
310 }