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++)
37 memory.setCell(i, parse(miDef, line));
38 } catch (IOException e)
43 for(; i <= maxAddr; i++)
44 memory.setCell(i, miDef.createDefaultInstruction());
47 public static MicroInstruction parse(MicroInstructionDefinition definition, String toParse)
49 int size = definition.size();
50 String[] strings = toParse.split(",");
51 if (size != strings.length)
52 throw new MicroInstructionMemoryParseException(
53 "String does not match definition! The number of parameters does not match.");
54 MicroInstructionParameter[] params = new MicroInstructionParameter[size];
55 ParameterClassification[] classes = definition.getParameterClassifications();
58 for (int i = 0; i < size; i++)
60 params[i] = classes[i].parse(strings[i]);
62 return new StandardMicroInstruction(params);
65 throw new MicroInstructionMemoryParseException(e.getCause());
69 public static void write(MicroInstructionMemory memory, String outputPath) throws IOException
71 try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputPath)))
73 write(memory, writer);
77 public static void write(MicroInstructionMemory memory, OutputStreamWriter output) throws IOException
79 MemoryDefinition def = memory.getDefinition();
80 long min = def.getMinimalAddress(), max = def.getMaximalAddress() + 1;
81 for (long i = min; i < max; i++)
83 output.write(toCSV(memory.getCell(i)) + "\n");
87 private static String toCSV(MicroInstruction inst)
89 int max = inst.getSize() - 1;
90 StringBuilder sb = new StringBuilder();
91 for (int i = 0; i < max; i++)
93 sb.append(inst.getParameter(i).toString());
96 sb.append(inst.getParameter(max).toString());