lemma-engine 0.11.4

A pure, declarative language for business rules.
Documentation
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Writes through paths (rule 2 of `plan-filling-data.md`): `-> with a.j.x: v` and
//! `-> with a.stappen.2.x: v` on `uses a` write field `x` of the instance the path names.
//!
//! A plan holds the writes it makes through paths, keyed by the instance's path from the
//! plan and the field. The plan is the writer: a reference it writes is read there. A
//! field is written once: by the row that holds it, or by one plan above it.

use crate::parsing::source::Source;
use crate::planning::execution_plan::ExecutionPlan;
use crate::planning::instance_list::RowStore;
use crate::planning::semantics::{
    DataDefinition, DataPath, LemmaType, ListKey, RowBinding, RowInstance, SpecIdentity,
};
use indexmap::IndexMap;
use std::sync::Arc;

/// The writes a plan makes through paths, by the instance's path from the plan
/// (`["a", "j"]`, `["a", "stappen", "2"]`) and the field.
#[derive(Debug, Clone, Default)]
pub struct Writes {
    instances: IndexMap<Vec<String>, Vec<Write>>,
    /// Lists, by the path of the instance holding them and their name, one of whose rows
    /// has a key field written: the index of the list's store does not hold that key.
    rekeyed: Vec<(Vec<String>, DataPath)>,
    /// Rows that are copies (rule 4): their path, the copy row, and the row of the `uses`
    /// of the plan they copy. A plan below can fill a list at the same path with rows of
    /// its own, so a record is the copy row's.
    copies: Vec<Copy>,
    /// Lists of instances the plan fills with rows (`-> with items: a, b`), by the path of
    /// the instance and the list.
    lists: Vec<(Vec<String>, DataPath, Arc<RowStore>)>,
    /// The plan's own lists whose `uses` writes on every row (rule 2), with the row of
    /// that `uses` ([`crate::planning::instance_list::InstanceListSource::row_writes`]).
    row_writes: Vec<(DataPath, Arc<RowInstance>)>,
    /// The rows the entries above are on, by address: a lookup that finds its row in
    /// none of them is done without building a path.
    rows: RowSets,
}

/// Addresses of the rows a plan writes on through a path, the copy rows it records, and
/// the rows of the instances whose lists it fills or rekeys. Rows of a plan are shared
/// for its lifetime, so an address names one row.
#[derive(Debug, Clone, Default)]
pub(crate) struct RowSets {
    pub(crate) written: std::collections::HashSet<usize>,
    pub(crate) copies: std::collections::HashSet<usize>,
    pub(crate) filled: std::collections::HashSet<usize>,
    pub(crate) rekeyed: std::collections::HashSet<usize>,
}

impl RowSets {
    pub(crate) fn extend(&mut self, other: &RowSets) {
        self.written.extend(&other.written);
        self.copies.extend(&other.copies);
        self.filled.extend(&other.filled);
        self.rekeyed.extend(&other.rekeyed);
    }
}

/// The writes of a plan and of every plan of a spec it holds, by spec, with the rows any
/// of them is on: what evaluation looks a field up in.
#[derive(Debug, Clone, Default)]
pub(crate) struct WritesIndex {
    by_spec: std::collections::HashMap<SpecIdentity, Writes>,
    pub(crate) rows: RowSets,
    /// Every copy row by address: the number of path parts from the plan that records it
    /// to the row, and the row of the `uses` it copies. A copy row is made by the plan
    /// that records it, so its address names one record.
    copies: std::collections::HashMap<usize, (usize, Arc<RowInstance>)>,
}

impl WritesIndex {
    pub(crate) fn new(by_spec: std::collections::HashMap<SpecIdentity, Writes>) -> Self {
        let mut rows = RowSets::default();
        let mut copies = std::collections::HashMap::new();
        for writes in by_spec.values() {
            rows.extend(writes.rows());
            for copy in &writes.copies {
                copies.insert(
                    address(&copy.copy),
                    (copy.path.len(), Arc::clone(&copy.source)),
                );
            }
        }
        Self {
            by_spec,
            rows,
            copies,
        }
    }

