Skip to content

Commit 7644120

Browse files
committed
Revert "Some changes from Dev/ashish (#748)"
This reverts commit 296ed08. Undo changes to codebase outside PExplicitRuntime (that got added when merging $748).
1 parent 296ed08 commit 7644120

File tree

8 files changed

+60
-120
lines changed

8 files changed

+60
-120
lines changed

Src/PCompiler/CompilerCore/Backend/Java/MachineGenerator.cs

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -252,19 +252,9 @@ private void WriteMonitorCstr()
252252

253253
foreach (var s in _currentMachine.States)
254254
{
255-
WriteStateBuilderDecl(s, true);
255+
WriteStateBuilderDecl(s);
256256
}
257257
WriteLine("} // constructor");
258-
WriteLine();
259-
260-
WriteLine($"public void reInitializeMonitor() {{");
261-
262-
foreach (var s in _currentMachine.States)
263-
{
264-
WriteStateBuilderDecl(s, false);
265-
}
266-
WriteLine("}");
267-
268258
}
269259

270260
private void WriteEventsAccessor()
@@ -281,14 +271,9 @@ private void WriteEventsAccessor()
281271
WriteLine("}");
282272
}
283273

284-
private void WriteStateBuilderDecl(State s, bool isConstructor)
274+
private void WriteStateBuilderDecl(State s)
285275
{
286-
if (isConstructor) {
287-
WriteLine($"addState(prt.State.keyedOn({Names.IdentForState(s)})");
288-
} else {
289-
WriteLine($"registerState(prt.State.keyedOn({Names.IdentForState(s)})");
290-
}
291-
276+
WriteLine($"addState(prt.State.keyedOn({Names.IdentForState(s)})");
292277
if (s.IsStart)
293278
{
294279
WriteLine($".isInitialState(true)");

Src/PRuntimes/PJavaRuntime/src/main/java/prt/Monitor.java

Lines changed: 30 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,23 @@
88
import org.apache.logging.log4j.Logger;
99
import org.apache.logging.log4j.Marker;
1010
import org.apache.logging.log4j.MarkerManager;
11+
import org.apache.logging.log4j.message.StringMapMessage;
1112
import prt.exceptions.*;
12-
import java.io.Serializable;
1313

1414
/**
1515
* A prt.Monitor encapsulates a state machine.
1616
*
1717
*/
18-
public abstract class Monitor<StateKey extends Enum<StateKey>> implements Consumer<PEvent<?>>, Serializable {
19-
private static final Logger logger = LogManager.getLogger(Monitor.class);
18+
public abstract class Monitor<StateKey extends Enum<StateKey>> implements Consumer<PEvent<?>> {
19+
private final Logger logger = LogManager.getLogger(this.getClass());
2020
private static final Marker PROCESSING_MARKER = MarkerManager.getMarker("EVENT_PROCESSING");
2121
private static final Marker TRANSITIONING_MARKER = MarkerManager.getMarker("STATE_TRANSITIONING");
2222

23-
private StateKey startStateKey;
24-
private StateKey currentStateKey;
23+
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
24+
private Optional<State<StateKey>> startState;
25+
private State<StateKey> currentState;
2526

26-
private transient EnumMap<StateKey, State<StateKey>> states; // All registered states
27+
private EnumMap<StateKey, State<StateKey>> states; // All registered states
2728
private StateKey[] stateUniverse; // all possible states
2829

2930
/**
@@ -43,17 +44,6 @@ protected void addState(State<StateKey> s) {
4344
throw new RuntimeException("prt.Monitor is already running; no new states may be added.");
4445
}
4546

46-
registerState(s);
47-
48-
if (s.isInitialState()) {
49-
if (startStateKey != null) {
50-
throw new RuntimeException("Initial state already set to " + startStateKey);
51-
}
52-
startStateKey = s.getKey();
53-
}
54-
}
55-
56-
protected void registerState(State<StateKey> s) {
5747
if (states == null) {
5848
states = new EnumMap<>((Class<StateKey>) s.getKey().getClass());
5949
stateUniverse = s.getKey().getDeclaringClass().getEnumConstants();
@@ -63,14 +53,21 @@ protected void registerState(State<StateKey> s) {
6353
throw new RuntimeException("prt.State already present");
6454
}
6555
states.put(s.getKey(), s);
56+
57+
if (s.isInitialState()) {
58+
if (startState.isPresent()) {
59+
throw new RuntimeException("Initial state already set to " + startState.get().getKey());
60+
}
61+
startState = Optional.of(s);
62+
}
6663
}
6764

6865
public StateKey getCurrentState() {
6966
if (!isRunning) {
7067
throw new RuntimeException("prt.Monitor is not running (did you call ready()?)");
7168
}
7269

73-
return currentStateKey;
70+
return currentState.getKey();
7471
}
7572

7673
/**
@@ -142,11 +139,10 @@ public void accept(PEvent<?> p) throws UnhandledEventException {
142139
throw new RuntimeException("prt.Monitor is not running (did you call ready()?)");
143140
}
144141

145-
//logger.info(PROCESSING_MARKER, new StringMapMessage().with("event", p));
142+
logger.info(PROCESSING_MARKER, new StringMapMessage().with("event", p));
146143

147144
// XXX: We can technically avoid this downcast, but to fulfill the interface for Consumer<T>
148145
// this method cannot accept a type parameter, so this can't be a TransitionableConsumer<P>.
149-
State<StateKey> currentState = states.get(currentStateKey);
150146
Optional<State.TransitionableConsumer<Object>> oc = currentState.getHandler(p.getClass());
151147
if (oc.isEmpty()) {
152148
logger.atFatal().log(currentState + " missing event handler for " + p.getClass().getSimpleName());
@@ -161,20 +157,19 @@ public void accept(PEvent<?> p) throws UnhandledEventException {
161157
* entry handler, and updating internal bookkeeping.
162158
* @param s The new state.
163159
*/
164-
private <P> void handleTransition(State<StateKey> s, P payload) {
160+
private <P> void handleTransition(State<StateKey> s, Optional<P> payload) {
165161
if (!isRunning) {
166162
throw new RuntimeException("prt.Monitor is not running (did you call ready()?)");
167163
}
168164

169-
//logger.info(TRANSITIONING_MARKER, new StringMapMessage().with("state", s));
165+
logger.info(TRANSITIONING_MARKER, new StringMapMessage().with("state", s));
170166

171-
State<StateKey> currentState = states.get(currentStateKey);
172167
currentState.getOnExit().ifPresent(Runnable::run);
173168
currentState = s;
174-
currentStateKey = s.getKey();
175169

176170
currentState.getOnEntry().ifPresent(handler -> {
177-
invokeWithTrampoline(handler, payload);
171+
Object p = payload.orElse(null);
172+
invokeWithTrampoline(handler, p);
178173
});
179174
}
180175

@@ -204,7 +199,7 @@ private <P> void invokeWithTrampoline(State.TransitionableConsumer<P> handler, P
204199
* must be a handler of zero parameters, will be invoked.
205200
*/
206201
public void ready() {
207-
readyImpl(null);
202+
readyImpl(Optional.empty());
208203
}
209204

210205
/**
@@ -213,10 +208,10 @@ public void ready() {
213208
* @param payload The argument to the initial state's entry handler.
214209
*/
215210
public <P> void ready(P payload) {
216-
readyImpl(payload);
211+
readyImpl(Optional.of(payload));
217212
}
218213

219-
private <P> void readyImpl(P payload) {
214+
private <P> void readyImpl(Optional<P> payload) {
220215
if (isRunning) {
221216
throw new RuntimeException("prt.Monitor is already running.");
222217
}
@@ -229,27 +224,27 @@ private <P> void readyImpl(P payload) {
229224

230225
isRunning = true;
231226

232-
currentStateKey = startStateKey;
233-
State<StateKey> currentState = states.get(currentStateKey);
227+
currentState = startState.orElseThrow(() ->
228+
new RuntimeException(
229+
"No initial state set (did you specify an initial state, or is the machine halted?)"));
234230

235231
currentState.getOnEntry().ifPresent(handler -> {
236-
invokeWithTrampoline(handler, payload);
232+
Object p = payload.orElse(null);
233+
invokeWithTrampoline(handler, p);
237234
});
238235
}
239236

240237
/**
241238
* Instantiates a new prt.Monitor; users should provide domain-specific functionality in a subclass.
242239
*/
243240
protected Monitor() {
244-
startStateKey = null;
241+
startState = Optional.empty();
245242
isRunning = false;
246243

247244
states = null; // We need a concrete class to instantiate an EnumMap; do this lazily on the first addState() call.
248-
currentStateKey = null; // So long as we have not yet readied, this will be null!
245+
currentState = null; // So long as we have not yet readied, this will be null!
249246
}
250247

251248
public abstract List<Class<? extends PEvent<?>>> getEventTypes();
252249

253-
public abstract void reInitializeMonitor();
254-
255250
}

Src/PRuntimes/PJavaRuntime/src/test/java/MonitorTest.java

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
import java.util.ArrayList;
99
import java.util.List;
10-
import java.util.Optional;
1110

1211
import static org.junit.jupiter.api.Assertions.*;
1312

@@ -26,9 +25,6 @@ public NoDefaultStateMonitor() {
2625
super();
2726
addState(new State.Builder<>(SingleState.INIT_STATE).build());
2827
}
29-
30-
public void reInitializeMonitor() {}
31-
3228
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
3329
}
3430

@@ -42,8 +38,6 @@ public MultipleDefaultStateMonitors() {
4238
addState(new State.Builder<>(BiState.OTHER_STATE).isInitialState(true).build());
4339
}
4440

45-
public void reInitializeMonitor() {}
46-
4741
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
4842
}
4943

@@ -56,8 +50,6 @@ public NonTotalStateMapMonitor() {
5650
addState(new State.Builder<>(BiState.INIT_STATE).isInitialState(true).build());
5751
}
5852

59-
public void reInitializeMonitor() {}
60-
6153
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
6254
}
6355
/**
@@ -70,8 +62,6 @@ public NonUniqueStateKeyMonitor() {
7062
addState(new State.Builder<>(BiState.INIT_STATE).isInitialState(true).build());
7163
}
7264

73-
public void reInitializeMonitor() {}
74-
7565
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
7666
}
7767

@@ -101,8 +91,6 @@ public CounterMonitor() {
10191
.build());
10292
}
10393

104-
public void reInitializeMonitor() {}
105-
10694
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
10795
}
10896

@@ -127,8 +115,6 @@ public ChainedEntryHandlerMonitor() {
127115
.build());
128116
}
129117

130-
public void reInitializeMonitor() {}
131-
132118
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
133119
}
134120

@@ -158,8 +144,6 @@ public GotoStateWithPayloadsMonitor() {
158144
.build());
159145
}
160146

161-
public void reInitializeMonitor() {}
162-
163147
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
164148
}
165149

@@ -190,8 +174,6 @@ public GotoStateWithPayloadsMonitorIncludingInitialEntryHandler() {
190174
.build());
191175
}
192176

193-
public void reInitializeMonitor() {}
194-
195177
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(CounterMonitor.AddEvent.class); }
196178
}
197179

@@ -215,8 +197,6 @@ public GotoStateWithIllTypedPayloadsMonitor() {
215197
.build());
216198
}
217199

218-
public void reInitializeMonitor() {}
219-
220200
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
221201
}
222202

@@ -232,8 +212,6 @@ public ImmediateAssertionMonitor() {
232212
.build());
233213
}
234214

235-
public void reInitializeMonitor() {}
236-
237215
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(); }
238216
}
239217

@@ -245,8 +223,6 @@ public class noopEvent extends PEvent<Void> {
245223
public Void getPayload() { return null; }
246224
}
247225

248-
public void reInitializeMonitor() {}
249-
250226
public List<Class<? extends PEvent<?>>> getEventTypes() { return List.of(testEvent.class, noopEvent.class); }
251227

252228
public RaiseEventMonitor() {
@@ -262,6 +238,18 @@ public RaiseEventMonitor() {
262238
}
263239
}
264240

241+
@Test
242+
@DisplayName("Monitors require exactly one default state")
243+
public void testDefaultStateConstruction() {
244+
Throwable e;
245+
246+
e = assertThrows(RuntimeException.class, () -> new NoDefaultStateMonitor().ready());
247+
assertTrue(e.getMessage().contains("No initial state set"));
248+
249+
e = assertThrows(RuntimeException.class, () -> new MultipleDefaultStateMonitors().ready());
250+
assertTrue(e.getMessage().contains("Initial state already set"));
251+
}
252+
265253
@Test
266254
@DisplayName("Monitors' state maps must be total")
267255
public void testTotalMonitorMap() {
@@ -313,8 +301,7 @@ public void testChainedEntryHandlersWithPayloads() {
313301
GotoStateWithPayloadsMonitor m = new GotoStateWithPayloadsMonitor();
314302
m.ready();
315303

316-
assertTrue(m.eventsProcessed.equals(List.of(Optional.of("Hello from prt.State A"),
317-
Optional.of("Hello from prt.State B"))));
304+
assertTrue(m.eventsProcessed.equals(List.of("Hello from prt.State A", "Hello from prt.State B")));
318305
}
319306

320307
@Test
@@ -325,6 +312,20 @@ public void testCantCallReadyTwice() {
325312
assertThrows(RuntimeException.class, () -> m.ready(), "prt.Monitor is already running.");
326313
}
327314

315+
316+
@Test
317+
@DisplayName("Payloads can be passed to entry handlers through ready()")
318+
public void testChainedEntryHandlersWithPayloadsIncludingInitialEntryHandler() {
319+
GotoStateWithPayloadsMonitorIncludingInitialEntryHandler m =
320+
new GotoStateWithPayloadsMonitorIncludingInitialEntryHandler();
321+
m.ready("Hello from the caller!");
322+
323+
assertTrue(m.eventsProcessed.equals(
324+
List.of("Hello from the caller!",
325+
"Hello from prt.State A",
326+
"Hello from prt.State B")));
327+
}
328+
328329
@Test
329330
@DisplayName("Event handlers consuuming arguments in ready() must consume them!")
330331
public void testInitialEntryHandlerMustHaveAnArg() {

Src/PRuntimes/PJavaRuntime/src/test/java/testcases/clientserver/PMachines.java

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,6 @@ public BankBalanceIsAlwaysCorrect() {
4747
.build());
4848
} // constructor
4949

50-
public void reInitializeMonitor() {
51-
registerState(prt.State.keyedOn(PrtStates.Init)
52-
.isInitialState(true)
53-
.withEvent(PEvents.eSpec_BankBalanceIsAlwaysCorrect_Init.class, p -> { Anon(p); gotoState(PrtStates.WaitForWithDrawReqAndResp); })
54-
.build());
55-
registerState(prt.State.keyedOn(PrtStates.WaitForWithDrawReqAndResp)
56-
.withEvent(PEvents.eWithDrawReq.class, this::Anon_1)
57-
.withEvent(PEvents.eWithDrawResp.class, this::Anon_2)
58-
.build());
59-
}
60-
6150
public java.util.List<Class<? extends prt.events.PEvent<?>>> getEventTypes() {
6251
return java.util.Arrays.asList(PEvents.eSpec_BankBalanceIsAlwaysCorrect_Init.class, PEvents.eWithDrawReq.class, PEvents.eWithDrawResp.class);
6352
}
@@ -238,17 +227,6 @@ public GuaranteedWithDrawProgress() {
238227
.build());
239228
} // constructor
240229

241-
public void reInitializeMonitor() {
242-
registerState(prt.State.keyedOn(PrtStates.NopendingRequests)
243-
.isInitialState(true)
244-
.withEvent(PEvents.eWithDrawReq.class, p -> { Anon_3(p); gotoState(PrtStates.PendingReqs); })
245-
.build());
246-
registerState(prt.State.keyedOn(PrtStates.PendingReqs)
247-
.withEvent(PEvents.eWithDrawResp.class, this::Anon_4)
248-
.withEvent(PEvents.eWithDrawReq.class, p -> { Anon_5(p); gotoState(PrtStates.PendingReqs); })
249-
.build());
250-
};
251-
252230
public java.util.List<Class<? extends prt.events.PEvent<?>>> getEventTypes() {
253231
return java.util.Arrays.asList(PEvents.eWithDrawReq.class, PEvents.eWithDrawResp.class);
254232
}

0 commit comments

Comments
 (0)