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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! Where a field of an instance gets its value (rule 5 of `plan-filling-data.md`): the
//! value written on the instance, else the value supplied for it, else the declared
//! default of its spec (read by the instance's context), else missing data.

use crate::computation::rational::{checked_div, RationalInteger};
use crate::computation::OperationResult;
use crate::planning::execution_plan::ExecutionPlan;
use crate::planning::fill::{address, Writes, WritesIndex};
use crate::planning::instance_list::RowStore;
use crate::planning::semantics::{
    BoundValueKind, DataPath, InstanceKey, LemmaType, RowBinding, RowInstance, RowOrigin,
    SpecIdentity, ValueKind,
};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Values evaluation data supplies for fields of instances, by instance and field slot of
/// the instance's spec. Only a field nothing writes is supplied (rule 3).
#[derive(Debug, Clone, Default)]
pub(crate) struct Supplied {
    fields: HashMap<InstanceKey, Vec<(usize, RowBinding)>>,
    /// Stored lists, by holding instance and path, whose rows have a key field supplied:
    /// the index of the list's store does not hold the supplied keys.
    keyed: HashSet<(Option<InstanceKey>, DataPath)>,
}

impl Supplied {
    /// Supplies `value` for field `slot` of `instance`, over a value supplied before.
    pub(crate) fn insert(&mut self, instance: InstanceKey, slot: usize, value: OperationResult) {
        let fields = self.fields.entry(instance).or_default();
        fields.retain(|(held, _)| *held != slot);
        fields.push((slot, RowBinding::Bound(value)));
    }

    /// The value supplied for field `slot` of `instance`.
    pub(crate) fn get(&self, instance: &InstanceKey, slot: usize) -> Option<&OperationResult> {
        match self.binding(instance, slot)? {
            RowBinding::Bound(value) => Some(value),
            RowBinding::Deferred { .. } => unreachable!("BUG: a supplied value is a value"),
        }
    }

    fn binding(&self, instance: &InstanceKey, slot: usize) -> Option<&RowBinding> {
        if self.fields.is_empty() {
            return None;
        }
        self.fields
            .get(instance)?
            .iter()
            .find(|(held, _)| *held == slot)
            .map(|(_, binding)| binding)
    }

    /// Records that a key field of a row of the stored list `path` of `holder` is supplied.
    pub(crate) fn key_supplied(&mut self, holder: Option<InstanceKey>, path: DataPath) {
        self.keyed.insert((holder, path));
    }

    /// Whether a key field of a row of the stored list `path` of `holder` is supplied.
    pub(crate) fn is_key_supplied(&self, holder: &Option<InstanceKey>, path: &DataPath) -> bool {
        !self.keyed.is_empty() && self.keyed.contains(&(holder.clone(), path.clone()))
    }

    /// The first vetoed value supplied.
    pub(crate) fn first_veto(&self) -> Option<&OperationResult> {
        self.fields
            .values()
            .flatten()
            .map(|(_, binding)| binding)
            .find_map(|binding| match binding {
                RowBinding::Bound(veto @ OperationResult::Veto(_)) => Some(veto),
                RowBinding::Bound(OperationResult::Value(_)) | RowBinding::Deferred { .. } => None,
            })
    }

    /// These values, supplied in the evaluation data of row `row`: each instance they
    /// name is inside that row ([`owned_by`]).
    pub(crate) fn under(self, row: &InstanceKey) -> Supplied {
        let inside = |instance: InstanceKey| inside(&instance, row);
        Supplied {
            fields: self
                .fields
                .into_iter()
                .map(|(instance, fields)| (inside(instance), fields))
                .collect(),
            keyed: self
                .keyed
                .into_iter()
                .map(|(holder, path)| (Some(holder.map_or_else(|| row.clone(), inside)), path))
                .collect(),
        }
    }

    pub(crate) fn extend(&mut self, other: Supplied) {
        for (instance, fields) in other.fields {
            for (slot, binding) in fields {
                let RowBinding::Bound(value) = binding else {
                    unreachable!("BUG: a supplied value is a value");
                };
                self.insert(instance.clone(), slot, value);
            }
        }
        self.keyed.extend(other.keyed);
    }
}

