1 package net.mograsim.machine.mi;
3 import java.io.BufferedReader;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.OutputStreamWriter;
10 import net.mograsim.machine.MemoryDefinition;
11 import net.mograsim.machine.mi.parameters.MicroInstructionParameter;
12 import net.mograsim.machine.mi.parameters.ParameterClassification;
14 public class MicroInstructionMemoryParser
16 public static void parseMemory(final MicroInstructionMemory memory, String inputPath) throws IOException
18 try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputPath))))
20 parseMemory(memory, reader);
24 public static void parseMemory(final MicroInstructionMemory memory, BufferedReader input)
26 MicroInstructionMemoryDefinition def = memory.getDefinition();
27 MicroInstructionDefinition miDef = def.getMicroInstructionDefinition();
29 long minAddr = def.getMinimalAddress();
30 long maxAddr = def.getMaximalAddress();
36 for (; i <= maxAddr && input.ready() && !"".equals((line = input.readLine())); i++)
39 memory.setCell(i, parse(() -> memory.notifyObservers(iFinal), miDef, line));
47 for (; i <= maxAddr; i++)
50 memory.setCell(i, miDef.createDefaultInstruction(() -> memory.notifyObservers(iFinal)));
54 public static MicroInstruction parse(Runnable updateCallback, MicroInstructionDefinition definition, String toParse)
56 int size = definition.size();
57 String[] strings = toParse.split(",");
58 if (size != strings.length)
59 throw new MicroInstructionMemoryParseException("String does not match definition! The number of parameters does not match.");
60 MicroInstructionParameter[] params = new MicroInstructionParameter[size];
61 ParameterClassification[] classes = definition.getParameterClassifications();
64 for (int i = 0; i < size; i++)
66 params[i] = classes[i].parse(strings[i]);
68 return new StandardMicroInstruction(updateCallback, params);
72 throw new MicroInstructionMemoryParseException(e.getCause());
76 public static void write(MicroInstructionMemory memory, String outputPath) throws IOException
78 try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputPath)))
80 write(memory, writer);
84 public static void write(MicroInstructionMemory memory, OutputStreamWriter output) throws IOException
86 MemoryDefinition def = memory.getDefinition();
87 long min = def.getMinimalAddress(), max = def.getMaximalAddress() + 1;
88 for (long i = min; i < max; i++)
90 output.write(toCSV(memory.getCell(i)) + "\n");
94 private static String toCSV(MicroInstruction inst)
96 int max = inst.getSize() - 1;
97 StringBuilder sb = new StringBuilder();
98 for (int i = 0; i < max; i++)
100 sb.append(inst.getParameter(i).toString());
103 sb.append(inst.getParameter(max).toString());
104 return sb.toString();