better colorization of interpreter logs
[fleet.git] / src / edu / berkeley / fleet / interpreter / Interpreter.java
index 2e934a3..c43ad40 100644 (file)
 package edu.berkeley.fleet.interpreter;
 import java.io.*;
 import java.util.*;
+import java.util.concurrent.*;
 import java.lang.reflect.*;
-import edu.berkeley.fleet.*;
+import edu.berkeley.sbp.util.ANSI;
 import edu.berkeley.fleet.api.*;
-import edu.berkeley.fleet.ies44.*;
-import edu.berkeley.fleet.ships.*;
-
-public class Interpreter extends Fleet /*, Fleet.WithDynamicShips*/ {
-
-    /** some "halt ship" can turn this on to stop the interpreter */
-    public boolean       halt         = false;
-
-    public ArrayList<InterpreterShip> shiplist   = new ArrayList<InterpreterShip>();
-    public HashMap<String,InterpreterShip> ships = new HashMap<String,InterpreterShip>();
-
-    public void go(byte[] instructions) {
-
-        // find the first icache
-        Icache icache = null;
-        for(Ship ship : this)
-            if (ship instanceof Icache) {
-                icache = (Icache)ship;
-                break;
-            }
-
-        // load the icache and take note of the 0-address CBD
-        long launch = 0;
-        for(int i=0; i<instructions.length; i+=6) {
-            long word = 0;
-            for(int j=0; j<6; j++)
-                word = (word << 8) | (instructions[i+j] & 0xff);
-            icache.writeMem(i/6, word);
-            if (i==0) launch = word;
-        }
-
-        // dispatch the 0-address CBD
-        int base = (int)(launch >> 6);
-        base = base & ~(0xffffffff << 18);
-        int size = (int)launch;
-        size = size & ~(0xffffffff <<  6);
-        icache.dispatch(base, size);
-
-        while(!halt)
-            for(InterpreterShip ship : ships.values())
-                for(int j=0; j<10; j++)
-                    ship._service();
-
-        // run the ships a bit longer for good measure
-        for(int i=0; i<100; i++)
-            for(InterpreterShip ship : ships.values())
-                for(int j=0; j<10; j++)
-                    ship._service();
-
-        // check the state of the ships
-        for(InterpreterShip ship : ships.values())
-            ship.shutdown();
+import edu.berkeley.fleet.two.*;
+import edu.berkeley.fleet.assembler.*;
+import edu.berkeley.fleet.util.*;
+
+public class Interpreter extends FleetTwoFleet {
+
+    /** used to allocate serial numbers; see InterpreterDestination for further detail */
+    int maxAllocatedDestinationSerialNumber = 0;
+
+    private InterpreterShip debugShip = null;
+    private BlockingQueue<BitVector> debugStream = new LinkedBlockingQueue<BitVector>();
+    private LinkedHashMap<String,InterpreterShip> ships = new LinkedHashMap<String,InterpreterShip>();
+    public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
+    public Ship getShip(String type, int ordinal) {
+        for(Ship s : this)
+            if (s.getType().equals(type))
+                if (ordinal-- <= 0)
+                    return s;
+        return null;
+    }
 
-        Log.println(Log.yellow("    DONE: ====== FLEET is halted.  Have a nice day.  ======"));
+    /** do not use this; it is going to go away */
+    public Interpreter() { this(true); }
+    public Interpreter(boolean logging) {
+        this(new String[] {
+                "Debug",
+                "Memory",
+                "Memory",
+                "Memory",
+                "Alu",
+                "Alu",
+                "Alu",
+                "Alu",
+                "Alu",
+                "Alu",
+                "Alu",
+                "Fifo",
+                "Fifo",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Counter",
+                "Lut3",
+                "CarrySaveAdder",
+                "Rotator",
+                "Timer",
+            }, logging);
     }
 
-    public void dispatch(Instruction i, long address) {
-        Log.dispatch(i);
-        if (i instanceof Instruction.Executable) {
-            InterpreterBenkoBox sourceBenkoBox = (InterpreterBenkoBox)(((Instruction.Executable)i).benkoBox);
-            ((InstructionPort)sourceBenkoBox).addInstruction(((Instruction.Executable)i));
-
-        } else if (i instanceof Instruction.Literal.CodeBagDescriptor) {
-            Instruction.Literal.CodeBagDescriptor cbd = (Instruction.Literal.CodeBagDescriptor)i;
-            InterpreterBenkoBox destBenkoBox = (InterpreterBenkoBox)(cbd.dest);
-            long absolute_cbd = ((cbd.offset+address) << 6) | cbd.size;
-            destBenkoBox.addDataFromFabric((int)absolute_cbd);
-            
-        } else if (i instanceof Instruction.Literal.Absolute) {
-            InterpreterBenkoBox destBenkoBox = (InterpreterBenkoBox)(((Instruction.Literal.Absolute)i).dest);
-            Log.data(((Instruction.Literal.Absolute)i).value+"", null, destBenkoBox);
-            destBenkoBox.addDataFromFabric((int)((Instruction.Literal.Absolute)i).value);
-
-        } else if (i instanceof Instruction.Kill) {
-            InterpreterBenkoBox benkoBox = (InterpreterBenkoBox)(((Instruction.Kill)i).benkoBox);
-            ((InstructionPort)benkoBox).kill(((Instruction.Kill)i).count);
-
-        } else {
-            throw new Error("unsupported: " + i.getClass().getName());
+    public Interpreter(String[] ships, boolean logging) {
+        int i=0;
+        Log.quiet = !logging;
+        for(String s : ships) {
+            createShip(ships[i], ships[i]+"_"+i);
+            i++;
         }
     }
 
-    public void sendToken(InterpreterBenkoBox source, InterpreterBenkoBox dest) {
-        Log.token(source, dest);
-        dest.addTokenFromFabric();
+    private Ship createShip(String shipType, String shipname) {
+        try {
+            if (ships.get(shipname)!=null) return ships.get(shipname);
+            Class c = Class.forName("edu.berkeley.fleet.interpreter."+shipType);
+            Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class, ShipDescription.class });
+            String src = "/ships/" + shipType + ".ship";
+            InputStream is = getClass().getResourceAsStream(src);
+            BufferedReader br = new BufferedReader(new InputStreamReader(is));
+            ShipDescription sd = new ShipDescription(this, shipType, br);
+            InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname, sd });
+            ships.put(shipname, ret);
+            if (shipType.equals("Debug") && debugShip == null)
+                debugShip = ret;
+            return ret;
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
     }
 
-    public void sendData(InterpreterBenkoBox source, int data, InterpreterBenkoBox dest) {
-        Log.data(data+"", source, dest);
-        dest.addDataFromFabric(data);
+    void debug(long d) { debug(new BitVector(getWordWidth()).set(d)); }
+    void debug(BitVector data) {
+        try {
+            if (debugStream != null) debugStream.put(data);
+            else Log.println(ANSI.invert("   DEBUG: got a datum: " +  data+ANSI.clreol()));
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
     }
 
+    // Instruction Encoding /////////////////////////////////////////////////////////////////////////
 
-    // Implementation of the Fleet class abstract methods /////////////////////////////////////////////////////////
-
-    public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)shiplist.iterator(); }
-
-    public int computeOffset(int origin, int target) { return (target - origin)/6; }
-    public int computeTarget(int origin, int offset) { return origin + (offset*6); }
-
-    private InterpreterInstructionEncoder iie = new InterpreterInstructionEncoder();
-    public Instruction readInstruction(DataInputStream is) throws IOException { return iie.readInstruction(is); }
-    public Instruction readInstruction(long instr) { return iie.readInstruction(instr); }
-    public long writeInstruction(Instruction d) { return writeInstruction(d); }
-    public void writeInstruction(DataOutputStream os, Instruction d) throws IOException { iie.writeInstruction(os, d); }
-
-    private class InterpreterInstructionEncoder extends InstructionEncoder {
-        public long getBoxAddr(BenkoBox box) { return ((InterpreterBenkoBox)box).addr; }
-        public long getBoxInstAddr(BenkoBox box) { return ((InterpreterBenkoBox)box).instr_addr; }
-        public BenkoBox getBoxByAddr(long dest) {
-            for(Ship ship : Interpreter.this)
-                for(BenkoBox bb : ship.getBenkoBoxes())
-                    if (((InterpreterBenkoBox)bb).addr == dest)
-                        return bb;
-            return null;
-        }
-        public BenkoBox getBoxByInstAddr(long dest) {
-            for(Ship ship : Interpreter.this)
-                for(BenkoBox bb : ship.getBenkoBoxes())
-                    if (((InterpreterBenkoBox)bb).instr_addr == dest)
-                        return bb;
-            return null;
+    public BitVector getDestAddr(Path path) {
+        long ret = ((InterpreterDestination)path.getDestination()).getSerialNumber();
+        BitVector sig = path.getSignal();
+        BitVector bv = new BitVector(DISPATCH_PATH.valmaskwidth+1);
+        bv.set(ret);
+        if (sig != null) {
+            if (sig.length() > 1) throw new RuntimeException("signal was " + sig.length() + " bits long!");
+            if (sig.length() > 0 && sig.get(0)) bv.set(bv.length()-1,true);
         }
+        return bv;
     }
 
-    public Ship createShip(String shipType, String shipname) {
+
+    // ShipDescription //////////////////////////////////////////////////////////////////////////////
+
+    public void expand(ShipDescription sd) {
         try {
-            Class c = Class.forName("edu.berkeley.fleet.ships."+shipType);
-            Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class });
-            InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname });
-            ships.put(shipname, ret);
-            shiplist.add(ret);
-            return ret;
-        } catch (Exception e) {
-            return null;
-        }
+            String filename = sd.getName();
+            //String filename = (sd.getName().charAt(0)+"").toUpperCase() + sd.getName().substring(1).toLowerCase();
+            File outf = new File("build/java/edu/berkeley/fleet/interpreter/"+filename+".java");
+            new File(outf.getParent()).mkdirs();
+            System.err.println("writing to " + outf);
+            FileOutputStream out = new FileOutputStream(outf);
+            PrintWriter pw = new PrintWriter(out);
+
+            pw.println("package edu.berkeley.fleet.interpreter;");
+            pw.println("import edu.berkeley.sbp.util.ANSI;");
+            pw.println("import edu.berkeley.fleet.api.*;");
+            pw.println("import edu.berkeley.fleet.two.*;");
+            pw.println("import edu.berkeley.fleet.*;");
+            pw.println("import java.util.*;");
+            pw.println("import java.io.*;");
+            pw.println("");
+            pw.println("public class "+filename+" extends InterpreterShip {");
+            pw.println("");
+            pw.println("    public "+filename+"(Interpreter fleet, String name, ShipDescription sd) {");
+            pw.println("       super(fleet, sd);");
+            pw.println("    }");
+            pw.println("");
+            for(DockDescription b : sd) {
+                String name = b.getName();
+                pw.print("    InterpreterDock box_");
+                pw.print(name);
+                pw.print(" = new InterpreterDock(this, shipDescription.getDockDescription(\""+name+"\"));");
+            }
+            pw.println("");
+            pw.println(sd.getSection("fleeterpreter"));
+            pw.println("}");
+            pw.flush();
+            pw.close();
+        } catch (Exception e) { throw new RuntimeException(e); }
     }
 
+    // Run //////////////////////////////////////////////////////////////////////////////
 
-    // Memory //////////////////////////////////////////////////////////////////////////////
+    public FleetProcess run(final Instruction[] instructions) {
+        InterpreterProcess ip = initialize(instructions);
+        new Thread(ip).start();
+        return ip;
+    }
 
-    public int[] mem = new int[0];
+    public InterpreterProcess initialize(Instruction[] instr) {
+        return new InterpreterProcess(instr);
+    }
 
-    public void dumpMem() {
-        Log.print(Log.cyan("  MEMORY: "));
-        for(int i=0; i<mem.length; i++) {
-            if ((i%10)==0 && i!=0) Log.print(Log.cyan("          "));
-            Log.print(Log.cyan(mem[i] + " "));
-            if ((i%10)==9 && i!=mem.length-1) Log.println("");
+    public class InterpreterProcess extends FleetProcess implements Runnable {
+        private Instruction[] instructions;
+        public synchronized void sendWord(Destination d, BitVector word) { sendWord(d, word, null); }
+        public synchronized void sendWord(Destination d, BitVector word, BitVector signal) {
+            InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, signal==null?new BitVector(1):signal);
+            ((InterpreterDestination)d).
+                addDataFromFabric(new Packet(path, word, false));
+        }
+        public synchronized void sendToken(Destination d) {
+            InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, new BitVector(1));
+            ((InterpreterDestination)d).
+                addDataFromFabric(new Packet(path, new BitVector(getWordWidth()), true));
+        }
+        public InterpreterProcess(Instruction[] instructions) {
+            this.instructions = instructions;
+            for(Instruction i : instructions)
+                sendInstruction(i);
+        }
+        public Fleet getFleet() { return Interpreter.this; }
+        public synchronized void sendInstruction(Instruction i) {
+            long il = writeInstruction(i, debugShip.getDock("in"));
+            Path path = debugShip.getDock("in").getPath(i.dock.getInstructionDestination(), null);
+            new Packet((InterpreterPath)path, new BitVector(getWordWidth()).set(il), false).send();
+        }
+        public Dock getDebugInputDock() { return debugShip.getDock("in"); }
+        public BitVector recvWord() {
+            try {
+                return debugStream.take();
+            } catch (Exception e) { throw new RuntimeException(e); }
+        }
+        protected void _terminate() { }
+        public void run() {
+            try {
+                while(!isTerminated()) {
+                    flush();
+                }
+                for(InterpreterShip ship : ships.values())
+                    ship.reset();
+                debugStream.clear();
+            } catch (Exception e) {
+                if (isTerminated()) return;
+                throw new RuntimeException(e);
+            }
         }
-        Log.println();
-    }
 
-    public int readMem(int addr) {
-        return addr >= mem.length ? 0 : mem[addr];
-    }
-    public void writeMem(int addr, int data) {
-        if (addr >= mem.length) {
-            int[] mem2 = new int[addr*2+1];
-            System.arraycopy(mem, 0, mem2, 0, mem2.length);
-            mem = mem2;
+        public void flush() {
+            // FIXME: should this run until we detect some sort of "quiescence"?  OTOH that might never happen.
+            for(InterpreterShip ship : ships.values())
+                for(int j=0; j<10; j++)
+                    if (!isTerminated())
+                        synchronized(this) {
+                            ship._service();
+                        }
         }
-        mem[addr] = data;
-    }
 
+        public synchronized void step(Dock d) {
+            ((InterpreterDock)d).service();
+        }
+        
+        public synchronized void step(Ship s) {
+            ((InterpreterShip)s).service();
+        }
 
+    }
 }
-