    /// The copy row at `row`: the number of path parts from the plan recording it, and
    /// the row it copies.
    pub(crate) fn copy(&self, row: &RowInstance) -> Option<&(usize, Arc<RowInstance>)> {
        self.copies.get(&address(row))
    }

    /// Every copy row by address, as [`Self::copy`] gives it.
    pub(crate) fn copies(&self) -> impl Iterator<Item = (&usize, &(usize, Arc<RowInstance>))> {
        self.copies.iter()
    }

    pub(crate) fn get(&self, identity: &SpecIdentity) -> Option<&Writes> {
        self.by_spec.get(identity)
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.by_spec.is_empty()
    }
}

/// The address of `row`, as [`RowSets`] holds it.
pub(crate) fn address(row: &RowInstance) -> usize {
    std::ptr::from_ref(row) as usize
}

/// A row that is a copy (rule 4): its path, the row, and the `uses` of the plan it
/// copies, by alias and row.
#[derive(Debug, Clone)]
struct Copy {
    path: Vec<String>,
    copy: Arc<RowInstance>,
    alias: String,
    source: Arc<RowInstance>,
}

/// One write: the field, its value, the spec of the instance written and where the
/// write is.
#[derive(Debug, Clone)]
pub(crate) struct Write {
    pub(crate) field: DataPath,
    pub(crate) binding: RowBinding,
    pub(crate) spec: SpecIdentity,
    pub(crate) source: Source,
}

impl Writes {
    /// Whether the plan writes through a path.
    pub(crate) fn has_instances(&self) -> bool {
        !self.instances.is_empty()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.instances.is_empty()
            && self.rekeyed.is_empty()
            && self.copies.is_empty()
            && self.lists.is_empty()
            && self.row_writes.is_empty()
    }

    /// What the plan writes on field `field` of the instance at `instance`.
    pub(crate) fn get(&self, instance: &[String], field: &DataPath) -> Option<&RowBinding> {
        self.instances
            .get(instance)?
            .iter()
            .find(|write| write.field == *field)
            .map(|write| &write.binding)
    }

    /// The rows this plan's entries are on.
    pub(crate) fn rows(&self) -> &RowSets {
        &self.rows
    }

    /// Records that a key field of a row of list `list` of the instance at `holder`,
    /// whose row is `holder_row`, is written.
    pub(crate) fn rekey(&mut self, holder: Vec<String>, list: DataPath, holder_row: &RowInstance) {
        self.rows.rekeyed.insert(address(holder_row));
        if !self.rekeyed.iter().any(|(h, l)| *h == holder && *l == list) {
            self.rekeyed.push((holder, list));
        }
    }

    /// Whether a key field of a row of list `list` of the instance at `holder` is written.
    pub(crate) fn is_rekeyed(&self, holder: &[String], list: &DataPath) -> bool {
        self.rekeyed.iter().any(|(h, l)| h == holder && l == list)
    }

    /// Whether a row of list `list` of the instance at `holder` is written through.
    pub(crate) fn writes_rows_of(&self, holder: &[String], list: &DataPath) -> bool {
        self.instances.keys().any(|instance| {
            instance.len() > holder.len()
                && instance.starts_with(holder)
                && instance[holder.len()] == list.data
        })
    }

    /// Records that `copy`, the row at `path`, is a copy of this plan's `uses alias`,
    /// whose row is `source`.
    pub(crate) fn copy(
        &mut self,
        path: Vec<String>,
        copy: &Arc<RowInstance>,
        alias: &str,
        source: Arc<RowInstance>,
    ) {
        self.rows.copies.insert(address(copy));
        self.copies.push(Copy {
            path,
            copy: Arc::clone(copy),
            alias: alias.to_string(),
            source,
        });
    }

