Skip to main content

adam_lang/
typecheck.rs

1//! Checks standalone Adam sheets through the shared data-only symbolic backend.
2
3use crate::{TypeRegistry, ast::Sheet};
4use cel_parser::{OpLookup, ParseError, checking::MetadataAvailability};
5
6/// Projects runtime registrations and checks a sheet without application callbacks.
7///
8/// Projection failures and incomplete prerequisites produce explicit diagnostics.
9/// Match-key value comparisons and graph solvability remain runtime checks.
10///
11/// - Complexity: Environment projection plus symbolic body and dependency checking.
12///
13/// # Examples
14/// ```
15/// let sheet = adam_lang::AdamAstParser::new()
16///     .parse_str("sheet app { cell x: i32 = true; }").unwrap();
17/// assert!(!adam_lang::check_sheet(&sheet, &adam_lang::TypeRegistry::new(),
18///     &cel_parser::OpLookup::new()).is_empty());
19/// ```
20pub fn check_sheet(sheet: &Sheet, registry: &TypeRegistry, lookup: &OpLookup) -> Vec<ParseError> {
21    match crate::checking_environment(registry, lookup) {
22        Ok(environment) => {
23            let report = crate::check_sheet_with_environment(
24                sheet,
25                &environment,
26                MetadataAvailability::Complete,
27            );
28            report
29                .diagnostics
30                .into_iter()
31                .chain(report.incomplete)
32                .collect()
33        }
34        Err(error) => {
35            let mut errors = vec![ParseError::new(error.to_string(), sheet.name_span.start)];
36            if let Ok(environment) = crate::checking_environment(registry, &OpLookup::new()) {
37                let report = crate::check_sheet_with_environment(
38                    sheet,
39                    &environment,
40                    MetadataAvailability::Unavailable,
41                );
42                errors.extend(report.diagnostics);
43                errors.extend(report.incomplete);
44            }
45            errors
46        }
47    }
48}
49
50#[cfg(test)]
51/// Reports lexical references in legacy syntax fixtures, independently of resolution.
52fn expr_references_ident(expr: &cel_parser::Expr, name: &str) -> bool {
53    use cel_parser::Expr;
54    match expr {
55        Expr::Literal { .. } => false,
56        Expr::Ident { name: ident, .. } => ident == name,
57        Expr::Struct { fields, .. } => fields
58            .iter()
59            .any(|field| expr_references_ident(&field.value, name)),
60        Expr::Op { operands, .. } => operands.iter().any(|e| expr_references_ident(e, name)),
61        Expr::Apply { callee, args, .. } => {
62            expr_references_ident(callee, name)
63                || args.iter().any(|e| expr_references_ident(e, name))
64        }
65        Expr::Member { receiver, args, .. } => {
66            expr_references_ident(receiver, name)
67                || args
68                    .iter()
69                    .flatten()
70                    .any(|e| expr_references_ident(e, name))
71        }
72        Expr::Tuple { elements, .. } => elements.iter().any(|e| expr_references_ident(e, name)),
73        Expr::Array { elements, .. } => elements.iter().any(|e| expr_references_ident(e, name)),
74        Expr::TupleIndex { base, .. } => expr_references_ident(base, name),
75        Expr::If {
76            cond,
77            then_branch,
78            else_branch,
79            ..
80        } => {
81            expr_references_ident(cond, name)
82                || expr_references_ident(then_branch, name)
83                || else_branch
84                    .as_deref()
85                    .is_some_and(|e| expr_references_ident(e, name))
86        }
87        Expr::Logical { lhs, rhs, .. } => {
88            expr_references_ident(lhs, name) || expr_references_ident(rhs, name)
89        }
90        Expr::Cast { expr, .. } => expr_references_ident(expr, name),
91        Expr::Closure { params, body, .. } => {
92            !params.iter().any(|param| param.name == name) && expr_references_ident(body, name)
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::AdamAstParser;
101
102    /// Parses a semantic fixture without accepting syntax-recovery placeholders.
103    fn parse(source: &str) -> Sheet {
104        let sheet = AdamAstParser::new().parse_str(source).unwrap();
105        assert!(sheet.errors.is_empty(), "{:?}", sheet.errors);
106        sheet
107    }
108
109    /// Supplies a registered leaf distinct from the built-in scalar types.
110    #[derive(Clone, Debug, PartialEq)]
111    struct Custom(i32);
112
113    /// Accepts an initializer matching its cell annotation.
114    #[test]
115    fn cell_initializer_matching_its_annotation_has_no_diagnostic() {
116        let sheet = parse("sheet s { cell x: i32 = 1; }");
117        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
118        assert!(diags.is_empty());
119    }
120
121    /// Diagnoses a cell initializer that conflicts with its annotation.
122    #[test]
123    fn cell_initializer_mismatched_with_its_annotation_is_a_diagnostic() {
124        // Unsuffixed float literal defaults to f64, not i32.
125        let sheet = parse("sheet s { cell x: i32 = 1.0; }");
126        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
127        assert_eq!(diags.len(), 1);
128    }
129
130    /// Diagnoses a source initializer that conflicts with its annotation.
131    #[test]
132    fn source_initializer_mismatched_with_its_annotation_is_a_diagnostic() {
133        // Unsuffixed float literal defaults to f64, not i32.
134        let sheet = parse("sheet s { source x: i32 = 1.0; }");
135        let diagnostics = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
136        assert_eq!(diagnostics.len(), 1);
137    }
138
139    /// Resolves registered custom leaves within array annotations.
140    #[test]
141    fn custom_array_annotations_use_the_registry_type_resolver() {
142        let sheet = parse(
143            "sheet s { \
144                out values := []: [Custom]; \
145                out nested := [[]: [Custom]]: [[Custom]]; \
146            }",
147        );
148        let mut registry = TypeRegistry::new();
149        registry.register_no_default::<Custom>("Custom").unwrap();
150
151        let diagnostics = check_sheet(&sheet, &registry, &cel_parser::OpLookup::new());
152        assert!(diagnostics.is_empty(), "{diagnostics:?}");
153    }
154
155    /// Rejects differing custom leaf types despite matching array structure.
156    #[test]
157    fn custom_array_annotations_reject_exact_scalar_type_mismatches() {
158        let sheet = parse("sheet s { out values := [1]: [Custom]; }");
159        let mut registry = TypeRegistry::new();
160        registry.register_no_default::<Custom>("Custom").unwrap();
161
162        let diagnostics = check_sheet(&sheet, &registry, &cel_parser::OpLookup::new());
163        assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
164        assert!(
165            diagnostics[0]
166                .message()
167                .contains("expected `Custom`, found `i32`"),
168            "got: {}",
169            diagnostics[0].message()
170        );
171    }
172
173    /// Diagnoses an unknown custom leaf in an array annotation.
174    #[test]
175    fn unknown_custom_array_annotation_type_is_reported() {
176        let sheet = parse("sheet s { out values := []: [Missing]; }");
177        let diagnostics = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
178        assert_eq!(diagnostics.len(), 1);
179        assert!(
180            diagnostics[0].message().contains("unknown type `Missing`"),
181            "got: {}",
182            diagnostics[0].message()
183        );
184    }
185
186    /// Accepts arrays whose elements have tuple annotations.
187    #[test]
188    fn tuple_typed_array_annotations_are_accepted_by_cel_checking() {
189        let sheet = parse("sheet s { out values := []: [(i32, f64)]; }");
190        let diagnostics = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
191        assert!(diagnostics.is_empty(), "{diagnostics:?}");
192    }
193
194    /// Diagnoses a non-Boolean cell requirement.
195    #[test]
196    fn cell_requirement_non_bool_body_is_a_diagnostic() {
197        let sheet = parse("sheet s { cell x: i32 = 5 require { x, positive; }; }");
198        let diagnostics = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
199        assert_eq!(diagnostics.len(), 1);
200    }
201
202    /// Checks non-literal cell initializer expressions.
203    #[test]
204    fn cell_initializer_non_literal_expression_is_checked() {
205        let sheet = parse("sheet s { cell x: f64 = 1 + 2; }");
206        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
207        let messages: Vec<&str> = diags.iter().map(cel_parser::ParseError::message).collect();
208        assert_eq!(
209            messages,
210            ["cell `x`: initializer: type mismatch: expected `f64`, got `i32`"]
211        );
212    }
213
214    /// Retains array element errors and the independently known array-result mismatch.
215    #[test]
216    fn cell_initializer_array_annotation_diagnostics_still_surface() {
217        let sheet = parse("sheet s { cell x: f64 = [0, 1]: [f64]; }");
218        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
219        let messages: Vec<&str> = diags.iter().map(cel_parser::ParseError::message).collect();
220        assert_eq!(
221            messages,
222            [
223                "array elements must match the annotation exactly: expected `f64`, found `i32`",
224                "cell `x`: initializer: type mismatch: expected `f64`, got `[f64]`",
225            ]
226        );
227    }
228
229    /// Accepts an annotation-only cell without inventing initializer diagnostics.
230    #[test]
231    fn cell_with_only_an_annotation_has_nothing_to_cross_check() {
232        let sheet = parse("sheet s { cell x: i32; }");
233        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
234        assert!(diags.is_empty());
235    }
236
237    /// Diagnoses a default signed integer literal assigned to an unsigned cell.
238    #[test]
239    fn cell_initializer_unsuffixed_int_literal_mismatched_with_a_declared_unsigned_type_is_a_diagnostic()
240     {
241        // adam_lang::parser's real cell_decl grammar requires the initializer's inferred type to
242        // equal the declared type exactly, no int-width coercion. An unsuffixed integer literal
243        // always infers as `i32`, so it mismatches a `u32` annotation; `cell x: u32 = 1;` is
244        // rejected by the real parser, and the checker must flag it too.
245        let sheet = parse("sheet s { cell x: u32 = 1; }");
246        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
247        assert_eq!(diags.len(), 1);
248    }
249
250    /// Diagnoses an integer literal assigned to a floating-point cell.
251    #[test]
252    fn cell_initializer_unsuffixed_int_literal_mismatched_with_a_declared_float_type_is_a_diagnostic()
253     {
254        // Same exact-type rule as above, but across the int/float boundary: an unsuffixed integer
255        // literal infers as `i32`, never as `f64`, so no int-to-float coercion is allowed either.
256        let sheet = parse("sheet s { cell x: f64 = 1; }");
257        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
258        assert_eq!(diags.len(), 1);
259    }
260
261    /// Diagnoses character literals incompatible with registered cell types.
262    #[test]
263    fn cell_initializer_char_literal_against_any_registered_type_is_a_diagnostic() {
264        // adam-lang's real parser has no rule accepting a char literal against any registered
265        // type, so the checker must flag it too.
266        let sheet = parse("sheet s { cell x: i32 = 'a'; }");
267        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
268        assert_eq!(diags.len(), 1);
269    }
270
271    /// Rejects unknown annotations when the effective environment is complete.
272    #[test]
273    fn cell_annotated_with_an_unregistered_type_name_is_rejected() {
274        let sheet = parse("sheet s { cell x: WidgetHandle = 1; }");
275        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
276        assert!(
277            diags
278                .iter()
279                .any(|error| error.message().contains("unknown type"))
280        );
281    }
282
283    /// Accepts a scalar binding matching its declared output type.
284    #[test]
285    fn binding_single_output_matching_declared_type_has_no_diagnostic() {
286        let sheet = parse(
287            "sheet s { cell width: f64; cell height: f64; cell area: f64; \
288             relationship { area := width * height; } }",
289        );
290        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
291        assert!(diags.is_empty());
292    }
293
294    /// Diagnoses a scalar binding that conflicts with its declared output.
295    #[test]
296    fn binding_single_output_mismatched_with_declared_type_is_a_diagnostic() {
297        let sheet = parse(
298            "sheet s { cell width: f64; cell height: f64; cell area: i32; \
299             relationship { area := width * height; } }",
300        );
301        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
302        assert_eq!(diags.len(), 1);
303    }
304
305    /// Accepts a destructuring binding with matching tuple elements.
306    #[test]
307    fn binding_multi_output_matching_tuple_has_no_diagnostic() {
308        let sheet = parse(
309            "sheet s { cell a: i32; cell b: i32; cell sum: i32; cell diff: i32; \
310             relationship { (sum, diff) := (a + b, a - b); } }",
311        );
312        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
313        assert!(diags.is_empty());
314    }
315
316    /// Complete call-result shapes check arity and leaves without suppressing body errors.
317    #[test]
318    fn binding_multi_output_iife_defers_unknown_shape_but_checks_children() {
319        for (body, expected) in [
320            ("(|x: i32| (x, x))(1)", 0),
321            ("(|x: i32| (x, true + x))(1)", 1),
322            ("(|x: i32| (x, true))(1)", 1),
323            ("(|x: i32| (x,))(1)", 1),
324            ("1", 1),
325            ("(1, 2, 3)", 1),
326        ] {
327            let sheet = parse(&format!(
328                "sheet s {{ cell a: i32; cell b: i32; relationship {{ (a,b) := {body}; }} }}"
329            ));
330            let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
331            assert_eq!(diags.len(), expected, "{body}: {diags:?}");
332        }
333    }
334
335    /// Inferred tuple call results satisfy matching annotations and reject mismatched leaves.
336    #[test]
337    fn tuple_call_results_match_declared_shapes() {
338        for (annotation, expected) in [("(i32, i32)", 0), ("(i32, bool)", 1)] {
339            let sheet = parse(&format!(
340                "sheet s {{ cell pair: {annotation} = (|x: i32| (x,x))(1); }}"
341            ));
342            let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
343            assert_eq!(diags.len(), expected, "{annotation}: {diags:?}");
344        }
345    }
346
347    /// Diagnoses destructuring with the wrong tuple arity.
348    #[test]
349    fn binding_multi_output_arity_mismatch_is_a_diagnostic() {
350        let sheet = parse(
351            "sheet s { cell a: i32; cell b: i32; cell sum: i32; cell diff: i32; \
352             relationship { (sum, diff) := a + b; } }",
353        );
354        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
355        assert_eq!(diags.len(), 1);
356    }
357
358    /// Diagnoses a tuple body assigned to a declared scalar output.
359    #[test]
360    fn binding_single_output_with_a_tuple_shaped_body_is_a_diagnostic() {
361        // Body is a 2-tuple but only 1 output is declared: `check_expr` would otherwise infer
362        // `Ty::Any` for the tuple and let this slip through with no diagnostic at all.
363        let sheet = parse(
364            "sheet s { cell a: i32; cell b: i32; cell out: i32; \
365             relationship { out := (a, b); } }",
366        );
367        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
368        assert_eq!(diags.len(), 1);
369    }
370
371    /// Diagnoses incompatible element types in a destructured result.
372    #[test]
373    fn binding_multi_output_per_element_type_mismatch_is_a_diagnostic() {
374        let sheet = parse(
375            "sheet s { cell a: i32; cell b: i32; cell sum: i32; cell diff: f64; \
376             relationship { (sum, diff) := (a + b, a - b); } }",
377        );
378        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
379        assert_eq!(diags.len(), 1);
380    }
381
382    /// Retains operator diagnostics from relationship expressions.
383    #[test]
384    fn an_operator_error_inside_a_binding_body_surfaces() {
385        let sheet = parse(
386            "sheet s { cell name: String; cell count: i32; cell out: i32; \
387             relationship { out := name + count; } }",
388        );
389        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
390        assert_eq!(diags.len(), 1);
391    }
392
393    /// Accepts valid branch bodies and diagnoses a distinct mismatch in each branch.
394    #[test]
395    fn conditional_branch_and_default_bindings_are_both_checked() {
396        let sheet = parse(
397            "sheet s { cell mode: i32; cell a: i32; cell b: i32; cell out: i32; \
398             conditional mode { \
399                 0i32 => { relationship { out := a; } } \
400                 _ => { relationship { out := b; } } \
401             } }",
402        );
403        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
404        assert!(diags.is_empty());
405        let invalid = parse(
406            "sheet s { cell mode: i32; cell a: bool; cell b: f64; cell out: i32; \
407             conditional mode { \
408                 0i32 => { relationship { out := a; } } \
409                 _ => { relationship { out := b; } } \
410             } }",
411        );
412        let diags = check_sheet(&invalid, &TypeRegistry::new(), &cel_parser::OpLookup::new());
413        assert_eq!(diags.len(), 2);
414    }
415
416    /// Permits bindings to cells without explicit type annotations.
417    #[test]
418    fn a_cell_with_no_type_annotation_unifies_with_anything_used_in_a_binding() {
419        // `cell a = 1;` has an initializer but no `: type_name` — declared_cell_types maps it to
420        // Ty::Any, which must unify silently with `out`'s declared `i32`.
421        let sheet = parse(
422            "sheet s { cell a = 1; cell out: i32; \
423             relationship { out := a; } }",
424        );
425        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
426        assert!(diags.is_empty());
427    }
428
429    /// Skips syntax-recovery placeholders during semantic checking.
430    #[test]
431    fn recovered_error_items_are_skipped_without_panicking() {
432        let sheet = AdamAstParser::new()
433            .parse_str(
434                "sheet s { cell good: i32 = 1; cell bad unknown_syntax cell after: i32 = 2; }",
435            )
436            .unwrap();
437        assert!(
438            !sheet.errors.is_empty(),
439            "fixture must actually recover an error item"
440        );
441        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
442        assert!(diags.is_empty());
443    }
444
445    /// Accepts an output body matching its explicit annotation.
446    #[test]
447    fn out_body_matching_its_annotation_has_no_diagnostic() {
448        let sheet = parse(
449            "sheet s { cell width: f64; cell height: f64; \
450             out area: f64 := width * height; }",
451        );
452        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
453        assert!(diags.is_empty());
454    }
455
456    /// Diagnoses an output body that conflicts with its annotation.
457    #[test]
458    fn out_body_mismatched_with_its_annotation_is_a_diagnostic() {
459        let sheet = parse(
460            "sheet s { cell width: f64; cell height: f64; \
461             out area: i32 := width * height; }",
462        );
463        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
464        assert_eq!(diags.len(), 1);
465    }
466
467    /// Accepts an output whose type is inferred from its body.
468    #[test]
469    fn out_with_no_annotation_infers_its_type_and_has_no_diagnostic() {
470        // No `: type_name` to cross-check against — nothing to flag, and a later reference to
471        // `area`'s name (were one added) would resolve through the inferred f64, not Ty::Any.
472        let sheet = parse(
473            "sheet s { cell width: f64; cell height: f64; \
474             out area := width * height; }",
475        );
476        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
477        assert!(diags.is_empty());
478    }
479
480    /// Accepts a Boolean requirement body.
481    #[test]
482    fn requirement_with_bool_body_has_no_diagnostic() {
483        let sheet = parse(
484            "sheet s { cell width: f64; cell max_width: f64; \
485             out area: f64 := width require { \
486                 width <= max_width, max_width; \
487             }; }",
488        );
489        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
490        assert!(diags.is_empty());
491    }
492
493    /// Diagnoses a non-Boolean labeled requirement.
494    #[test]
495    fn requirement_with_non_bool_body_is_a_diagnostic() {
496        let sheet = parse(
497            "sheet s { cell width: f64; \
498             out area: f64 := width require { \
499                 width, bogus; \
500             }; }",
501        );
502        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
503        assert_eq!(diags.len(), 1);
504    }
505
506    /// Diagnoses a non-Boolean unlabeled requirement.
507    #[test]
508    fn unlabeled_requirement_with_non_bool_body_is_a_diagnostic() {
509        let sheet = parse(
510            "sheet s { cell width: f64; \
511             out area: f64 := width require { \
512                 width; \
513             }; }",
514        );
515        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
516        assert_eq!(diags.len(), 1);
517    }
518
519    /// Accepts a tuple initializer matching its annotation.
520    #[test]
521    fn cell_tuple_initializer_matching_its_annotation_has_no_diagnostic() {
522        let sheet = parse("sheet s { cell a: (i32, f64) = (1, 2.5); }");
523        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
524        assert!(diags.is_empty());
525    }
526
527    /// Diagnoses tuple initializer arity mismatch.
528    #[test]
529    fn cell_tuple_initializer_arity_mismatch_is_a_diagnostic() {
530        let sheet = parse("sheet s { cell a: (i32, f64, i32) = (1, 2.5); }");
531        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
532        assert_eq!(diags.len(), 1);
533    }
534
535    /// Diagnoses tuple initializer element-type mismatch.
536    #[test]
537    fn cell_tuple_initializer_element_type_mismatch_is_a_diagnostic() {
538        let sheet = parse("sheet s { cell a: (i32, i32) = (1, 2.5); }");
539        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
540        assert_eq!(diags.len(), 1);
541    }
542
543    /// Accepts a nested tuple initializer matching its recursive annotation.
544    #[test]
545    fn cell_nested_tuple_initializer_matching_its_annotation_has_no_diagnostic() {
546        let sheet = parse("sheet s { cell a: (i32, (f64, String)) = (1, (2.5, \"x\")); }");
547        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
548        assert!(diags.is_empty());
549    }
550
551    /// Accepts a cell filter with matching candidate and result types.
552    #[test]
553    fn filter_with_matching_types_has_no_diagnostic() {
554        let sheet = parse("sheet s { cell a: i32 = 1 filter _; }");
555        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
556        assert!(diags.is_empty());
557    }
558
559    /// Accepts a source filter with matching candidate and result types.
560    #[test]
561    fn filter_with_matching_types_on_a_source_has_no_diagnostic() {
562        let sheet = parse("sheet s { source a: i32 = 1 filter _; }");
563        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
564        assert!(diags.is_empty());
565    }
566
567    /// Resolves named cell dependencies within filters.
568    #[test]
569    fn filter_referencing_a_cell_has_no_diagnostic() {
570        let sheet = parse(
571            "sheet s { cell hi: i32 = 100; cell a: i32 = 1 filter if _ > hi { hi } else { _ }; }",
572        );
573        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
574        assert!(diags.is_empty());
575    }
576
577    /// Diagnoses a cell filter returning an incompatible type.
578    #[test]
579    fn filter_body_type_mismatch_is_a_diagnostic() {
580        // Body is `bool`-typed (a comparison), but `a` is declared `i32`.
581        let sheet = parse("sheet s { cell a: i32 = 1 filter _ > 0; }");
582        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
583        assert_eq!(diags.len(), 1);
584    }
585
586    /// Diagnoses a non-range cell filter without a candidate reference.
587    #[test]
588    fn filter_without_underscore_is_a_diagnostic() {
589        let sheet = parse("sheet s { cell a: i32 = 1 filter 1; }");
590        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
591        assert_eq!(diags.len(), 1);
592    }
593
594    /// A closure parameter hides value references, not labels or type names.
595    #[test]
596    fn closure_parameter_shadows_only_value_references() {
597        for (source, references) in [
598            ("|_: i32| _", false),
599            ("|x: i32| _", true),
600            ("|_: i32| value._", false),
601            ("|_: i32| _ { x: value }", false),
602            ("|x: i32| Record { x: _ }.x", true),
603        ] {
604            let expr =
605                cel_parser::Parser::<cel_parser::AstContext>::new(cel_parser::OpLookup::new())
606                    .parse_str_ast(source)
607                    .unwrap();
608            assert_eq!(expr_references_ident(&expr, "_"), references, "{source}");
609        }
610    }
611
612    /// Verifies record values contribute dependencies, while constructor and field labels do not.
613    #[test]
614    fn record_filter_dependencies_only_visit_field_values() {
615        let sheet = parse("sheet s { cell a: i32 = 1 filter Record { value: _ }; }");
616        let diagnostics = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
617        assert_eq!(diagnostics.len(), 1);
618        assert!(diagnostics[0].message().contains("unknown record type"));
619        for source in [
620            "sheet s { cell a: i32 = 1 filter Record { _: 1 }; }",
621            "sheet s { cell a: i32 = 1 filter _ { value: 1 }; }",
622        ] {
623            let sheet = parse(source);
624            let diagnostics =
625                check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
626            assert_eq!(diagnostics.len(), 1);
627            assert!(diagnostics[0].message().contains("unknown record type"));
628        }
629    }
630
631    /// Diagnoses an output filter returning an incompatible type.
632    #[test]
633    fn filter_body_type_mismatch_on_an_out_is_a_diagnostic() {
634        // Mirrors `filter_body_type_mismatch_is_a_diagnostic`, but for an `out`'s filter clause:
635        // body is `bool`-typed (a comparison), but `area` is declared `i32`.
636        let sheet = parse("sheet s { cell width: i32 = 1; out area: i32 := width filter _ > 0; }");
637        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
638        assert_eq!(diags.len(), 1);
639    }
640
641    /// Diagnoses a non-range output filter without a candidate reference.
642    #[test]
643    fn filter_without_underscore_on_an_out_is_a_diagnostic() {
644        // Mirrors `filter_without_underscore_is_a_diagnostic`, but for an `out`'s filter clause.
645        let sheet = parse("sheet s { cell width: i32 = 1; out area: i32 := width filter 1; }");
646        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
647        assert_eq!(diags.len(), 1);
648    }
649
650    /// Diagnoses a source filter returning an incompatible type.
651    #[test]
652    fn filter_body_type_mismatch_on_a_source_is_a_diagnostic() {
653        // Mirrors `filter_body_type_mismatch_is_a_diagnostic`, but for a `source`'s filter
654        // clause: body is `bool`-typed (a comparison), but `a` is declared `i32`.
655        let sheet = parse("sheet s { source a: i32 = 1 filter _ > 0; }");
656        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
657        assert_eq!(diags.len(), 1);
658    }
659
660    /// Diagnoses a non-range source filter without a candidate reference.
661    #[test]
662    fn filter_without_underscore_on_a_source_is_a_diagnostic() {
663        // Mirrors `filter_without_underscore_is_a_diagnostic`, but for a `source`'s filter
664        // clause.
665        let sheet = parse("sheet s { source a: i32 = 1 filter 1; }");
666        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
667        assert_eq!(diags.len(), 1);
668    }
669
670    /// Accepts a filter on a tuple-valued cell.
671    #[test]
672    fn filter_on_a_tuple_typed_cell_is_supported() {
673        let sheet = parse("sheet s { cell a: (i32, f64) = (1, 2.5) filter (_.0, _.1); }");
674        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
675        assert!(diags.is_empty());
676    }
677
678    /// Recognizes candidate references nested inside calls.
679    #[test]
680    fn filter_references_underscore_nested_inside_a_call_has_no_missing_underscore_diagnostic() {
681        // `_` appears only inside an `if`'s then-branch, not as the whole body or a bare
682        // operand — exercises `expr_references_ident`'s `Expr::If` arm specifically.
683        let sheet = parse("sheet s { cell a: i32 = 1 filter if true { _ } else { 1 }; }");
684        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
685        assert!(diags.is_empty());
686    }
687
688    /// Verifies filter identifier walks visit receivers and arguments, but not member labels.
689    #[test]
690    fn member_filter_references_are_operands_not_labels() {
691        for body in ["_.accessor", "value.accessor(_)", "_.accessor()"] {
692            let sheet = parse(&format!("sheet s {{ cell value: i32 = 1 filter {body}; }}"));
693            assert!(
694                check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new())
695                    .iter()
696                    .all(|error| !error.message().contains("must reference `_`")),
697                "{body}"
698            );
699        }
700        let sheet = parse("sheet s { cell value: i32 = 1 filter value._; }");
701        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
702        assert_eq!(diags.len(), 2, "{diags:?}");
703        assert!(diags.iter().any(|error| error.message().contains("cycle")));
704    }
705
706    /// Accepts a direct binding with a matching tuple-valued body.
707    #[test]
708    fn binding_single_tuple_typed_output_matching_body_has_no_diagnostic() {
709        let sheet = parse(
710            "sheet s { cell a: i32; cell b: i32; cell pair: (i32, i32); \
711             relationship { pair := (a, b); } }",
712        );
713        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
714        assert!(diags.is_empty());
715    }
716
717    /// Diagnoses an element mismatch in a directly assigned tuple.
718    #[test]
719    fn binding_single_tuple_typed_output_element_type_mismatch_is_a_diagnostic() {
720        let sheet = parse(
721            "sheet s { cell a: i32; cell b: f64; cell pair: (i32, i32); \
722             relationship { pair := (a, b); } }",
723        );
724        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
725        assert_eq!(diags.len(), 1);
726    }
727
728    /// Accepts matching tuple shapes in both conditional-expression arms.
729    #[test]
730    fn binding_single_tuple_typed_output_if_else_body_matching_both_branches_has_no_diagnostic() {
731        let sheet = parse(
732            "sheet s { cell cond: bool; cell a: i32; cell b: i32; cell pair: (i32, i32); \
733             relationship { pair := \
734                 if cond { (a, b) } else { (b, a) }; \
735             } }",
736        );
737        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
738        assert!(diags.is_empty());
739    }
740
741    /// Rejects a tuple-valued then arm against the implicit unit-valued else arm.
742    #[test]
743    fn binding_single_tuple_typed_output_without_else_rejects_implicit_unit() {
744        let sheet = parse(
745            "sheet s { cell cond: bool; cell a: i32; cell b: i32; cell pair: (i32, i32); \
746             relationship { pair := \
747                 if cond { (a, b) }; \
748             } }",
749        );
750        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
751        assert!(
752            diags
753                .iter()
754                .any(|error| error.message().contains("if branch type mismatch"))
755        );
756    }
757
758    /// Accepts matching tuple shapes throughout an else-if chain.
759    #[test]
760    fn binding_single_tuple_typed_output_if_else_if_chain_matching_all_branches_has_no_diagnostic()
761    {
762        let sheet = parse(
763            "sheet s { cell mode: i32; cell a: i32; cell b: i32; cell pair: (i32, i32); \
764             relationship { pair := \
765                 if mode == 0 { (a, b) } else if mode == 1 { (b, a) } else { (0, 0) }; \
766             } }",
767        );
768        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
769        assert!(diags.is_empty());
770    }
771
772    /// Reports independent tuple-element mismatches from both conditional arms.
773    #[test]
774    fn binding_single_tuple_typed_output_if_else_body_element_mismatch_in_each_branch_is_two_diagnostics()
775     {
776        // Both branches use the same mismatched `c`, so a correctly recursing checker reports one
777        // diagnostic per branch (2 total). The old catch-all — which never recursed into an
778        // `Expr::If` at all — could only ever report exactly 1 diagnostic for the whole node
779        // regardless of how many branches were wrong, so `diags.len() == 2` distinguishes the fix
780        // from the bug (unlike asserting `== 1`, which both the buggy and fixed behavior satisfy
781        // when only one branch mismatches).
782        let sheet = parse(
783            "sheet s { cell cond: bool; cell a: i32; cell c: f64; cell pair: (i32, i32); \
784             relationship { pair := \
785                 if cond { (a, c) } else { (a, c) }; \
786             } }",
787        );
788        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
789        assert_eq!(diags.len(), 2);
790    }
791
792    /// Accepts matching destructured tuple shapes in both conditional arms.
793    #[test]
794    fn binding_multi_output_if_else_body_matching_both_branches_has_no_diagnostic() {
795        let sheet = parse(
796            "sheet s { cell cond: bool; cell a: i32; cell b: i32; cell sum: i32; cell diff: i32; \
797             relationship { (sum, diff) := \
798                 if cond { (a + b, a - b) } else { (a - b, a + b) }; \
799             } }",
800        );
801        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
802        assert!(diags.is_empty());
803    }
804
805    /// Diagnoses a destructured element mismatch in one conditional arm.
806    #[test]
807    fn binding_multi_output_if_else_body_element_mismatch_in_a_branch_is_a_diagnostic() {
808        let sheet = parse(
809            "sheet s { cell cond: bool; cell a: i32; cell b: i32; cell c: f64; \
810             cell sum: i32; cell diff: i32; \
811             relationship { (sum, diff) := \
812                 if cond { (a, b) } else { (a, c) }; \
813             } }",
814        );
815        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
816        assert_eq!(diags.len(), 1);
817    }
818
819    /// Accepts singleton tuple destructuring with a matching element.
820    #[test]
821    fn binding_single_element_tuple_destructure_has_no_diagnostic() {
822        let sheet =
823            parse("sheet s { cell a: i32; cell out: i32; relationship { (out,) := (a,); } }");
824        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
825        assert!(diags.is_empty());
826    }
827
828    /// Diagnoses the wrong element type in singleton tuple destructuring.
829    #[test]
830    fn binding_single_element_tuple_destructure_type_mismatch_is_a_diagnostic() {
831        let sheet =
832            parse("sheet s { cell a: f64; cell out: i32; relationship { (out,) := (a,); } }");
833        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
834        assert_eq!(diags.len(), 1);
835    }
836
837    /// Diagnoses the wrong arity in singleton tuple destructuring.
838    #[test]
839    fn binding_single_element_tuple_destructure_arity_mismatch_is_a_diagnostic() {
840        let sheet = parse("sheet s { cell a: i32; cell out: i32; relationship { (out,) := a; } }");
841        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
842        assert_eq!(diags.len(), 1);
843    }
844
845    /// Accepts range filters without requiring a candidate placeholder.
846    #[test]
847    fn filter_range_inclusive_body_does_not_require_underscore() {
848        let sheet = parse("sheet s { cell a: i32 filter 0..=100; }");
849        let diags = check_sheet(&sheet, &TypeRegistry::new(), &cel_parser::OpLookup::new());
850        assert!(diags.is_empty());
851    }
852
853    /// Range filters use their inferred endpoint identity, including callable-produced bounds.
854    #[test]
855    fn inferred_range_filters_agree_with_executable() {
856        for source in [
857            "sheet s { cell a: i32 filter (|x: i32| 0..=x)(100); }",
858            "sheet s { source a: f64 = 1.0 filter 0.0..=100.0; }",
859            "sheet s { out a: i32 := 1 filter (|x: i32| 0..=x)(100); }",
860        ] {
861            assert!(
862                crate::AdamParser::new(TypeRegistry::new(), cel_parser::OpLookup::new())
863                    .parse_str(source)
864                    .is_ok(),
865                "{source}"
866            );
867            let diags = check_sheet(
868                &parse(source),
869                &TypeRegistry::new(),
870                &cel_parser::OpLookup::new(),
871            );
872            assert!(diags.is_empty(), "{source}: {diags:?}");
873        }
874        for source in [
875            "sheet s { cell a: i32 filter 0.0..=100.0; }",
876            "sheet s { source a: i32 = 1 filter (|x: f64| 0.0..=x)(100.0); }",
877            "sheet s { out a: i32 := 1 filter 0.0..=100.0; }",
878            "sheet s { cell a: i32 filter 0..100; }",
879        ] {
880            assert!(
881                crate::AdamParser::new(TypeRegistry::new(), cel_parser::OpLookup::new())
882                    .parse_str(source)
883                    .is_err(),
884                "{source}"
885            );
886            let diags = check_sheet(
887                &parse(source),
888                &TypeRegistry::new(),
889                &cel_parser::OpLookup::new(),
890            );
891            assert!(!diags.is_empty(), "{source}");
892        }
893    }
894}