1 package net.mograsim.logic.model.am2900.util;
3 import static org.junit.jupiter.api.Assertions.fail;
5 import java.lang.reflect.Field;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.LinkedList;
9 import java.util.Objects;
10 import java.util.Optional;
11 import java.util.Queue;
13 import java.util.TreeSet;
15 import net.mograsim.logic.core.components.CoreBitDisplay;
16 import net.mograsim.logic.core.components.CoreManualSwitch;
17 import net.mograsim.logic.core.timeline.Timeline;
18 import net.mograsim.logic.model.LogicUIStandaloneGUI;
19 import net.mograsim.logic.model.am2900.Am2900Loader;
20 import net.mograsim.logic.model.am2900.TestableCircuit;
21 import net.mograsim.logic.model.am2900.TestableCircuit.Result;
22 import net.mograsim.logic.model.model.LogicModel;
23 import net.mograsim.logic.model.model.LogicModelModifiable;
24 import net.mograsim.logic.model.model.components.ModelComponent;
25 import net.mograsim.logic.model.model.components.atomic.ModelBitDisplay;
26 import net.mograsim.logic.model.model.components.atomic.ModelManualSwitch;
27 import net.mograsim.logic.model.model.components.submodels.SubmodelComponent;
28 import net.mograsim.logic.model.model.wires.ModelWire;
29 import net.mograsim.logic.model.model.wires.Pin;
30 import net.mograsim.logic.model.modeladapter.CoreModelParameters.CoreModelParametersBuilder;
31 import net.mograsim.logic.model.modeladapter.LogicCoreAdapter;
32 import net.mograsim.logic.model.preferences.DefaultRenderPreferences;
33 import net.mograsim.logic.model.serializing.IndirectModelComponentCreator;
34 import net.mograsim.logic.model.util.ModellingTool;
36 public class TestEnvironmentHelper
38 private final TestableCircuit testEnvInstance;
39 private final Class<?> testEnvClass;
40 private final String modelId;
41 private Field componentField;
42 private Optional<Field> timelineField = Optional.empty();
44 private ModelComponent component;
45 private Timeline timeline;
46 private LogicModelModifiable logicModel;
47 private ModellingTool modellingTool;
48 private HashMap<String, ModelManualSwitch> idSwitchMap = new HashMap<>();
49 private HashMap<String, ModelBitDisplay> idDisplayMap = new HashMap<>();
51 private DebugState debug = DebugState.NO_DEBUG;
52 private Set<String> wireDebugChangeSet;
53 private boolean debugWires = false;
54 public int debugEventThreshold = 20_000;
55 public int debugEventCount = 500;
56 private int eventCounter;
58 public TestEnvironmentHelper(TestableCircuit testEnv, String modelId)
60 this.testEnvInstance = testEnv;
61 this.modelId = modelId;
62 this.testEnvClass = testEnvInstance.getClass();
63 for (Field f : testEnvClass.getDeclaredFields())
65 if (ModelComponent.class.isAssignableFrom(f.getType()))
68 componentField.setAccessible(true);
69 } else if (Timeline.class.isAssignableFrom(f.getType()))
71 f.setAccessible(true);
72 timelineField = Optional.of(f);
75 if (componentField == null)
76 throw new IllegalStateException("No component or timeline field found!");
79 public void setup(DebugState debug)
83 logicModel = new LogicModelModifiable();
84 modellingTool = ModellingTool.createFor(logicModel);
86 component = IndirectModelComponentCreator.createComponent(logicModel, modelId);
87 setField(componentField, component);
89 component.getPins().values().forEach(this::extendModelPin);
92 CoreModelParametersBuilder paramsBuilder = new CoreModelParametersBuilder();
93 paramsBuilder.gateProcessTime = 50;
94 paramsBuilder.hardcodedComponentProcessTime = paramsBuilder.gateProcessTime * 5;
95 paramsBuilder.wireTravelTime = 10;
96 timeline = LogicCoreAdapter.convert(logicModel, paramsBuilder.build());
97 timelineField.ifPresent(f -> setField(f, timeline));
99 // Bind switches/displays to this test class
100 component.getPins().values().forEach(this::bindModelPin);
102 if (debug == DebugState.DEBUG_AT_PERFORMANCE_COST)
106 timeline.addEventAddedListener(te -> eventCounter++);
109 private void extendModelPin(Pin p)
111 String javaIdentId = idToJavaIdentifier(p.name);
114 Field f = testEnvClass.getDeclaredField(javaIdentId);
115 Class<?> type = f.getType();
116 if (CoreManualSwitch.class.isAssignableFrom(type))
118 ModelManualSwitch gms = new ModelManualSwitch(logicModel, p.logicWidth);
119 modellingTool.connect(p, gms.getOutputPin());
120 idSwitchMap.put(p.name, gms);
121 } else if (CoreBitDisplay.class.isAssignableFrom(type))
123 ModelBitDisplay gbd = new ModelBitDisplay(logicModel, p.logicWidth);
124 modellingTool.connect(p, gbd.getInputPin());
125 idDisplayMap.put(p.name, gbd);
126 } else if (SwitchWithDisplay.class.isAssignableFrom(type))
128 SwitchWithDisplay swd = new SwitchWithDisplay(logicModel, p);
132 fail("unkown field type " + type);
135 catch (NoSuchFieldException | SecurityException e)
141 private void bindModelPin(Pin p)
143 String javaIdentId = idToJavaIdentifier(p.name);
144 if (idDisplayMap.containsKey(p.name))
145 setField(javaIdentId, idDisplayMap.get(p.name).getBitDisplay());
146 if (idSwitchMap.containsKey(p.name))
147 setField(javaIdentId, idSwitchMap.get(p.name).getManualSwitch());
150 private void setupDebugging()
153 HashSet<ModelWire> wiresIncludingSubmodels = new HashSet<>();
154 Queue<LogicModel> modelsToIterate = new LinkedList<>();
155 modelsToIterate.add(logicModel);
156 while (modelsToIterate.size() > 0)
158 LogicModel model = modelsToIterate.poll();
159 wiresIncludingSubmodels.addAll(model.getWiresByName().values());
160 for (ModelComponent comp : model.getComponentsByName().values())
161 if (comp instanceof SubmodelComponent)
162 modelsToIterate.offer(((SubmodelComponent) comp).submodel);
164 System.out.println(wiresIncludingSubmodels.size());
165 logicModel.setRedrawHandler(() -> wiresIncludingSubmodels.forEach(w ->
169 wireDebugChangeSet.add(w.toString());
176 // Normal execution until completion or eventLimit
177 int eventLimit = debugEventThreshold;
180 while (eventCounter < eventLimit)
182 timeline.executeNext();
183 if (!timeline.hasNext())
184 return Result.SUCCESS;
187 // Start debugging if event limit is reached (if debug is active)
188 if (debug == DebugState.DEBUG_AT_PERFORMANCE_COST)
189 return debugThisRun();
191 return Result.OUT_OF_TIME;
194 private Result debugThisRun()
196 int eventLimit = debugEventThreshold;
198 wireDebugChangeSet = new TreeSet<>();
199 Set<String> oldChangeSet;
200 // observe wire changes to detect, if we are really stuck in an endless loop
203 eventLimit += debugEventCount;
204 oldChangeSet = wireDebugChangeSet;
205 wireDebugChangeSet = new TreeSet<>();
206 while (eventCounter < eventLimit)
208 timeline.executeNext();
209 if (!timeline.hasNext())
211 // no endless loop, but more events needed than expected
212 System.out.println("run() took longer than expected: " + eventCounter);
213 return Result.SUCCESS;
216 } while (!oldChangeSet.equals(wireDebugChangeSet));
217 // if stuck, abort execution and print wires
218 System.err.print("Problematic Wire updates:");
219 wireDebugChangeSet.forEach(System.out::println);
220 System.err.println("run() failed: " + eventCounter);
221 return Result.OUT_OF_TIME;
224 private static String idToJavaIdentifier(String s)
226 StringBuilder sb = new StringBuilder(s.length());
227 char c = s.charAt(0);
228 sb.append(Character.isJavaIdentifierStart(c) ? c : '_');
229 for (int i = 1; i < s.length(); i++)
230 sb.append(Character.isJavaIdentifierPart(c = s.charAt(i)) ? c : '_');
231 return sb.toString();
234 private <S> void setField(Field f, S value)
238 f.setAccessible(true);
239 f.set(testEnvInstance, Objects.requireNonNull(value));
247 private <S> void setField(String name, S value)
251 Field f = testEnvClass.getDeclaredField(name);
252 f.setAccessible(true);
253 f.set(testEnvInstance, Objects.requireNonNull(value));
261 public void displayState()
265 new LogicUIStandaloneGUI(logicModel, new DefaultRenderPreferences()).run();
266 logicModel.setRedrawHandler(null);
274 public enum DebugState
276 NO_DEBUG, DEBUG_AT_PERFORMANCE_COST;