/// Rule 6: `value`, copied into a field of type `receiving`. A measure in a unit that is
/// dynamic there is taken as written, its number in that unit, and the field sizes it.
/// `factor` gives the size the value was settled with when it carries none.
pub(crate) fn as_written(
    value: OperationResult,
    receiving: &LemmaType,
    factor: impl FnOnce(&BoundValueKind, &str) -> Option<RationalInteger>,
) -> OperationResult {
    let OperationResult::Value(bound) = &value else {
        return value;
    };
    let (ValueKind::Measure(canonical), Some(unit)) = (&bound.value, &bound.unit) else {
        return value;
    };
    if !receiving.unit_is_dynamic(unit) {
        return value;
    }
    let size = bound
        .instance_factors
        .as_ref()
        .and_then(|factors| factors.get(unit.as_ref()).cloned())
        .or_else(|| factor(bound, unit));
    let Some(size) = size else {
        return value;
    };
    let magnitude =
        checked_div(canonical, &size).expect("BUG: a settled unit size is greater than zero");
    OperationResult::from_bound(BoundValueKind {
        value: ValueKind::UnscaledMeasure {
            magnitude,
            unit: Arc::clone(unit),
        },
        unit: Some(Arc::clone(unit)),
        instance_factors: None,
    })
}

/// `instance`, named from the top of a level of evaluation data, as an instance inside
/// `holder`: its outermost owner is `holder`.
pub(crate) fn inside(instance: &InstanceKey, holder: &InstanceKey) -> InstanceKey {
    let mut chain = vec![Arc::clone(&instance.row)];
    let mut owner = instance.owner();
    while let Some(key) = owner {
        chain.push(Arc::clone(&key.row));
        owner = key.owner();
    }
    chain.into_iter().rev().fold(holder.clone(), |owner, held| {
        InstanceKey::new(held, Some(owner))
    })
}

/// A field of an instance as evaluation reads it: its binding, and for a reference the
/// instance it is read in (`None` for the evaluated spec). A field a copy takes from the
/// instance it copies is that instance's: it is owned here.
pub(crate) struct Field<'a> {
    pub(crate) binding: Cow<'a, RowBinding>,
    pub(crate) resolves_in: Option<Cow<'a, InstanceKey>>,
}

/// Field `slot` of `instance`, whose spec's plan is `template` (rule 5): the value its
/// row holds, else the value the nearest instance above it writes through a path (read
/// there), else the value supplied for it, else what the instance it is a copy of holds
/// (rule 4). `None`: the declared default of its spec, or missing data.
pub(crate) fn field<'a>(
    instance: &'a InstanceKey,
    template: &ExecutionPlan,
    slot: usize,
    writes: &'a WritesIndex,
    root: &SpecIdentity,
    supplied: &'a Supplied,
) -> Option<Field<'a>> {
    if let Some(found) = own_field(instance, template, slot, writes, root, supplied) {
        return Some(found);
    }
    let mut source = copy_source(instance, writes, root)?;
    loop {
        if let Some(found) = own_field(&source, template, slot, writes, root, supplied) {
            return Some(Field {
                binding: Cow::Owned(found.binding.into_owned()),
                resolves_in: found.resolves_in.map(|key| Cow::Owned(key.into_owned())),
            });
        }
        source = copy_source(&source, writes, root)?;
    }
}

/// Whether the `uses` a list names, `uses` (its instance in the list's holder), writes
/// field `slot` of `template` on every row of that list (rule 2). `inner` is the instance
/// inside the row that holds the field, named from the row (`b`, `b.c`); `None` for a
/// field of the row itself. Such a field is sealed on the rows: evaluation data cannot
/// supply it, and Show leaves it out of the row schema.
pub(crate) fn list_writes_field(
    uses: &InstanceKey,
    inner: Option<&InstanceKey>,
    template: &ExecutionPlan,
    slot: usize,
    writes: &WritesIndex,
    root: &SpecIdentity,
) -> bool {
    let instance = match inner {
        Some(inner) => inside(inner, uses),
        None => uses.clone(),
    };
    field(
        &instance,
        template,
        slot,
        writes,
        root,
        &Supplied::default(),
    )
    .is_some()
}

