-
Notifications
You must be signed in to change notification settings - Fork 0
/
control_flow.rs
461 lines (436 loc) · 14.1 KB
/
control_flow.rs
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Meta-components for specifying control flow.
use derivative::Derivative;
use serde::Serialize;
use crate::{
component::ExecResult,
components::Component,
conditions::Condition,
problems::Problem,
state::{common, State, StateReq},
};
/// A block of components executed sequentially.
///
/// This is equivalent to sequential statements:
/// ```no_run
/// # fn statement1() {}
/// # fn statement2() {}
/// # fn statement3() {}
///
/// statement1();
/// statement2();
/// statement3();
/// ```
///
/// # Call propagation
///
/// Calling any of the `{init, require, execute}` methods on a block calls the specific
/// method sequentially in order on the inner components.
///
/// # Examples
///
/// A `Block` is usually only created implicitly by calling the [`do_`] method on [`Configuration::builder`]:
///
/// [`do_`]: crate::configuration::ConfigurationBuilder::do_
/// [`Configuration::builder`]: crate::Configuration::builder
///
/// ```no_run
/// # use mahf::Problem;
/// # fn component1<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component2<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component3<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// use mahf::Configuration;
/// # pub fn example<P: Problem>() -> Configuration<P> {
/// Configuration::builder()
/// .do_(component1())
/// .do_(component2())
/// .do_(component3())
/// .build()
/// # }
/// ```
#[derive(Serialize, Derivative)]
#[serde(bound = "")]
#[serde(transparent)]
#[derivative(Clone(bound = ""))]
pub struct Block<P: Problem>(Vec<Box<dyn Component<P>>>);
impl<P: Problem> Block<P> {
/// Creates a new `Block` from a collection of [`Component`]s.
pub fn new(
components: impl IntoIterator<Item = Box<dyn Component<P>>>,
) -> Box<dyn Component<P>> {
Box::new(Self(components.into_iter().collect()))
}
}
impl<P: Problem> Component<P> for Block<P> {
fn init(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
for component in &self.0 {
component.init(problem, state)?;
}
Ok(())
}
fn require(&self, problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
for component in &self.0 {
component.require(problem, state_req)?;
}
Ok(())
}
fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
for component in &self.0 {
component.execute(problem, state)?;
}
Ok(())
}
}
impl<I: IntoIterator<Item = Box<dyn Component<P>>>, P: Problem> From<I> for Box<dyn Component<P>> {
fn from(value: I) -> Self {
Block::new(value)
}
}
/// Loops the `body` while a `condition` is `true`.
///
/// This is equivalent to a `while` loop:
/// ```no_run
/// # fn condition() -> bool { true }
/// # fn body() {}
/// while condition() {
/// body()
/// }
/// ```
///
/// Arbitrary conditions are possible, but common is terminating the loop when a certain
/// number of [`Iterations`] or [`Evaluations`] are reached.
///
/// See the documentation of [`LessThanN`] for more details.
///
/// [`Evaluations`]: common::Evaluations
/// [`LessThanN`]: crate::conditions::LessThanN
///
/// # State
///
/// This component inserts and updates the current number of [`Iterations`].
///
/// Note that a [`Scope`] is needed for nested loops, so that the inner `Loop` doesn't overwrite
/// the outer amount of [`Iterations`].
///
/// [`Iterations`]: common::Iterations
///
/// # Call propagation
///
/// Calling any of the `{init, require}` methods on a loop calls the specific
/// method once on the inner component and condition.
///
/// On calling the `execute` method, the `condition` is re-initialized, after which the
/// `body` is executed until the `condition` evaluates to `false`.
///
/// # Examples
///
/// A `Loop` is usually created by calling the [`while_`] method on [`Configuration::builder`]:
///
/// [`while_`]: crate::configuration::ConfigurationBuilder::while_
/// [`Configuration::builder`]: crate::Configuration::builder
///
/// ```no_run
/// # use mahf::Problem;
/// # fn condition<P: Problem>() -> Box<dyn mahf::Condition<P>> { unimplemented!() }
/// # fn component1<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component2<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component3<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// use mahf::Configuration;
/// # pub fn example<P: Problem>() -> Configuration<P> {
/// Configuration::builder()
/// .while_(condition(), |builder| {
/// builder
/// .do_(component1())
/// .do_(component2())
/// .do_(component3())
/// })
/// .build()
/// # }
/// ```
#[derive(Serialize, Derivative)]
#[serde(bound = "")]
#[derivative(Clone(bound = ""))]
pub struct Loop<P: Problem> {
#[serde(rename = "while")]
condition: Box<dyn Condition<P>>,
#[serde(rename = "do")]
body: Box<dyn Component<P>>,
}
impl<P: Problem> Loop<P> {
/// Creates a new `Loop` with some `condition` and a body.
pub fn new(
condition: Box<dyn Condition<P>>,
body: impl Into<Box<dyn Component<P>>>,
) -> Box<dyn Component<P>> {
Box::new(Loop {
condition,
body: body.into(),
})
}
}
impl<P: Problem> Component<P> for Loop<P> {
fn init(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
state.insert(common::Iterations(0));
self.condition.init(problem, state)?;
self.body.init(problem, state)?;
Ok(())
}
fn require(&self, problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
self.condition.require(problem, state_req)?;
self.body.require(problem, state_req)?;
Ok(())
}
fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
self.condition.init(problem, state)?;
while self.condition.evaluate(problem, state)? {
self.body.execute(problem, state)?;
*state.try_borrow_value_mut::<common::Iterations>()? += 1;
}
Ok(())
}
}
/// Executes the `if` or `else` branch depending on the `condition`.
///
/// This is equivalent to an `if` statement with an optional `else`:
/// ```no_run
/// # fn condition() -> bool { true }
/// # fn if_body() {}
/// # fn else_body() {}
///
/// if condition() {
/// if_body();
/// }
///
/// if condition() {
/// if_body();
/// } else {
/// else_body();
/// }
/// ```
///
/// # Call propagation
///
/// Calling any of the `{init, require}` methods on a branch calls the specific
/// method once on the inner components and condition.
///
/// On calling the `execute` method, the `if_body` is executed if the `condition`
/// evaluates to `true`, and the optional `else_body` if executed if present, otherwise.
///
/// # Examples
///
/// A `Branch` is usually created by calling the [`if_`] method on [`Configuration::builder`]:
///
/// [`if_`]: crate::configuration::ConfigurationBuilder::if_
/// [`Configuration::builder`]: crate::Configuration::builder
///
/// ```no_run
/// # use mahf::Problem;
/// # fn condition<P: Problem>() -> Box<dyn mahf::Condition<P>> { unimplemented!() }
/// # fn component1<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component2<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component3<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// use mahf::Configuration;
/// # pub fn example<P: Problem>() -> Configuration<P> {
/// Configuration::builder()
/// .if_(condition(), |builder| {
/// builder
/// .do_(component1())
/// .do_(component2())
/// .do_(component3())
/// })
/// .build()
/// # }
/// ```
///
/// For also creating an `else` branch, use the [`if_else_`] method:
///
/// [`if_else_`]: crate::configuration::ConfigurationBuilder::if_else_
///
/// ```no_run
/// # use mahf::Problem;
/// # fn condition<P: Problem>() -> Box<dyn mahf::Condition<P>> { unimplemented!() }
/// # fn component1<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component2<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component3<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component4<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// use mahf::Configuration;
///
/// # pub fn example<P: Problem>() -> Configuration<P> {
/// Configuration::builder()
/// .if_else_(condition(),
/// |if_builder| {
/// if_builder
/// .do_(component1())
/// .do_(component2())
/// },
/// |else_builder| {
/// else_builder
/// .do_(component3())
/// .do_(component4())
/// })
/// .build()
/// # }
/// ```
#[derive(Serialize, Derivative)]
#[serde(bound = "")]
#[derivative(Clone(bound = ""))]
pub struct Branch<P: Problem> {
condition: Box<dyn Condition<P>>,
if_body: Box<dyn Component<P>>,
else_body: Option<Box<dyn Component<P>>>,
}
impl<P: Problem> Branch<P> {
/// Creates a new `Branch` with only an `if` branch:
///
/// ```text
/// if(condition) { body }
/// ```
pub fn new(
condition: Box<dyn Condition<P>>,
body: impl Into<Box<dyn Component<P>>>,
) -> Box<dyn Component<P>> {
Box::new(Branch {
condition,
if_body: body.into(),
else_body: None,
})
}
/// Creates a new `Branch` with an `if`-`else` branch:
///
/// ```text
/// if(condition) { if_body } else { else_body }
/// ```
pub fn new_with_else(
condition: Box<dyn Condition<P>>,
if_body: impl Into<Box<dyn Component<P>>>,
else_body: impl Into<Box<dyn Component<P>>>,
) -> Box<dyn Component<P>> {
Box::new(Branch {
condition,
if_body: if_body.into(),
else_body: Some(else_body.into()),
})
}
}
impl<P: Problem> Component<P> for Branch<P> {
fn init(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
self.condition.init(problem, state)?;
self.if_body.init(problem, state)?;
if let Some(else_body) = &self.else_body {
else_body.init(problem, state)?;
}
Ok(())
}
fn require(&self, problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
self.condition.require(problem, state_req)?;
self.if_body.require(problem, state_req)?;
if let Some(else_body) = &self.else_body {
else_body.require(problem, state_req)?;
}
Ok(())
}
fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
if self.condition.evaluate(problem, state)? {
self.if_body.execute(problem, state)?;
} else if let Some(else_body) = &self.else_body {
else_body.execute(problem, state)?;
}
Ok(())
}
}
/// Executes the `body` in a new scope, where shadowing custom state is possible.
///
/// This is especially useful for nested heuristics with an inner loop.
///
/// It is equivalent to a scope:
/// ```no_run
/// # fn statement1() {}
/// # fn statement2() {}
/// # fn statement3() {}
/// {
/// statement1();
/// statement2();
/// statement3();
/// }
/// ```
///
/// # Call propagation
///
/// Calling any of the `{init, require}` methods on a scope **doesn't do anything**.
///
/// On calling the `execute` method, the `state` is first initialized using
/// the provided `state_init` function.
/// Afterwards, the `body` is executed as if it was an independent
/// [`Configuration`], e.g. the `{init, require, execute}` methods are called in order
/// in the body.
/// Finally, the provided `states_merge` function is called to merge the original state with
/// the newly created child state.
///
/// [`Configuration`]: crate::Configuration
///
/// # Examples
///
/// A `Scope` is usually only created implicitly by calling the [`scope_`] method on [`Configuration::builder`]:
///
/// [`scope_`]: crate::configuration::ConfigurationBuilder::do_
/// [`Configuration::builder`]: crate::Configuration::builder
///
/// ```no_run
/// # use mahf::Problem;
/// # fn component1<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component2<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// # fn component3<P: Problem>() -> Box<dyn mahf::Component<P>> { unimplemented!() }
/// use mahf::Configuration;
///
/// # pub fn example<P: Problem>() -> Configuration<P> {
/// Configuration::builder()
/// .scope_(|builder| {
/// builder
/// .do_(component1())
/// .do_(component2())
/// .do_(component3())
/// })
/// .build()
/// # }
/// ```
#[derive(Serialize, Derivative)]
#[serde(bound = "")]
#[derivative(Clone(bound = ""))]
pub struct Scope<P: Problem> {
body: Box<dyn Component<P>>,
#[serde(skip)]
state_init: fn(&mut State<P>) -> ExecResult<()>,
#[serde(skip)]
states_merge: fn(&mut State<P>, State<P>) -> ExecResult<()>,
}
impl<P: Problem> Scope<P> {
/// Creates a new `Scope` with the `body`.
pub fn new(body: Vec<Box<dyn Component<P>>>) -> Box<dyn Component<P>> {
Self::new_with(|_| Ok(()), body, |_, _| Ok(()))
}
/// Creates a new `Scope` with the `body`, and methods for initializing the [`State`] beforehand
/// and merging the parent and child [`State`] afterwards.
pub fn new_with(
state_init: fn(&mut State<P>) -> ExecResult<()>,
body: impl Into<Box<dyn Component<P>>>,
states_merge: fn(&mut State<P>, State<P>) -> ExecResult<()>,
) -> Box<dyn Component<P>> {
Box::new(Scope {
body: body.into(),
state_init,
states_merge,
})
}
}
impl<P: Problem> Component<P> for Scope<P> {
fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
let inner = state.with_inner_state(|state| {
(self.state_init)(state)?;
self.body.init(problem, state)?;
self.body.require(problem, &state.requirements())?;
self.body.execute(problem, state)?;
Ok(())
})?;
(self.states_merge)(state, inner)?;
Ok(())
}
}