Skip to main content

adam_web_ui/
build.rs

1//! Parses, initializes, and validates adam-lang sheets before returning them.
2
3use crate::labels::{
4    Labels, Renderer, format_adam_error, format_module_diagnostic, format_parse_error,
5    format_source_labels, format_validation_issue, labels_from_cell_names,
6};
7use adam_lang::{
8    AdamParser, ModuleDiagnostic, ParsedSheet, SheetDiagnostics, SourceLabel, TypeRegistry,
9};
10use adam_rs::{CellId, Error};
11use indexmap::IndexMap;
12use std::collections::HashMap;
13
14/// A runtime mutation error with independently owned source diagnostics.
15///
16/// The failed candidate is discarded and is never part of this value.
17///
18/// # Examples
19///
20/// See [`BuildError::render`] for formatting a runtime failure.
21#[derive(Debug)]
22pub struct RuntimeFailure {
23    /// The typed error returned by a mutating sheet operation.
24    pub error: Error,
25    /// Source and provenance metadata captured before mutation.
26    pub diagnostics: Box<SheetDiagnostics>,
27    /// Requested display name for the anonymous root source.
28    pub file_name: String,
29}
30
31/// A requirement that evaluated to false after successful propagation.
32///
33/// `key` identifies the affected root cell when it has a public name. Private
34/// cells use their authored declaration label, or a cell ID when no source
35/// label exists. `labels` retains source owners.
36///
37/// # Examples
38///
39/// See [`BuildError::Validation`] for the construction result that contains issues.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct ValidationIssue {
42    /// Stable public name or authored label of the affected cell.
43    pub key: String,
44    /// Explicit `@name` requirement label, when present.
45    pub requirement: Option<String>,
46    /// Source labels for the false requirement.
47    pub labels: Vec<SourceLabel>,
48    /// Human-readable explanation of the failed requirement.
49    pub message: String,
50}
51
52/// A sheet that parsed, propagated successfully, and passed its requirements.
53///
54/// The key map starts with public root names. A host may add keys for private
55/// cells after it configures its model.
56///
57/// # Examples
58///
59/// See [`build_sheet`] for constructing an initialized sheet.
60pub struct BuiltSheet {
61    /// The initialized live sheet and its source metadata.
62    pub parsed: ParsedSheet,
63    /// Display and write metadata for the live sheet.
64    pub labels: Labels,
65    /// Independently owned source and error-site metadata.
66    pub diagnostics: SheetDiagnostics,
67    /// Stable public root names mapped to their cell IDs.
68    pub keys: IndexMap<String, CellId>,
69    /// Root diagnostic display name retained for later host mutations.
70    pub file_name: String,
71}
72
73/// A construction or restoration failure that never owns a candidate sheet.
74///
75/// # Examples
76///
77/// ```
78/// let error = adam_web_ui::build_sheet("sheet s { cell x }", "input.adm2")
79///     .err()
80///     .expect("the module is invalid");
81/// assert!(matches!(error, adam_web_ui::BuildError::Module(_)));
82/// ```
83#[derive(Debug)]
84pub enum BuildError {
85    /// A typed host replay or publication failure, without a candidate model.
86    Recovery(Box<crate::binding::HostRejection>),
87    /// A lexical or syntactic error with its source text and display name.
88    Parse {
89        /// The parser's typed error.
90        error: Box<cel_parser::ParseError>,
91        /// The complete input source.
92        source: String,
93        /// The display name used for the diagnostic header.
94        name: String,
95    },
96    /// A module compilation or instantiation diagnostic.
97    Module(ModuleDiagnostic),
98    /// A fatal initial runtime propagation error.
99    Runtime(Box<RuntimeFailure>),
100    /// Requirements that evaluated to false after propagation.
101    Validation {
102        /// False requirements with their owning source labels.
103        issues: Vec<ValidationIssue>,
104        /// Source owners used to restrict the root display-name override.
105        diagnostics: Box<SheetDiagnostics>,
106        /// Requested display name for the anonymous root source.
107        file_name: String,
108    },
109}
110
111impl BuildError {
112    /// Renders the failure without requiring access to a candidate sheet.
113    ///
114    /// - Complexity: O(rendered source and diagnostic bytes), excluding snippet
115    ///   rendering and the underlying error formatter's costs.
116    ///
117    /// # Examples
118    ///
119    /// ```
120    /// let result = adam_web_ui::build_sheet("sheet s { cell x }", "input.adm2");
121    /// let error = result.err().expect("invalid module");
122    /// assert!(error.render(&adam_web_ui::Renderer::plain()).contains("error"));
123    /// ```
124    pub fn render(&self, renderer: &Renderer) -> String {
125        match self {
126            Self::Recovery(rejection) => match rejection.as_ref() {
127                crate::binding::HostRejection::Input(error) => error.to_string(),
128                crate::binding::HostRejection::Binding(error) => error.to_string(),
129                crate::binding::HostRejection::Validation(issues) => issues
130                    .iter()
131                    .map(|issue| {
132                        format_source_labels(
133                            &format!("{}: {}", issue.key, issue.message),
134                            &issue.labels,
135                            None,
136                            renderer,
137                        )
138                    })
139                    .collect::<Vec<_>>()
140                    .join("\n"),
141                crate::binding::HostRejection::Mutation(failure) => {
142                    let source = failure.diagnostics.anonymous_source();
143                    format_adam_error(
144                        &failure.error,
145                        &failure.diagnostics,
146                        source.map_or("", adam_lang::SourceId::text),
147                        &failure.file_name,
148                        renderer,
149                    )
150                }
151            },
152            Self::Parse {
153                error,
154                source,
155                name,
156            } => format_parse_error(error, source, name, renderer),
157            Self::Module(error) => format_module_diagnostic(error, renderer),
158            Self::Runtime(failure) => {
159                let source = failure.diagnostics.anonymous_source();
160                format_adam_error(
161                    &failure.error,
162                    &failure.diagnostics,
163                    source.map_or("", adam_lang::SourceId::text),
164                    &failure.file_name,
165                    renderer,
166                )
167            }
168            Self::Validation {
169                issues,
170                diagnostics,
171                file_name,
172            } => issues
173                .iter()
174                .map(|issue| format_validation_issue(issue, diagnostics, file_name, renderer))
175                .collect::<Vec<_>>()
176                .join("\n"),
177        }
178    }
179}
180
181/// Builds a [`cel_parser::OpLookup`] with the CEL standard and Euclid libraries installed, so every
182/// adam-lang source [`build_sheet`] parses has the same function set (`min`, `max`, `clamp`,
183/// etc.) available.
184///
185/// Every source parsed through this function therefore has `cel-std` installed — a source
186/// that deliberately relies on the standard library being *absent* cannot use this function
187/// or [`build_sheet`]; construct an `AdamParser` directly with an empty `OpLookup` instead.
188///
189/// - Complexity: O(s²) in the number of installed signatures.
190///
191/// # Examples
192/// ```
193/// let lookup = adam_web_ui::build::op_lookup();
194/// assert!(lookup.record_schema("Rect").is_some());
195/// ```
196pub fn op_lookup() -> cel_parser::OpLookup {
197    let mut lookup = cel_parser::OpLookup::new();
198    cel_std::install(&mut lookup);
199    cel_euclid::install(&mut lookup);
200    lookup
201}
202
203/// Builds the matching scalar and Euclid cell-type environment.
204///
205/// - Complexity: O(t) in the number of registered types.
206///
207/// # Examples
208/// ```
209/// let types = adam_web_ui::build::type_registry();
210/// assert!(types.get("Rect").is_some());
211/// ```
212pub fn type_registry() -> TypeRegistry {
213    let mut types = TypeRegistry::new();
214    cel_euclid::register_adam_types(&mut types);
215    types
216}
217
218/// Parses and initializes a sheet, returning only a fully valid candidate.
219///
220/// `file_name` supplies the display name for diagnostics; it does not locate
221/// the source text.
222///
223/// # Errors
224///
225/// Returns a parse, module, propagation, or requirement-validation failure.
226/// Propagation errors retain their typed `adam_rs::Error` and independent
227/// diagnostics. No error variant contains the failed candidate.
228///
229/// - Complexity: O(n) in source length plus propagation and validation work.
230///
231/// # Examples
232///
233/// ```
234/// let built = adam_web_ui::build_sheet(
235///     "sheet example { cell width: i64 = 10i64; }", "example.adm2",
236/// ).unwrap();
237/// assert!(built.keys.contains_key("width"));
238/// ```
239pub fn build_sheet(source: &str, file_name: &str) -> Result<BuiltSheet, BuildError> {
240    let mut parser = AdamParser::new(type_registry(), op_lookup());
241    let parsed = match parser.parse_str(source) {
242        Ok(p) => p,
243        Err(error) => {
244            if let Some(module) = module_diagnostic(&error) {
245                return Err(BuildError::Module(module.clone()));
246            }
247            return Err(BuildError::Parse {
248                error: Box::new(error),
249                source: source.to_owned(),
250                name: file_name.to_owned(),
251            });
252        }
253    };
254
255    initialize_sheet_with_file_name(parsed, Some(file_name))
256}
257
258/// Finds an owning module diagnostic in a parser error's source chain.
259///
260/// - Complexity: O(h) time for source-chain depth h.
261fn module_diagnostic(error: &cel_parser::ParseError) -> Option<&ModuleDiagnostic> {
262    let mut cause = std::error::Error::source(error);
263    while let Some(error) = cause {
264        if let Some(module) = error.downcast_ref() {
265            return Some(module);
266        }
267        cause = error.source();
268    }
269    None
270}
271
272/// Propagates an explicitly selected parsed root and returns it only if valid.
273///
274/// Capture diagnostics before mutation. If propagation fails, discard the
275/// unspecified candidate and return only its typed error and owned metadata.
276///
277/// # Errors
278///
279/// Returns a runtime or validation error when initial propagation fails or a
280/// requirement evaluates to false.
281///
282/// - Complexity: O(m) metadata snapshot cost plus propagation and validation
283///   work, where m is the retained metadata size.
284///
285/// # Examples
286///
287/// ```
288/// use adam_lang::{AdamParser, TypeRegistry};
289/// let parsed = AdamParser::new(TypeRegistry::new(), cel_parser::OpLookup::new())
290///     .parse_str("sheet example { cell width: i64 = 10i64; }")
291///     .unwrap();
292/// let built = adam_web_ui::initialize_sheet(parsed).unwrap();
293/// assert!(built.keys.contains_key("width"));
294/// ```
295pub fn initialize_sheet(parsed: ParsedSheet) -> Result<BuiltSheet, BuildError> {
296    initialize_sheet_with_file_name(parsed, None)
297}
298
299/// Initializes a parsed sheet while retaining a caller-selected root display name.
300///
301/// - Complexity: O(m) metadata snapshot cost plus propagation and validation
302///   work, where m is the retained metadata size.
303fn initialize_sheet_with_file_name(
304    mut parsed: ParsedSheet,
305    requested_file_name: Option<&str>,
306) -> Result<BuiltSheet, BuildError> {
307    let diagnostics = parsed.diagnostics();
308    let labels = labels_from_cell_names(&parsed.sheet, &parsed.cell_names);
309    let keys = parsed
310        .cell_names
311        .iter()
312        .map(|(name, (id, _))| (name.clone(), *id))
313        .collect();
314    match parsed.propagate() {
315        Ok(()) => {
316            let issues = validation_issues(&parsed);
317            if !issues.is_empty() {
318                return Err(BuildError::Validation {
319                    issues,
320                    file_name: display_file_name(&diagnostics, requested_file_name),
321                    diagnostics: Box::new(diagnostics),
322                });
323            }
324            parsed.clear_changed();
325            Ok(BuiltSheet {
326                file_name: display_file_name(&diagnostics, requested_file_name),
327                parsed,
328                labels,
329                diagnostics,
330                keys,
331            })
332        }
333        Err(error) => Err(BuildError::Runtime(Box::new(RuntimeFailure {
334            error,
335            file_name: display_file_name(&diagnostics, requested_file_name),
336            diagnostics: Box::new(diagnostics),
337        }))),
338    }
339}
340
341/// Selects an explicit root display name or the parser's retained source name.
342///
343/// - Complexity: O(n) in the selected file-name byte length.
344fn display_file_name(diagnostics: &SheetDiagnostics, requested_file_name: Option<&str>) -> String {
345    requested_file_name
346        .map(str::to_owned)
347        .or_else(|| {
348            diagnostics
349                .anonymous_source()
350                .map(|source| source.file_name().to_owned())
351        })
352        .unwrap_or_default()
353}
354
355/// Collects every false requirement from the successfully propagated candidate.
356///
357/// - Complexity: O(c + r) time and O(v) output space for cells c, requirements r,
358///   and violations v.
359pub(crate) fn validation_issues(parsed: &ParsedSheet) -> Vec<ValidationIssue> {
360    let names: HashMap<_, _> = parsed
361        .cell_names
362        .iter()
363        .map(|(name, (id, _))| (*id, name.as_str()))
364        .collect();
365    let mut issues = Vec::new();
366    for cell in parsed.cells() {
367        for requirement_id in parsed.violated_requirements(cell) {
368            let requirement = parsed.requirement_names.get(&requirement_id).cloned();
369            let key = names
370                .get(&cell)
371                .map(|name| (*name).to_owned())
372                .or_else(|| {
373                    parsed
374                        .cell_origins
375                        .get(&cell)
376                        .and_then(|origins| origins.first())
377                        .map(|origin| origin.label.label.clone())
378                })
379                .unwrap_or_else(|| format!("{cell:?}"));
380            let message = match requirement.as_deref() {
381                Some(name) => format!("requirement `{name}` evaluated to false"),
382                None => "requirement evaluated to false".to_string(),
383            };
384            let labels = parsed
385                .requirement_labels
386                .get(&requirement_id)
387                .cloned()
388                .into_iter()
389                .collect();
390            issues.push(ValidationIssue {
391                key,
392                requirement,
393                labels,
394                message,
395            });
396        }
397    }
398    issues
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    /// Rejects a candidate when its first propagation fails.
406    #[test]
407    fn construction_rejects_initial_runtime_failure() {
408        assert!(matches!(
409            build_sheet("sheet s { out x: i64 := 1i64 / 0i64; }", "s.adm2"),
410            Err(BuildError::Runtime(_))
411        ));
412    }
413
414    /// Runtime diagnostics use the requested root display name.
415    #[test]
416    fn runtime_diagnostic_uses_requested_file_name() {
417        let error = build_sheet(
418            "sheet s { cell x: i32 = 0; cell y: i32; relationship { y := 10i32 / x; } }",
419            "s.adm2",
420        )
421        .err()
422        .expect("division by zero rejects construction");
423
424        let rendered = error.render(&Renderer::plain());
425        assert!(rendered.contains("s.adm2"), "{rendered}");
426    }
427
428    /// Rejects a candidate when a requirement is false after propagation.
429    #[test]
430    fn construction_rejects_initial_requirement_violation() {
431        let result = build_sheet(
432            "sheet s { cell x: i64 = -1i64 require { @positive x > 0i64; }; }",
433            "s.adm2",
434        );
435        let Err(error) = result else {
436            panic!("false initial requirement must reject construction");
437        };
438        let BuildError::Validation { issues, .. } = &error else {
439            panic!("false initial requirement must be Validation");
440        };
441        assert_eq!(issues.len(), 1);
442        assert_eq!(issues[0].key, "x");
443        assert_eq!(issues[0].requirement.as_deref(), Some("positive"));
444        assert!(
445            issues[0].labels.iter().any(|label| {
446                label
447                    .location
448                    .as_ref()
449                    .is_some_and(|location| location.source.text().contains("@positive"))
450            }),
451            "validation issue should retain its authored requirement source"
452        );
453        assert!(
454            error
455                .render(&Renderer::plain())
456                .contains("requirement `positive` evaluated to false")
457        );
458    }
459
460    /// Validation diagnostics use the requested root display name.
461    #[test]
462    fn validation_diagnostic_uses_requested_file_name() {
463        let error = build_sheet(
464            "sheet s { cell x: i64 = -1i64 require { @positive x > 0i64; }; }",
465            "s.adm2",
466        )
467        .err()
468        .expect("false requirement rejects construction");
469
470        let rendered = error.render(&Renderer::plain());
471        assert!(rendered.contains("s.adm2"), "{rendered}");
472    }
473
474    /// The opted-in host builds registered fields, members, and typed closures.
475    #[test]
476    fn geometry_sheet_builds_in_opted_in_host() {
477        let built = build_sheet(
478            "sheet s { out x := (|p: Point2D| p.x)(Point2D { y: 2.0, x: 1.0 }); out n := min(3.0, 4.0); }",
479            "geometry.adm2",
480        )
481        .unwrap();
482        assert_eq!(
483            *built
484                .parsed
485                .read::<f64>(built.parsed.cell_names["x"].0)
486                .unwrap(),
487            1.0
488        );
489        for actual in [
490            include_str!("../../cel-euclid/examples/crop_straighten.adm2"),
491            include_str!("../../cel-euclid/examples/pan_zoom.adm2"),
492        ] {
493            build_sheet(actual, "geometry.adm2").unwrap();
494        }
495    }
496
497    const VALID_SOURCE: &str = r#"
498        sheet s {
499            cell a: f64 = 2.0;
500            cell b: f64 = 3.0;
501            cell c: f64;
502            relationship {
503                c := a * b;
504                a := c / b;
505                b := c / a;
506            }
507        }
508    "#;
509
510    #[test]
511    /// Valid source builds and propagates without a diagnostic.
512    fn build_sheet_valid_source_succeeds_with_no_error() {
513        let built = build_sheet(VALID_SOURCE, "test.adm2").unwrap();
514        assert!(built.keys.contains_key("a"));
515    }
516
517    #[test]
518    /// Module failures return typed errors that render a source-located diagnostic.
519    fn build_sheet_module_error_has_no_sheet_and_formatted_message() {
520        let error = build_sheet("sheet s { cell x }", "test.adm2")
521            .err()
522            .expect("expected module error");
523        assert!(matches!(error, BuildError::Module(_)), "{error:?}");
524        let msg = error.render(&Renderer::styled());
525        assert!(msg.contains("error"), "{msg}");
526    }
527
528    #[test]
529    /// Propagation failures return no candidate and retain the typed error.
530    fn build_sheet_runtime_error_rejects_candidate() {
531        let source = "sheet s { cell x: i32 = 0; cell y: i32; relationship { y := 10i32 / x; } }";
532        let error = build_sheet(source, "test.adm2")
533            .err()
534            .expect("expected runtime error");
535        let BuildError::Runtime(failure) = error else {
536            panic!("expected runtime failure");
537        };
538        assert!(matches!(failure.error, Error::MethodFailed { .. }));
539        assert!(!failure.diagnostics.locate_error(&failure.error).is_empty());
540    }
541
542    #[test]
543    /// Plain module diagnostics contain no terminal escape sequences.
544    fn build_sheet_plain_renderer_module_error_has_no_ansi_escape_codes() {
545        let msg = build_sheet("sheet s { cell x }", "test.adm2")
546            .err()
547            .expect("expected parse error")
548            .render(&Renderer::plain());
549        assert!(
550            !msg.contains('\u{1b}'),
551            "expected no ANSI escapes, got: {msg}"
552        );
553    }
554
555    #[test]
556    /// Plain runtime diagnostics contain no terminal escape sequences.
557    fn build_sheet_plain_renderer_runtime_error_has_no_ansi_escape_codes() {
558        let source = "sheet s { cell x: i32 = 0; cell y: i32; relationship { y := 10i32 / x; } }";
559        let msg = build_sheet(source, "test.adm2")
560            .err()
561            .expect("expected propagation error")
562            .render(&Renderer::plain());
563        assert!(
564            !msg.contains('\u{1b}'),
565            "expected no ANSI escapes, got: {msg}"
566        );
567    }
568
569    #[test]
570    /// Cycle diagnostics identify both relationships' binding spans.
571    fn build_sheet_cycle_names_both_relationships_bindings_in_the_backtrace() {
572        // Two relationships forming an algebraic loop with no external source for
573        // either cell: `x` needs `y` and `y` needs `x`, so `propagate` can't pick a
574        // valid method assignment and returns a multi-span `Error::Cycle` backtrace
575        // naming both bindings.
576        let source = "sheet s { cell x: i32 = 0; cell y: i32 = 0; \
577            relationship { x := y + 1i32; } relationship { y := x + 1i32; } }";
578        let msg = build_sheet(source, "test.adm2")
579            .err()
580            .expect("expected cycle error")
581            .render(&Renderer::plain());
582        assert!(msg.contains("x :=") && msg.contains("y :="), "{msg}");
583    }
584}