/// [`field`] without following copies.
fn own_field<'a>(
    instance: &'a InstanceKey,
    template: &ExecutionPlan,
    slot: usize,
    writes: &'a WritesIndex,
    root: &SpecIdentity,
    supplied: &'a Supplied,
) -> Option<Field<'a>> {
    if let Some(binding) = instance.row.bindings[slot].as_ref() {
        return Some(Field {
            binding: Cow::Borrowed(binding),
            resolves_in: instance.owner().map(Cow::Borrowed),
        });
    }
    if !writes.is_empty() {
        if let Some(written) = written_above(instance, template, slot, writes, root) {
            return Some(written);
        }
        if let Some(written) = written_by_list(instance, template, slot, writes, root) {
            return Some(written);
        }
    }
    supplied.binding(instance, slot).map(|binding| Field {
        binding: Cow::Borrowed(binding),
        resolves_in: None,
    })
}

/// The instance `instance` is a copy of (rule 4): a row a plan above puts in a list from
/// one of its `uses`, or an instance inside such a row, which is a copy of the same
/// instance inside the copied one.
pub(crate) fn copy_source(
    instance: &InstanceKey,
    writes: &WritesIndex,
    root: &SpecIdentity,
) -> Option<InstanceKey> {
    // Only a written row can be a copy: one made at evaluation, or one a plan records.
    let mut chain = Some(instance);
    let mut runtime = false;
    while let Some(key) = chain {
        if matches!(
            key.row.origin,
            RowOrigin::Written {
                copy_of: Some(_),
                ..
            }
        ) {
            runtime = true;
            break;
        }
        chain = key.owner();
    }
    if !runtime {
        let mut chain = Some(instance);
        let mut recorded = false;
        while let Some(key) = chain {
            if writes.rows.copies.contains(&address(&key.row)) {
                recorded = true;
                break;
            }
            chain = key.owner();
        }
        if !recorded {
            return None;
        }
    }
    let mut below: Vec<&Arc<RowInstance>> = Vec::new();
    let mut current = Some(instance);
    while let Some(key) = current {
        if let Some(source) = copied(key, writes, root) {
            return Some(below.into_iter().rev().fold(source, |owner, row| {
                InstanceKey::new(Arc::clone(row), Some(owner))
            }));
        }
        below.push(&key.row);
        current = key.owner();
    }
    None
}

/// The instance the row `key` is a copy of: one evaluation made from a list reference,
/// or one a plan above records as a copy: that plan's `uses`, read in that plan.
fn copied(key: &InstanceKey, writes: &WritesIndex, _root: &SpecIdentity) -> Option<InstanceKey> {
    if let RowOrigin::Written {
        copy_of: Some(source),
        ..
    } = &key.row.origin
    {
        return Some(source.as_ref().clone());
    }
    let (parts, source) = writes.copy(&key.row)?;
    // The plan recording the copy is the instance `parts` path parts above the row.
    let mut remaining = *parts;
    let mut current = key;
    loop {
        remaining = remaining.checked_sub(name_parts(&current.row.origin)?)?;
        let holder = current.owner();
        if remaining == 0 {
            return Some(InstanceKey::new(Arc::clone(source), holder.cloned()));
        }
        current = holder?;
    }
}

/// How many path parts name an instance of row origin `origin` in its holder.
fn name_parts(origin: &RowOrigin) -> Option<usize> {
    match origin {
        RowOrigin::Import { .. } => Some(1),
        RowOrigin::Written { instance, .. } => Some(
            instance
                .prefix
                .iter()
                .map(|segment| 1 + usize::from(segment.row.is_some()))
                .sum(),
        ),
        RowOrigin::Numbered { .. } | RowOrigin::Inline { .. } => None,
    }
}

