Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
347 lines (315 loc) · 12.1 KB
/
Copy pathlib.rs
File metadata and controls
347 lines (315 loc) · 12.1 KB
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! The microwave oven, the textbook model-checking example (Clarke, Grumberg
//! and Peled, *Model Checking*, ch. 4). Start it and it cooks for a while, then
//! stops. Open the door while it cooks and it must pause: heat off, time kept;
//! close the door and press start to resume. Start it with the door open and
//! that is an error: no heat until the door is closed.
//!
//! One rule everyone has trusted with their hand: the magnetron is never on
//! while the door is open. `Microwave` keeps it. `BuggyMicrowave` handles the
//! door opening by recording that the door opened, and nothing else.
use correcto_core::{
CheckResult, Choice, Environment, Explorer, MachineId, Model, Registered, Report, Step, Timers,
TransitionInvariant, World, WorldInvariant,
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum Door {
Open,
Closed,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum Phase {
Idle,
Cooking,
/// The door opened mid-cook: heat off, remaining time kept. Start resumes; stop clears.
Paused,
/// Start was pressed with the door open. Cleared by closing the door or pressing stop.
Error,
}
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MicrowaveState {
pub door: Door,
pub phase: Phase,
/// What the controller last told the magnetron.
pub magnetron: bool,
}
impl MicrowaveState {
pub fn new() -> Self {
MicrowaveState { door: Door::Closed, phase: Phase::Idle, magnetron: false }
}
}
impl Default for MicrowaveState {
fn default() -> Self {
Self::new()
}
}
/// "idle, door closed, magnetron off": the same line every Correcto core prints.
impl fmt::Display for MicrowaveState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let phase = match self.phase {
Phase::Idle => "idle",
Phase::Cooking => "cooking",
Phase::Paused => "paused",
Phase::Error => "error",
};
let door = match self.door {
Door::Open => "open",
Door::Closed => "closed",
};
write!(f, "{}, door {}, magnetron {}", phase, door, if self.magnetron { "ON" } else { "off" })
}
}
impl fmt::Debug for MicrowaveState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum MicrowaveEvent {
PressStart,
PressStop,
OpenDoor,
CloseDoor,
/// The cook time ran out.
TimerDone,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum MicrowaveEffect {
Magnetron { on: bool },
ArmCookTimer,
/// Stop the countdown and keep the remaining time.
PauseCookTimer,
/// Continue the countdown from the remaining time.
ResumeCookTimer,
CancelCookTimer,
Beep,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Microwave;
impl Model for Microwave {
type State = MicrowaveState;
type Event = MicrowaveEvent;
type Effect = MicrowaveEffect;
fn step(state: &MicrowaveState, event: &MicrowaveEvent) -> Step<MicrowaveState, MicrowaveEffect> {
microwave_step(state, event, true)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BuggyMicrowave;
impl Model for BuggyMicrowave {
type State = MicrowaveState;
type Event = MicrowaveEvent;
type Effect = MicrowaveEffect;
fn step(state: &MicrowaveState, event: &MicrowaveEvent) -> Step<MicrowaveState, MicrowaveEffect> {
microwave_step(state, event, false)
}
}
fn microwave_step(state: &MicrowaveState, event: &MicrowaveEvent, fixed: bool) -> Step<MicrowaveState, MicrowaveEffect> {
use MicrowaveEffect::*;
use MicrowaveEvent::*;
let mut next = state.clone();
match (state.phase, event) {
(Phase::Idle, PressStart) => {
if state.door == Door::Open {
next.phase = Phase::Error;
return Step::new(next, vec![Beep]);
}
next.phase = Phase::Cooking;
next.magnetron = true;
Step::new(next, vec![Magnetron { on: true }, ArmCookTimer])
}
(Phase::Cooking, TimerDone) => {
next.phase = Phase::Idle;
next.magnetron = false;
Step::new(next, vec![Magnetron { on: false }, Beep])
}
(Phase::Cooking, PressStop) => {
next.phase = Phase::Idle;
next.magnetron = false;
Step::new(next, vec![Magnetron { on: false }, CancelCookTimer])
}
(Phase::Cooking, OpenDoor) => {
next.door = Door::Open;
if !fixed {
// The buggy version records that the door opened, and nothing else.
return Step::new(next, vec![]);
}
next.phase = Phase::Paused;
next.magnetron = false;
Step::new(next, vec![Magnetron { on: false }, PauseCookTimer])
}
(Phase::Paused, PressStart) => {
if state.door == Door::Open {
return Step::ignore(state);
}
next.phase = Phase::Cooking;
next.magnetron = true;
Step::new(next, vec![Magnetron { on: true }, ResumeCookTimer])
}
(Phase::Paused, PressStop) => {
next.phase = Phase::Idle;
Step::new(next, vec![CancelCookTimer])
}
(Phase::Error, CloseDoor) => {
next.door = Door::Closed;
next.phase = Phase::Idle;
Step::new(next, vec![])
}
(Phase::Error, PressStop) => {
next.phase = Phase::Idle;
Step::new(next, vec![])
}
(_, OpenDoor) => {
next.door = Door::Open;
Step::new(next, vec![])
}
(_, CloseDoor) => {
next.door = Door::Closed;
Step::new(next, vec![])
}
_ => Step::ignore(state),
}
}
// ---------------------------------------------------------------------------
// Environment: the person, the cook timer, and budgets that keep it finite.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub struct MicrowaveEnv {
pub timers: Timers<String>,
pub starts_left: u32,
pub door_moves_left: u32,
pub stops_left: u32,
}
impl Default for MicrowaveEnv {
fn default() -> Self {
MicrowaveEnv { timers: Timers::default(), starts_left: 2, door_moves_left: 2, stops_left: 1 }
}
}
pub fn machine_id() -> MachineId {
MachineId::new("oven")
}
pub fn environment<M>() -> Environment<M, MicrowaveEnv>
where
M: Model<State = MicrowaveState, Event = MicrowaveEvent, Effect = MicrowaveEffect>,
{
Environment::new(
|env: &mut MicrowaveEnv, owner: &MachineId, effects: &[MicrowaveEffect]| {
for effect in effects {
match effect {
MicrowaveEffect::ArmCookTimer | MicrowaveEffect::ResumeCookTimer => env.timers.arm("cook".into(), 0, owner),
MicrowaveEffect::PauseCookTimer | MicrowaveEffect::CancelCookTimer => {
env.timers.cancel(&"cook".to_string(), owner)
}
MicrowaveEffect::Magnetron { .. } | MicrowaveEffect::Beep => {}
}
}
},
|env: &MicrowaveEnv, machines: &BTreeMap<MachineId, MicrowaveState>| {
let mut out: Vec<Choice<M, MicrowaveEnv>> = Vec::new();
for (id, state) in machines {
if env.starts_left > 0 {
let mut next = env.clone();
next.starts_left -= 1;
out.push(Choice::deliver("press start", MicrowaveEvent::PressStart, id, next));
}
if env.door_moves_left > 0 {
let mut next = env.clone();
next.door_moves_left -= 1;
let (label, event) = match state.door {
Door::Closed => ("door opens", MicrowaveEvent::OpenDoor),
Door::Open => ("door closes", MicrowaveEvent::CloseDoor),
};
out.push(Choice::deliver(label, event, id, next));
}
if env.stops_left > 0 {
let mut next = env.clone();
next.stops_left -= 1;
out.push(Choice::deliver("press stop", MicrowaveEvent::PressStop, id, next));
}
}
out.extend(env.timers.choices::<M, _>(env, |env| &mut env.timers, |_| MicrowaveEvent::TimerDone));
out
},
)
}
pub fn world<M>(env: MicrowaveEnv) -> World<M, MicrowaveEnv>
where
M: Model<State = MicrowaveState>,
{
let mut machines = BTreeMap::new();
machines.insert(machine_id(), MicrowaveState::new());
World::new(machines, env)
}
// ---------------------------------------------------------------------------
// Rules
pub fn invariants<M>() -> Vec<WorldInvariant<M, MicrowaveEnv>>
where
M: Model<State = MicrowaveState>,
{
vec![
WorldInvariant::always("the magnetron is never on with the door open", |world: &World<M, MicrowaveEnv>| {
world.machines.values().all(|oven| !(oven.magnetron && oven.door == Door::Open))
}),
WorldInvariant::always("the magnetron is on only while cooking", |world: &World<M, MicrowaveEnv>| {
world.machines.values().all(|oven| oven.magnetron == (oven.phase == Phase::Cooking))
}),
WorldInvariant::always("paused means the door was opened mid-cook and the heat is off", |world: &World<M, MicrowaveEnv>| {
world.machines.values().all(|oven| oven.phase != Phase::Paused || !oven.magnetron)
}),
WorldInvariant::always("cooking means the cook timer is armed", |world: &World<M, MicrowaveEnv>| {
world.machines.iter().all(|(id, oven)| {
(oven.phase == Phase::Cooking) == !world.env.timers.armed_for(id).is_empty()
})
}),
WorldInvariant::quiescent("when nothing more can happen, the oven is not cooking", |world: &World<M, MicrowaveEnv>| {
world.machines.values().all(|oven| oven.phase != Phase::Cooking)
}),
]
}
pub fn transition_invariants<M>() -> Vec<TransitionInvariant<M>>
where
M: Model<State = MicrowaveState, Event = MicrowaveEvent>,
{
vec![TransitionInvariant::new("a timer that fires when not cooking is a no-op", |t: &correcto_core::Transition<M>| {
t.event != MicrowaveEvent::TimerDone || t.before.phase == Phase::Cooking || t.is_no_op()
})]
}
pub fn check_model<M>() -> Report<M, MicrowaveEnv>
where
M: Model<State = MicrowaveState, Event = MicrowaveEvent, Effect = MicrowaveEffect>,
{
Explorer::new(environment::<M>())
.with_invariants(invariants::<M>())
.with_transition_invariants(transition_invariants::<M>())
.explore(world::<M>(MicrowaveEnv::default()))
}
/// Registration for the generic surfaces, by name.
pub fn registered_fixed() -> Registered<Microwave> {
Registered::new("microwave", |_| Ok(MicrowaveState::new()), |s: &MicrowaveState| s.to_string(), || {
CheckResult::from_report_described("microwave", &check_model::<Microwave>(), |s| s.to_string())
})
}
pub fn registered_buggy() -> Registered<BuggyMicrowave> {
Registered::new("microwave-buggy", |_| Ok(MicrowaveState::new()), |s: &MicrowaveState| s.to_string(), || {
CheckResult::from_report_described("microwave-buggy", &check_model::<BuggyMicrowave>(), |s| s.to_string())
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fixed_oven_holds_every_rule() {
let report = check_model::<Microwave>();
assert!(report.passed(), "{report}");
assert!(report.exhaustive());
}
#[test]
fn buggy_oven_heats_with_the_door_open_in_two_moves() {
let report = check_model::<BuggyMicrowave>();
let v = report.violation.as_ref().expect("a violation");
assert_eq!(v.invariant, "the magnetron is never on with the door open");
assert_eq!(v.trace.steps.len(), 2, "{report}");
println!("{report}");
}
}