/
TLCExt.java
253 lines (227 loc) · 9.97 KB
/
TLCExt.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*******************************************************************************
* Copyright (c) 2019 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package tlc2.module;
import java.io.IOException;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
import tla2sany.semantic.ExprOrOpArgNode;
import tla2sany.semantic.OpDeclNode;
import tla2sany.semantic.StringNode;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.overrides.TLAPlusOperator;
import tlc2.overrides.Evaluation;
import tlc2.tool.Action;
import tlc2.tool.ConcurrentTLCTrace;
import tlc2.tool.EvalException;
import tlc2.tool.ModelChecker;
import tlc2.tool.SimulationWorker;
import tlc2.tool.StateVec;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateInfo;
import tlc2.tool.coverage.CostModel;
import tlc2.tool.impl.Tool;
import tlc2.util.Context;
import tlc2.value.impl.BoolValue;
import tlc2.value.impl.RecordValue;
import tlc2.value.impl.StringValue;
import tlc2.value.impl.TupleValue;
import tlc2.value.impl.Value;
import util.Assert;
import util.Assert.TLCRuntimeException;
public class TLCExt {
@Evaluation(definition = "AssertError", module = "TLCExt", warn = false, silent = true)
public synchronized static Value assertError(final Tool tool, final ExprOrOpArgNode[] args, final Context c,
final TLCState s0, final TLCState s1, final int control, final CostModel cm) {
// Check expected err is a string.
Assert.check(args[0] instanceof StringNode, "In computing AssertError, a non-string expression (" + args[0]
+ ") was used as the err " + "of an AssertError(err, exp).");
try {
tool.eval(args[1], c, s0, s1, control, cm);
} catch (EvalException | TLCRuntimeException e) {
final StringValue err = (StringValue) tool.eval(args[0], c, s0);
if (err.val.equals(e.getMessage())) {
return BoolValue.ValTrue;
}
}
return BoolValue.ValFalse;
}
private static final Scanner scanner = new Scanner(System.in);
// This is likely only useful with a single worker, but let's synchronize
// anyway.
@Evaluation(definition = "PickSuccessor", module = "TLCExt", warn = false, silent = true)
public synchronized static Value pickSuccessor(final Tool tool, final ExprOrOpArgNode[] args, final Context c,
final TLCState s0, final TLCState s1, final int control, final CostModel cm) {
// TLC checks action constraints before it checks if states are new or not. Exclude seen states here
// to not repeatedly ask a user to extend a behavior with the same state over and over again.
try {
if (((ModelChecker) TLCGlobals.mainChecker).theFPSet.contains(s1.fingerPrint())) {
// If it is a seen state it is by definition in the model.
return BoolValue.ValTrue;
}
} catch (IOException notExpectedToHappen) {
notExpectedToHappen.printStackTrace();
return BoolValue.ValTrue;
}
// Eval expression and only let user interactively pick successor states when it
// evaluates to FALSE.
final Value guard = tool.eval(args[0], c, s0, s1, control, cm);
if (!(guard instanceof BoolValue)) {
Assert.fail("In evaluating TLCExt!PickSuccessor, a non-boolean expression (" + guard.getKindString()
+ ") was used as the condition " + "of an IF.\n" + args[0]);
}
if (((BoolValue) guard).val) {
return BoolValue.ValTrue;
}
// Find the (first) Action this pair of states belongs to. If more than one
// Action match, we pick the first one.
// TODO: This is clumsy (we regenerate all next-states again) and incorrect if
// two actions generate the same successor states. It's good enough for now
// until the Action instance was passed down the call-stack.
Action action = null;
LOOP: for (Action act : tool.getActions()) {
StateVec nextStates = tool.getNextStates(act, s0);
if (nextStates.contains(s1)) {
action = act;
break LOOP;
}
}
while (true) {
// TODO Add more commands such as continue/resume to pick every successor,
// randomly pick next N successors, terminate to stop state space exploration,
// ...
MP.printMessage(EC.TLC_MODULE_OVERRIDE_STDOUT,
String.format(
"Extend behavior of length %s with a \"%s\" step [%s]? (Yes/no/explored/states/diff):",
s0.getLevel(), action.getName(), action));
final String nextLine = scanner.nextLine();
if (nextLine.trim().isEmpty() || nextLine.toLowerCase().startsWith("y")) {
return BoolValue.ValTrue;
} else if (nextLine.charAt(0) == 's') {
MP.printMessage(EC.TLC_MODULE_OVERRIDE_STDOUT,
String.format("%s\n~>\n%s", s0.toString().trim(), s1.toString().trim()));
} else if (nextLine.charAt(0) == 'd') {
MP.printMessage(EC.TLC_MODULE_OVERRIDE_STDOUT, s1.toString(s0));
} else if (nextLine.charAt(0) == 'e') {
try {
((ModelChecker) TLCGlobals.mainChecker).theFPSet.put(s1.fingerPrint());
} catch (IOException notExpectedToHappen) {
notExpectedToHappen.printStackTrace();
}
return BoolValue.ValTrue;
} else if (nextLine.charAt(0) == 'n') {
return BoolValue.ValFalse;
}
}
}
@Evaluation(definition = "Trace", module = "TLCExt", minLevel = 1, warn = false, silent = true)
public synchronized static TupleValue getTrace(final Tool tool, final ExprOrOpArgNode[] args, final Context c,
final TLCState s0, final TLCState s1, final int control, final CostModel cm) throws IOException {
return getTrace(s0);
}
public synchronized static TupleValue getTrace(final TLCState s0) throws IOException {
if (!s0.allAssigned()) {
/*
* Fail when Trace appears before the state is completely specified (see
* EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_INITIAL)
*
* VARIABLE var
* ...
* Init == PrintT(Trace) /\ var = 42
* ...
*/
final Set<OpDeclNode> unassigned = s0.getUnassigned();
Assert.fail(EC.GENERAL, String.format(
"In evaluating TLCExt!Trace, the state is not completely specified yet (variable%s %s undefined).",
unassigned.size() > 1 ? "s" : "",
unassigned.stream().map(n -> n.getName().toString()).collect(Collectors.joining(", "))));
}
if (s0.isInitial()) {
return new TupleValue(new Value[] { new RecordValue(s0) });
}
if (TLCGlobals.simulator != null) {
// TODO Somehow load only this implementation in simulation mode => module
// overrides for a specific tool mode.
return getTrace0(s0, TLCGlobals.simulator.getTraceInfo());
}
final ModelChecker mc = (ModelChecker) TLCGlobals.mainChecker;
final ConcurrentTLCTrace traceFile = mc.trace;
return getTrace0(s0, traceFile.getTrace(s0));
}
@Evaluation(definition = "TraceFrom", module = "TLCExt", minLevel = 1, warn = false, silent = true)
public synchronized static TupleValue getTraceFrom(final Tool tool, final ExprOrOpArgNode[] args, final Context c,
final TLCState s0, final TLCState s1, final int control, final CostModel cm) throws IOException {
final Value v = tool.eval(args[0], c, s0, s1, control, cm);
if (!(v instanceof RecordValue)) {
Assert.fail(EC.GENERAL, "In evaluating TLCExt!TraceFrom, a non-record expression (" + v.getKindString()
+ ") was used as the parameter.\n" + args[0]);
}
final TLCState from = ((RecordValue) v).toState();
Assert.check(from.allAssigned(), EC.GENERAL,
"In evaluating TLCExt!TraceFrom, the given parameter could not be converted into a valid state.");
if (s0.isInitial() || from.equals(s0)) {
return new TupleValue(new RecordValue(s0));
}
if (TLCGlobals.simulator != null) {
final SimulationWorker w = (SimulationWorker) Thread.currentThread();
return new TupleValue(w.getTrace().toRecords(from, s0));
}
final ModelChecker mc = (ModelChecker) TLCGlobals.mainChecker;
final ConcurrentTLCTrace traceFile = mc.trace;
return getTrace0(s0, traceFile.getTrace(from, s0));
}
private static final TupleValue getTrace0(final TLCState s0, final TLCStateInfo[] trace) {
final Value[] values = new Value[trace.length + 1];
for (int j = 0; j < (trace.length); j++) {
values[j] = new RecordValue(trace[j].state);
}
values[values.length - 1] = new RecordValue(s0);
return new TupleValue(values);
}
@Evaluation(definition = "TLCDefer", module = "TLCExt", warn = false, silent = true)
public static Value tlcDefer(final Tool tool, final ExprOrOpArgNode[] args, final Context c,
final TLCState s0, final TLCState s1, final int control, final CostModel cm) {
try {
s1.setCallable(() -> {
final Value[] argVals = new Value[args.length];
// evaluate the operator's arguments:
for (int i = 0; i < args.length; i++) {
argVals[i] = tool.eval(args[i], c, s0, s1, control, cm);
}
return null;
});
} catch (Throwable e) {
Assert.fail(EC.TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE, new String[] { "TLCDefer", e.getMessage() });
}
return BoolValue.ValTrue;
}
@TLAPlusOperator(identifier = "TLCNoOp", module = "TLCExt", warn = false)
public static Value tlcNoOp(final Value val) {
return val;
}
}