/// What is written on field `slot` of the instance of the `uses` a list names, for
/// `instance`, a row of that list or an instance inside one (rule 2): every row takes what
/// is written on that `uses`, at the same path. Its supplied values do not reach the rows.
fn written_by_list<'a>(
    instance: &'a InstanceKey,
    template: &ExecutionPlan,
    slot: usize,
    writes: &'a WritesIndex,
    root: &SpecIdentity,
) -> Option<Field<'a>> {
    // The row itself: what the `uses` its list names holds, read in the list's holder.
    if let Some((named, holder)) = row_list_uses(instance, writes, root) {
        let binding = named.bindings.get(slot)?.as_ref();
        if let Some(binding) = binding {
            return Some(Field {
                binding: Cow::Borrowed(binding),
                resolves_in: holder.map(Cow::Borrowed),
            });
        }
        // Else what a plan above writes on that `uses` row.
        if !writes.rows.written.contains(&address(named)) {
            return None;
        }
    } else if !writes.rows.written.contains(&address(&instance.row)) {
        // An instance inside a row is on the same row as the one inside the `uses`.
        return None;
    }
    let named = list_uses(instance, writes, root)?;
    let found = named
        .row
        .bindings
        .get(slot)?
        .as_ref()
        .map(|binding| (binding.clone(), named.owner().cloned()))
        .or_else(|| {
            written_above(&named, template, slot, writes, root).map(|field| {
                (
                    field.binding.into_owned(),
                    field.resolves_in.map(Cow::into_owned),
                )
            })
        })?;
    Some(Field {
        binding: Cow::Owned(found.0),
        resolves_in: found.1.map(Cow::Owned),
    })
}

/// For `instance` that is itself a row of a list: the row of the `uses` that list names,
/// and the instance holding the list. No allocation.
fn row_list_uses<'a>(
    instance: &'a InstanceKey,
    writes: &'a WritesIndex,
    root: &SpecIdentity,
) -> Option<(&'a Arc<RowInstance>, Option<&'a InstanceKey>)> {
    let list = match &instance.row.origin {
        RowOrigin::Written { instance, .. } => instance.prefix.last()?.uses.as_ref(),
        RowOrigin::Numbered { list, .. } => list.rsplit('.').next()?,
        RowOrigin::Import { .. } | RowOrigin::Inline { .. } => return None,
    };
    let holder = instance.owner();
    let identity = holder.map_or(root, |holder| holder.row.identity.as_ref());
    let named = writes.get(identity)?.rows_write(list)?;
    Some((named, holder))
}

/// For `instance`, a row of a list or an instance inside one, the instance at the same
/// path inside the `uses` that list names, when that `uses` writes on its rows.
fn list_uses(
    instance: &InstanceKey,
    writes: &WritesIndex,
    root: &SpecIdentity,
) -> Option<InstanceKey> {
    let mut below: Vec<&Arc<RowInstance>> = Vec::new();
    let mut current = Some(instance);
    while let Some(key) = current {
        let list = match &key.row.origin {
            RowOrigin::Written { instance, .. } => instance
                .prefix
                .last()
                .map(|segment| segment.uses.to_string()),
            RowOrigin::Numbered { list, .. } => list.rsplit('.').next().map(str::to_string),
            RowOrigin::Import { .. } | RowOrigin::Inline { .. } => None,
        };
        if let Some(list) = list {
            let holder = key.owner();
            let identity = holder.map_or(root, |holder| holder.row.identity.as_ref());
            let named = writes.get(identity)?.rows_write(&list)?;
            let uses = InstanceKey::new(Arc::clone(named), holder.cloned());
            return Some(below.into_iter().rev().fold(uses, |owner, row| {
                InstanceKey::new(Arc::clone(row), Some(owner))
            }));
        }
        below.push(&key.row);
        current = key.owner();
    }
    None
}

/// Whether a plan above `instance` writes through a path: checked before any path is
/// built, so a lookup that cannot find anything allocates nothing.
fn writes_above(instance: &InstanceKey, writes: &WritesIndex, root: &SpecIdentity) -> bool {
    let mut holder = instance.owner();
    loop {
        let identity = holder.map_or(root, |holder| holder.row.identity.as_ref());
        if writes.get(identity).is_some_and(Writes::has_instances) {
            return true;
        }
        match holder {
            Some(key) => holder = key.owner(),
            None => return false,
        }
    }
}

