Skip to main content

lemma/evaluation/
evaluate_data.rs

1use crate::computation::{OperationResult, VetoType};
2use crate::evaluation::lookup::Supplied;
3use crate::parsing::ast::{ascii_lowercase_logical_name, canonical_logical_name};
4use crate::planning::execution_plan::{validate_value_against_type, ExecutionPlan, RequestGlobals};
5use crate::planning::instance_list::{
6    default_of, row_end_type, typed_from_bound, InstanceListSource, KeyIndex,
7};
8use crate::planning::semantics::{
9    is_global_slot_name, parse_value_from_string, row_literal, typed_literal_from_bound,
10    typed_literal_from_parsed, typed_literal_with_binding_unit, BoundValueKind, DataDefinition,
11    DataPath, InstanceKey, KeyField, LemmaType, ListKey, ListValue, LiteralValue, RowBinding,
12    RowEnd, RowInstance, RowOrigin, Source, SpecIdentity, SpecValue, TypeSpecification,
13    TypedLiteral, ValueKind,
14};
15use crate::planning::unit_index::UnitIndex;
16use crate::Error;
17use crate::ResourceLimits;
18use indexmap::IndexMap;
19use std::collections::HashSet;
20use std::sync::Arc;
21
22/// Neutral overlay tree. [`EvaluateData::resolve`] reads each value by declared type.
23///
24/// Host input may nest arbitrarily deep, so `Clone`, `Debug`, `PartialEq` and `Drop` are
25/// iterative. Derived versions recurse on the native stack.
26pub enum EvaluateDataValue {
27    /// Unparsed Lemma literal text, parsed against the declared type by [`parse_value_from_string`].
28    Literal(String),
29    Boolean(bool),
30    Map(IndexMap<String, EvaluateDataValue>),
31    List(Vec<EvaluateDataValue>),
32}
33
34impl EvaluateDataValue {
35    pub fn string(value: impl Into<String>) -> Self {
36        Self::Literal(value.into())
37    }
38
39    pub(crate) fn is_empty(&self) -> bool {
40        match self {
41            Self::Literal(s) => s.trim().is_empty(),
42            Self::Boolean(_) | Self::Map(_) | Self::List(_) => false,
43        }
44    }
45
46    pub(crate) fn into_list(mut self) -> Option<Vec<EvaluateDataValue>> {
47        match &mut self {
48            Self::List(items) => Some(std::mem::take(items)),
49            Self::Literal(_) | Self::Boolean(_) | Self::Map(_) => None,
50        }
51    }
52
53    pub(crate) fn into_map(mut self) -> Option<IndexMap<String, EvaluateDataValue>> {
54        match &mut self {
55            Self::Map(map) => Some(std::mem::take(map)),
56            Self::Literal(_) | Self::Boolean(_) | Self::List(_) => None,
57        }
58    }
59}
60
61impl Drop for EvaluateDataValue {
62    fn drop(&mut self) {
63        let mut pending = Vec::new();
64        take_children(self, &mut pending);
65        while let Some(mut node) = pending.pop() {
66            take_children(&mut node, &mut pending);
67        }
68    }
69}
70
71fn take_children(node: &mut EvaluateDataValue, pending: &mut Vec<EvaluateDataValue>) {
72    match node {
73        EvaluateDataValue::Literal(_) | EvaluateDataValue::Boolean(_) => {}
74        EvaluateDataValue::Map(map) => pending.extend(std::mem::take(map).into_values()),
75        EvaluateDataValue::List(items) => pending.append(items),
76    }
77}
78
79impl Clone for EvaluateDataValue {
80    fn clone(&self) -> Self {
81        let mut frames: Vec<CloneFrame<'_>> = Vec::new();
82        let mut step = CloneStep::Descend(self);
83        loop {
84            step = match step {
85                CloneStep::Descend(value) => match value {
86                    EvaluateDataValue::Literal(s) => {
87                        CloneStep::Deliver(EvaluateDataValue::Literal(s.clone()))
88                    }
89                    EvaluateDataValue::Boolean(b) => {
90                        CloneStep::Deliver(EvaluateDataValue::Boolean(*b))
91                    }
92                    EvaluateDataValue::List(items) => {
93                        frames.push(CloneFrame::List {
94                            out: Vec::with_capacity(items.len()),
95                            children: items.iter(),
96                        });
97                        CloneStep::NextChild
98                    }
99                    EvaluateDataValue::Map(map) => {
100                        frames.push(CloneFrame::Map {
101                            out: IndexMap::with_capacity(map.len()),
102                            pending_key: None,
103                            children: map.iter(),
104                        });
105                        CloneStep::NextChild
106                    }
107                },
108                CloneStep::NextChild => {
109                    let frame = frames
110                        .last_mut()
111                        .expect("BUG: clone frame stack empty while reading a child");
112                    match frame.next_child() {
113                        Some(child) => CloneStep::Descend(child),
114                        None => {
115                            let frame = frames
116                                .pop()
117                                .expect("BUG: clone frame stack empty on completion");
118                            CloneStep::Deliver(frame.finish())
119                        }
120                    }
121                }
122                CloneStep::Deliver(value) => match frames.last_mut() {
123                    None => return value,
124                    Some(frame) => {
125                        frame.push(value);
126                        CloneStep::NextChild
127                    }
128                },
129            };
130        }
131    }
132}
133
134enum CloneStep<'a> {
135    Descend(&'a EvaluateDataValue),
136    NextChild,
137    Deliver(EvaluateDataValue),
138}
139
140enum CloneFrame<'a> {
141    List {
142        out: Vec<EvaluateDataValue>,
143        children: std::slice::Iter<'a, EvaluateDataValue>,
144    },
145    Map {
146        out: IndexMap<String, EvaluateDataValue>,
147        pending_key: Option<String>,
148        children: indexmap::map::Iter<'a, String, EvaluateDataValue>,
149    },
150}
151
152impl<'a> CloneFrame<'a> {
153    fn next_child(&mut self) -> Option<&'a EvaluateDataValue> {
154        match self {
155            CloneFrame::List { children, .. } => children.next(),
156            CloneFrame::Map {
157                pending_key,
158                children,
159                ..
160            } => children.next().map(|(key, child)| {
161                *pending_key = Some(key.clone());
162                child
163            }),
164        }
165    }
166
167    fn push(&mut self, value: EvaluateDataValue) {
168        match self {
169            CloneFrame::List { out, .. } => out.push(value),
170            CloneFrame::Map {
171                out, pending_key, ..
172            } => {
173                let key = pending_key
174                    .take()
175                    .expect("BUG: clone map child delivered without its key");
176                out.insert(key, value);
177            }
178        }
179    }
180
181    fn finish(self) -> EvaluateDataValue {
182        match self {
183            CloneFrame::List { out, .. } => EvaluateDataValue::List(out),
184            CloneFrame::Map { out, .. } => EvaluateDataValue::Map(out),
185        }
186    }
187}
188
189impl PartialEq for EvaluateDataValue {
190    fn eq(&self, other: &Self) -> bool {
191        let mut pending: Vec<(&EvaluateDataValue, &EvaluateDataValue)> = vec![(self, other)];
192        while let Some((left, right)) = pending.pop() {
193            match (left, right) {
194                (EvaluateDataValue::Literal(a), EvaluateDataValue::Literal(b)) => {
195                    if a != b {
196                        return false;
197                    }
198                }
199                (EvaluateDataValue::Boolean(a), EvaluateDataValue::Boolean(b)) => {
200                    if a != b {
201                        return false;
202                    }
203                }
204                (EvaluateDataValue::List(a), EvaluateDataValue::List(b)) => {
205                    if a.len() != b.len() {
206                        return false;
207                    }
208                    pending.extend(a.iter().zip(b.iter()));
209                }
210                (EvaluateDataValue::Map(a), EvaluateDataValue::Map(b)) => {
211                    if a.len() != b.len() {
212                        return false;
213                    }
214                    for (key, value) in a {
215                        match b.get(key) {
216                            Some(other_value) => pending.push((value, other_value)),
217                            None => return false,
218                        }
219                    }
220                }
221                _ => return false,
222            }
223        }
224        true
225    }
226}
227
228impl Eq for EvaluateDataValue {}
229
230enum DebugTask<'a> {
231    Node(&'a EvaluateDataValue, usize),
232    Text(&'static str),
233    Quoted(&'a str),
234    Indent(usize),
235}
236
237impl std::fmt::Debug for EvaluateDataValue {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        let pretty = f.alternate();
240        let mut tasks = vec![DebugTask::Node(self, 0)];
241        while let Some(task) = tasks.pop() {
242            match task {
243                DebugTask::Node(value, level) => {
244                    let mut seq = Vec::new();
245                    debug_seq(value, level, pretty, &mut seq);
246                    tasks.extend(seq.into_iter().rev());
247                }
248                DebugTask::Text(text) => f.write_str(text)?,
249                DebugTask::Quoted(text) => write!(f, "{text:?}")?,
250                DebugTask::Indent(level) => write!(f, "{:width$}", "", width = 4 * level)?,
251            }
252        }
253        Ok(())
254    }
255}
256
257/// Tokens of `value` at nesting `level`, matching the derived `Debug` layout.
258fn debug_seq<'a>(
259    value: &'a EvaluateDataValue,
260    level: usize,
261    pretty: bool,
262    seq: &mut Vec<DebugTask<'a>>,
263) {
264    match value {
265        EvaluateDataValue::Literal(text) => debug_tuple(seq, level, pretty, "Literal", |out, _| {
266            out.push(DebugTask::Quoted(text))
267        }),
268        EvaluateDataValue::Boolean(b) => debug_tuple(seq, level, pretty, "Boolean", |out, _| {
269            out.push(DebugTask::Text(if *b { "true" } else { "false" }))
270        }),
271        EvaluateDataValue::Map(map) => {
272            debug_tuple(seq, level, pretty, "Map", |out, field_level| {
273                if map.is_empty() {
274                    out.push(DebugTask::Text("{}"));
275                } else if pretty {
276                    out.push(DebugTask::Text("{\n"));
277                    for (key, child) in map {
278                        out.push(DebugTask::Indent(field_level + 1));
279                        out.push(DebugTask::Quoted(key));
280                        out.push(DebugTask::Text(": "));
281                        out.push(DebugTask::Node(child, field_level + 1));
282                        out.push(DebugTask::Text(",\n"));
283                    }
284                    out.push(DebugTask::Indent(field_level));
285                    out.push(DebugTask::Text("}"));
286                } else {
287                    out.push(DebugTask::Text("{"));
288                    for (index, (key, child)) in map.iter().enumerate() {
289                        if index > 0 {
290                            out.push(DebugTask::Text(", "));
291                        }
292                        out.push(DebugTask::Quoted(key));
293                        out.push(DebugTask::Text(": "));
294                        out.push(DebugTask::Node(child, field_level));
295                    }
296                    out.push(DebugTask::Text("}"));
297                }
298            })
299        }
300        EvaluateDataValue::List(items) => {
301            debug_tuple(seq, level, pretty, "List", |out, field_level| {
302                if items.is_empty() {
303                    out.push(DebugTask::Text("[]"));
304                } else if pretty {
305                    out.push(DebugTask::Text("[\n"));
306                    for child in items {
307                        out.push(DebugTask::Indent(field_level + 1));
308                        out.push(DebugTask::Node(child, field_level + 1));
309                        out.push(DebugTask::Text(",\n"));
310                    }
311                    out.push(DebugTask::Indent(field_level));
312                    out.push(DebugTask::Text("]"));
313                } else {
314                    out.push(DebugTask::Text("["));
315                    for (index, child) in items.iter().enumerate() {
316                        if index > 0 {
317                            out.push(DebugTask::Text(", "));
318                        }
319                        out.push(DebugTask::Node(child, field_level));
320                    }
321                    out.push(DebugTask::Text("]"));
322                }
323            })
324        }
325    }
326}
327
328/// `Name(field)` with the field's tokens at `field_level`; pretty mode puts it on its own line.
329fn debug_tuple<'a>(
330    seq: &mut Vec<DebugTask<'a>>,
331    level: usize,
332    pretty: bool,
333    name: &'static str,
334    field: impl FnOnce(&mut Vec<DebugTask<'a>>, usize),
335) {
336    seq.push(DebugTask::Text(name));
337    if pretty {
338        seq.push(DebugTask::Text("(\n"));
339        seq.push(DebugTask::Indent(level + 1));
340        field(seq, level + 1);
341        seq.push(DebugTask::Text(",\n"));
342        seq.push(DebugTask::Indent(level));
343        seq.push(DebugTask::Text(")"));
344    } else {
345        seq.push(DebugTask::Text("("));
346        field(seq, level);
347        seq.push(DebugTask::Text(")"));
348    }
349}
350
351impl From<bool> for EvaluateDataValue {
352    fn from(value: bool) -> Self {
353        Self::Boolean(value)
354    }
355}
356
357impl From<String> for EvaluateDataValue {
358    fn from(value: String) -> Self {
359        Self::Literal(value)
360    }
361}
362
363impl From<&str> for EvaluateDataValue {
364    fn from(value: &str) -> Self {
365        Self::Literal(value.to_string())
366    }
367}
368
369fn reject_case_insensitive_duplicates<'a>(
370    keys: impl IntoIterator<Item = &'a str>,
371    describe: impl Fn(&str) -> String,
372) -> Result<(), Error> {
373    let mut seen = HashSet::new();
374    for key in keys {
375        let canonical = ascii_lowercase_logical_name(key.to_string());
376        if !seen.insert(canonical.clone()) {
377            return Err(Error::request(
378                describe(&canonical),
379                Some("Keys are case-insensitive; remove the duplicate"),
380            ));
381        }
382    }
383    Ok(())
384}
385
386/// Top-level run-data entries from a host walker. Keys differing only in case: request Error.
387pub fn evaluate_data_from_entries(
388    entries: Vec<(String, EvaluateDataValue)>,
389) -> Result<IndexMap<String, EvaluateDataValue>, Error> {
390    reject_case_insensitive_duplicates(entries.iter().map(|(k, _)| k.as_str()), |k| {
391        format!("Duplicate data key '{k}'")
392    })?;
393    Ok(entries.into_iter().collect())
394}
395
396/// Nested object entries from a host walker. Keys differing only in case: request Error.
397pub fn evaluate_data_map_from_entries(
398    entries: Vec<(String, EvaluateDataValue)>,
399) -> Result<EvaluateDataValue, Error> {
400    reject_case_insensitive_duplicates(entries.iter().map(|(k, _)| k.as_str()), |k| {
401        format!("Duplicate object key '{k}'")
402    })?;
403    Ok(EvaluateDataValue::Map(entries.into_iter().collect()))
404}
405
406/// Host list item that is null (JSON `null`, JS `null` / `undefined`, Elixir `nil`).
407/// A list has no unsupplied row, so this is a request Error, never an omitted item.
408/// `position` is 1-based within its list.
409pub fn evaluate_data_null_list_item(position: usize) -> Error {
410    Error::request(
411        format!("list item {position} is null"),
412        Some("remove the item or supply a value"),
413    )
414}
415
416/// Attribute a walker error to its top-level data key unless already attributed.
417pub fn attribute_evaluate_data_error(error: Error, key: &str) -> Error {
418    if error.related_data().is_some() {
419        error
420    } else {
421        error.with_related_data(key)
422    }
423}
424
425pub fn parse_data_value(
426    input: &EvaluateDataValue,
427    lemma_type: &Arc<LemmaType>,
428    source: &Source,
429    unit_index: &UnitIndex,
430    named_types: &IndexMap<String, Arc<LemmaType>>,
431) -> Result<TypedLiteral, Error> {
432    let mut frames: Vec<ListParseFrame<'_>> = Vec::new();
433    let mut step = ParseStep::Parse(input, Arc::clone(lemma_type));
434    loop {
435        step = match step {
436            ParseStep::Parse(value, ty) => {
437                match parse_node(value, &ty, source, unit_index, named_types)? {
438                    ParseNode::Literal(literal) => ParseStep::Deliver(literal),
439                    ParseNode::List {
440                        rows,
441                        lemma_type,
442                        element_type,
443                    } => {
444                        frames.push(ListParseFrame {
445                            rows: rows.iter(),
446                            lemma_type,
447                            element_type,
448                            converted: Vec::with_capacity(rows.len()),
449                        });
450                        ParseStep::NextChild
451                    }
452                }
453            }
454            ParseStep::NextChild => {
455                let frame = frames
456                    .last_mut()
457                    .expect("BUG: list parse frame stack empty while reading a child");
458                match frame.rows.next() {
459                    Some(child) => ParseStep::Parse(child, Arc::clone(&frame.element_type)),
460                    None => {
461                        let frame = frames
462                            .pop()
463                            .expect("BUG: list parse frame stack empty on completion");
464                        ParseStep::Deliver(TypedLiteral {
465                            value: ValueKind::List(frame.converted.into()),
466                            lemma_type: frame.lemma_type,
467                        })
468                    }
469                }
470            }
471            ParseStep::Deliver(literal) => match frames.last_mut() {
472                None => return Ok(literal),
473                Some(frame) => {
474                    frame.converted.push(literal);
475                    ParseStep::NextChild
476                }
477            },
478        };
479    }
480}
481
482enum ParseStep<'a> {
483    Parse(&'a EvaluateDataValue, Arc<LemmaType>),
484    NextChild,
485    Deliver(TypedLiteral),
486}
487
488struct ListParseFrame<'a> {
489    rows: std::slice::Iter<'a, EvaluateDataValue>,
490    lemma_type: Arc<LemmaType>,
491    element_type: Arc<LemmaType>,
492    converted: Vec<TypedLiteral>,
493}
494
495enum ParseNode<'a> {
496    Literal(TypedLiteral),
497    List {
498        rows: &'a [EvaluateDataValue],
499        lemma_type: Arc<LemmaType>,
500        element_type: Arc<LemmaType>,
501    },
502}
503
504/// Shape mismatches are request Errors from `evaluate_data_shape_error`, checked before parsing.
505/// The mismatch panics below are therefore unreachable.
506fn parse_node<'a>(
507    input: &'a EvaluateDataValue,
508    lemma_type: &Arc<LemmaType>,
509    source: &Source,
510    unit_index: &UnitIndex,
511    named_types: &IndexMap<String, Arc<LemmaType>>,
512) -> Result<ParseNode<'a>, Error> {
513    let type_spec = &lemma_type.specifications;
514
515    let (kind, binding_unit) = match (input, type_spec) {
516        (EvaluateDataValue::Literal(s), _) => {
517            return parse_literal(s, lemma_type, source, unit_index, named_types)
518                .map(ParseNode::Literal);
519        }
520        (EvaluateDataValue::Boolean(b), TypeSpecification::Boolean { .. }) => {
521            (ValueKind::Boolean(*b), None)
522        }
523        (EvaluateDataValue::Boolean(_), _) => {
524            panic!("BUG: boolean overlay on non-boolean type is a request shape error, not parse")
525        }
526        (EvaluateDataValue::Map(map), TypeSpecification::Measure { .. })
527        | (EvaluateDataValue::Map(map), TypeSpecification::Ratio { .. }) => {
528            let (magnitude, unit) = single_unit_literal_map(map).expect(
529                "BUG: measure/ratio map overlay is a request shape error unless it is a single-unit Literal",
530            );
531            return parse_literal(
532                &format!("{magnitude} {unit}"),
533                lemma_type,
534                source,
535                unit_index,
536                named_types,
537            )
538            .map(ParseNode::Literal);
539        }
540        (EvaluateDataValue::Map(_), _) => {
541            panic!("BUG: map overlay on this type is a request shape error, not parse")
542        }
543        (EvaluateDataValue::List(rows), TypeSpecification::List { .. }) => {
544            return Ok(ParseNode::List {
545                rows: rows.as_slice(),
546                lemma_type: Arc::clone(lemma_type),
547                element_type: Arc::clone(lemma_type.list_element_lemma_type()),
548            });
549        }
550        (EvaluateDataValue::List(_), _) => {
551            panic!("BUG: list overlay on this type is a request shape error, not parse")
552        }
553    };
554
555    Ok(ParseNode::Literal(typed_literal_with_binding_unit(
556        kind,
557        binding_unit,
558        lemma_type,
559    )))
560}
561
562fn parse_literal(
563    text: &str,
564    lemma_type: &Arc<LemmaType>,
565    source: &Source,
566    unit_index: &UnitIndex,
567    named_types: &IndexMap<String, Arc<LemmaType>>,
568) -> Result<TypedLiteral, Error> {
569    let parsed = parse_value_from_string(text, &lemma_type.specifications, source)?;
570    typed_literal_from_parsed(&parsed, lemma_type, unit_index, named_types)
571        .map_err(|msg| Error::validation(msg, Some(source.clone()), None::<String>))
572}
573
574/// Resolve a unit the caller actually wrote to a bare declared name.
575///
576/// Qualified paths go through [`UnitIndex::resolve_with_named_types`]. Bare names
577/// accepted only when this data type (or range element) declares that exact name.
578/// Never invents a unit the caller did not pass.
579fn single_unit_literal_map(map: &IndexMap<String, EvaluateDataValue>) -> Option<(&str, &str)> {
580    if map.len() != 1 {
581        return None;
582    }
583    let (unit, value) = map.iter().next()?;
584    match value {
585        EvaluateDataValue::Literal(magnitude) => Some((magnitude.as_str(), unit.as_str())),
586        _ => None,
587    }
588}
589
590enum ShapeCheck<'a> {
591    Accepts,
592    Mismatch(String),
593    Rows {
594        rows: &'a [EvaluateDataValue],
595        element: &'a LemmaType,
596    },
597}
598
599fn shape_check<'a>(input: &'a EvaluateDataValue, lemma_type: &'a LemmaType) -> ShapeCheck<'a> {
600    let type_spec = &lemma_type.specifications;
601    match (input, type_spec) {
602        (EvaluateDataValue::Literal(_), TypeSpecification::List { .. }) => ShapeCheck::Mismatch(
603            format!("literal overlay is not valid for list data ({type_spec})"),
604        ),
605        (EvaluateDataValue::Literal(_), _) => ShapeCheck::Accepts,
606        (EvaluateDataValue::Boolean(_), TypeSpecification::Boolean { .. }) => ShapeCheck::Accepts,
607        (EvaluateDataValue::Boolean(_), _) => ShapeCheck::Mismatch(format!(
608            "boolean input is only valid for boolean data, not {type_spec}"
609        )),
610        (
611            EvaluateDataValue::Map(map),
612            TypeSpecification::Measure { .. } | TypeSpecification::Ratio { .. },
613        ) => {
614            if single_unit_literal_map(map).is_some() {
615                ShapeCheck::Accepts
616            } else {
617                ShapeCheck::Mismatch(
618                    "measure and ratio data must be a convenience string or a single-unit map"
619                        .to_string(),
620                )
621            }
622        }
623        (EvaluateDataValue::Map(_), _) => ShapeCheck::Mismatch(format!(
624            "object overlay is only valid for measure or ratio data, not {type_spec}"
625        )),
626        (EvaluateDataValue::List(rows), TypeSpecification::List { .. }) => ShapeCheck::Rows {
627            rows: rows.as_slice(),
628            element: lemma_type.list_element_lemma_type().as_ref(),
629        },
630        (EvaluateDataValue::List(_), _) => ShapeCheck::Mismatch(format!(
631            "array overlay is not valid for scalar data ({type_spec})"
632        )),
633    }
634}
635
636struct ShapeFrame<'a> {
637    rows: std::slice::Iter<'a, EvaluateDataValue>,
638    element: &'a LemmaType,
639    position: usize,
640}
641
642/// First shape mismatch in `input` against `lemma_type`, at any list depth. `None` if every
643/// value matches the type its parse node will use. List items are reported by 1-based position.
644fn evaluate_data_shape_error(input: &EvaluateDataValue, lemma_type: &LemmaType) -> Option<String> {
645    let mut frames: Vec<ShapeFrame<'_>> = Vec::new();
646    let mut pending = Some((input, lemma_type));
647    loop {
648        if let Some((value, ty)) = pending.take() {
649            match shape_check(value, ty) {
650                ShapeCheck::Accepts => {}
651                ShapeCheck::Mismatch(message) => return Some(item_path_message(&frames, message)),
652                ShapeCheck::Rows { rows, element } => frames.push(ShapeFrame {
653                    rows: rows.iter(),
654                    element,
655                    position: 0,
656                }),
657            }
658        }
659        let frame = frames.last_mut()?;
660        match frame.rows.next() {
661            Some(child) => {
662                frame.position += 1;
663                pending = Some((child, frame.element));
664            }
665            None => {
666                frames.pop();
667            }
668        }
669    }
670}
671
672fn item_path_message(frames: &[ShapeFrame<'_>], message: String) -> String {
673    if frames.is_empty() {
674        return message;
675    }
676    let positions: Vec<String> = frames.iter().map(|f| f.position.to_string()).collect();
677    format!("list item {}: {message}", positions.join(", item "))
678}
679
680/// User-provided data values resolved against a plan's type declarations.
681///
682/// Lightweight and cheap to construct — no plan cloning required. The
683/// [`ExecutionPlan`] stays immutable; callers pass `(&ExecutionPlan, &EvaluateData)`
684/// to evaluation and show paths.
685#[derive(Debug, Clone, Default)]
686pub struct EvaluateData {
687    /// Caller bindings by plan data slot, in caller order: successful literals or Veto
688    /// (bad override) per Data.
689    pub bindings: IndexMap<usize, OperationResult>,
690    /// Values supplied for fields of instances: `uses` instances (`i.x`, `i.j.x`) and
691    /// rows (`staff.1.salary`, `i.staff.2.x`).
692    pub(crate) supplied: Supplied,
693    /// Input keys that did not match any plan Data (including Import aliases).
694    pub ignored_unknown: Vec<String>,
695}
696
697impl EvaluateData {
698    /// Parse and validate caller-supplied values against the plan's data declarations.
699    ///
700    /// Unknown keys and Import aliases are ignored (recorded in [`Self::ignored_unknown`]).
701    /// Parse, constraint, options, decimals, and input-oversize failures bind that Data
702    /// as [`OperationResult::Veto`]; evaluation still runs. Duplicate canonical keys Error.
703    pub fn resolve(
704        plan: &ExecutionPlan,
705        raw_values: IndexMap<String, EvaluateDataValue>,
706        limits: &ResourceLimits,
707    ) -> Result<Self, Error> {
708        Self::resolve_level(plan, raw_values, limits, ListLevel::Top)
709    }
710
711    fn resolve_level(
712        plan: &ExecutionPlan,
713        raw_values: IndexMap<String, EvaluateDataValue>,
714        limits: &ResourceLimits,
715        level: ListLevel,
716    ) -> Result<Self, Error> {
717        reject_whole_list_with_row_keys(plan, &raw_values)?;
718        match run_resolve(ResolveFrame::Level(LevelFrame::new(
719            plan, plan, None, raw_values, limits, level,
720        )))? {
721            ResolveOutput::Level(evaluate_data) => Ok(evaluate_data),
722            ResolveOutput::Binding(..) => {
723                panic!("BUG: root level frame returned a list binding")
724            }
725        }
726    }
727}
728
729enum ResolveOutput {
730    Level(EvaluateData),
731    /// A list value, with the values supplied for fields of instances inside its rows.
732    Binding(OperationResult, Supplied),
733}
734
735enum ResolveStep<'a> {
736    Call(Box<ResolveFrame<'a>>),
737    Return(ResolveOutput),
738}
739
740enum ResolveFrame<'a> {
741    Level(LevelFrame<'a>),
742    List(ListFrame<'a>),
743}
744
745impl<'a> ResolveFrame<'a> {
746    fn resume(&mut self, input: Option<ResolveOutput>) -> Result<ResolveStep<'a>, Error> {
747        match self {
748            ResolveFrame::Level(frame) => frame.resume(input),
749            ResolveFrame::List(frame) => frame.resume(input),
750        }
751    }
752}
753
754fn run_resolve(root: ResolveFrame<'_>) -> Result<ResolveOutput, Error> {
755    let mut frames = vec![root];
756    let mut input = None;
757    loop {
758        let frame = frames.last_mut().expect("BUG: resolve frame stack empty");
759        match frame.resume(input.take())? {
760            ResolveStep::Call(child) => frames.push(*child),
761            ResolveStep::Return(output) => {
762                frames.pop();
763                if frames.is_empty() {
764                    return Ok(output);
765                }
766                input = Some(output);
767            }
768        }
769    }
770}
771
772/// Cells of value lists: holding row, data slot and 1-based row number.
773type PatchedCells = HashSet<(Option<InstanceKey>, usize, usize)>;
774
775/// The request error for a key that supplies a field something writes (rule 3).
776fn sealed(name: &str) -> Error {
777    Error::request(
778        format!("data '{name}' is sealed by `uses -> with` and cannot be supplied at evaluate"),
779        Some("remove this key, or change the `uses` binding if the value should be caller-owned data"),
780    )
781    .with_related_data(name.to_string())
782}
783
784/// One level of run data: its entries in caller order. A list entry suspends the level
785/// until its rows are resolved.
786struct LevelFrame<'a> {
787    plan: &'a ExecutionPlan,
788    /// The plan of the request: what its plans write is read from it.
789    root: &'a ExecutionPlan,
790    /// Evaluation-data key of the run-data row this level writes (`items.1`); `None`
791    /// for the request's plan.
792    row_key: Option<Arc<str>>,
793    /// What the list of the run-data row this level writes writes on every row of it
794    /// (rule 2): those fields cannot be supplied.
795    row_writes: Option<Arc<RowInstance>>,
796    /// The instance of the `uses` that list names, where what is written on it is read.
797    row_uses: Option<InstanceKey>,
798    limits: &'a ResourceLimits,
799    level: ListLevel,
800    entries: indexmap::map::IntoIter<String, EvaluateDataValue>,
801    seen_canonical: HashSet<String>,
802    /// The instances the global slots of this level's plan read: built for the first key
803    /// that names a field of a `uses` instance, then reused for the level.
804    globals: Option<Box<RequestGlobals>>,
805    evaluate_data: EvaluateData,
806    /// Cells of value lists dotted keys of this level supplied: built for the first.
807    patched_cells: Option<Box<PatchedCells>>,
808    awaiting: Option<AwaitBinding>,
809    /// List fields of instances one key supplies, still to resolve, last first: one per
810    /// body of a `uses … -> effective` slot that has the field.
811    queued_lists: Vec<QueuedList<'a>>,
812}
813
814/// A list field of an instance a key supplies, resolved against the instance's spec.
815struct QueuedList<'a> {
816    instance: InstanceKey,
817    slot: usize,
818    template: &'a ExecutionPlan,
819    field: &'a DataPath,
820    list_key: String,
821    name: String,
822    raw_value: EvaluateDataValue,
823}
824
825/// Where a suspended level frame puts the list a nested list frame returns: a data slot
826/// of the plan, or a field of an instance.
827enum AwaitBinding {
828    Data { slot: usize },
829    Field { instance: InstanceKey, slot: usize },
830}
831
832impl<'a> LevelFrame<'a> {
833    fn new(
834        plan: &'a ExecutionPlan,
835        root: &'a ExecutionPlan,
836        row_key: Option<Arc<str>>,
837        raw_values: IndexMap<String, EvaluateDataValue>,
838        limits: &'a ResourceLimits,
839        level: ListLevel,
840    ) -> Self {
841        let capacity = raw_values.len();
842        Self {
843            plan,
844            root,
845            row_key,
846            row_writes: None,
847            row_uses: None,
848            limits,
849            level,
850            entries: raw_values.into_iter(),
851            seen_canonical: HashSet::with_capacity(capacity),
852            globals: None,
853            evaluate_data: EvaluateData {
854                bindings: IndexMap::with_capacity(capacity),
855                ..EvaluateData::default()
856            },
857            patched_cells: None,
858            awaiting: None,
859            queued_lists: Vec::new(),
860        }
861    }
862
863    fn resume(&mut self, input: Option<ResolveOutput>) -> Result<ResolveStep<'a>, Error> {
864        match (self.awaiting.take(), input) {
865            (None, None) => {}
866            (Some(AwaitBinding::Data { slot }), Some(ResolveOutput::Binding(binding, rows))) => {
867                self.evaluate_data.bindings.insert(slot, binding);
868                self.evaluate_data.supplied.extend(rows);
869            }
870            (
871                Some(AwaitBinding::Field { instance, slot }),
872                Some(ResolveOutput::Binding(binding, rows)),
873            ) => {
874                // The rows are the instance's: what is supplied inside them is too.
875                self.evaluate_data.supplied.extend(rows.under(&instance));
876                self.evaluate_data.supplied.insert(instance, slot, binding);
877            }
878            _ => panic!("BUG: level frame resumed with an unexpected output"),
879        }
880        self.advance()
881    }
882
883    /// The list frame of the next queued list field, if any.
884    fn next_queued_list(&mut self) -> Option<ResolveStep<'a>> {
885        let queued = self.queued_lists.pop()?;
886        self.awaiting = Some(AwaitBinding::Field {
887            instance: queued.instance.clone(),
888            slot: queued.slot,
889        });
890        Some(ResolveStep::Call(Box::new(ResolveFrame::List(ListFrame {
891            plan: queued.template,
892            root: self.root,
893            path: queued.field,
894            list_key: queued.list_key,
895            under: self.row_key.clone(),
896            name: queued.name,
897            holder: Some(queued.instance.clone()),
898            supplied: Supplied::default(),
899            limits: self.limits,
900            level: self.level,
901            raw_value: Some(queued.raw_value),
902            rows: None,
903        }))))
904    }
905
906    fn advance(&mut self) -> Result<ResolveStep<'a>, Error> {
907        if let Some(step) = self.next_queued_list() {
908            return Ok(step);
909        }
910        let plan = self.plan;
911        let limits = self.limits;
912        let level = self.level;
913        let evaluate_data = &mut self.evaluate_data;
914        let seen_canonical = &mut self.seen_canonical;
915        let globals = &mut self.globals;
916
917        for (name, raw_value) in self.entries.by_ref() {
918            let canonical = canonical_logical_name(&name);
919            if seen_canonical.contains(canonical.as_ref()) {
920                let canonical = canonical.into_owned();
921                return Err(Error::request(
922                    format!("Duplicate data key '{canonical}'"),
923                    Some("Data keys are case-insensitive; remove the duplicate"),
924                )
925                .with_related_data(name));
926            }
927            seen_canonical.insert(canonical.to_string());
928
929            let Some((slot, data_path, data_definition)) =
930                resolve_evaluate_data_target(plan, &canonical)
931            else {
932                let mut fields = Vec::new();
933                let mut cells = Vec::new();
934                let globals: &RequestGlobals =
935                    globals.get_or_insert_with(|| Box::new(plan.request_globals()));
936                for lookup in resolve_row_field_keys(plan, globals, &canonical, Vec::new()) {
937                    match lookup {
938                        RowKeyLookup::Field(row_field) => fields.push(row_field),
939                        RowKeyLookup::Cell(cell) => cells.push(cell),
940                        RowKeyLookup::Unknown => {}
941                        RowKeyLookup::Invalid(error) => return Err(error.with_related_data(name)),
942                    }
943                }
944                if fields
945                    .iter()
946                    .any(|field| matches!(field.definition, DataDefinition::Import { .. }))
947                {
948                    if matches!(
949                        raw_value,
950                        EvaluateDataValue::Map(_) | EvaluateDataValue::List(_)
951                    ) {
952                        return Err(Error::request(
953                            format!(
954                                "data '{name}': '{name}' is a uses alias; objects and arrays are not a nesting level"
955                            ),
956                            Some(format!("bind fields with dotted keys, e.g. '{name}.<field>'")),
957                        )
958                        .with_related_data(name));
959                    }
960                    fields
961                        .retain(|field| !matches!(field.definition, DataDefinition::Import { .. }));
962                }
963                if fields.is_empty() && cells.is_empty() {
964                    evaluate_data.ignored_unknown.push(name);
965                    continue;
966                }
967                // One field, or one per body of a `uses … -> effective` slot that has it.
968                let mut lists = Vec::new();
969                for field in fields {
970                    // At a run-data row, what is written on the `uses` its list names
971                    // at the same path is written on the row (rule 2).
972                    let by_list = self.row_uses.as_ref().is_some_and(|uses| {
973                        crate::evaluation::lookup::list_writes_field(
974                            uses,
975                            Some(&field.key),
976                            field.template,
977                            field.slot,
978                            &self.root.writes_by_spec,
979                            &self.root.identity,
980                        )
981                    });
982                    if field.written || by_list {
983                        return Err(sealed(&name));
984                    }
985                    if let Some(list) = field.keyed_list.clone() {
986                        evaluate_data.supplied.key_supplied(list.0, list.1);
987                    }
988                    if matches!(field.definition, DataDefinition::InstanceList { .. }) {
989                        // A list a plan writes a row of through a path cannot be replaced.
990                        // So can a list a plan fills with copies (`-> with items: a, b`).
991                        if crate::evaluation::lookup::writes_rows_above(
992                            Some(&field.key),
993                            field.field,
994                            &plan.writes_by_spec,
995                            &plan.identity,
996                        ) || crate::evaluation::lookup::list_above(
997                            Some(&field.key),
998                            field.field,
999                            &plan.writes_by_spec,
1000                            &plan.identity,
1001                        )
1002                        .is_some()
1003                        {
1004                            return Err(sealed(&name));
1005                        }
1006                        lists.push(field);
1007                        continue;
1008                    }
1009                    let type_arc = Arc::clone(
1010                        field
1011                            .definition
1012                            .resolved_type_arc()
1013                            .expect("BUG: a field of an instance is typed data"),
1014                    );
1015                    let binding = resolve_scalar_binding(
1016                        field.template,
1017                        &name,
1018                        &canonical,
1019                        &raw_value,
1020                        &type_arc,
1021                        field.definition.source(),
1022                        limits,
1023                    )?;
1024                    evaluate_data
1025                        .supplied
1026                        .insert(field.key, field.slot, binding);
1027                }
1028                for field in lists {
1029                    self.queued_lists.push(QueuedList {
1030                        instance: field.key,
1031                        slot: field.slot,
1032                        template: field.template,
1033                        field: field.field,
1034                        list_key: canonical.to_string(),
1035                        name: name.clone(),
1036                        raw_value: raw_value.clone(),
1037                    });
1038                }
1039                // One cell, or one per body of a `uses … -> effective` slot that has the
1040                // list.
1041                for cell in cells {
1042                    bind_value_cell(
1043                        evaluate_data,
1044                        self.patched_cells.get_or_insert_with(Box::default),
1045                        &name,
1046                        &canonical,
1047                        &raw_value,
1048                        cell,
1049                        limits,
1050                    )?;
1051                }
1052                if !self.queued_lists.is_empty() {
1053                    break;
1054                }
1055                continue;
1056            };
1057
1058            let written_by_list = !matches!(data_definition, DataDefinition::Import { .. })
1059                && self.row_uses.as_ref().is_some_and(|uses| {
1060                    crate::evaluation::lookup::list_writes_field(
1061                        uses,
1062                        None,
1063                        plan,
1064                        slot,
1065                        &self.root.writes_by_spec,
1066                        &self.root.identity,
1067                    )
1068                });
1069            if data_definition.is_bound() || written_by_list {
1070                return Err(sealed(&name));
1071            }
1072
1073            let data_source = data_definition.source();
1074            let type_arc = match data_definition {
1075                DataDefinition::TypeDeclaration { resolved_type, .. }
1076                | DataDefinition::Value { resolved_type, .. }
1077                | DataDefinition::Reference { resolved_type, .. } => Arc::clone(resolved_type),
1078                DataDefinition::Import { .. } => {
1079                    if matches!(
1080                        raw_value,
1081                        EvaluateDataValue::Map(_) | EvaluateDataValue::List(_)
1082                    ) {
1083                        return Err(Error::request(
1084                            format!(
1085                                "data '{name}': '{name}' is a uses alias; objects and arrays are not a nesting level"
1086                            ),
1087                            Some(format!("bind fields with dotted keys, e.g. '{name}.<field>'")),
1088                        )
1089                        .with_related_data(name));
1090                    }
1091                    evaluate_data.ignored_unknown.push(name);
1092                    continue;
1093                }
1094                DataDefinition::InstanceList { .. } => {
1095                    self.awaiting = Some(AwaitBinding::Data { slot });
1096                    return Ok(ResolveStep::Call(Box::new(ResolveFrame::List(ListFrame {
1097                        plan,
1098                        root: self.root,
1099                        path: data_path,
1100                        list_key: data_path.input_key(),
1101                        under: self.row_key.clone(),
1102                        name,
1103                        holder: None,
1104                        supplied: Supplied::default(),
1105                        limits,
1106                        level,
1107                        raw_value: Some(raw_value),
1108                        rows: None,
1109                    }))));
1110                }
1111            };
1112
1113            let binding = resolve_scalar_binding(
1114                plan,
1115                &name,
1116                &canonical,
1117                &raw_value,
1118                &type_arc,
1119                data_source,
1120                limits,
1121            )?;
1122            evaluate_data.bindings.insert(slot, binding);
1123        }
1124
1125        if let Some(step) = self.next_queued_list() {
1126            return Ok(step);
1127        }
1128        Ok(ResolveStep::Return(ResolveOutput::Level(std::mem::take(
1129            &mut self.evaluate_data,
1130        ))))
1131    }
1132}
1133
1134/// Bind run-data value `raw_value` for the dotted key `name` to one cell of a value
1135/// list: the list the request holds so far, or the rows the spec writes, with that row
1136/// replaced. A bad value vetoes the list.
1137fn bind_value_cell(
1138    evaluate_data: &mut EvaluateData,
1139    patched: &mut PatchedCells,
1140    name: &str,
1141    canonical: &str,
1142    raw_value: &EvaluateDataValue,
1143    cell: ValueCell<'_>,
1144    limits: &ResourceLimits,
1145) -> Result<(), Error> {
1146    if !patched.insert((cell.holder.clone(), cell.slot, cell.number)) {
1147        return Err(Error::request(
1148            format!("data '{name}' supplies a row another key supplies"),
1149            Some(format!("supply row {} of the list once", cell.number)),
1150        )
1151        .with_related_data(name.to_string()));
1152    }
1153    let list_type = cell
1154        .definition
1155        .resolved_type_arc()
1156        .expect("BUG: a value list is typed data");
1157    let element = list_type.list_element_lemma_type();
1158    let replacement = resolve_scalar_binding(
1159        cell.template,
1160        name,
1161        canonical,
1162        raw_value,
1163        element,
1164        cell.definition.source(),
1165        limits,
1166    )?;
1167    let supplied = match &cell.holder {
1168        None => evaluate_data.bindings.get(&cell.slot),
1169        Some(instance) => evaluate_data.supplied.get(instance, cell.slot),
1170    };
1171    let binding = match (supplied, &replacement) {
1172        (Some(veto @ OperationResult::Veto(_)), _) => veto.clone(),
1173        (_, OperationResult::Veto(_)) => replacement,
1174        (supplied, OperationResult::Value(bound)) => {
1175            let mut rows = match supplied.and_then(OperationResult::value) {
1176                Some(list) => value_list_rows(&list.value),
1177                None => cell.written_rows(),
1178            };
1179            rows[cell.number - 1] = typed_literal_from_bound(bound, element);
1180            let list = LiteralValue::new(ValueKind::List(rows.into()));
1181            match validate_value_against_type(
1182                list_type,
1183                &list,
1184                cell.template.expression_unit_index(),
1185                None,
1186            ) {
1187                Ok(()) => OperationResult::from_literal(list),
1188                Err(message) => OperationResult::Veto(VetoType::computation(
1189                    list_type.data_veto_message(canonical, &message),
1190                )),
1191            }
1192        }
1193    };
1194    match cell.holder {
1195        None => {
1196            evaluate_data.bindings.insert(cell.slot, binding);
1197        }
1198        Some(instance) => evaluate_data.supplied.insert(instance, cell.slot, binding),
1199    }
1200    Ok(())
1201}
1202
1203/// The rows of value list `value`.
1204fn value_list_rows(value: &ValueKind) -> Vec<TypedLiteral> {
1205    let ValueKind::List(rows) = value else {
1206        panic!("BUG: value list data holds {value:?}");
1207    };
1208    rows.values().to_vec()
1209}
1210
1211/// One caller value against its slot type: parse, size-check and validate it. The
1212/// result to bind — the parsed value or a veto for a bad overlay; structural
1213/// failures (shape, too many rows) are request errors.
1214fn resolve_scalar_binding(
1215    plan: &ExecutionPlan,
1216    name: &str,
1217    input_key: &str,
1218    raw_value: &EvaluateDataValue,
1219    type_arc: &Arc<LemmaType>,
1220    data_source: &Source,
1221    limits: &ResourceLimits,
1222) -> Result<OperationResult, Error> {
1223    if raw_value.is_empty() && type_arc.empty_runtime_input_vetoes() {
1224        return Ok(OperationResult::Veto(VetoType::computation(format!(
1225            "Data {} cannot be empty.",
1226            type_arc.label_for_data_input(input_key)
1227        ))));
1228    }
1229
1230    if let Some(message) = evaluate_data_shape_error(raw_value, type_arc) {
1231        return Err(Error::request(
1232            format!("data '{name}': {message}"),
1233            Some(format!("fix the overlay for '{name}'")),
1234        )
1235        .with_related_data(name));
1236    }
1237
1238    let typed = match parse_data_value(
1239        raw_value,
1240        type_arc,
1241        data_source,
1242        plan.expression_unit_index(),
1243        &plan.resolved_types.resolved,
1244    ) {
1245        Ok(value) => value,
1246        Err(error) => {
1247            return Ok(OperationResult::Veto(VetoType::computation(
1248                type_arc.data_veto_message(input_key, error.message()),
1249            )));
1250        }
1251    };
1252
1253    if let ValueKind::List(rows) = &typed.value {
1254        if rows.len() > limits.max_list_rows {
1255            return Err(Error::request(
1256                format!(
1257                    "data '{name}' has {} rows, over max_list_rows {}",
1258                    rows.len(),
1259                    limits.max_list_rows
1260                ),
1261                Some("reduce the list size or raise max_list_rows".to_string()),
1262            )
1263            .with_related_data(name));
1264        }
1265    }
1266
1267    let literal_value = LiteralValue {
1268        value: typed.value.clone(),
1269    };
1270    let oversize = match &typed.value {
1271        ValueKind::List(items) => items
1272            .iter()
1273            .position(|item| item.byte_size() > limits.max_data_value_bytes)
1274            .map(|index| {
1275                format!(
1276                    "Data {} list item {} exceeds the size limit.",
1277                    type_arc.label_for_data_input(input_key),
1278                    index + 1
1279                )
1280            }),
1281        _ => (literal_value.byte_size() > limits.max_data_value_bytes).then(|| {
1282            format!(
1283                "Data {} exceeds the size limit.",
1284                type_arc.label_for_data_input(input_key)
1285            )
1286        }),
1287    };
1288    if let Some(reason) = oversize {
1289        return Ok(OperationResult::Veto(VetoType::computation(reason)));
1290    }
1291
1292    if let Err(message) = validate_value_against_type(
1293        typed.lemma_type.as_ref(),
1294        &literal_value,
1295        plan.expression_unit_index(),
1296        None,
1297    ) {
1298        return Ok(OperationResult::Veto(VetoType::computation(
1299            type_arc.data_veto_message(input_key, &message),
1300        )));
1301    }
1302
1303    Ok(OperationResult::from_bound(BoundValueKind {
1304        value: typed.value.clone(),
1305        unit: typed.lemma_type.unit().map(std::sync::Arc::from),
1306        instance_factors: None,
1307    }))
1308}
1309
1310/// Plan data slot and path matched by `input_key`: local data or data of a flattened
1311/// import. Fields of spec-written rows (`staff.1.salary`) are not plan data; they
1312/// resolve through [`resolve_row_field_key`].
1313fn resolve_evaluate_data_target<'a>(
1314    plan: &'a ExecutionPlan,
1315    key: &str,
1316) -> Option<(usize, &'a DataPath, &'a DataDefinition)> {
1317    let path = plan.input_key_index.get(key)?;
1318    let (slot, path, definition) = plan
1319        .data
1320        .get_full(path)
1321        .unwrap_or_else(|| panic!("BUG: indexed input '{key}' has no data definition"));
1322    Some((slot, path, definition))
1323}
1324
1325/// A stored list as a row reads it: the row holding it (`None` for the plan) and its path.
1326type ListAddress = (Option<InstanceKey>, DataPath);
1327
1328/// A dotted key naming one field of a row the plan holds: a field of a `uses` row
1329/// (`i.x`, `i.j.x`) or of a spec-written list row (`staff.2.salary`, `i.staff.1.x`).
1330struct RowFieldKey<'a> {
1331    /// The row as evaluation reads it.
1332    key: InstanceKey,
1333    template: &'a ExecutionPlan,
1334    slot: usize,
1335    field: &'a DataPath,
1336    definition: &'a DataDefinition,
1337    /// The instance writes the field: it cannot be supplied (rule 3).
1338    written: bool,
1339    /// The stored list whose index the field changes: set when the instance is a row of
1340    /// that list and the field is one of its key fields.
1341    keyed_list: Option<ListAddress>,
1342    /// Every list the key steps through a row of, with its dotted key.
1343    lists: Vec<(ListAddress, String)>,
1344}
1345
1346/// A dotted key naming one row of a value list (`fares.2`, `staff.1.tags.2`).
1347struct ValueCell<'a> {
1348    /// The row holding the list; `None` for a list of the level's plan.
1349    holder: Option<InstanceKey>,
1350    template: &'a ExecutionPlan,
1351    slot: usize,
1352    definition: &'a DataDefinition,
1353    /// Row of the list, 1-based.
1354    number: usize,
1355    /// The list, and every list the key steps through a row of, with its dotted key.
1356    lists: Vec<(ListAddress, String)>,
1357}
1358
1359impl ValueCell<'_> {
1360    /// The rows the spec writes in the list.
1361    fn written_rows(&self) -> Vec<TypedLiteral> {
1362        written_value_rows(self.definition)
1363    }
1364}
1365
1366/// The rows a spec writes in value list `definition`; none for a list without rows.
1367fn written_value_rows(definition: &DataDefinition) -> Vec<TypedLiteral> {
1368    match definition.bound_value() {
1369        Some(bound) => value_list_rows(&bound.value),
1370        None => definition
1371            .value()
1372            .map(|literal| value_list_rows(&literal.value))
1373            .unwrap_or_default(),
1374    }
1375}
1376
1377/// Whether `definition` is a list of values: a list whose rows are no instances.
1378fn is_value_list(definition: &DataDefinition) -> bool {
1379    match definition {
1380        DataDefinition::Value { resolved_type, .. }
1381        | DataDefinition::TypeDeclaration { resolved_type, .. }
1382        | DataDefinition::Reference { resolved_type, .. } => resolved_type.is_list(),
1383        DataDefinition::InstanceList { .. } | DataDefinition::Import { .. } => false,
1384    }
1385}
1386
1387enum RowKeyLookup<'a> {
1388    Field(RowFieldKey<'a>),
1389    Cell(ValueCell<'a>),
1390    /// No row field of the plan: an ignorable key.
1391    Unknown,
1392    /// A key under a list that names no row or field of it: the caller addressed a row
1393    /// that is not there, or a field those rows do not have.
1394    Invalid(Error),
1395}
1396
1397/// Bodies chosen for `uses … -> effective` slots while resolving one key: the slot's
1398/// holder (`None` for the plan), the slot, and the body read there.
1399pub(crate) type BodyChoice = Vec<(Option<InstanceKey>, DataPath, Arc<RowInstance>)>;
1400
1401/// A `-> effective` slot a key walk reached without a chosen body: its holder, the
1402/// slot, and the bodies it can read.
1403struct BodyFork {
1404    holder: Option<InstanceKey>,
1405    slot: DataPath,
1406    bodies: Vec<Arc<RowInstance>>,
1407}
1408
1409/// Every field the dotted key `key` names: one per body a `uses … -> effective` slot on
1410/// its path can select (a body without the field contributes `Unknown`).
1411/// Whether the `uses` a list names, `uses`, writes the dotted row field `key` (`b.d`) of
1412/// rows of `template` on every row: the key resolved as evaluation data for a row
1413/// resolves it.
1414pub(crate) fn list_writes_row_key(
1415    template: &ExecutionPlan,
1416    uses: &InstanceKey,
1417    key: &str,
1418    writes: &crate::planning::fill::WritesIndex,
1419    root: &SpecIdentity,
1420) -> bool {
1421    let globals = template.request_globals();
1422    resolve_row_field_keys(template, &globals, key, Vec::new())
1423        .into_iter()
1424        .any(|lookup| match lookup {
1425            RowKeyLookup::Field(field) => crate::evaluation::lookup::list_writes_field(
1426                uses,
1427                Some(&field.key),
1428                field.template,
1429                field.slot,
1430                writes,
1431                root,
1432            ),
1433            RowKeyLookup::Cell(_) | RowKeyLookup::Unknown | RowKeyLookup::Invalid(_) => false,
1434        })
1435}
1436
1437fn resolve_row_field_keys<'a>(
1438    plan: &'a ExecutionPlan,
1439    globals: &RequestGlobals,
1440    key: &str,
1441    chosen: BodyChoice,
1442) -> Vec<RowKeyLookup<'a>> {
1443    let mut lookups = Vec::new();
1444    let mut pending = vec![chosen];
1445    while let Some(chosen) = pending.pop() {
1446        match resolve_row_field_key_body(plan, globals, key, &chosen) {
1447            Ok(lookup) => lookups.push(lookup),
1448            Err(BodyFork {
1449                holder,
1450                slot,
1451                bodies,
1452            }) => {
1453                for body in bodies.into_iter().rev() {
1454                    let mut next = chosen.clone();
1455                    next.push((holder.clone(), slot.clone(), body));
1456                    pending.push(next);
1457                }
1458            }
1459        }
1460    }
1461    lookups
1462}
1463
1464/// `i.j.x`, `staff.2.salary`, `i.staff.1.x` → the field of the row the key names under
1465/// `chosen`, stepping through `uses` slots and the rows of stored lists; `Err` at a
1466/// `-> effective` slot `chosen` leaves open.
1467fn resolve_row_field_key_body<'a>(
1468    plan: &'a ExecutionPlan,
1469    globals: &RequestGlobals,
1470    key: &str,
1471    chosen: &BodyChoice,
1472) -> Result<RowKeyLookup<'a>, BodyFork> {
1473    let mut parts: Vec<std::borrow::Cow<'_, str>> =
1474        key.split('.').map(std::borrow::Cow::Borrowed).collect();
1475    // `global.x.f` / `<repo> global.x.f`: the first two parts name the slot of global `x`.
1476    if parts.len() > 1 && (parts[0] == "global" || parts[0].ends_with(" global")) {
1477        let slot = format!("{}.{}", parts[0], parts[1]);
1478        parts.splice(0..2, [std::borrow::Cow::Owned(slot)]);
1479    }
1480    let parts: Vec<&str> = parts.iter().map(AsRef::as_ref).collect();
1481    let mut template = plan;
1482    let mut holder: Option<InstanceKey> = None;
1483    let mut lists: Vec<(ListAddress, String)> = Vec::new();
1484    // The stored list whose row `holder` is, with its key.
1485    let mut keyed: Option<(ListAddress, &'a ListKey)> = None;
1486    let mut index = 0;
1487    loop {
1488        let Some(path) = template.input_key_index.get(parts[index]) else {
1489            return Ok(unknown_under_list(key, &lists));
1490        };
1491        let (slot, _, definition) = template
1492            .data
1493            .get_full(path)
1494            .expect("BUG: indexed input key has a data definition");
1495        let row = holder.as_ref().map(|key| key.row.as_ref());
1496        if index + 1 < parts.len() && is_value_list(definition) {
1497            let list_key = parts[..=index].join(".");
1498            let keyed_as = || {
1499                no_list_data(
1500                    key,
1501                    &list_key,
1502                    format!("rows of '{list_key}' are keyed '{list_key}.<row>'"),
1503                )
1504            };
1505            let number = match parts[index + 1..] {
1506                [number] => number.parse::<usize>().ok(),
1507                _ => None,
1508            };
1509            let Some(number) = number else {
1510                return Ok(RowKeyLookup::Invalid(keyed_as()));
1511            };
1512            let written = holder.as_ref().is_some_and(|key| {
1513                crate::evaluation::lookup::field(
1514                    key,
1515                    template,
1516                    slot,
1517                    &plan.writes_by_spec,
1518                    &plan.identity,
1519                    &Supplied::default(),
1520                )
1521                .is_some()
1522            });
1523            if definition.is_bound() || written {
1524                return Ok(RowKeyLookup::Invalid(Error::request(
1525                    format!(
1526                        "data '{key}' is sealed by `uses -> with` and cannot be supplied at evaluate"
1527                    ),
1528                    Some("remove this key, or change the `uses` binding if the value should be caller-owned data"),
1529                )));
1530            }
1531            let rows = written_value_rows(definition).len();
1532            if number == 0 || number > rows {
1533                return Ok(RowKeyLookup::Invalid(no_list_data(
1534                    key,
1535                    &list_key,
1536                    format!(
1537                        "'{list_key}' has {rows} spec-written row(s); rows are numbered from 1"
1538                    ),
1539                )));
1540            }
1541            lists.push(((holder.clone(), path.clone()), list_key));
1542            return Ok(RowKeyLookup::Cell(ValueCell {
1543                holder,
1544                template,
1545                slot,
1546                definition,
1547                number,
1548                lists,
1549            }));
1550        }
1551        if index + 1 == parts.len() {
1552            if matches!(definition, DataDefinition::Import { .. }) && !lists.is_empty() {
1553                return Ok(unknown_under_list(key, &lists));
1554            }
1555            let Some(key) = holder else {
1556                return Ok(RowKeyLookup::Unknown);
1557            };
1558            let keyed_list = keyed.and_then(|(list, list_key)| match list_key {
1559                ListKey::Fields(fields) => fields
1560                    .iter()
1561                    .any(|field| field.path == *path)
1562                    .then_some(list),
1563                ListKey::Numbered => None,
1564            });
1565            let written = crate::evaluation::lookup::field(
1566                &key,
1567                template,
1568                slot,
1569                &plan.writes_by_spec,
1570                &plan.identity,
1571                &Supplied::default(),
1572            )
1573            .is_some();
1574            return Ok(RowKeyLookup::Field(RowFieldKey {
1575                written,
1576                key,
1577                template,
1578                slot,
1579                field: path,
1580                definition,
1581                keyed_list,
1582                lists,
1583            }));
1584        }
1585        match definition {
1586            DataDefinition::Import { global, .. } => {
1587                if let Some(global) = global {
1588                    if holder.is_some() || !is_global_slot_name(&path.data) {
1589                        let rest = parts[index + 1..].join(".");
1590                        let canonical = global.alias_in(plan.identity.repository.as_deref());
1591                        return Ok(RowKeyLookup::Invalid(Error::request(
1592                            format!(
1593                                "data '{key}' is data of the global instance '{canonical}' (`uses global`)"
1594                            ),
1595                            Some(format!("supply it as '{canonical}.{rest}'")),
1596                        )));
1597                    }
1598                }
1599                let import = match definition {
1600                    // A `-> effective` slot: each body.
1601                    DataDefinition::Import {
1602                        pin: Some(_),
1603                        candidates,
1604                        ..
1605                    } => {
1606                        let chosen_body = chosen.iter().find_map(|(at, slot, body)| {
1607                            (*at == holder && slot == path).then_some(body)
1608                        });
1609                        let Some(body) = chosen_body else {
1610                            return Err(BodyFork {
1611                                holder,
1612                                slot: path.clone(),
1613                                bodies: candidates.values().cloned().collect(),
1614                            });
1615                        };
1616                        InstanceKey::new(Arc::clone(body), holder.clone())
1617                    }
1618                    _ => template.import_key(holder.as_ref(), path, None, globals),
1619                };
1620                template = template.row_template(&import.row.identity);
1621                holder = Some(import);
1622                keyed = None;
1623                index += 1;
1624            }
1625            DataDefinition::InstanceList { .. } => {
1626                let list_key = parts[..=index].join(".");
1627                let source = template
1628                    .instance_lists
1629                    .get(path)
1630                    .unwrap_or_else(|| panic!("BUG: instance list '{list_key}' has no source"));
1631                let filled = crate::evaluation::lookup::list_above(
1632                    holder.as_ref(),
1633                    path,
1634                    &plan.writes_by_spec,
1635                    &plan.identity,
1636                );
1637                let (rows, owner) = match row.and_then(|row| row.bindings[slot].as_ref()) {
1638                    // Rows a plan above fills the list with (`-> with items: a, b`).
1639                    None if filled.is_some() => (
1640                        filled.expect("BUG: checked above").rows.as_slice(),
1641                        holder.clone(),
1642                    ),
1643                    None => (source.store.rows.as_slice(), holder.clone()),
1644                    Some(RowBinding::Bound(_) | RowBinding::Deferred { .. }) => {
1645                        return Ok(RowKeyLookup::Invalid(Error::request(
1646                            format!(
1647                                "data '{key}' is sealed by `uses -> with` and cannot be supplied at evaluate"
1648                            ),
1649                            Some(format!(
1650                                "'{list_key}' is bound by `uses -> with`; its rows take no run data"
1651                            )),
1652                        )));
1653                    }
1654                };
1655                let rest = &parts[index + 1..];
1656                let number = match rest.first().map(|row| row.parse::<usize>()) {
1657                    Some(Ok(number)) if rest.len() > 1 => number,
1658                    _ => {
1659                        return Ok(RowKeyLookup::Invalid(no_list_data(
1660                            key,
1661                            &list_key,
1662                            format!("fields of a row of '{list_key}' are keyed '{list_key}.<row>.<field>'"),
1663                        )));
1664                    }
1665                };
1666                if number == 0 || number > rows.len() {
1667                    return Ok(RowKeyLookup::Invalid(no_list_data(
1668                        key,
1669                        &list_key,
1670                        format!(
1671                            "'{list_key}' has {} spec-written row(s); rows are numbered from 1",
1672                            rows.len()
1673                        ),
1674                    )));
1675                }
1676                let list = (owner.clone(), path.clone());
1677                lists.push((list.clone(), list_key));
1678                keyed = Some((list, &source.key));
1679                let listed = Arc::clone(&rows[number - 1]);
1680                template = template.row_template(&listed.identity);
1681                holder = Some(InstanceKey::new(listed, owner));
1682                index += 2;
1683            }
1684            DataDefinition::Value { .. }
1685            | DataDefinition::TypeDeclaration { .. }
1686            | DataDefinition::Reference { .. } => {
1687                return Ok(unknown_under_list(key, &lists));
1688            }
1689        }
1690    }
1691}
1692
1693/// Template, definition, instance and field path of every `uses` instance field a dotted
1694/// run-data key names (`i.x`, `i.j.x`, `global.x.f`); empty for any other key.
1695///
1696/// `selected` holds the bodies evaluation selected for `uses … -> effective` slots, by
1697/// holding instance (`None` for the plan) and slot. A slot on the key's path without a
1698/// selection (a nested slot evaluation has not read, or a global with several bodies)
1699/// yields the field of every body it can select.
1700pub(crate) fn row_field_definitions<'a>(
1701    plan: &'a ExecutionPlan,
1702    globals: &RequestGlobals,
1703    key: &str,
1704    selected: BodyChoice,
1705) -> Vec<(
1706    &'a ExecutionPlan,
1707    &'a DataDefinition,
1708    InstanceKey,
1709    &'a DataPath,
1710)> {
1711    resolve_row_field_keys(plan, globals, key, selected)
1712        .into_iter()
1713        .filter_map(|lookup| match lookup {
1714            RowKeyLookup::Field(row_field) if row_field.lists.is_empty() => Some((
1715                row_field.template,
1716                row_field.definition,
1717                row_field.key,
1718                row_field.field,
1719            )),
1720            _ => None,
1721        })
1722        .collect()
1723}
1724
1725/// A key that names nothing past its last list row (`items.1.bonus`): a request error
1726/// under a list, an ignorable key otherwise.
1727fn unknown_under_list<'a>(key: &str, lists: &[(ListAddress, String)]) -> RowKeyLookup<'a> {
1728    match lists.last() {
1729        Some((_, list_key)) => {
1730            let field = key[list_key.len() + 1..]
1731                .split_once('.')
1732                .map_or("", |(_, field)| field);
1733            RowKeyLookup::Invalid(no_list_data(
1734                key,
1735                list_key,
1736                format!("rows of '{list_key}' have no field '{field}'"),
1737            ))
1738        }
1739        None => RowKeyLookup::Unknown,
1740    }
1741}
1742
1743fn no_list_data(key: &str, list_key: &str, hint: String) -> Error {
1744    Error::request(
1745        format!("data '{key}' names no data of '{list_key}'"),
1746        Some(hint),
1747    )
1748}
1749
1750/// A request that replaces a list as a whole and also supplies a row of it, or a field
1751/// of one of its spec-written rows, is contradictory: the whole list has no such row.
1752/// `raw_values` are the entries of one level: the request, or a run-data row.
1753fn reject_whole_list_with_row_keys(
1754    plan: &ExecutionPlan,
1755    raw_values: &IndexMap<String, EvaluateDataValue>,
1756) -> Result<(), Error> {
1757    if !raw_values.keys().any(|name| name.contains('.')) {
1758        return Ok(());
1759    }
1760    let is_list = |definition: &DataDefinition| {
1761        matches!(definition, DataDefinition::InstanceList { .. }) || is_value_list(definition)
1762    };
1763    let mut whole_lists: HashSet<ListAddress> = HashSet::new();
1764    let mut row_fields: Vec<(&String, Vec<(ListAddress, String)>)> = Vec::new();
1765    let globals = plan.request_globals();
1766    for name in raw_values.keys() {
1767        let canonical = canonical_logical_name(name);
1768        if let Some((_, path, definition)) = resolve_evaluate_data_target(plan, &canonical) {
1769            if is_list(definition) {
1770                whole_lists.insert((None, path.clone()));
1771            }
1772            continue;
1773        }
1774        for lookup in resolve_row_field_keys(plan, &globals, &canonical, Vec::new()) {
1775            match lookup {
1776                RowKeyLookup::Field(row_field) => {
1777                    if is_list(row_field.definition) {
1778                        whole_lists.insert((Some(row_field.key.clone()), row_field.field.clone()));
1779                    }
1780                    row_fields.push((name, row_field.lists));
1781                }
1782                RowKeyLookup::Cell(cell) => row_fields.push((name, cell.lists)),
1783                RowKeyLookup::Unknown | RowKeyLookup::Invalid(_) => {}
1784            }
1785        }
1786    }
1787    for (name, lists) in row_fields {
1788        for (list, list_key) in lists {
1789            if whole_lists.contains(&list) {
1790                return Err(Error::request(
1791                    format!(
1792                        "data '{list_key}': cannot supply both the whole list and dotted row keys such as '{name}'"
1793                    ),
1794                    Some(format!(
1795                        "pass either '{list_key}' as an array, or only dotted keys under '{list_key}'"
1796                    )),
1797                )
1798                .with_related_data(list_key));
1799            }
1800        }
1801    }
1802    Ok(())
1803}
1804
1805/// Whether a run-data list value is a top-level one, whose whole row tree is checked
1806/// against the list limits, or rows nested inside one already checked.
1807#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1808enum ListLevel {
1809    Top,
1810    Nested,
1811}
1812
1813/// Rows of one top-level list value across all its levels, `template` being the plan
1814/// its rows read. Over `max_list_nodes` rows in total, or rows nesting deeper than
1815/// `max_list_depth` levels (the spec holding the list is level 1), is a request Error.
1816/// Node count is checked first so a wide tree reports its size, not its depth.
1817fn check_list_tree(
1818    template: &ExecutionPlan,
1819    raw_rows: &[EvaluateDataValue],
1820    limits: &ResourceLimits,
1821) -> Result<(), String> {
1822    let mut stack: Vec<(&ExecutionPlan, &EvaluateDataValue, usize)> =
1823        raw_rows.iter().map(|row| (template, row, 2)).collect();
1824    let mut nodes = 0usize;
1825    let mut deepest = 0usize;
1826    while let Some((row_template, raw_row, depth)) = stack.pop() {
1827        nodes += 1;
1828        if nodes > limits.max_list_nodes {
1829            return Err(format!(
1830                "has more than max_list_nodes {} rows across all levels",
1831                limits.max_list_nodes
1832            ));
1833        }
1834        deepest = deepest.max(depth);
1835        let EvaluateDataValue::Map(fields) = raw_row else {
1836            continue;
1837        };
1838        for (field, value) in fields {
1839            let EvaluateDataValue::List(rows) = value else {
1840                continue;
1841            };
1842            let Some(source) = row_template
1843                .input_key_index
1844                .get(canonical_logical_name(field).as_ref())
1845                .and_then(|path| row_template.instance_lists.get(path))
1846            else {
1847                continue;
1848            };
1849            let nested = row_template.row_template(&source.identity);
1850            stack.extend(rows.iter().map(|row| (nested, row, depth + 1)));
1851        }
1852    }
1853    if deepest > limits.max_list_depth {
1854        return Err(format!(
1855            "rows nest {deepest} levels deep counting the spec itself, over max_list_depth {}",
1856            limits.max_list_depth
1857        ));
1858    }
1859    Ok(())
1860}
1861
1862/// Frame of one instance list entry: validates the list, then resolves each row through
1863/// a level frame of the row template. A vetoed field, duplicate key or overlapping key
1864/// range resolves the list to a veto.
1865struct ListFrame<'a> {
1866    plan: &'a ExecutionPlan,
1867    /// The plan of the request.
1868    root: &'a ExecutionPlan,
1869    path: &'a DataPath,
1870    /// Dotted key of the list from the plan of its level, naming its rows.
1871    list_key: String,
1872    /// Evaluation-data key of the run-data row holding the list; `None` for a list of
1873    /// the request's plan.
1874    under: Option<Arc<str>>,
1875    name: String,
1876    /// The instance whose list this is; `None` for a list of the plan of its level.
1877    holder: Option<InstanceKey>,
1878    /// Values supplied for fields of instances inside the rows resolved so far.
1879    supplied: Supplied,
1880    limits: &'a ResourceLimits,
1881    level: ListLevel,
1882    raw_value: Option<EvaluateDataValue>,
1883    rows: Option<ListRows<'a>>,
1884}
1885
1886struct ListRows<'a> {
1887    source: &'a InstanceListSource,
1888    /// Row spec identity, shared by the rows.
1889    identity: Arc<SpecIdentity>,
1890    template: &'a ExecutionPlan,
1891    row_type: Arc<LemmaType>,
1892    raw_rows: std::vec::IntoIter<EvaluateDataValue>,
1893    number: usize,
1894    literals: Vec<TypedLiteral>,
1895    /// Template data slot and type of each key field, in key order.
1896    key_slots: Box<[KeySlot<'a>]>,
1897    keyed: Vec<Vec<TypedLiteral>>,
1898}
1899
1900struct KeySlot<'a> {
1901    field: &'a KeyField,
1902    slot: usize,
1903    field_type: Arc<LemmaType>,
1904}
1905
1906fn request_error(name: &str, message: String) -> Error {
1907    Error::request(format!("data '{name}': {message}"), None::<String>).with_related_data(name)
1908}
1909
1910impl<'a> ListFrame<'a> {
1911    fn resume(&mut self, input: Option<ResolveOutput>) -> Result<ResolveStep<'a>, Error> {
1912        match self.rows.take() {
1913            None => {
1914                assert!(
1915                    input.is_none(),
1916                    "BUG: list frame started with a child output"
1917                );
1918                let raw_value = self
1919                    .raw_value
1920                    .take()
1921                    .expect("BUG: list frame started twice");
1922                let rows = self.start(raw_value)?;
1923                self.next_row(rows)
1924            }
1925            Some(mut rows) => {
1926                let Some(ResolveOutput::Level(row_data)) = input else {
1927                    panic!("BUG: list frame resumed without a row result");
1928                };
1929                match self.finish_row(&mut rows, row_data)? {
1930                    Some(veto) => Ok(ResolveStep::Return(ResolveOutput::Binding(
1931                        veto,
1932                        Supplied::default(),
1933                    ))),
1934                    None => self.next_row(rows),
1935                }
1936            }
1937        }
1938    }
1939
1940    fn start(&self, raw_value: EvaluateDataValue) -> Result<ListRows<'a>, Error> {
1941        let plan = self.plan;
1942        let source = plan
1943            .instance_lists
1944            .get(self.path)
1945            .expect("BUG: instance list data without a source");
1946        let template = plan.row_template(&source.identity);
1947        let Some(raw_rows) = raw_value.into_list() else {
1948            return Err(request_error(
1949                &self.name,
1950                format!(
1951                    "rows of a `{}` list are an array of objects",
1952                    source.identity.spec
1953                ),
1954            ));
1955        };
1956        if raw_rows.len() > self.limits.max_list_rows {
1957            return Err(request_error(
1958                &self.name,
1959                format!(
1960                    "has {} rows, over max_list_rows {}",
1961                    raw_rows.len(),
1962                    self.limits.max_list_rows
1963                ),
1964            ));
1965        }
1966        if self.level == ListLevel::Top {
1967            check_list_tree(template, &raw_rows, self.limits)
1968                .map_err(|message| request_error(&self.name, message))?;
1969        }
1970        let row_type = Arc::new(LemmaType::primitive(TypeSpecification::Spec {
1971            spec: source.identity.clone(),
1972        }));
1973        let key_slots = match &source.key {
1974            ListKey::Fields(key_fields) => key_fields
1975                .iter()
1976                .map(|field| KeySlot {
1977                    field,
1978                    slot: template
1979                        .data
1980                        .get_index_of(&field.path)
1981                        .expect("BUG: key field is template data"),
1982                    field_type: row_end_type(template, &RowEnd::Data(field.path.clone())),
1983                })
1984                .collect(),
1985            ListKey::Numbered => Box::default(),
1986        };
1987        Ok(ListRows {
1988            source,
1989            identity: Arc::new(source.identity.clone()),
1990            template,
1991            row_type,
1992            literals: Vec::with_capacity(raw_rows.len()),
1993            key_slots,
1994            keyed: Vec::new(),
1995            number: 0,
1996            raw_rows: raw_rows.into_iter(),
1997        })
1998    }
1999
2000    fn next_row(&mut self, mut rows: ListRows<'a>) -> Result<ResolveStep<'a>, Error> {
2001        let Some(raw_row) = rows.raw_rows.next() else {
2002            return Ok(ResolveStep::Return(ResolveOutput::Binding(
2003                self.finish_list(rows),
2004                std::mem::take(&mut self.supplied),
2005            )));
2006        };
2007        rows.number += 1;
2008        let Some(fields) = raw_row.into_map() else {
2009            return Err(request_error(
2010                &self.name,
2011                format!("row {} must be an object", rows.number),
2012            ));
2013        };
2014        let template = rows.template;
2015        let origin = crate::planning::semantics::numbered_row_origin(&self.list_key, rows.number);
2016        let row_key: Arc<str> = match &self.under {
2017            Some(under) => Arc::from(format!("{under}.{origin}")),
2018            None => Arc::from(origin),
2019        };
2020        reject_whole_list_with_row_keys(template, &fields)?;
2021        let row_writes = rows.source.row_writes.clone();
2022        let row_uses = row_writes
2023            .as_ref()
2024            .map(|named| InstanceKey::new(Arc::clone(named), self.holder.clone()));
2025        self.rows = Some(rows);
2026        let mut level = LevelFrame::new(
2027            template,
2028            self.root,
2029            Some(row_key),
2030            fields,
2031            self.limits,
2032            ListLevel::Nested,
2033        );
2034        level.row_writes = row_writes;
2035        level.row_uses = row_uses;
2036        Ok(ResolveStep::Call(Box::new(ResolveFrame::Level(level))))
2037    }
2038
2039    /// Adds the resolved row `rows.number`. `Some` is a veto of the whole list.
2040    fn finish_row(
2041        &mut self,
2042        rows: &mut ListRows<'a>,
2043        row_data: EvaluateData,
2044    ) -> Result<Option<OperationResult>, Error> {
2045        let number = rows.number;
2046        let name = self.name.as_str();
2047        let mut bindings: Vec<Option<RowBinding>> = vec![None; rows.template.data.len()];
2048        if let Some(OperationResult::Veto(veto)) = row_data.supplied.first_veto() {
2049            return Ok(Some(OperationResult::Veto(VetoType::computation(format!(
2050                "In {name} row {number}: {veto}"
2051            )))));
2052        }
2053        for (slot, binding) in row_data.bindings {
2054            if let OperationResult::Veto(veto) = &binding {
2055                return Ok(Some(OperationResult::Veto(VetoType::computation(format!(
2056                    "In {name} row {number}: {veto}"
2057                )))));
2058            }
2059            bindings[slot] = Some(RowBinding::Bound(binding));
2060        }
2061        if let ListKey::Fields(_) = &rows.source.key {
2062            let mut values = Vec::with_capacity(rows.key_slots.len());
2063            for KeySlot {
2064                field: key_field,
2065                slot,
2066                field_type,
2067            } in &rows.key_slots
2068            {
2069                let key_path = &key_field.path;
2070                let value = match bindings.get(*slot).and_then(Option::as_ref) {
2071                    Some(RowBinding::Bound(OperationResult::Value(bound))) => {
2072                        typed_from_bound(bound, field_type)
2073                    }
2074                    Some(RowBinding::Bound(OperationResult::Veto(_))) => {
2075                        unreachable!("BUG: vetoed row binding returned above")
2076                    }
2077                    Some(RowBinding::Deferred { .. }) => {
2078                        unreachable!(
2079                            "BUG: a key field of an evaluation data row is a resolved value"
2080                        )
2081                    }
2082                    None => default_of(&rows.template.data, key_path).ok_or_else(|| {
2083                        request_error(
2084                            name,
2085                            format!(
2086                                "row {number} has no value for key field '{}'",
2087                                key_field.name
2088                            ),
2089                        )
2090                    })?,
2091                };
2092                values.push(value);
2093            }
2094            rows.keyed.push(values);
2095        }
2096        let literal = row_literal(
2097            Arc::clone(&rows.identity),
2098            RowOrigin::Numbered {
2099                list: self.list_key.clone(),
2100                number,
2101                under: self.under.clone(),
2102            },
2103            bindings,
2104            Arc::clone(&rows.row_type),
2105        );
2106        let ValueKind::Spec(SpecValue::Row(row)) = &literal.value else {
2107            unreachable!("BUG: a row literal is a row value");
2108        };
2109        self.supplied.extend(row_data.supplied.under(row));
2110        rows.literals.push(literal);
2111        Ok(None)
2112    }
2113
2114    fn finish_list(&self, rows: ListRows<'a>) -> OperationResult {
2115        let literals: Arc<[TypedLiteral]> = rows.literals.into();
2116        let list = match &rows.source.key {
2117            ListKey::Fields(key_fields) => {
2118                let field_names: Vec<String> = key_fields
2119                    .iter()
2120                    .map(|key_field| key_field.name.clone())
2121                    .collect();
2122                match KeyIndex::build_numbered(field_names, &rows.keyed) {
2123                    Ok(index) => ListValue::indexed(literals, Arc::new(index)),
2124                    Err(conflict) => {
2125                        return OperationResult::Veto(VetoType::computation(format!(
2126                            "{}: {conflict}",
2127                            self.name
2128                        )));
2129                    }
2130                }
2131            }
2132            ListKey::Numbered => ListValue::from(literals),
2133        };
2134        OperationResult::from_literal(LiteralValue {
2135            value: ValueKind::List(list),
2136        })
2137    }
2138}
2139
2140#[cfg(test)]
2141mod tests {
2142    use super::*;
2143    use crate::computation::rational::{decimal_to_rational, rational_new, rational_one};
2144    use crate::planning::semantics::{
2145        primitive_number_arc, MeasureUnit, MeasureUnits, RatioUnit, RatioUnits, TypeExtends,
2146    };
2147    use rust_decimal::Decimal;
2148
2149    fn dummy_source() -> Source {
2150        Source::new(
2151            crate::parsing::source::SourceType::Volatile,
2152            crate::parsing::ast::Span {
2153                start: 0,
2154                end: 0,
2155                line: 1,
2156                col: 1,
2157            },
2158        )
2159    }
2160
2161    fn mass_measure_type() -> Arc<LemmaType> {
2162        Arc::new(LemmaType::new(
2163            "Mass".to_string(),
2164            TypeSpecification::Measure {
2165                minimum: None,
2166                maximum: None,
2167                units: MeasureUnits::from(vec![
2168                    MeasureUnit {
2169                        name: "kilogram".to_string(),
2170                        scale: crate::literals::UnitScale::Literal(rational_one()),
2171                        derived_measure_factors: Vec::new(),
2172                        decomposition: crate::literals::BaseMeasureVector::new(),
2173                        minimum: None,
2174                        maximum: None,
2175                        suggestion_magnitude: None,
2176                    },
2177                    MeasureUnit {
2178                        name: "gram".to_string(),
2179                        scale: crate::literals::UnitScale::Literal(
2180                            decimal_to_rational(Decimal::new(1, 3)).expect("factor"),
2181                        ),
2182                        derived_measure_factors: Vec::new(),
2183                        decomposition: crate::literals::BaseMeasureVector::new(),
2184                        minimum: None,
2185                        maximum: None,
2186                        suggestion_magnitude: None,
2187                    },
2188                ]),
2189                traits: Vec::new(),
2190                decomposition: None,
2191                unit: None,
2192                help: String::new(),
2193            },
2194            TypeExtends::Primitive,
2195        ))
2196    }
2197
2198    fn ratio_with_percent_type() -> Arc<LemmaType> {
2199        Arc::new(LemmaType::new(
2200            "Rate".to_string(),
2201            TypeSpecification::Ratio {
2202                minimum: None,
2203                maximum: None,
2204                units: RatioUnits::from(vec![
2205                    RatioUnit {
2206                        name: "percent".to_string(),
2207                        value: decimal_to_rational(Decimal::new(100, 0)).expect("factor"),
2208                        minimum: None,
2209                        maximum: None,
2210                        suggestion_magnitude: None,
2211                    },
2212                    RatioUnit {
2213                        name: "fraction".to_string(),
2214                        value: rational_one(),
2215                        minimum: None,
2216                        maximum: None,
2217                        suggestion_magnitude: None,
2218                    },
2219                ]),
2220                unit: None,
2221                help: String::new(),
2222            },
2223            TypeExtends::Primitive,
2224        ))
2225    }
2226
2227    #[test]
2228    fn string_input_parsed_against_type() {
2229        let ty = primitive_number_arc();
2230        let lit = parse_data_value(
2231            &EvaluateDataValue::Literal("42".to_string()),
2232            ty,
2233            &dummy_source(),
2234            &UnitIndex::new(),
2235            &IndexMap::new(),
2236        )
2237        .unwrap();
2238        assert!(matches!(lit.value, ValueKind::Number(_)));
2239    }
2240
2241    fn unit_map(unit: &str, magnitude: &str) -> EvaluateDataValue {
2242        let mut map = IndexMap::new();
2243        map.insert(
2244            unit.to_string(),
2245            EvaluateDataValue::Literal(magnitude.into()),
2246        );
2247        EvaluateDataValue::Map(map)
2248    }
2249
2250    #[test]
2251    fn single_unit_measure_map_parses() {
2252        let ty = mass_measure_type();
2253        let lit = parse_data_value(
2254            &unit_map("kilogram", "2"),
2255            &ty,
2256            &dummy_source(),
2257            &UnitIndex::new(),
2258            &IndexMap::new(),
2259        )
2260        .unwrap();
2261        let ValueKind::Measure(magnitude) = &lit.value else {
2262            panic!("expected measure");
2263        };
2264        assert_eq!(magnitude, &rational_new(2, 1));
2265    }
2266
2267    #[test]
2268    fn single_unit_ratio_map_parses() {
2269        let ty = ratio_with_percent_type();
2270        let lit = parse_data_value(
2271            &unit_map("percent", "5"),
2272            &ty,
2273            &dummy_source(),
2274            &UnitIndex::new(),
2275            &IndexMap::new(),
2276        )
2277        .unwrap();
2278        let ValueKind::Ratio(canonical) = &lit.value else {
2279            panic!("expected ratio");
2280        };
2281        assert_eq!(
2282            *canonical,
2283            decimal_to_rational(Decimal::new(5, 2)).expect("canonical")
2284        );
2285    }
2286
2287    #[test]
2288    fn multi_key_map_is_shape_error() {
2289        let mut map = IndexMap::new();
2290        map.insert(
2291            "kilogram".to_string(),
2292            EvaluateDataValue::Literal("2".to_string()),
2293        );
2294        map.insert(
2295            "gram".to_string(),
2296            EvaluateDataValue::Literal("2000".into()),
2297        );
2298        let message = evaluate_data_shape_error(&EvaluateDataValue::Map(map), &mass_measure_type())
2299            .expect("shape");
2300        assert!(message.contains("single-unit"), "{message}");
2301    }
2302
2303    #[test]
2304    fn empty_map_is_shape_error() {
2305        let message = evaluate_data_shape_error(
2306            &EvaluateDataValue::Map(IndexMap::new()),
2307            &mass_measure_type(),
2308        )
2309        .expect("shape");
2310        assert!(message.contains("single-unit"), "{message}");
2311    }
2312
2313    #[test]
2314    fn map_on_text_is_shape_error() {
2315        let message = evaluate_data_shape_error(
2316            &unit_map("eur", "84"),
2317            &LemmaType::primitive(TypeSpecification::Text {
2318                length: None,
2319                help: String::new(),
2320            }),
2321        )
2322        .expect("shape");
2323        assert!(message.contains("text"), "{message}");
2324    }
2325
2326    #[test]
2327    fn list_on_scalar_is_shape_error() {
2328        let message = evaluate_data_shape_error(
2329            &EvaluateDataValue::List(vec![EvaluateDataValue::Literal("1".to_string())]),
2330            &LemmaType::primitive(TypeSpecification::Number {
2331                minimum: None,
2332                maximum: None,
2333                decimals: None,
2334                help: String::new(),
2335            }),
2336        )
2337        .expect("shape");
2338        assert!(message.contains("array"), "{message}");
2339    }
2340
2341    #[test]
2342    fn boolean_on_number_is_shape_error() {
2343        let message = evaluate_data_shape_error(
2344            &EvaluateDataValue::Boolean(true),
2345            &LemmaType::primitive(TypeSpecification::Number {
2346                minimum: None,
2347                maximum: None,
2348                decimals: None,
2349                help: String::new(),
2350            }),
2351        )
2352        .expect("shape");
2353        assert!(message.contains("boolean"), "{message}");
2354    }
2355
2356    fn mass_list_type() -> LemmaType {
2357        LemmaType::list_of(mass_measure_type())
2358    }
2359
2360    #[test]
2361    fn nested_boolean_item_is_shape_error() {
2362        let message = evaluate_data_shape_error(
2363            &EvaluateDataValue::List(vec![
2364                EvaluateDataValue::Literal("1 kilogram".to_string()),
2365                EvaluateDataValue::Boolean(true),
2366            ]),
2367            &mass_list_type(),
2368        )
2369        .expect("shape");
2370        assert!(
2371            message.starts_with("list item 2: boolean input is only valid for boolean data"),
2372            "{message}"
2373        );
2374    }
2375
2376    #[test]
2377    fn nested_map_item_is_shape_error() {
2378        let text_list =
2379            LemmaType::list_of(Arc::new(LemmaType::primitive(TypeSpecification::Text {
2380                length: None,
2381                help: String::new(),
2382            })));
2383        let message = evaluate_data_shape_error(
2384            &EvaluateDataValue::List(vec![unit_map("eur", "84")]),
2385            &text_list,
2386        )
2387        .expect("shape");
2388        assert!(
2389            message.starts_with("list item 1: object overlay"),
2390            "{message}"
2391        );
2392    }
2393
2394    #[test]
2395    fn nested_list_item_is_shape_error() {
2396        let message = evaluate_data_shape_error(
2397            &EvaluateDataValue::List(vec![EvaluateDataValue::List(vec![
2398                EvaluateDataValue::Literal("1 eur".to_string()),
2399            ])]),
2400            &mass_list_type(),
2401        )
2402        .expect("shape");
2403        assert!(
2404            message.starts_with("list item 1: array overlay"),
2405            "{message}"
2406        );
2407    }
2408
2409    #[test]
2410    fn deeply_nested_item_reports_full_item_path() {
2411        let nested = LemmaType::list_of(Arc::new(mass_list_type()));
2412        let message = evaluate_data_shape_error(
2413            &EvaluateDataValue::List(vec![
2414                EvaluateDataValue::List(vec![EvaluateDataValue::Literal("1 kilogram".to_string())]),
2415                EvaluateDataValue::List(vec![EvaluateDataValue::Boolean(true)]),
2416            ]),
2417            &nested,
2418        )
2419        .expect("shape");
2420        assert!(
2421            message
2422                .starts_with("list item 2, item 1: boolean input is only valid for boolean data"),
2423            "{message}"
2424        );
2425    }
2426
2427    #[test]
2428    fn nested_literal_under_list_type_is_shape_error() {
2429        let nested = LemmaType::list_of(Arc::new(mass_list_type()));
2430        let message = evaluate_data_shape_error(
2431            &EvaluateDataValue::List(vec![EvaluateDataValue::Literal("1 kilogram".to_string())]),
2432            &nested,
2433        )
2434        .expect("shape");
2435        assert!(
2436            message.starts_with("list item 1: literal overlay"),
2437            "{message}"
2438        );
2439    }
2440
2441    #[test]
2442    fn valid_nested_measure_list_has_no_shape_error() {
2443        let message = evaluate_data_shape_error(
2444            &EvaluateDataValue::List(vec![
2445                unit_map("kilogram", "2"),
2446                EvaluateDataValue::Literal("500 gram".to_string()),
2447            ]),
2448            &mass_list_type(),
2449        );
2450        assert!(message.is_none(), "{message:?}");
2451    }
2452
2453    fn load_engine(code: &str) -> crate::Engine {
2454        let mut engine = crate::Engine::new();
2455        engine
2456            .load([(crate::SourceType::Volatile, code.to_string())])
2457            .expect("load");
2458        engine
2459    }
2460
2461    fn ordered(pairs: &[(&str, EvaluateDataValue)]) -> IndexMap<String, EvaluateDataValue> {
2462        pairs
2463            .iter()
2464            .map(|(k, v)| (k.to_string(), v.clone()))
2465            .collect()
2466    }
2467
2468    fn sample_shallow() -> EvaluateDataValue {
2469        EvaluateDataValue::Map(ordered(&[
2470            (
2471                "price",
2472                EvaluateDataValue::Map(ordered(&[("eur", EvaluateDataValue::from("84"))])),
2473            ),
2474            (
2475                "fares",
2476                EvaluateDataValue::List(vec![
2477                    EvaluateDataValue::from("89 eur"),
2478                    EvaluateDataValue::Boolean(true),
2479                    EvaluateDataValue::Map(IndexMap::new()),
2480                    EvaluateDataValue::List(Vec::new()),
2481                ]),
2482            ),
2483        ]))
2484    }
2485
2486    #[test]
2487    fn debug_matches_derived_layout_compact_and_pretty() {
2488        let value = sample_shallow();
2489        assert_eq!(
2490            format!("{value:?}"),
2491            r#"Map({"price": Map({"eur": Literal("84")}), "fares": List([Literal("89 eur"), Boolean(true), Map({}), List([])])})"#
2492        );
2493        assert_eq!(
2494            format!("{value:#?}"),
2495            concat!(
2496                "Map(\n",
2497                "    {\n",
2498                "        \"price\": Map(\n",
2499                "            {\n",
2500                "                \"eur\": Literal(\n",
2501                "                    \"84\",\n",
2502                "                ),\n",
2503                "            },\n",
2504                "        ),\n",
2505                "        \"fares\": List(\n",
2506                "            [\n",
2507                "                Literal(\n",
2508                "                    \"89 eur\",\n",
2509                "                ),\n",
2510                "                Boolean(\n",
2511                "                    true,\n",
2512                "                ),\n",
2513                "                Map(\n",
2514                "                    {},\n",
2515                "                ),\n",
2516                "                List(\n",
2517                "                    [],\n",
2518                "                ),\n",
2519                "            ],\n",
2520                "        ),\n",
2521                "    },\n",
2522                ")",
2523            )
2524        );
2525    }
2526
2527    #[test]
2528    fn deep_chains_clone_eq_debug_and_drop_on_small_stack() {
2529        const DEPTH: usize = 1_000_000;
2530        std::thread::Builder::new()
2531            .stack_size(256 * 1024)
2532            .spawn(|| {
2533                let mut list = EvaluateDataValue::Literal("leaf".to_string());
2534                for _ in 0..DEPTH {
2535                    list = EvaluateDataValue::List(vec![list]);
2536                }
2537                let cloned = list.clone();
2538                assert!(list == cloned);
2539                let rendered = format!("{list:?}");
2540                assert_eq!(
2541                    rendered.len(),
2542                    DEPTH * "List([".len() + "Literal(\"leaf\")".len() + DEPTH * "])".len()
2543                );
2544                drop(cloned);
2545
2546                let mut map = EvaluateDataValue::Boolean(false);
2547                for _ in 0..DEPTH {
2548                    let mut level = IndexMap::new();
2549                    level.insert("n".to_string(), map);
2550                    map = EvaluateDataValue::Map(level);
2551                }
2552                let cloned = map.clone();
2553                assert!(map == cloned);
2554                assert!(map != list);
2555                drop(cloned);
2556                drop(map);
2557                drop(list);
2558            })
2559            .expect("spawn small-stack thread")
2560            .join()
2561            .expect("deep run data must not overflow the stack");
2562    }
2563
2564    #[test]
2565    fn eq_is_order_insensitive_for_maps_and_ordered_for_lists() {
2566        let forward = EvaluateDataValue::Map(ordered(&[
2567            ("a", EvaluateDataValue::from("1")),
2568            ("b", EvaluateDataValue::from("2")),
2569        ]));
2570        let reversed = EvaluateDataValue::Map(ordered(&[
2571            ("b", EvaluateDataValue::from("2")),
2572            ("a", EvaluateDataValue::from("1")),
2573        ]));
2574        assert!(forward == reversed);
2575        assert!(
2576            EvaluateDataValue::List(vec![
2577                EvaluateDataValue::from("1"),
2578                EvaluateDataValue::from("2")
2579            ]) != EvaluateDataValue::List(vec![
2580                EvaluateDataValue::from("2"),
2581                EvaluateDataValue::from("1")
2582            ])
2583        );
2584        assert!(EvaluateDataValue::from("1") != EvaluateDataValue::Boolean(true));
2585    }
2586
2587    #[test]
2588    fn request_error_names_first_key_in_caller_order() {
2589        let engine = load_engine(
2590            r#"
2591spec inner
2592data n: 1
2593
2594spec s
2595uses left: inner
2596uses right: inner
2597rule out: 1
2598"#,
2599        );
2600        let now = crate::DateTimeValue::now();
2601        let overlay = EvaluateDataValue::Map(ordered(&[("n", EvaluateDataValue::from("2"))]));
2602        let left_first = engine
2603            .evaluate(
2604                None,
2605                "s",
2606                Some(&now),
2607                ordered(&[("left", overlay.clone()), ("right", overlay.clone())]),
2608                None,
2609                false,
2610            )
2611            .expect_err("uses alias map is a request error");
2612        assert!(left_first.to_string().contains("'left'"), "{left_first}");
2613        assert!(!left_first.to_string().contains("'right'"), "{left_first}");
2614
2615        let right_first = engine
2616            .evaluate(
2617                None,
2618                "s",
2619                Some(&now),
2620                ordered(&[("right", overlay.clone()), ("left", overlay)]),
2621                None,
2622                false,
2623            )
2624            .expect_err("uses alias map is a request error");
2625        assert!(right_first.to_string().contains("'right'"), "{right_first}");
2626        assert!(!right_first.to_string().contains("'left'"), "{right_first}");
2627    }
2628
2629    fn roster_engine() -> crate::Engine {
2630        load_engine(
2631            r#"
2632spec person
2633data age: number
2634  -> minimum 0
2635data score: number
2636  -> minimum 0
2637
2638spec roster
2639uses person
2640data people: person list
2641rule n: people -> count
2642"#,
2643        )
2644    }
2645
2646    #[test]
2647    fn row_veto_names_first_field_in_caller_order() {
2648        let engine = roster_engine();
2649        let now = crate::DateTimeValue::now();
2650        let age_first = engine
2651            .evaluate(
2652                None,
2653                "roster",
2654                Some(&now),
2655                ordered(&[(
2656                    "people",
2657                    EvaluateDataValue::List(vec![EvaluateDataValue::Map(ordered(&[
2658                        ("age", EvaluateDataValue::from("-1")),
2659                        ("score", EvaluateDataValue::from("-1")),
2660                    ]))]),
2661                )]),
2662                Some(&["n".to_string()]),
2663                false,
2664            )
2665            .expect("evaluate");
2666        let reason = age_first
2667            .results
2668            .get("n")
2669            .expect("n")
2670            .veto_reason
2671            .as_deref()
2672            .expect("veto");
2673        assert!(reason.contains("age"), "{reason}");
2674        assert!(!reason.contains("score"), "{reason}");
2675
2676        let score_first = engine
2677            .evaluate(
2678                None,
2679                "roster",
2680                Some(&now),
2681                ordered(&[(
2682                    "people",
2683                    EvaluateDataValue::List(vec![EvaluateDataValue::Map(ordered(&[
2684                        ("score", EvaluateDataValue::from("-1")),
2685                        ("age", EvaluateDataValue::from("-1")),
2686                    ]))]),
2687                )]),
2688                Some(&["n".to_string()]),
2689                false,
2690            )
2691            .expect("evaluate");
2692        let reason = score_first
2693            .results
2694            .get("n")
2695            .expect("n")
2696            .veto_reason
2697            .as_deref()
2698            .expect("veto");
2699        assert!(reason.contains("score"), "{reason}");
2700        assert!(!reason.contains("age"), "{reason}");
2701    }
2702
2703    #[test]
2704    fn row_unknown_fields_are_ignored() {
2705        let engine = roster_engine();
2706        let now = crate::DateTimeValue::now();
2707        let bogus_first = engine
2708            .evaluate(
2709                None,
2710                "roster",
2711                Some(&now),
2712                ordered(&[(
2713                    "people",
2714                    EvaluateDataValue::List(vec![EvaluateDataValue::Map(ordered(&[
2715                        ("bogus", EvaluateDataValue::from("1")),
2716                        ("also", EvaluateDataValue::from("2")),
2717                        ("age", EvaluateDataValue::from("1")),
2718                        ("score", EvaluateDataValue::from("1")),
2719                    ]))]),
2720                )]),
2721                None,
2722                false,
2723            )
2724            .expect("unknown row fields are ignored");
2725        assert!(bogus_first.results.get("n").is_some());
2726
2727        let also_first = engine
2728            .evaluate(
2729                None,
2730                "roster",
2731                Some(&now),
2732                ordered(&[(
2733                    "people",
2734                    EvaluateDataValue::List(vec![EvaluateDataValue::Map(ordered(&[
2735                        ("also", EvaluateDataValue::from("2")),
2736                        ("bogus", EvaluateDataValue::from("1")),
2737                        ("age", EvaluateDataValue::from("1")),
2738                        ("score", EvaluateDataValue::from("1")),
2739                    ]))]),
2740                )]),
2741                None,
2742                false,
2743            )
2744            .expect("unknown row fields are ignored");
2745        assert!(also_first.results.get("n").is_some());
2746    }
2747
2748    fn tags_engine(limits: crate::ResourceLimits) -> crate::Engine {
2749        let mut engine = crate::Engine::with_limits(limits);
2750        engine
2751            .load([(
2752                crate::SourceType::Volatile,
2753                "spec tagged\ndata tags: text list\nrule n: tags -> count".to_string(),
2754            )])
2755            .expect("load");
2756        engine
2757    }
2758
2759    fn evaluate_tags(engine: &crate::Engine, tags: Vec<String>) -> crate::Response {
2760        let now = crate::DateTimeValue::now();
2761        engine
2762            .evaluate(
2763                None,
2764                "tagged",
2765                Some(&now),
2766                ordered(&[(
2767                    "tags",
2768                    EvaluateDataValue::List(
2769                        tags.into_iter().map(EvaluateDataValue::Literal).collect(),
2770                    ),
2771                )]),
2772                Some(&["n".to_string()]),
2773                false,
2774            )
2775            .expect("evaluate")
2776    }
2777
2778    #[test]
2779    fn value_list_over_value_byte_limit_binds() {
2780        let engine = tags_engine(crate::ResourceLimits::default());
2781        let limit = crate::ResourceLimits::default().max_data_value_bytes;
2782        let tags: Vec<String> = (0..200).map(|i| format!("customer-tag-{i:04}")).collect();
2783        let total: usize = tags.iter().map(String::len).sum();
2784        assert!(
2785            total > limit,
2786            "fixture must exceed {limit} bytes, has {total}"
2787        );
2788
2789        let response = evaluate_tags(&engine, tags);
2790        let result = response.results.get("n").expect("n");
2791        assert_eq!(result.veto_reason, None);
2792        assert_eq!(result.result(), Some("200"));
2793    }
2794
2795    #[test]
2796    fn value_list_item_over_value_byte_limit_vetoes() {
2797        let engine = tags_engine(crate::ResourceLimits {
2798            max_data_value_bytes: 50,
2799            ..crate::ResourceLimits::default()
2800        });
2801        let response = evaluate_tags(
2802            &engine,
2803            vec!["vip".to_string(), "x".repeat(51), "trial".to_string()],
2804        );
2805        let reason = response
2806            .results
2807            .get("n")
2808            .expect("n")
2809            .veto_reason
2810            .as_deref()
2811            .expect("veto");
2812        assert!(
2813            reason.contains("list item 2 exceeds the size limit."),
2814            "{reason}"
2815        );
2816    }
2817}