    /// The row of the `uses` of this plan `row`, at `path`, is a copy of.
    pub(crate) fn copy_of(&self, path: &[String], row: &RowInstance) -> Option<&Arc<RowInstance>> {
        self.copy_record(path, row).map(|copy| &copy.source)
    }

    /// Every copy this plan records: the copy row's address, the number of path parts from
    /// the plan to it, and the row it copies.
    pub(crate) fn copy_rows(&self) -> impl Iterator<Item = (usize, usize, &Arc<RowInstance>)> {
        self.copies
            .iter()
            .map(|copy| (address(&copy.copy), copy.path.len(), &copy.source))
    }

    /// The alias of the `uses` of this plan `row`, at `path`, is a copy of.
    pub(crate) fn copy_alias(&self, path: &[String], row: &RowInstance) -> Option<&str> {
        self.copy_record(path, row).map(|copy| copy.alias.as_str())
    }

    fn copy_record(&self, path: &[String], row: &RowInstance) -> Option<&Copy> {
        self.copies
            .iter()
            .find(|copy| copy.path == path && std::ptr::eq(copy.copy.as_ref(), row))
    }

    /// Every list this plan fills, with the path of the instance holding it.
    pub(crate) fn lists(&self) -> impl Iterator<Item = (&[String], &DataPath, &Arc<RowStore>)> {
        self.lists
            .iter()
            .map(|(holder, list, rows)| (holder.as_slice(), list, rows))
    }

    /// Records the rows this plan fills list `list` of the instance at `holder`, whose
    /// row is `holder_row`, with.
    pub(crate) fn fill_list(
        &mut self,
        holder: Vec<String>,
        holder_row: &RowInstance,
        list: DataPath,
        rows: Arc<RowStore>,
    ) {
        self.rows.filled.insert(address(holder_row));
        self.lists.push((holder, list, rows));
    }

    /// The rows this plan fills list `list` of the instance at `holder` with.
    pub(crate) fn list(&self, holder: &[String], list: &DataPath) -> Option<&Arc<RowStore>> {
        self.lists
            .iter()
            .find(|(h, l, _)| h == holder && l == list)
            .map(|(_, _, rows)| rows)
    }

    /// Records that `row`, the row of the `uses` list `list` names, writes on every row.
    pub(crate) fn write_rows(&mut self, list: DataPath, row: Arc<RowInstance>) {
        self.row_writes.retain(|(written, _)| *written != list);
        self.row_writes.push((list, row));
    }

    /// What the `uses` the plan's list `list` names writes on every row of it.
    pub(crate) fn rows_write(&self, list: &str) -> Option<&Arc<RowInstance>> {
        self.row_writes
            .iter()
            .find(|(written, _)| written.data == list)
            .map(|(_, row)| row)
    }

    /// Records `write` on the instance at `instance`, whose row (one per body of a
    /// `uses … -> effective` slot on the way) is among `rows`.
    pub(crate) fn insert(
        &mut self,
        instance: Vec<String>,
        write: Write,
        rows: &[Arc<RowInstance>],
    ) {
        for row in rows {
            self.rows.written.insert(address(row));
        }
        self.instances.entry(instance).or_default().push(write);
    }

    /// Every write, with the instance's path.
    pub(crate) fn iter(&self) -> impl Iterator<Item = (&[String], &Write)> {
        self.instances.iter().flat_map(|(instance, writes)| {
            writes.iter().map(move |write| (instance.as_slice(), write))
        })
    }
}

/// A field a path names: the plan of the instance holding it, and whether a holder on
/// the way already writes it.
pub(crate) struct Reached {
    pub(crate) template: Arc<ExecutionPlan>,
    /// The row of the instance holding the field.
    pub(crate) row: Arc<RowInstance>,
    pub(crate) field: DataPath,
    pub(crate) written: bool,
    /// The field is a key field of the list the instance is a row of: the plan holding
    /// that list, the list, and the row of the instance holding it.
    pub(crate) keys_list: Option<(Arc<ExecutionPlan>, DataPath, Arc<RowInstance>)>,
}