/// What the nearest instance above `instance` writes on field `slot` through a path.
fn written_above<'a>(
    instance: &'a InstanceKey,
    template: &ExecutionPlan,
    slot: usize,
    writes: &'a WritesIndex,
    root: &SpecIdentity,
) -> Option<Field<'a>> {
    if !writes.rows.written.contains(&address(&instance.row))
        || !writes_above(instance, writes, root)
    {
        return None;
    }
    let (field, _) = template.data.get_index(slot)?;
    let mut path: Vec<String> = Vec::new();
    let mut current = instance;
    loop {
        let mut named = name_in_holder(&current.row.origin)?;
        named.append(&mut path);
        path = named;
        let holder = current.owner();
        let identity = holder.map_or(root, |holder| holder.row.identity.as_ref());
        if let Some(binding) = writes.get(identity).and_then(|w| w.get(&path, field)) {
            return Some(Field {
                binding: Cow::Borrowed(binding),
                resolves_in: holder.map(Cow::Borrowed),
            });
        }
        current = holder?;
    }
}

/// The rows a plan above `holder` fills its list `list` with (`-> with items: a, b`).
pub(crate) fn list_above<'a>(
    holder: Option<&InstanceKey>,
    list: &DataPath,
    writes: &'a WritesIndex,
    root: &SpecIdentity,
) -> Option<&'a Arc<RowStore>> {
    let mut path: Vec<String> = Vec::new();
    let mut current = holder?;
    if !writes.rows.filled.contains(&address(&current.row)) {
        return None;
    }
    loop {
        let mut named = name_in_holder(&current.row.origin)?;
        named.append(&mut path);
        path = named;
        let above = current.owner();
        let identity = above.map_or(root, |above| above.row.identity.as_ref());
        if let Some(rows) = writes.get(identity).and_then(|w| w.list(&path, list)) {
            return Some(rows);
        }
        current = above?;
    }
}

/// Whether a plan above `holder` (the instance holding list `list`; `None` for the
/// evaluated spec) writes a key field of a row of the list: its store's index does not
/// hold that key.
pub(crate) fn is_rekeyed_above(
    holder: Option<&InstanceKey>,
    list: &DataPath,
    writes: &WritesIndex,
    root: &SpecIdentity,
) -> bool {
    !writes.is_empty()
        && holder.is_some_and(|holder| writes.rows.rekeyed.contains(&address(&holder.row)))
        && any_above(holder, writes, root, |w, path| w.is_rekeyed(path, list))
}

/// Whether a plan above `holder` writes through a row of its list `list`.
pub(crate) fn writes_rows_above(
    holder: Option<&InstanceKey>,
    list: &DataPath,
    writes: &WritesIndex,
    root: &SpecIdentity,
) -> bool {
    !writes.is_empty()
        && holder.is_some_and(|holder| writes_above(holder, writes, root))
        && any_above(holder, writes, root, |w, path| w.writes_rows_of(path, list))
}

/// Whether `test` holds for the writes of a plan above `instance`, with the instance's
/// path from that plan.
fn any_above(
    instance: Option<&InstanceKey>,
    writes: &WritesIndex,
    root: &SpecIdentity,
    test: impl Fn(&Writes, &[String]) -> bool,
) -> bool {
    let mut path: Vec<String> = Vec::new();
    let mut current = instance;
    while let Some(key) = current {
        let Some(mut named) = name_in_holder(&key.row.origin) else {
            return false;
        };
        named.append(&mut path);
        path = named;
        let holder = key.owner();
        let identity = holder.map_or(root, |holder| holder.row.identity.as_ref());
        if writes.get(identity).is_some_and(|w| test(w, &path)) {
            return true;
        }
        current = holder;
    }
    false
}

/// How the instance with row origin `origin` is named in the instance holding it; `None`
/// for a row evaluation data or a rule writes, which no path names.
pub(crate) fn name_in_holder(origin: &RowOrigin) -> Option<Vec<String>> {
    match origin {
        RowOrigin::Import { alias } => Some(vec![alias.to_string()]),
        RowOrigin::Written { instance, .. } => Some(
            instance
                .prefix
                .iter()
                .flat_map(|segment| {
                    std::iter::once(segment.uses.to_string())
                        .chain(segment.row.map(|number| number.to_string()))
                })
                .collect(),
        ),
        RowOrigin::Numbered { .. } | RowOrigin::Inline { .. } => None,
    }
}

