1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::hash::Hash;
4
5use crate::siw::{Subgoals, serialize};
6use crate::{SearchResult, WidthProblem};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Condition {
15 Zero(usize),
17 Positive(usize),
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Effect {
26 Positive(usize),
28 Zero(usize),
30 Increase(usize),
32 Decrease(usize),
34 Any(usize),
36}
37
38impl Effect {
39 fn feature(self) -> usize {
41 match self {
42 Self::Positive(f)
43 | Self::Zero(f)
44 | Self::Increase(f)
45 | Self::Decrease(f)
46 | Self::Any(f) => f,
47 }
48 }
49
50 fn allows(self, from: u64, to: u64) -> bool {
52 match self {
53 Self::Positive(_) => to > 0,
54 Self::Zero(_) => to == 0,
55 Self::Increase(_) => to > from,
56 Self::Decrease(_) => to < from,
57 Self::Any(_) => true,
58 }
59 }
60}
61
62#[derive(Clone, Debug, Default, PartialEq, Eq)]
66pub struct Rule {
67 pub conditions: Vec<Condition>,
69 pub effects: Vec<Effect>,
72}
73
74impl Rule {
75 fn allows(&self, from: &[u64], to: &[u64]) -> bool {
82 let conditions = self.conditions.iter().all(|c| match *c {
83 Condition::Zero(f) => value(from, f) == 0,
84 Condition::Positive(f) => value(from, f) > 0,
85 });
86 if !conditions {
87 return false;
88 }
89
90 let effects = self
91 .effects
92 .iter()
93 .all(|e| e.allows(value(from, e.feature()), value(to, e.feature())));
94 let others_unchanged = (0..from.len())
95 .filter(|&f| self.effects.iter().all(|e| e.feature() != f))
96 .all(|f| from[f] == to[f]);
97
98 effects && others_unchanged
99 }
100}
101
102fn value(values: &[u64], f: usize) -> u64 {
108 *values.get(f).unwrap_or_else(|| {
109 panic!(
110 "sketch rule names feature {f}, but only {} features are defined",
111 values.len()
112 )
113 })
114}
115
116pub fn siw_r<P, F>(
142 problem: &P,
143 rules: &[Rule],
144 features: F,
145 max_k: usize,
146) -> SearchResult<P::Action>
147where
148 P: WidthProblem,
149 P::State: Hash + Eq,
150 F: Fn(&P::State, &mut Vec<u64>),
151{
152 let subgoals = SketchSubgoals {
153 problem,
154 rules,
155 features,
156 passed: HashSet::from([problem.initial_state()]),
157 buf: RefCell::new(Vec::new()),
158 };
159
160 serialize(
161 problem,
162 max_k,
163 None::<fn(&P::State, &mut Vec<u32>)>,
164 subgoals,
165 )
166}
167
168struct SketchSubgoals<'p, P: WidthProblem, F> {
170 problem: &'p P,
172 rules: &'p [Rule],
174 features: F,
176 passed: HashSet<P::State>,
178 buf: RefCell<Vec<u64>>,
181}
182
183impl<P, F> SketchSubgoals<'_, P, F>
184where
185 P: WidthProblem,
186 F: Fn(&P::State, &mut Vec<u64>),
187{
188 fn values(&self, state: &P::State) -> Vec<u64> {
190 let mut out = Vec::new();
191 (self.features)(state, &mut out);
192 out
193 }
194
195 fn allows(&self, from_values: &[u64], state: &P::State) -> bool {
198 let mut buf = self.buf.borrow_mut();
199 buf.clear();
200 (self.features)(state, &mut buf);
201 allowed(self.rules, from_values, &buf)
202 }
203}
204
205impl<P, F> Subgoals<P::State> for SketchSubgoals<'_, P, F>
206where
207 P: WidthProblem,
208 P::State: Hash + Eq,
209 F: Fn(&P::State, &mut Vec<u64>),
210{
211 type Anchor = (P::State, Vec<u64>);
213
214 fn anchor(&mut self, from: &P::State) -> Self::Anchor {
215 (from.clone(), self.values(from))
216 }
217
218 fn reached(&self, (from, from_values): &Self::Anchor, state: &P::State) -> bool {
219 self.problem.is_goal(state) || (state != from && self.allows(from_values, state))
220 }
221
222 fn advance(&mut self, state: &P::State) -> bool {
224 self.passed.insert(state.clone())
225 }
226}
227
228fn allowed(rules: &[Rule], from: &[u64], to: &[u64]) -> bool {
235 assert_eq!(
236 from.len(),
237 to.len(),
238 "sketch features must push the same number of values for every state"
239 );
240 rules.iter().any(|r| r.allows(from, to))
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246 use crate::test_problems::Line;
247
248 #[expect(
250 clippy::trivially_copy_pass_by_ref,
251 reason = "matches the sketch feature closure signature"
252 )]
253 fn position(s: &u32, out: &mut Vec<u64>) {
254 out.push(u64::from(*s));
255 }
256
257 #[test]
259 fn an_increasing_sketch_steps_to_the_goal() {
260 let rules = [Rule {
261 conditions: vec![],
262 effects: vec![Effect::Increase(0)],
263 }];
264 let r = siw_r(&Line { len: 6 }, &rules, position, 1);
265
266 assert_eq!(r.plan.as_deref(), Some(&[1; 6][..]));
267 }
268
269 #[test]
272 fn a_cycling_sketch_gives_up() {
273 let rules = [Rule {
274 conditions: vec![],
275 effects: vec![Effect::Any(0)],
276 }];
277 let r = siw_r(&Line { len: 6 }, &rules, position, 1);
278
279 assert!(r.plan.is_none());
280 }
281
282 #[test]
284 fn unmet_conditions_leave_only_the_goal() {
285 let rules = [Rule {
286 conditions: vec![Condition::Zero(0), Condition::Positive(0)],
287 effects: vec![Effect::Any(0)],
288 }];
289 let r = siw_r(&Line { len: 4 }, &rules, position, 1);
290
291 assert_eq!(r.plan.as_deref(), Some(&[1; 4][..]));
292 }
293
294 #[test]
296 fn rule_compatibility() {
297 let rule = |effects| Rule {
298 conditions: vec![],
299 effects,
300 };
301
302 assert!(rule(vec![Effect::Positive(0)]).allows(&[0, 5], &[2, 5]));
303 assert!(!rule(vec![Effect::Positive(0)]).allows(&[0, 5], &[2, 6]));
304 assert!(rule(vec![Effect::Zero(0)]).allows(&[3], &[0]));
305 assert!(rule(vec![Effect::Decrease(0)]).allows(&[3], &[2]));
306 assert!(!rule(vec![Effect::Decrease(0)]).allows(&[3], &[3]));
307 assert!(rule(vec![]).allows(&[3, 1], &[3, 1]));
308 }
309
310 #[test]
312 #[should_panic(expected = "names feature 3")]
313 fn rejects_unknown_features() {
314 let rules = [Rule {
315 conditions: vec![Condition::Positive(3)],
316 effects: vec![],
317 }];
318 siw_r(&Line { len: 2 }, &rules, position, 1);
319 }
320}