/// What a path names: the fields it reaches (one per body of a `uses … -> effective`
/// slot on the way), or the `uses global` slot at position `slot` it steps through.
pub(crate) enum Reach {
    Fields(Vec<Reached>),
    Global { slot: usize },
}

/// One instance on the way: its plan, its row as its holder holds it, and every holder
/// above it with the instance's path from that holder.
#[derive(Clone)]
struct Walk {
    template: Arc<ExecutionPlan>,
    row: Arc<RowInstance>,
    holders: Vec<(Arc<ExecutionPlan>, Vec<String>)>,
    /// The list the instance is a row of, with the plan holding it and the row of the
    /// instance holding it.
    listed: Option<(Arc<ExecutionPlan>, DataPath, Arc<RowInstance>)>,
    /// The `uses` row the instance is a copy of (rule 4), with its path from the writer.
    copied: Option<(Arc<RowInstance>, Vec<String>)>,
    /// The instance's path from the writing plan.
    from_writer: Vec<String>,
}

/// The field `field` of the instance `path` names inside instance `row` of plan
/// `template`: one per body a `uses … -> effective` slot on the way can select.
/// `template_of` gives the plan of a spec the way holds. `Err` names what the path does
/// not reach.
pub(crate) fn reach(
    template: Arc<ExecutionPlan>,
    row: Arc<RowInstance>,
    path: &[String],
    field: &str,
    templates: &Templates,
    writer: (&Writes, &[String]),
) -> Result<Reach, String> {
    // A path through a `uses global` slot writes on the one global instance (rule 7).
    if let Some(slot) = through_global(&template, path, templates) {
        return Ok(Reach::Global { slot });
    }
    let mut walks = vec![(
        Walk {
            template,
            row,
            holders: Vec::new(),
            listed: None,
            copied: None,
            from_writer: writer.1.to_vec(),
        },
        0usize,
    )];
    let mut reached = Vec::new();
    while let Some((walk, at)) = walks.pop() {
        let Some(name) = path.get(at) else {
            reached.push(reach_field(&walk, field, writer.0)?);
            continue;
        };
        let slot = DataPath::local(name.clone());
        match walk.template.data.get(&slot) {
            Some(DataDefinition::Import {
                row,
                pin,
                candidates,
                ..
            }) => {
                let bodies: Vec<&Arc<RowInstance>> = match pin {
                    Some(_) => candidates.values().collect(),
                    None => vec![row],
                };
                for body in bodies {
                    walks.push((
                        step(
                            &walk,
                            Arc::clone(body),
                            template_of(templates, &body.identity),
                            &[name],
                            None,
                        ),
                        at + 1,
                    ));
                }
            }
            Some(DataDefinition::InstanceList { .. }) => {
                let source = walk
                    .template
                    .instance_lists
                    .get(&slot)
                    .expect("BUG: an instance list has a source");
                let number = path.get(at + 1).and_then(|n| n.parse::<usize>().ok());
                let Some(number) = number else {
                    return Err(format!(
                        "`{name}` is a list; write a row of it as `{name}.<row>.<field>`"
                    ));
                };
                // The rows the writer or a holder on the way fills the list with, else
                // the rows the instance's spec writes.
                let (writes, from) = std::iter::once((writer.0, walk.from_writer.clone()))
                    .chain(
                        walk.holders
                            .iter()
                            .map(|(holder, path)| (&holder.writes, path.clone())),
                    )
                    .find(|(writes, from)| writes.list(from, &slot).is_some())
                    .map_or((None, Vec::new()), |(writes, from)| (Some(writes), from));
                let rows = writes
                    .and_then(|writes| writes.list(&from, &slot))
                    .unwrap_or(&source.store);
                let Some(listed) = number.checked_sub(1).and_then(|i| rows.rows.get(i)) else {
                    return Err(format!(
                        "'{name}' has {} spec-written row(s); rows are numbered from 1",
                        rows.rows.len()
                    ));
                };
                let row_path: Vec<String> = from
                    .iter()
                    .cloned()
                    .chain([name.clone(), number.to_string()])
                    .collect();
                // The plan that put the row in the list records it as a copy: the writer, a
                // holder on the way, or the instance's own plan. The source is a `uses` of
                // that plan, named from the writer.
                let recorder_path: Vec<String> = match writes {
                    Some(_) => walk.from_writer[..walk.from_writer.len() - from.len()].to_vec(),
                    None => walk.from_writer.clone(),
                };
                let recorder = writes.unwrap_or(&walk.template.writes);
                let copied = recorder.copy_of(&row_path, listed).cloned().map(|source| {
                    let alias = recorder
                        .copy_alias(&row_path, listed)
                        .expect("BUG: a copy record has an alias")
                        .to_string();
                    let mut at = recorder_path.clone();
                    at.push(alias);
                    (source, at)
                });
                let row_template = if source.identity == walk.template.identity {
                    Arc::clone(&walk.template)
                } else {
                    template_of(templates, &source.identity)
                };
                let mut next = step(
                    &walk,
                    Arc::clone(listed),
                    row_template,
                    &[name, &number.to_string()],
                    Some((
                        Arc::clone(&walk.template),
                        slot.clone(),
                        Arc::clone(&walk.row),
                    )),
                );
                next.copied = copied;
                walks.push((next, at + 2));
            }
            Some(_) => {
                return Err(format!(
                    "`{name}` of `{}` is no `uses` instance or list",
                    walk.template.identity.spec
                ))
            }
            None => {
                return Err(format!(
                    "`{}` has no data field `{name}`",
                    walk.template.identity.spec
                ))
            }
        }
    }
    Ok(Reach::Fields(reached))
}