/// `value`, a value of a field of instance `holder`: the rows of a list evaluation data
/// supplies for it are rows of `holder`'s list, owned by `holder`.
pub(crate) fn owned_by(value: &OperationResult, holder: &InstanceKey) -> OperationResult {
    let OperationResult::Value(bound) = value else {
        return value.clone();
    };
    let ValueKind::List(items) = &bound.value else {
        return value.clone();
    };
    if items.stored().is_some() {
        return value.clone();
    }
    let unowned = |item: &crate::planning::semantics::TypedLiteral| {
        matches!(
            &item.value,
            ValueKind::Spec(crate::planning::semantics::SpecValue::Row(key))
                if key.owner().is_none() && matches!(key.row.origin, RowOrigin::Numbered { .. })
        )
    };
    if !items.values().iter().any(unowned) {
        return value.clone();
    }
    let mut bound = bound.clone();
    bound.value = ValueKind::List(items.owned_by(holder));
    OperationResult::Value(bound)
}

/// `value`, the rows a list reference gives list `path` of `holder` (whose spec's plan is
/// `template`), as rows of that list: each a copy of the row it is given (rule 4), owned
/// by `holder`, when the `uses` the list names writes on its rows (rule 2). Otherwise the
/// rows are read as they are given.
pub(crate) fn rows_copied_into(
    value: OperationResult,
    holder: &InstanceKey,
    path: &DataPath,
    list: &crate::planning::instance_list::InstanceListSource,
    template: &ExecutionPlan,
    caches: &crate::evaluation::RequestCaches,
) -> OperationResult {
    let Some(named) = &list.row_writes else {
        return value;
    };
    let OperationResult::Value(bound) = &value else {
        return value;
    };
    let ValueKind::List(items) = &bound.value else {
        return value;
    };
    let row_template = template.row_template(&list.identity);
    let uses = InstanceKey::new(Arc::clone(named), Some(holder.clone()));
    let writes_rows =
        (0..named.bindings.len()).any(|slot| caches.field(&uses, row_template, slot).is_some());
    if !writes_rows {
        return value;
    }
    let given: Vec<InstanceKey> = items
        .iter()
        .filter_map(|item| match &item.value {
            ValueKind::Spec(crate::planning::semantics::SpecValue::Row(key)) => Some(key.clone()),
            _ => None,
        })
        .collect();
    let source = template
        .data
        .get(path)
        .map(|definition| definition.source().clone())
        .expect("BUG: an instance list is data of its template");
    let list_name: Arc<str> = Arc::from(path.data.as_str());
    let spec: Arc<str> = Arc::from(list.identity.spec.as_str());
    let repository: Option<Arc<str>> = list.identity.repository.as_deref().map(Arc::from);
    let copies: Vec<crate::planning::semantics::TypedLiteral> = given
        .into_iter()
        .enumerate()
        .map(|(index, key)| crate::planning::semantics::TypedLiteral {
            value: ValueKind::Spec(crate::planning::semantics::SpecValue::Row(
                InstanceKey::new(
                    Arc::new(RowInstance {
                        identity: Arc::clone(&key.row.identity),
                        origin: RowOrigin::Written {
                            instance: crate::planning::semantics::SpecInstance {
                                prefix: vec![
                                    crate::planning::semantics::PathSegment::list_row_shared(
                                        &list_name,
                                        index + 1,
                                        &spec,
                                        repository.as_ref(),
                                    ),
                                ],
                            },
                            source: source.clone(),
                            copy_of: Some(Box::new(key)),
                        },
                        bindings: vec![None; row_template.data.len()].into(),
                    }),
                    Some(holder.clone()),
                ),
            )),
            lemma_type: Arc::clone(&list.row_type),
        })
        .collect();
    OperationResult::from_bound(BoundValueKind {
        value: ValueKind::List(copies.into()),
        unit: None,
        instance_factors: None,
    })
}