Skip to main content

adam_web_ui/
labels.rs

1//! Cell display/write metadata and diagnostic formatting for a live [`adam_rs::Sheet`].
2//!
3//! [`Labels`] associates display metadata (names, type-erased display and write closures)
4//! with stable [`CellId`] keys, driving [`crate::SheetInspector`]'s rendering.
5//! [`format_adam_error`] formats an [`adam_rs::Error`] as a rustc-style diagnostic when
6//! possible.
7
8use crate::input::{InputError, NumberKind, NumericRange};
9use adam_lang::SheetDiagnostics;
10use adam_lang::type_registry::TypeShape;
11use adam_rs::{CellId, Error, Sheet};
12pub use annotate_snippets::Renderer;
13use cel_parser::{FormatRustcStyle, SpanContext, SpanLabel};
14use indexmap::IndexMap;
15use std::any::TypeId;
16
17/// Parses canonical input without mutating a model.
18///
19/// # Examples
20///
21/// `(meta.prepare)("42")` produces an owned write before a transaction starts.
22pub type PrepareFn = Box<dyn Fn(&str) -> Result<PreparedWrite, InputError>>;
23
24/// Encodes an effective value exactly or reports an unavailable capability.
25///
26/// # Examples
27/// `(meta.capture)(&sheet)` returns canonical text, not rounded display text.
28pub type CaptureFn = Box<dyn Fn(&Sheet) -> Result<String, InputError>>;
29
30/// Reads exact live filter endpoints without a binary64 conversion.
31///
32/// # Examples
33/// `meta.exact_range.as_ref().map(|range| range(&sheet))` queries a range filter.
34pub type ExactRangeFn = Box<dyn Fn(&Sheet) -> Result<NumericRange, InputError>>;
35
36/// Owns the heterogeneous write operation until its transaction applies it.
37type ApplyFn = Box<dyn FnOnce(&mut Sheet, CellId) -> Result<(), Error>>;
38
39/// Owns an already decoded scalar, independent of any mutable sheet.
40///
41/// # Examples
42/// ```
43/// let mut sheet = adam_rs::Sheet::new();
44/// let id = sheet.add_cell(1_i32);
45/// adam_web_ui::PreparedWrite::new(2_i32).apply(&mut sheet, id).unwrap();
46/// assert_eq!(*sheet.read::<i32>(id).unwrap(), 2);
47/// ```
48pub struct PreparedWrite {
49    apply: ApplyFn,
50}
51
52impl PreparedWrite {
53    /// Takes ownership of a decoded scalar for one later write.
54    ///
55    /// # Examples
56    /// See [`PreparedWrite`] for applying a decoded scalar.
57    pub fn new<T: std::any::Any>(value: T) -> Self {
58        Self {
59            apply: Box::new(move |sheet, id| sheet.write(id, value)),
60        }
61    }
62
63    /// Consumes the value in one mutating write without parsing.
64    ///
65    /// # Errors
66    /// Returns the sheet's invalid-ID or type error. On error the caller must
67    /// discard the sheet without reading or reusing it.
68    ///
69    /// # Examples
70    /// See [`PreparedWrite`] for a successful write.
71    pub fn apply(self, sheet: &mut Sheet, id: CellId) -> Result<(), Error> {
72        (self.apply)(sheet, id)
73    }
74}
75
76/// Supplies an exact scalar encoding and its inverse.
77///
78/// - Precondition: decoding an encoded value preserves that value, including
79///   signed zero for floating-point scalars. NaN payload identity is not part of
80///   Rust primitive textual encoding.
81/// - Complexity: Encoding and decoding have the supplied functions' costs.
82///
83/// # Examples
84/// ```
85/// let codec = adam_web_ui::ScalarCodec::<u64> {
86///     encode: u64::to_string,
87///     decode: |s| s.parse().map_err(|_| adam_web_ui::input::InputError::Lexical(s.into())),
88/// };
89/// assert_eq!((codec.decode)(&(codec.encode)(&u64::MAX)).unwrap(), u64::MAX);
90/// ```
91pub struct ScalarCodec<T> {
92    /// Encodes without rounding or narrowing.
93    pub encode: fn(&T) -> String,
94    /// Decodes or reports an input diagnostic without mutation.
95    pub decode: fn(&str) -> Result<T, InputError>,
96}
97
98/// Display and write metadata for a single cell.
99///
100/// # Examples
101///
102/// Read `labels.cells[&id].number_input_safe` to select a binary64 numeric control, and
103/// invoke its `capture` callback to obtain exact current text.
104pub struct CellMeta {
105    /// Human-readable cell name shown in the inspector.
106    pub label: String,
107    /// `true` if the cell holds a `bool`, so [`crate::SheetInspector`] can render it as a
108    /// checkbox instead of a text field.
109    pub is_bool: bool,
110    /// `true` if the cell holds one of the 14 numeric primitive types.
111    /// Numeric draft and clamp semantics apply even when its editor is text-valued.
112    pub is_numeric: bool,
113    /// Selects binary64 number/slider controls for floats and integer domains up to
114    /// 32 bits. Wider integer domains use exact text controls, including ranged cells.
115    pub number_input_safe: bool,
116    /// Identifies integer parsing/clamp semantics. Binary64-safe integer controls
117    /// use a unit step; wider domains retain exact text.
118    pub is_integer: bool,
119    /// Returns the current cell value as a display string.
120    pub display: Box<dyn Fn(&Sheet) -> String>,
121    /// Decodes canonical input before any mutation in a transaction.
122    pub prepare: PrepareFn,
123    /// Encodes the effective scalar exactly, separately from display formatting.
124    pub capture: CaptureFn,
125    /// Reports whether exact scalar encoding and decoding are supported.
126    pub codec_supported: bool,
127    /// Identifies the concrete numeric primitive without narrowing.
128    pub number_kind: Option<NumberKind>,
129    /// Reads exact live filter bounds, if this cell has a range filter.
130    pub exact_range: Option<ExactRangeFn>,
131    /// Live slider bounds, present only for a numeric cell whose filter is a
132    /// [`adam_rs::FilterKind::Range`] — recomputed from the filter's current argument values on
133    /// every call, so a range driven by other cells or relationships stays live.
134    /// These approximate `f64` bounds do not format cell values; wide-integer editors
135    /// do not use them to render or transport values.
136    #[allow(clippy::type_complexity)]
137    pub range: Option<Box<dyn Fn(&Sheet) -> (f64, f64)>>,
138}
139
140/// Associates human-readable labels and type-erased closures with stable sheet IDs.
141///
142/// # Examples
143///
144/// `labels_from_cell_names(&parsed, &parsed.cell_names)` creates declaration-ordered
145/// metadata suitable for a `SheetInspector`.
146pub struct Labels {
147    /// Cells in insertion order (preserves display ordering).
148    pub cells: IndexMap<CellId, CellMeta>,
149}
150
151impl Labels {
152    /// Creates an empty label set.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// assert!(adam_web_ui::Labels::new().cells.is_empty());
158    /// ```
159    pub fn new() -> Self {
160        Self {
161            cells: IndexMap::new(),
162        }
163    }
164
165    /// Registers display metadata for a cell of type `T`.
166    ///
167    /// - Precondition: `id` is a live cell in the sheet this `Labels` will be used with.
168    /// - Precondition: `T` matches the type registered with `Sheet::add_cell` for `id`.
169    /// - Precondition: `T`'s `Display`/`FromStr` pair satisfies [`ScalarCodec`]'s
170    ///   preservation contract; otherwise use [`Self::add_cell_with_codec`].
171    ///
172    /// Infers Boolean and primitive numeric classification. Use
173    /// [`labels_from_cell_names`] to attach live filter-range metadata.
174    ///
175    /// - Complexity: O(label.len()) registration time and space; display and parsing
176    ///   callbacks subsequently incur their concrete type's formatting/parsing costs.
177    ///
178    /// # Examples
179    ///
180    /// ```
181    /// let mut sheet = adam_rs::Sheet::new();
182    /// let id = sheet.add_cell(3i64);
183    /// let mut labels = adam_web_ui::Labels::new();
184    /// labels.add_cell::<i64>(id, "count");
185    /// assert_eq!((labels.cells[&id].display)(&sheet), "3");
186    /// ```
187    pub fn add_cell<T>(&mut self, id: CellId, label: &str)
188    where
189        T: std::any::Any + std::fmt::Display + std::str::FromStr + 'static,
190        T::Err: std::fmt::Display + std::any::Any,
191    {
192        self.add_cell_with_codec(
193            id,
194            label,
195            ScalarCodec {
196                encode: T::to_string,
197                decode: decode_scalar::<T>,
198            },
199        );
200    }
201
202    /// Registers a custom scalar with an exact encoder and decoder.
203    ///
204    /// - Precondition: `id` stores `T` in the associated sheet.
205    /// - Precondition: `codec` satisfies [`ScalarCodec`]'s preservation contract.
206    /// - Complexity: O(label bytes) registration; callbacks incur codec costs.
207    ///
208    /// # Examples
209    /// ```
210    /// let mut sheet = adam_rs::Sheet::new();
211    /// let id = sheet.add_cell(true);
212    /// let mut labels = adam_web_ui::Labels::new();
213    /// labels.add_cell_with_codec(id, "enabled", adam_web_ui::ScalarCodec {
214    ///     encode: bool::to_string,
215    ///     decode: |s| s.parse::<bool>()
216    ///         .map_err(|e| adam_web_ui::input::InputError::Lexical(e.to_string())),
217    /// });
218    /// assert_eq!((labels.cells[&id].capture)(&sheet).unwrap(), "true");
219    /// ```
220    pub fn add_cell_with_codec<T: std::any::Any>(
221        &mut self,
222        id: CellId,
223        label: &str,
224        codec: ScalarCodec<T>,
225    ) {
226        let kind = numeric_kind::<T>();
227        let encode = codec.encode;
228        self.cells.insert(
229            id,
230            CellMeta {
231                label: label.to_owned(),
232                is_bool: TypeId::of::<T>() == TypeId::of::<bool>(),
233                is_numeric: kind.is_some(),
234                number_input_safe: kind.is_some_and(|kind| {
235                    !matches!(
236                        kind,
237                        NumberKind::Signed(64 | 128) | NumberKind::Unsigned(64 | 128)
238                    )
239                }),
240                is_integer: matches!(kind, Some(NumberKind::Signed(_) | NumberKind::Unsigned(_))),
241                display: Box::new(move |sheet| {
242                    sheet
243                        .read::<T>(id)
244                        .map(encode)
245                        .unwrap_or_else(|error| format!("<unavailable: {error}>"))
246                }),
247                prepare: Box::new(move |s| (codec.decode)(s).map(PreparedWrite::new)),
248                capture: Box::new(move |sheet| {
249                    sheet
250                        .read::<T>(id)
251                        .map(encode)
252                        .map_err(|e| InputError::UnsupportedEditor(e.to_string()))
253                }),
254                codec_supported: true,
255                number_kind: kind,
256                exact_range: None,
257                range: None,
258            },
259        );
260    }
261
262    /// Registers display-only metadata for a canonical compound cell of any shape.
263    ///
264    /// `prepare` and `capture` return `Err` — no exact compound codec exists yet (tracked as a
265    /// follow-up: see the "Support editing tuple-typed cells in `begin`" GitHub issue). The
266    /// field still participates fully in [`crate::SheetInspector`]'s existing
267    /// invalid/warning/disabled machinery, since that's entirely keyed on `CellId`, not on any
268    /// per-type behavior.
269    ///
270    /// Missing storage or formatting capability displays `?`; unsupported writes
271    /// always return an explicit error without mutating the sheet.
272    ///
273    /// - Complexity: Preparation O(1); display O(n + v + s) for n type nodes,
274    ///   v values and s output bytes, excluding leaf formatter costs.
275    ///
276    /// # Examples
277    /// ```
278    /// let sheet = adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
279    ///     .parse_str("sheet s { cell xs: [i32]; }").unwrap();
280    /// let id = sheet.cell_names["xs"].0;
281    /// let mut labels = adam_web_ui::Labels::new();
282    /// labels.add_compound_cell(&sheet, id, "xs");
283    /// assert_eq!((labels.cells[&id].display)(&sheet), "[]");
284    /// ```
285    pub fn add_compound_cell(&mut self, sheet: &Sheet, id: CellId, label: &str) {
286        let formatter = adam_lang::prepare_compound_cell_formatter(sheet, id);
287        self.cells.insert(
288            id,
289            CellMeta {
290                label: label.to_owned(),
291                is_bool: false,
292                is_numeric: false,
293                number_input_safe: false,
294                is_integer: false,
295                display: Box::new(move |sheet| {
296                    formatter
297                        .as_ref()
298                        .ok()
299                        .and_then(|format| format(sheet).ok())
300                        .unwrap_or_else(|| "?".to_owned())
301                }),
302                prepare: Box::new(|_| {
303                    Err(InputError::UnsupportedEditor(
304                        "editing compound cells is not yet supported".into(),
305                    ))
306                }),
307                capture: Box::new(|_| {
308                    Err(InputError::UnsupportedEditor(
309                        "exact compound capture is not yet supported".into(),
310                    ))
311                }),
312                codec_supported: false,
313                number_kind: None,
314                exact_range: None,
315                range: None,
316            },
317        );
318    }
319}
320
321impl Default for Labels {
322    /// Returns `Labels::new()`.
323    fn default() -> Self {
324        Self::new()
325    }
326}
327
328/// Formats a floating-point value for display, rounded to 2 decimal places with
329/// trailing zeros (and a bare trailing decimal point) trimmed.
330///
331/// Used in place of plain `Display` for `f32`/`f64` cells so inspector fields show `86.67`
332/// and `300` rather than `86.666666666667` and `300.0`. Not applied to other cell types:
333/// precision has no meaningful effect on integers, and it would truncate `String` values
334/// outright.
335///
336/// # Examples
337///
338/// ```text
339/// format_rounded(86.666666666667) == "86.67"
340/// format_rounded(300.0)            == "300"
341/// format_rounded(-0.001)           == "0"
342/// ```
343pub fn format_rounded(v: f64) -> String {
344    let s = format!("{v:.2}");
345    let s = s.trim_end_matches('0');
346    let s = s.trim_end_matches('.');
347    if s == "-0" {
348        "0".to_string()
349    } else {
350        s.to_string()
351    }
352}
353
354/// Converts a filter-recognized primitive to approximate `f64` slider bounds.
355///
356/// Large integers can lose precision beyond 2^53; this display-only conversion does
357/// not define integer storage, integer field formatting, or string-write semantics.
358trait ToF64Display {
359    /// Returns the primitive's nearest representable display approximation.
360    fn to_f64_display(&self) -> f64;
361}
362
363/// Implements the documented display-only conversion for numeric primitives.
364macro_rules! impl_to_f64_display {
365    ($($T:ty),*) => {
366        $(impl ToF64Display for $T {
367            /// Returns this primitive's display-only `f64` approximation.
368            fn to_f64_display(&self) -> f64 {
369                *self as f64
370            }
371        })*
372    };
373}
374impl_to_f64_display!(
375    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
376);
377
378/// Builds a [`Labels`] from an adam-lang-style declaration-ordered cell name map.
379///
380/// Matches each scalar cell's `TypeId` against the built-in primitive types
381/// `adam_lang::TypeRegistry::new()` registers. Tuple and array cells
382/// appear with a Debug-formatted, display-only entry via
383/// [`Labels::add_compound_cell`]. Cells whose `TypeId` is none of the built-in
384/// primitives, including callable signatures, remain visible with an explicit
385/// unsupported-codec diagnostic.
386///
387/// - Complexity: O(n + t + s) registration work for cells n, copied label bytes t,
388///   and prepared compound type structure s; later value formatting has its own costs.
389///
390/// # Examples
391///
392/// ```
393/// let parsed = adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
394///     .parse_str("sheet example { cell width: i64; }").unwrap();
395/// let labels = adam_web_ui::labels_from_cell_names(&parsed, &parsed.cell_names);
396/// assert!(labels.cells[&parsed.cell_names["width"].0].is_integer);
397/// ```
398pub fn labels_from_cell_names(
399    sheet: &Sheet,
400    cell_names: &IndexMap<String, (CellId, TypeShape)>,
401) -> Labels {
402    let mut labels = Labels::new();
403    for (name, (id, shape)) in cell_names {
404        let id = *id;
405        let type_id = match shape {
406            TypeShape::Named(type_id) => *type_id,
407            TypeShape::Tuple(_) | TypeShape::Array(_) => {
408                labels.add_compound_cell(sheet, id, name);
409                continue;
410            }
411            TypeShape::Callable(_, _) => {
412                labels.add_compound_cell(sheet, id, name);
413                continue;
414            }
415        };
416        macro_rules! try_numeric_ty {
417            ($T:ty) => {
418                if type_id == TypeId::of::<$T>() {
419                    labels.add_cell::<$T>(id, name);
420                    mark_numeric::<$T>(&mut labels, sheet, id, true);
421                    continue;
422                }
423            };
424        }
425        try_numeric_ty!(i8);
426        try_numeric_ty!(i16);
427        try_numeric_ty!(i32);
428        try_numeric_ty!(i64);
429        try_numeric_ty!(i128);
430        try_numeric_ty!(isize);
431        try_numeric_ty!(u8);
432        try_numeric_ty!(u16);
433        try_numeric_ty!(u32);
434        try_numeric_ty!(u64);
435        try_numeric_ty!(u128);
436        try_numeric_ty!(usize);
437
438        macro_rules! try_numeric_float_ty {
439            ($T:ty) => {
440                if type_id == TypeId::of::<$T>() {
441                    labels.add_cell::<$T>(id, name);
442                    if let Some(meta) = labels.cells.get_mut(&id) {
443                        meta.display = Box::new(move |sheet| {
444                            sheet
445                                .read::<$T>(id)
446                                .map(|v| format_rounded(*v as f64))
447                                .unwrap_or_else(|_| "?".to_owned())
448                        });
449                    }
450                    mark_numeric::<$T>(&mut labels, sheet, id, false);
451                    continue;
452                }
453            };
454        }
455        try_numeric_float_ty!(f32);
456        try_numeric_float_ty!(f64);
457
458        macro_rules! try_ty {
459            ($T:ty) => {
460                if type_id == TypeId::of::<$T>() {
461                    labels.add_cell::<$T>(id, name);
462                    continue;
463                }
464            };
465        }
466        try_ty!(bool);
467        try_ty!(String);
468        labels.add_compound_cell(sheet, id, name);
469    }
470    labels
471}
472
473/// Marks `id`'s `CellMeta` as numeric (and, per `is_integer`, as an integer type) and, if
474/// `sheet.filter_kind(id)` is a range clamp, populates its live-range closure.
475fn mark_numeric<T: std::any::Any + Clone + ToF64Display + std::fmt::Display>(
476    labels: &mut Labels,
477    sheet: &Sheet,
478    id: CellId,
479    is_integer: bool,
480) {
481    let Some(meta) = labels.cells.get_mut(&id) else {
482        return;
483    };
484    meta.is_numeric = true;
485    meta.is_integer = is_integer;
486    meta.number_input_safe = !is_integer || std::mem::size_of::<T>() <= 4;
487    if matches!(
488        sheet.filter_kind(id),
489        Some(adam_rs::FilterKind::Range { .. })
490    ) {
491        meta.exact_range = Some(Box::new(move |sheet: &Sheet| {
492            sheet
493                .filter_range::<T>(id)
494                .map(|(lo, hi)| NumericRange {
495                    min: lo.to_string(),
496                    max: hi.to_string(),
497                })
498                .ok_or_else(|| InputError::UnsupportedEditor("range filter unavailable".into()))
499        }));
500        meta.range = Some(Box::new(move |sheet: &Sheet| {
501            sheet
502                .filter_range::<T>(id)
503                .map(|(lo, hi)| (lo.to_f64_display(), hi.to_f64_display()))
504                .unwrap_or((0.0, 0.0))
505        }));
506    }
507}
508
509/// Identifies all fourteen Rust numeric primitive types without value conversion.
510fn numeric_kind<T: std::any::Any>() -> Option<NumberKind> {
511    let id = TypeId::of::<T>();
512    /// Dispatches concrete primitive identities without converting values.
513    macro_rules! kinds {
514        ($($ty:ty => $kind:expr),* $(,)?) => {
515            $(if id == TypeId::of::<$ty>() { return Some($kind); })*
516        };
517    }
518
519    kinds!(
520        i8 => NumberKind::Signed(8), i16 => NumberKind::Signed(16),
521        i32 => NumberKind::Signed(32), i64 => NumberKind::Signed(64),
522        i128 => NumberKind::Signed(128), isize => NumberKind::Signed(isize::BITS),
523        u8 => NumberKind::Unsigned(8), u16 => NumberKind::Unsigned(16),
524        u32 => NumberKind::Unsigned(32), u64 => NumberKind::Unsigned(64),
525        u128 => NumberKind::Unsigned(128), usize => NumberKind::Unsigned(usize::BITS),
526        f32 => NumberKind::F32, f64 => NumberKind::F64,
527    );
528    None
529}
530
531/// Decodes with Rust primitive parsing and preserves lexical/overflow classification.
532///
533/// # Errors
534/// Returns `TypeRange` for primitive integer overflow and `Lexical` for other
535/// parsing failures.
536///
537/// - Complexity: O(input bytes) plus the concrete parser's costs.
538fn decode_scalar<T>(s: &str) -> Result<T, InputError>
539where
540    T: std::any::Any + std::str::FromStr,
541    T::Err: std::fmt::Display + std::any::Any,
542{
543    s.parse::<T>().map_err(|error| {
544        let overflow = (&error as &dyn std::any::Any)
545            .downcast_ref::<std::num::ParseIntError>()
546            .is_some_and(|error| {
547                matches!(
548                    error.kind(),
549                    std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow
550                )
551            });
552        match numeric_kind::<T>().filter(|_| overflow) {
553            Some(kind) => InputError::TypeRange {
554                kind,
555                value: s.to_owned(),
556            },
557            None => InputError::Lexical(error.to_string()),
558        }
559    })
560}
561
562/// Formats an [`Error`] as a rustc-style diagnostic when possible.
563///
564/// Resolves native sites through `diagnostics`, groups labels by owning source identity
565/// and renders definition files followed by invocation context. Inner CEL spans use
566/// their definition text, never the caller's text. Source-free labels remain visible.
567/// `file_name` overrides only the anonymous `AdamParser` input's display name.
568/// For legacy anonymous errors with no native site, `source` supplies the CEL text.
569///
570/// - Complexity: Provenance resolution plus O(n + l) source bytes and labels rendered.
571///
572/// # Examples
573/// ```
574/// let parsed = adam_lang::ParsedSheet::new();
575/// let text = adam_web_ui::format_adam_error(&adam_rs::Error::InvalidId,
576///     &parsed.diagnostics(), "", "input.adm2", &adam_web_ui::Renderer::plain());
577/// assert_eq!(text, "invalid cell or relationship id");
578/// ```
579pub fn format_adam_error(
580    e: &Error,
581    diagnostics: &SheetDiagnostics,
582    source: &str,
583    file_name: &str,
584    renderer: &Renderer,
585) -> String {
586    let located = diagnostics.locate_error(e);
587    if located.is_empty()
588        && e.sites().is_empty()
589        && diagnostics.anonymous_source().is_some()
590        && let Error::MethodFailed { error, .. } = e
591        && error.downcast_ref::<SpanContext>().is_some()
592    {
593        return error.format_rustc_style(source, file_name, 1, renderer);
594    }
595    format_source_labels(
596        &runtime_message(e),
597        &located,
598        diagnostics
599            .anonymous_source()
600            .map(|source| (source, file_name)),
601        renderer,
602    )
603}
604
605/// Renders one false requirement with its owning source labels.
606///
607/// - Complexity: O(n + l) source and label bytes, excluding snippet rendering.
608pub(crate) fn format_validation_issue(
609    issue: &crate::build::ValidationIssue,
610    diagnostics: &SheetDiagnostics,
611    file_name: &str,
612    renderer: &Renderer,
613) -> String {
614    let display_source = diagnostics
615        .anonymous_source()
616        .map(|source| (source, file_name));
617    format_source_labels(
618        &format!("{}: {}", issue.key, issue.message),
619        &issue.labels,
620        display_source,
621        renderer,
622    )
623}
624
625/// Returns the operation's message without replacing or consuming its typed error.
626///
627/// - Complexity: O(formatted message bytes) output space, plus the error's formatting cost.
628fn runtime_message(error: &Error) -> String {
629    if let Error::MethodFailed { error, .. } = error
630        && error.downcast_ref::<SpanContext>().is_some()
631    {
632        return error
633            .source()
634            .map_or_else(|| error.to_string(), ToString::to_string);
635    }
636    error.to_string()
637}
638
639/// Formats a module diagnostic against its retained source owners.
640///
641/// Native labels remain visible without invented locations.
642/// - Complexity: O(n + l) source and label bytes, excluding snippet rendering.
643///
644/// # Examples
645/// ```
646/// let error = adam_lang::ModuleDiagnostic {
647///     message: "missing root".into(), labels: vec![], cause: None,
648/// };
649/// assert_eq!(adam_web_ui::format_module_diagnostic(&error,
650///     &adam_web_ui::Renderer::plain()), "missing root");
651/// ```
652pub fn format_module_diagnostic(
653    error: &adam_lang::ModuleDiagnostic,
654    renderer: &Renderer,
655) -> String {
656    format_source_labels(&diagnostic_message(error), &error.labels, None, renderer)
657}
658
659/// Formats the convenience parser's owning diagnostic, retaining the caller's file name.
660///
661/// Legacy lexical failures without owning labels use the parser's original formatter.
662/// This adapter borrows the error and preserves every concrete source cause.
663/// - Complexity: O(h + n + l) cause depth h, source bytes n and label bytes l.
664///
665/// # Examples
666/// ```
667/// let error = adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(),
668///     cel_parser::OpLookup::new()).parse_str("sheet {}").unwrap_err();
669/// let text = adam_web_ui::format_parse_error(&error, "sheet {}", "file.adm2",
670///     &adam_web_ui::Renderer::plain());
671/// assert!(!text.is_empty());
672/// ```
673pub fn format_parse_error(
674    error: &cel_parser::ParseError,
675    source: &str,
676    file_name: &str,
677    renderer: &Renderer,
678) -> String {
679    let diagnostic =
680        std::iter::successors(std::error::Error::source(error), |error| error.source())
681            .find_map(|cause| cause.downcast_ref::<adam_lang::ModuleDiagnostic>());
682    if let Some(diagnostic) = diagnostic
683        && diagnostic
684            .labels
685            .iter()
686            .any(|label| label.location.is_some())
687    {
688        let owner = diagnostic
689            .labels
690            .iter()
691            .find_map(|label| label.location.as_ref().map(|location| &location.source));
692        return format_source_labels(
693            &diagnostic_message(diagnostic),
694            &diagnostic.labels,
695            owner.map(|owner| (owner, file_name)),
696            renderer,
697        );
698    }
699    error.format_rustc_style(source, file_name, 1, renderer)
700}
701
702/// Includes the concrete innermost cause when a span context hides its message.
703///
704/// - Complexity: O(h + m) cause depth h and formatted message bytes m.
705fn diagnostic_message(error: &adam_lang::ModuleDiagnostic) -> String {
706    let mut message = error.message.clone();
707    if let Some(cause) =
708        std::iter::successors(std::error::Error::source(error), |error| error.source()).last()
709    {
710        let detail = cause.to_string();
711        if !message.contains(&detail) {
712            message.push_str(": ");
713            message.push_str(&detail);
714        }
715    }
716    message
717}
718
719/// Renders owning labels in first-source order, retaining span-free context.
720///
721/// Only `display_source`'s exact owner receives the supplied display name.
722/// Empty labels return the message unchanged.
723/// - Complexity: Expected O(n + l) time and O(n + l) space for source bytes n
724///   and label bytes l, excluding the existing snippet renderer.
725pub(crate) fn format_source_labels(
726    message: &str,
727    labels: &[adam_lang::SourceLabel],
728    display_source: Option<(&adam_lang::SourceId, &str)>,
729    renderer: &Renderer,
730) -> String {
731    let mut groups: IndexMap<&adam_lang::SourceId, Vec<SpanLabel>> = IndexMap::new();
732    for label in labels {
733        if let Some(location) = &label.location {
734            groups.entry(&location.source).or_default().push(SpanLabel {
735                span: location.span,
736                label: label.label.clone(),
737            });
738        }
739    }
740    let mut result = String::new();
741    for (source, spans) in groups {
742        let file_name = display_source
743            .filter(|(owner, _)| *owner == source)
744            .map_or_else(|| source.file_name(), |(_, name)| name);
745        if !result.is_empty() {
746            result.push('\n');
747        }
748        result.push_str(&cel_parser::format_multi_span(
749            message,
750            &spans,
751            source.text(),
752            file_name,
753            1,
754            renderer,
755        ));
756    }
757    if result.is_empty() {
758        result.push_str(message);
759    }
760    for label in labels.iter().filter(|label| label.location.is_none()) {
761        result.push_str("\n= context: ");
762        result.push_str(&label.label);
763    }
764    result
765}
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770    use adam_rs::Sheet as AdamSheet;
771
772    /// Renders each source owner separately and keeps span-free context visible.
773    #[test]
774    fn labels_render_owned_files_and_native_context() {
775        let mut sources = adam_lang::SourceMap::new();
776        let definition = sources.insert("definition.adm2", "a / b");
777        let invocation = sources.insert("caller.adm2", "relationship divide(a: a, b: b);");
778        let labels = vec![
779            adam_lang::SourceLabel {
780                location: Some(adam_lang::SourceLocation {
781                    source: definition,
782                    span: cel_parser::SourceSpan::new(1, 2, 1, 3),
783                }),
784                label: "division failed".into(),
785            },
786            adam_lang::SourceLabel {
787                location: Some(adam_lang::SourceLocation {
788                    source: invocation,
789                    span: cel_parser::SourceSpan::new(1, 0, 1, 31),
790                }),
791                label: "component use".into(),
792            },
793            adam_lang::SourceLabel {
794                location: None,
795                label: "native definition".into(),
796            },
797        ];
798        let rendered = format_source_labels("division by zero", &labels, None, &Renderer::plain());
799        for expected in [
800            "definition.adm2:1:3",
801            "caller.adm2:1:1",
802            "a / b",
803            "component use",
804            "native definition",
805        ] {
806            assert!(rendered.contains(expected), "{rendered}");
807        }
808        assert!(!rendered.contains('\u{1b}'));
809    }
810
811    /// Overrides only the anonymous root owner in a validation diagnostic.
812    #[test]
813    fn validation_display_name_preserves_imported_source_names() {
814        let parsed = parse("sheet root { cell x: i32 = 0; }");
815        let diagnostics = parsed.diagnostics();
816        let root = diagnostics
817            .anonymous_source()
818            .expect("parser retains its anonymous root")
819            .clone();
820        let mut sources = adam_lang::SourceMap::new();
821        let imported = sources.insert("component.adm2", "sheet component {}");
822        let issue = crate::build::ValidationIssue {
823            key: "x".to_string(),
824            requirement: None,
825            labels: vec![
826                adam_lang::SourceLabel {
827                    location: Some(adam_lang::SourceLocation {
828                        source: root,
829                        span: cel_parser::SourceSpan::new(1, 0, 1, 5),
830                    }),
831                    label: "root requirement".to_string(),
832                },
833                adam_lang::SourceLabel {
834                    location: Some(adam_lang::SourceLocation {
835                        source: imported,
836                        span: cel_parser::SourceSpan::new(1, 0, 1, 5),
837                    }),
838                    label: "component requirement".to_string(),
839                },
840            ],
841            message: "requirement evaluated to false".to_string(),
842        };
843
844        let rendered = format_validation_issue(&issue, &diagnostics, "s.adm2", &Renderer::plain());
845
846        assert!(rendered.contains("s.adm2"), "{rendered}");
847        assert!(rendered.contains("component.adm2"), "{rendered}");
848        assert!(!rendered.contains("<input>"), "{rendered}");
849    }
850
851    /// Preserves an anonymous root's display name, exact division subspan and original cause.
852    #[test]
853    fn labels_render_construction_cel_error_with_original_cause() {
854        let source = "sheet app { cell a: i32 = 1 + 4 / 0; }";
855        let error =
856            adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
857                .parse_str(source)
858                .unwrap_err();
859        let rendered = format_parse_error(&error, source, "root.adm2", &Renderer::plain());
860        assert!(rendered.contains("division by zero"), "{rendered}");
861        assert!(rendered.contains("root.adm2:1:31"), "{rendered}");
862        assert!(!rendered.contains("<input>"), "{rendered}");
863        let cause = std::error::Error::source(&error).unwrap();
864        assert!(cause.is::<adam_lang::ModuleDiagnostic>());
865    }
866
867    /// Keeps independent identical sources separate and overrides only the requested owner.
868    #[test]
869    fn labels_group_by_identity_and_keep_unlocated_and_empty_messages() {
870        let mut sources = adam_lang::SourceMap::new();
871        let a = sources.insert("same.adm2", "x");
872        let b = sources.insert("same.adm2", "x");
873        let labels: Vec<_> = [&a, &b]
874            .into_iter()
875            .map(|source| adam_lang::SourceLabel {
876                location: Some(adam_lang::SourceLocation {
877                    source: source.clone(),
878                    span: cel_parser::SourceSpan::new(1, 0, 1, 1),
879                }),
880                label: "definition".into(),
881            })
882            .collect();
883        let rendered = format_source_labels(
884            "boom",
885            &labels,
886            Some((&a, "caller.adm2")),
887            &Renderer::plain(),
888        );
889        assert!(rendered.contains("caller.adm2"), "{rendered}");
890        assert!(rendered.contains("same.adm2"), "{rendered}");
891        assert_eq!(
892            format_source_labels("boom", &[], None, &Renderer::plain()),
893            "boom"
894        );
895        let diagnostic = adam_lang::ModuleDiagnostic {
896            message: "boom".into(),
897            labels: vec![adam_lang::SourceLabel {
898                location: None,
899                label: "native".into(),
900            }],
901            cause: None,
902        };
903        assert_eq!(
904            format_module_diagnostic(&diagnostic, &Renderer::plain()),
905            "boom\n= context: native"
906        );
907    }
908
909    /// Uses imported definition text and the failing second invocation, never caller text.
910    #[test]
911    fn labels_render_imported_runtime_definition_and_actual_use() {
912        let mut modules = adam_lang::ModuleSet::new();
913        modules
914            .insert_source(
915                "library".parse().unwrap(),
916                "library.adm2",
917                "sheet divide(a: i32, b: i32) {\nrelationship { b := 1 + 4 / a; }\n}",
918            )
919            .unwrap();
920        modules
921            .insert_source(
922                "app".parse().unwrap(),
923                "app.adm2",
924                "use library::divide;
925sheet app {
926source good: i32 = 2; source bad: i32 = 0; cell first: i32; cell second: i32;
927relationship divide(a: good, b: first);
928relationship divide(a: bad, b: second);
929}",
930            )
931            .unwrap();
932        let compiled = adam_lang::ModuleCompiler::new(
933            adam_lang::TypeRegistry::new(),
934            cel_parser::OpLookup::new(),
935        )
936        .compile(modules)
937        .unwrap();
938        let mut parsed = compiled
939            .instantiate_root(&"app".parse().unwrap(), "app")
940            .unwrap();
941        drop(compiled);
942        let diagnostics = parsed.diagnostics();
943        let error = parsed.propagate().unwrap_err();
944        let rendered = format_adam_error(
945            &error,
946            &diagnostics,
947            "WRONG CALLER TEXT",
948            "wrong.adm2",
949            &Renderer::plain(),
950        );
951        for expected in [
952            "division by zero",
953            "library.adm2:2:25",
954            "app.adm2:5:1",
955            "b := 1 + 4 / a",
956            "b: second",
957        ] {
958            assert!(rendered.contains(expected), "{rendered}");
959        }
960        assert!(!rendered.contains("wrong.adm2"), "{rendered}");
961        assert!(!rendered.contains("WRONG CALLER TEXT"), "{rendered}");
962    }
963
964    /// Renders a post-edit conditional failure using its retained imported source and use site.
965    #[test]
966    fn labels_render_imported_conditional_runtime_after_edit() {
967        let mut modules = adam_lang::ModuleSet::new();
968        modules
969            .insert_source(
970                "library".parse().unwrap(),
971                "library.adm2",
972                "sheet choose(divisor: i32) {\nconditional 1 / divisor { 0 => {} _ => {} }\n}",
973            )
974            .unwrap();
975        modules
976            .insert_source(
977                "app".parse().unwrap(),
978                "app.adm2",
979                "use library::choose;
980sheet app {
981cell first: i32 = 1; cell second: i32 = 1;
982relationship choose(divisor: first);
983relationship choose(divisor: second);
984}",
985            )
986            .unwrap();
987        let compiled = adam_lang::ModuleCompiler::new(
988            adam_lang::TypeRegistry::new(),
989            cel_parser::OpLookup::new(),
990        )
991        .compile(modules)
992        .unwrap();
993        let mut parsed = compiled
994            .instantiate_root(&"app".parse().unwrap(), "app")
995            .unwrap();
996        drop(compiled);
997        parsed.propagate().unwrap();
998        let second = parsed.cell_names["second"].0;
999        let diagnostics = parsed.diagnostics();
1000        parsed.write(second, 0i32).unwrap();
1001        let error = parsed.propagate().unwrap_err();
1002        let rendered = format_adam_error(
1003            &error,
1004            &diagnostics,
1005            "WRONG TEXT",
1006            "wrong.adm2",
1007            &Renderer::plain(),
1008        );
1009        for expected in [
1010            "division by zero",
1011            "library.adm2:2:13",
1012            "app.adm2:5:1",
1013            "conditional 1 / divisor",
1014            "divisor: second",
1015        ] {
1016            assert!(rendered.contains(expected), "{rendered}");
1017        }
1018        for excluded in ["wrong.adm2", "WRONG TEXT", "divisor: first", "app.adm2:4:1"] {
1019            assert!(!rendered.contains(excluded), "{rendered}");
1020        }
1021    }
1022
1023    /// Parses `src` into a `ParsedSheet` via the standard adam-lang pipeline, for tests that
1024    /// need a real (rather than hand-built) span table to resolve `Error` sites against.
1025    ///
1026    /// - Complexity: parser/type-checker and sheet-construction work for the supplied source.
1027    fn parse(src: &str) -> adam_lang::ParsedSheet {
1028        use adam_lang::{AdamParser, TypeRegistry};
1029        use cel_parser::OpLookup;
1030        AdamParser::new(TypeRegistry::new(), OpLookup::new())
1031            .parse_str(src)
1032            .unwrap()
1033    }
1034
1035    #[test]
1036    /// Errors without source sites fall back to their display message.
1037    fn format_adam_error_invalid_id_falls_back_to_display() {
1038        let parsed = parse("sheet s { cell a: i32 = 0; }");
1039        let diagnostics = parsed.diagnostics();
1040        let msg = format_adam_error(
1041            &Error::InvalidId,
1042            &diagnostics,
1043            "sheet s { cell a: i32 = 0; }",
1044            "test.adm2",
1045            &Renderer::styled(),
1046        );
1047        assert_eq!(msg, "invalid cell or relationship id");
1048    }
1049
1050    #[test]
1051    /// Located method failures render source caret diagnostics.
1052    fn format_adam_error_method_failed_renders_caret_diagnostic() {
1053        use cel_parser::{SourceSpan, SpanContext};
1054
1055        let parsed = parse("sheet s { cell a: i32 = 0; }");
1056        let source = "1i32 / 0i32";
1057        let span = SourceSpan::new(1, 0, 1, 11);
1058        let inner = anyhow::anyhow!("division by zero").context(SpanContext::new(span));
1059        let err = Error::MethodFailed {
1060            error: inner,
1061            sites: vec![],
1062        };
1063        let diagnostics = parsed.diagnostics();
1064
1065        let msg = format_adam_error(&err, &diagnostics, source, "test.adm2", &Renderer::styled());
1066
1067        assert!(msg.contains("division by zero"), "{msg}");
1068        assert!(msg.contains(source), "{msg}");
1069    }
1070
1071    #[test]
1072    /// Plain error rendering omits terminal escape sequences.
1073    fn format_adam_error_plain_renderer_has_no_ansi_escape_codes() {
1074        use cel_parser::{SourceSpan, SpanContext};
1075
1076        let parsed = parse("sheet s { cell a: i32 = 0; }");
1077        let source = "1i32 / 0i32";
1078        let span = SourceSpan::new(1, 0, 1, 11);
1079        let inner = anyhow::anyhow!("division by zero").context(SpanContext::new(span));
1080        let err = Error::MethodFailed {
1081            error: inner,
1082            sites: vec![],
1083        };
1084        let diagnostics = parsed.diagnostics();
1085
1086        let msg = format_adam_error(&err, &diagnostics, source, "test.adm2", &Renderer::plain());
1087
1088        assert!(msg.contains("division by zero"), "{msg}");
1089        assert!(
1090            !msg.contains('\u{1b}'),
1091            "expected no ANSI escapes, got: {msg}"
1092        );
1093    }
1094
1095    #[test]
1096    /// A method failure without span context still renders its available located span.
1097    fn format_adam_error_method_failed_falls_back_to_a_single_located_span_without_a_span_context()
1098    {
1099        use adam_rs::ErrorSite;
1100
1101        let source =
1102            "sheet s {\n    cell a: i32;\n    relationship {\n        a := 1i32;\n    }\n}";
1103        let parsed = parse(source);
1104        let &(rel_id, idx) = parsed.method_spans.keys().next().expect("one relationship");
1105
1106        let err = Error::MethodFailed {
1107            error: anyhow::anyhow!("boom"),
1108            sites: vec![ErrorSite::Method(rel_id, idx)],
1109        };
1110        let diagnostics = parsed.diagnostics();
1111
1112        let msg = format_adam_error(&err, &diagnostics, source, "test.adm2", &Renderer::plain());
1113
1114        assert!(msg.contains("boom"), "{msg}");
1115        assert!(msg.contains("a := 1i32;"), "{msg}");
1116    }
1117
1118    #[test]
1119    /// Cycle errors render all supplied binding spans.
1120    fn format_adam_error_cycle_renders_a_multi_span_backtrace() {
1121        use adam_lang::{AdamParser, TypeRegistry};
1122        use cel_parser::OpLookup;
1123        let src = "sheet s { cell x: i32 = 0; cell y: i32 = 0; relationship { x := y + 1i32; } relationship { y := x + 1i32; } }";
1124        let mut parser = AdamParser::new(TypeRegistry::new(), OpLookup::new());
1125        let mut parsed = parser.parse_str(src).unwrap();
1126        let diagnostics = parsed.diagnostics();
1127        let err = parsed.propagate().unwrap_err();
1128        let msg = format_adam_error(&err, &diagnostics, src, "t.adm2", &Renderer::plain());
1129        assert!(msg.contains("cycle"), "{msg}");
1130        // both relationship bindings referenced
1131        assert!(msg.contains("x :=") && msg.contains("y :="), "{msg}");
1132    }
1133
1134    /// Renders the same diagnostic after dropping its failed model.
1135    #[test]
1136    fn format_adam_error_survives_dropping_the_model() {
1137        let source = "sheet s { cell x: i32 = 0; cell y: i32; relationship { y := 10i32 / x; } }";
1138        let mut parsed = parse(source);
1139        let diagnostics = parsed.diagnostics();
1140        let error = parsed.propagate().unwrap_err();
1141        let render_before_model_drop =
1142            format_adam_error(&error, &diagnostics, source, "s.adm2", &Renderer::plain());
1143
1144        drop(parsed);
1145
1146        let render_after_model_drop =
1147            format_adam_error(&error, &diagnostics, source, "s.adm2", &Renderer::plain());
1148        assert_eq!(render_after_model_drop, render_before_model_drop);
1149        assert!(render_after_model_drop.contains("division by zero"));
1150    }
1151
1152    #[test]
1153    /// Rounded numeric display removes redundant decimal zeros and points.
1154    fn format_rounded_trims_trailing_zeros_and_point() {
1155        assert_eq!(format_rounded(86.666666666667), "86.67");
1156        assert_eq!(format_rounded(300.0), "300");
1157        assert_eq!(format_rounded(2.5), "2.5");
1158        assert_eq!(format_rounded(0.0), "0");
1159    }
1160
1161    #[test]
1162    /// Rounded zero has no misleading negative sign.
1163    fn format_rounded_negative_zero_has_no_minus_sign() {
1164        assert_eq!(format_rounded(-0.0), "0");
1165        assert_eq!(format_rounded(-0.001), "0");
1166    }
1167
1168    #[test]
1169    /// Floating-point metadata selects numeric but not integer controls.
1170    fn labels_from_cell_names_marks_float_cells_as_numeric_but_not_integer() {
1171        let mut sheet = AdamSheet::new();
1172        let a = sheet.add_cell(2.0_f64);
1173
1174        let mut cell_names = IndexMap::new();
1175        cell_names.insert("a".to_string(), (a, TypeShape::Named(TypeId::of::<f64>())));
1176
1177        let labels = labels_from_cell_names(&sheet, &cell_names);
1178
1179        assert!(labels.cells[&a].is_numeric);
1180        assert!(!labels.cells[&a].is_integer);
1181    }
1182
1183    #[test]
1184    /// Floating-point metadata displays rounded decimal values.
1185    fn labels_from_cell_names_rounds_float_display_to_two_decimals() {
1186        let mut sheet = AdamSheet::new();
1187        let a = sheet.add_cell(86.666666666667_f64);
1188
1189        let mut cell_names = IndexMap::new();
1190        cell_names.insert("a".to_string(), (a, TypeShape::Named(TypeId::of::<f64>())));
1191
1192        let labels = labels_from_cell_names(&sheet, &cell_names);
1193
1194        assert_eq!((labels.cells[&a].display)(&sheet), "86.67");
1195    }
1196
1197    #[test]
1198    /// Supported scalar types receive display/write metadata.
1199    fn labels_from_cell_names_builds_entries_for_supported_types() {
1200        let mut sheet = AdamSheet::new();
1201        let a = sheet.add_cell(2.0_f64);
1202        let b = sheet.add_cell(3_i32);
1203        let c = sheet.add_cell(true);
1204        let d = sheet.add_cell("hi".to_string());
1205
1206        let mut cell_names = IndexMap::new();
1207        cell_names.insert("a".to_string(), (a, TypeShape::Named(TypeId::of::<f64>())));
1208        cell_names.insert("b".to_string(), (b, TypeShape::Named(TypeId::of::<i32>())));
1209        cell_names.insert("c".to_string(), (c, TypeShape::Named(TypeId::of::<bool>())));
1210        cell_names.insert(
1211            "d".to_string(),
1212            (d, TypeShape::Named(TypeId::of::<String>())),
1213        );
1214
1215        let labels = labels_from_cell_names(&sheet, &cell_names);
1216
1217        assert_eq!(labels.cells.len(), 4);
1218        assert_eq!((labels.cells[&a].display)(&sheet), "2");
1219        assert_eq!((labels.cells[&b].display)(&sheet), "3");
1220        assert_eq!((labels.cells[&c].display)(&sheet), "true");
1221        assert_eq!((labels.cells[&d].display)(&sheet), "hi");
1222        assert!(!labels.cells[&a].is_bool);
1223        assert!(!labels.cells[&b].is_bool);
1224        assert!(labels.cells[&c].is_bool);
1225        assert!(!labels.cells[&d].is_bool);
1226    }
1227
1228    #[test]
1229    /// Tuple cells receive compound display metadata.
1230    fn labels_from_cell_names_includes_tuple_typed_cells() {
1231        let sheet = tuple_sheet();
1232        let pair = sheet.cell_names["pair"].0;
1233
1234        let mut cell_names = IndexMap::new();
1235        cell_names.insert(
1236            "pair".to_string(),
1237            (
1238                pair,
1239                TypeShape::Tuple(vec![
1240                    TypeShape::Named(TypeId::of::<i32>()),
1241                    TypeShape::Named(TypeId::of::<f64>()),
1242                ]),
1243            ),
1244        );
1245
1246        let labels = labels_from_cell_names(&sheet, &cell_names);
1247
1248        assert_eq!(labels.cells.len(), 1);
1249        assert_eq!((labels.cells[&pair].display)(&sheet), "(3, 4.5)");
1250        assert!(!labels.cells[&pair].is_bool);
1251    }
1252
1253    /// Compound labels display nested tuples, arrays, empty arrays, and source unit.
1254    #[test]
1255    fn labels_display_compound_values_and_reject_edits() {
1256        let mut sheet =
1257            adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
1258                .parse_str(
1259                    "sheet s {
1260                        cell xs: [(i32, bool)] = [(3, true), (4, false)];
1261                        cell empty: [i32];
1262                        cell nested: ([(i32, bool)], [i32]) = ([(7, true)], []: [i32]);
1263                        cell unit: ();
1264                        cell scalar: i32 = 5;
1265                    }",
1266                )
1267                .unwrap();
1268        let labels = labels_from_cell_names(&sheet, &sheet.cell_names);
1269        assert_eq!(labels.cells.len(), 5);
1270        for (name, expected) in [
1271            ("xs", "[(3, true), (4, false)]"),
1272            ("empty", "[]"),
1273            ("nested", "([(7, true)], [])"),
1274            ("unit", "()"),
1275        ] {
1276            let meta = &labels.cells[&sheet.cell_names[name].0];
1277            assert_eq!((meta.display)(&sheet), expected);
1278            assert!(!meta.is_bool && !meta.is_numeric && !meta.is_integer);
1279            let error = (meta.prepare)("[]").err().unwrap();
1280            assert!(error.to_string().contains("not yet supported"));
1281            assert_eq!((meta.display)(&sheet), expected);
1282        }
1283        let scalar = &labels.cells[&sheet.cell_names["scalar"].0];
1284        assert_eq!((scalar.display)(&sheet), "5");
1285        let scalar_id = sheet.cell_names["scalar"].0;
1286        (scalar.prepare)("9")
1287            .unwrap()
1288            .apply(&mut sheet, scalar_id)
1289            .unwrap();
1290        assert_eq!((scalar.display)(&sheet), "9");
1291        let id = sheet.cell_names["empty"].0;
1292        sheet
1293            .write_compound::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>(
1294                id,
1295                cel_runtime::Array::from_vec(vec![1, 2]),
1296            )
1297            .unwrap();
1298        assert_eq!((labels.cells[&id].display)(&sheet), "[1, 2]");
1299    }
1300
1301    #[test]
1302    /// Metadata preserves declaration-ordered cell names.
1303    fn labels_from_cell_names_preserves_declaration_order() {
1304        let mut sheet = AdamSheet::new();
1305        let z = sheet.add_cell(1_i32);
1306        let a = sheet.add_cell(2_i32);
1307
1308        let mut cell_names = IndexMap::new();
1309        cell_names.insert("z".to_string(), (z, TypeShape::Named(TypeId::of::<i32>())));
1310        cell_names.insert("a".to_string(), (a, TypeShape::Named(TypeId::of::<i32>())));
1311
1312        let labels = labels_from_cell_names(&sheet, &cell_names);
1313        let ids: Vec<_> = labels.cells.keys().copied().collect();
1314        assert_eq!(ids, vec![z, a]);
1315    }
1316
1317    #[test]
1318    /// Unfiltered numeric cells have numeric classification without slider bounds.
1319    fn labels_from_cell_names_marks_numeric_cells_and_leaves_range_none_without_a_filter() {
1320        let mut sheet = AdamSheet::new();
1321        let a = sheet.add_cell(3_i32);
1322        let b = sheet.add_cell(true);
1323
1324        let mut cell_names = IndexMap::new();
1325        cell_names.insert("a".to_string(), (a, TypeShape::Named(TypeId::of::<i32>())));
1326        cell_names.insert("b".to_string(), (b, TypeShape::Named(TypeId::of::<bool>())));
1327
1328        let labels = labels_from_cell_names(&sheet, &cell_names);
1329
1330        assert!(labels.cells[&a].is_numeric);
1331        assert!(labels.cells[&a].is_integer);
1332        assert!(labels.cells[&a].range.is_none());
1333        assert!(!labels.cells[&b].is_numeric);
1334    }
1335
1336    #[test]
1337    /// Range-filtered numeric cells expose their current slider bounds.
1338    fn labels_from_cell_names_populates_range_for_a_range_filtered_cell() {
1339        use adam_rs::Filter;
1340        use std::any::Any;
1341
1342        let mut sheet = AdamSheet::new();
1343        let a = sheet.add_cell(50_i32);
1344        let filter = Filter::range(
1345            TypeId::of::<i32>(),
1346            vec![],
1347            vec![],
1348            |value, _args| Ok(Box::new(*value.downcast_ref::<i32>().unwrap()) as Box<dyn Any>),
1349            |_args| {
1350                Some((
1351                    Box::new(0i32) as Box<dyn Any>,
1352                    Box::new(100i32) as Box<dyn Any>,
1353                ))
1354            },
1355        );
1356        sheet.add_filter(a, filter).unwrap();
1357
1358        let mut cell_names = IndexMap::new();
1359        cell_names.insert("a".to_string(), (a, TypeShape::Named(TypeId::of::<i32>())));
1360
1361        let labels = labels_from_cell_names(&sheet, &cell_names);
1362
1363        let range_fn = labels.cells[&a].range.as_ref().expect("range populated");
1364        assert_eq!(range_fn(&sheet), (0.0, 100.0));
1365    }
1366
1367    /// Builds one floating-point cell with generic display/write metadata.
1368    fn sheet_with_one_cell() -> (AdamSheet, Labels) {
1369        let mut sheet = AdamSheet::new();
1370        let mut labels = Labels::new();
1371        let a = sheet.add_cell(2.0_f64);
1372        labels.add_cell::<f64>(a, "a");
1373        (sheet, labels)
1374    }
1375
1376    #[test]
1377    /// Generic display callbacks format the registered cell's value.
1378    fn display_closure_returns_value_string() {
1379        let (sheet, labels) = sheet_with_one_cell();
1380        let a_id = *labels.cells.keys().next().unwrap();
1381        let display = &labels.cells[&a_id].display;
1382        assert_eq!(display(&sheet), "2");
1383    }
1384
1385    #[test]
1386    /// Generic write callbacks parse and update the registered cell.
1387    fn prepared_write_parses_and_writes() {
1388        let (mut sheet, labels) = sheet_with_one_cell();
1389        let a_id = *labels.cells.keys().next().unwrap();
1390        assert!(
1391            (labels.cells[&a_id].prepare)("5.0")
1392                .unwrap()
1393                .apply(&mut sheet, a_id)
1394                .is_ok()
1395        );
1396        let display = &labels.cells[&a_id].display;
1397        assert_eq!(display(&sheet), "5");
1398    }
1399
1400    #[test]
1401    /// Compound metadata displays the tuple's canonical debug representation.
1402    fn add_tuple_cell_display_returns_rust_debug_formatted_string() {
1403        let sheet = tuple_sheet();
1404        let cell_id = sheet.cell_names["pair"].0;
1405        let mut labels = Labels::new();
1406        labels.add_compound_cell(&sheet, cell_id, "pair");
1407        let meta = labels.cells.get(&cell_id).unwrap();
1408        assert_eq!((meta.display)(&sheet), "(3, 4.5)");
1409    }
1410
1411    #[test]
1412    /// Unsupported compound edits return an error without changing the stored value.
1413    fn add_tuple_cell_prepare_always_errs_without_mutating_the_sheet() {
1414        let sheet = tuple_sheet();
1415        let cell_id = sheet.cell_names["pair"].0;
1416        let mut labels = Labels::new();
1417        labels.add_compound_cell(&sheet, cell_id, "pair");
1418        let meta = labels.cells.get(&cell_id).unwrap();
1419        let before = adam_lang::debug_compound_cell(&sheet, cell_id).unwrap();
1420        let result = (meta.prepare)("(1, 2.0)");
1421        assert!(result.is_err());
1422        let after = adam_lang::debug_compound_cell(&sheet, cell_id).unwrap();
1423        assert_eq!(before, after);
1424    }
1425
1426    /// Builds real canonical tuple storage for host-display boundary contracts.
1427    fn tuple_sheet() -> adam_lang::ParsedSheet {
1428        adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
1429            .parse_str("sheet s { cell pair: (i32, f64) = (3, 4.5); }")
1430            .unwrap()
1431    }
1432
1433    /// A missing compound formatting capability stays visible without enabling edits.
1434    #[test]
1435    fn compound_label_reports_unavailable_storage_without_panicking() {
1436        let mut sheet = AdamSheet::new();
1437        let id = sheet.add_cell(7i32);
1438        let mut labels = Labels::new();
1439        labels.add_compound_cell(&sheet, id, "unavailable");
1440        let meta = &labels.cells[&id];
1441        assert_eq!((meta.display)(&sheet), "?");
1442        assert!((meta.prepare)("9").is_err());
1443        assert_eq!(*sheet.read::<i32>(id).unwrap(), 7);
1444    }
1445}