/// The plan of the instance `path` names inside an instance of plan `template` (the
/// first body of a `uses … -> effective` slot on the way).
pub(crate) fn reach_instance(
    template: Arc<ExecutionPlan>,
    path: &[String],
    templates: &Templates,
) -> Result<Arc<ExecutionPlan>, String> {
    let mut current = template;
    let mut at = 0;
    while let Some(name) = path.get(at) {
        let slot = DataPath::local(name.clone());
        match current.data.get(&slot) {
            Some(DataDefinition::Import { row, .. }) => {
                current = template_of(templates, &row.identity);
                at += 1;
            }
            Some(DataDefinition::InstanceList { .. }) => {
                let source = &current.instance_lists[&slot];
                let next = if source.identity == current.identity {
                    Arc::clone(&current)
                } else {
                    template_of(templates, &source.identity)
                };
                current = next;
                at += 2;
            }
            Some(_) => {
                return Err(format!(
                    "`{name}` of `{}` is no `uses` instance or list",
                    current.identity.spec
                ))
            }
            None => {
                return Err(format!(
                    "`{}` has no data field `{name}`",
                    current.identity.spec
                ))
            }
        }
    }
    Ok(current)
}

/// The position in `path` of a `uses global` slot it steps through.
fn through_global(
    template: &Arc<ExecutionPlan>,
    path: &[String],
    templates: &Templates,
) -> Option<usize> {
    let mut current = Arc::clone(template);
    let mut at = 0;
    while let Some(name) = path.get(at) {
        match current.data.get(&DataPath::local(name.clone()))? {
            DataDefinition::Import {
                global: Some(_), ..
            } => return Some(at),
            DataDefinition::Import { row, .. } => {
                current = template_of(templates, &row.identity);
                at += 1;
            }
            _ => return None,
        }
    }
    None
}

/// The template plans of the specs a plan holds, by spec.
pub(crate) type Templates = std::collections::BTreeMap<SpecIdentity, Arc<ExecutionPlan>>;

/// The plan of `identity`, recorded with the plan holding an instance of it.
fn template_of(templates: &Templates, identity: &SpecIdentity) -> Arc<ExecutionPlan> {
    Arc::clone(
        templates.get(identity).unwrap_or_else(|| {
            panic!("BUG: template of `{identity}` is recorded with its importer")
        }),
    )
}

