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
#[must_use = "Without using the `Command` it doesn't do anything. You should execute it through `run!()` or `run_loop!()`."]
pub enum Command<R, T> {
Give(T),
Return(R),
Break,
Continue,
}
#[macro_export]
macro_rules! defer {
(return $val:expr) => { $crate::Command::Return($val) };
(return) => { defer!(return ()) };
(break) => { $crate::Command::Break };
(continue) => { $crate::Command::Continue };
($val:expr) => { $crate::Command::Give($val) };
() => { defer!(()) }
}
#[macro_export]
macro_rules! run {
($command:expr) => {
match $command {
$crate::Command::Give(x) => x,
$crate::Command::Return(x) => return x,
_ => panic!("\
Using loop-dependent `Command` variants without loop mode enabled. Consider using \
`control_loop` instead.
"),
}
}
}
#[macro_export]
macro_rules! run_loop {
($command:expr) => {
match $command {
$crate::Command::Give(x) => x,
$crate::Command::Return(x) => return x,
$crate::Command::Break => break,
$crate::Command::Continue => continue,
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn loop_break() {
let mut x = true;
loop {
run_loop!(defer!(break));
x = false;
}
assert!(x);
}
#[test]
fn loop_continue() {
let mut x = true;
for _ in 0..100 {
assert!(x);
run_loop!(defer!(continue));
x = false;
}
}
#[test]
#[allow(unused_assignments)]
fn return_early() {
let x = false;
run!(defer!(return));
assert!(x);
}
#[test]
#[allow(unused_assignments)]
fn store_ctrl() {
assert!((|| {
let mut x = defer!(return false);
x = defer!(return true);
run!(x);
unreachable!();
})());
}
#[test]
fn direct_value() {
assert!(run!(defer!(true)));
assert_eq!(run!(defer!()), ());
}
}