/// `walk` one instance further: to `row` of plan `template`, named `parts` in its holder.
fn step(
    walk: &Walk,
    row: Arc<RowInstance>,
    template: Arc<ExecutionPlan>,
    parts: &[&String],
    listed: Option<(Arc<ExecutionPlan>, DataPath, Arc<RowInstance>)>,
) -> Walk {
    let mut holders = walk.holders.clone();
    holders.push((Arc::clone(&walk.template), Vec::new()));
    for (_, path) in &mut holders {
        path.extend(parts.iter().map(|part| (*part).clone()));
    }
    let mut from_writer = walk.from_writer.clone();
    from_writer.extend(parts.iter().map(|part| (*part).clone()));
    Walk {
        template,
        row,
        holders,
        listed,
        copied: None,
        from_writer,
    }
}

fn reach_field(walk: &Walk, field: &str, writer: &Writes) -> Result<Reached, String> {
    let path = DataPath::local(field.to_string());
    let Some((slot, _, definition)) = walk.template.data.get_full(&path) else {
        return Err(format!(
            "`{}` has no data field `{field}`",
            walk.template.identity.spec
        ));
    };
    if matches!(definition, DataDefinition::Import { .. }) {
        return Err(format!("cannot bind import alias '{field}' as a value"));
    }
    // The row's own value, what it copies (rule 4), or what its list writes on every
    // row (rule 2).
    let by_row = walk.row.bindings[slot].is_some()
        || walk.copied.as_ref().is_some_and(|(copied, at)| {
            copied.bindings[slot].is_some() || writer.get(at, &path).is_some()
        })
        || walk.listed.as_ref().is_some_and(|(holder, list, _)| {
            holder.instance_lists[list]
                .row_writes
                .as_ref()
                .is_some_and(|written| written.bindings[slot].is_some())
        });
    // The holder right above writes the instance's fields on its row (above).
    let by_holder = walk
        .holders
        .iter()
        .rev()
        .skip(1)
        .any(|(holder, instance)| holder.writes.get(instance, &path).is_some());
    let keys_list = walk.listed.as_ref().filter(|(holder, list, _)| {
        matches!(
            &holder.instance_lists[list].key,
            ListKey::Fields(fields) if fields.iter().any(|key| key.path == path)
        )
    });
    // A list a holder on the way fills with rows (`-> with items: a, b`).
    let by_fill = walk
        .holders
        .iter()
        .any(|(holder, instance)| holder.writes.list(instance, &path).is_some());
    Ok(Reached {
        template: Arc::clone(&walk.template),
        row: Arc::clone(&walk.row),
        keys_list: keys_list.cloned(),
        field: path,
        written: by_row || by_holder || by_fill,
    })
}

/// Rule 6: a dynamic unit a value of `source` can hold that a field of type `field` lacks.
/// The value is taken in the unit it is written in, so the field cannot hold it.
pub(crate) fn unit_not_held(field: &LemmaType, source: &LemmaType) -> Option<String> {
    if !field.same_measure_family(source) {
        return None;
    }
    let held = field.measure_units_table();
    source
        .measure_units_table()?
        .iter()
        .find(|unit| unit.is_dynamic() && held.is_none_or(|units| units.get(&unit.name).is_err()))
        .map(|unit| unit.name.clone())
}

/// Rule 6: whether `lemma_type` bounds a value at other than 0. A value copied from data
/// of that type in a dynamic unit is checked against the bound with the sizes of the
/// instance the type belongs to; a bound of 0 needs no size, since sizes are above 0.
pub(crate) fn bounded_at_other_than_zero(lemma_type: &LemmaType) -> bool {
    let crate::planning::semantics::TypeSpecification::Measure {
        minimum, maximum, ..
    } = &lemma_type.specifications
    else {
        return false;
    };
    [minimum, maximum]
        .into_iter()
        .flatten()
        .any(|(magnitude, _)| !crate::computation::rational::rational_is_zero(magnitude))
}