fel-core 0.3.0

Formspec Expression Language — parser, evaluator, and dependency analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! FEL error types and diagnostic messages.
use std::fmt;
use std::ops::Range;

/// Lex or parse failure with optional source span (byte offsets into the expression).
///
/// [`Error`]'s [`std::fmt::Display`] output uses the `message` field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    /// Human-readable explanation.
    pub message: String,
    /// Byte range in the source, when known.
    pub span: Option<Range<usize>>,
}

impl ParseError {
    /// Parse failure with no associated span.
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            span: None,
        }
    }

    /// Parse failure with a source span.
    #[must_use]
    pub fn with_span(span: Range<usize>, message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            span: Some(span),
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

/// Failure from [`crate::parse`] or fatal-style evaluation errors surfaced as `Err`.
#[derive(Debug, Clone)]
pub enum Error {
    /// Lex/parse failure (message from lexer or parser).
    Parse(ParseError),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Parse(pe) => write!(f, "parse error: {}", pe.message),
        }
    }
}

impl std::error::Error for Error {}

/// A non-fatal diagnostic recorded during evaluation.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// Severity for hosts and JSON wire encoding.
    pub severity: Severity,
    /// Human-readable explanation.
    pub message: String,
    /// Stable machine-readable code for lint/UI (e.g. `FEL_SUM_REJECTS_MONEY`).
    pub code: Option<String>,
    /// Machine-readable category for robust downstream handling.
    pub kind: Option<DiagnosticKind>,
    /// Byte range in the source expression, when known.
    pub span: Option<Range<usize>>,
}

/// Diagnostic severity for tooling and JSON wire format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Blocking / error-level.
    Error,
    /// Warning-level.
    Warning,
    /// Informational.
    Info,
}

/// Machine-readable diagnostic categories.
///
/// Closed-set append-only per `README.md` (FEL 1.0 commitment): consumers may
/// match exhaustively. Adding a variant is a non-breaking minor revision; removing
/// or renaming is a breaking change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagnosticKind {
    /// Function name could not be resolved in builtins or extension registry.
    UndefinedFunction {
        /// The unresolved function identifier as written in the expression.
        name: String,
    },
    /// Builtin or expression context expected a different runtime type.
    TypeMismatch {
        /// Builtin name or logical callee (`"if"` for ternary / keyword-if).
        fn_name: String,
        /// Expected type phrase as emitted in the human message (e.g. `"boolean"`).
        expected: String,
        /// Observed type name from [`crate::types::Value::type_name`].
        got: String,
    },
    /// Extension or builtin invoked with the wrong number of arguments.
    ArityMismatch {
        /// Function or extension name.
        name: String,
        /// Minimum arguments (inclusive).
        min_args: usize,
        /// Maximum arguments (inclusive), if bounded.
        max_args: Option<usize>,
        /// Actual argument count supplied.
        got: usize,
    },
    /// A FEL temporal builtin (`today()` / `now()`) was evaluated while the host
    /// supplied no timezone context.
    ///
    /// Pins ADR 0069 D-6: silent UTC / server-timezone fallback is forbidden.
    /// The host MUST configure a clock (timezone-equivalent context) before
    /// invoking `today()` or `now()`; otherwise the evaluator returns
    /// [`crate::Value::Null`] and surfaces this diagnostic.
    MissingTimezoneContext {
        /// FEL builtin that hard-refused (`"today"` or `"now"`).
        fn_name: String,
        /// Why the timezone context is missing.
        reason: MissingTimezoneContextReason,
    },
}

/// Why a host failed to supply a timezone context to a FEL temporal builtin.
///
/// Closed-set per ADR 0069 D-6. The default case is `NotConfigured` (host never
/// set a clock); `MultiCalendarConflict` carries the conflicting calendar
/// identifiers when business-calendar resolution (per
/// `work-spec/specs/sidecars/business-calendar.md` §7.1) cannot pick a single
/// timezone. Hosts surface their own variant from
/// [`crate::evaluator::Environment::current_date`] /
/// [`crate::evaluator::Environment::current_datetime`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MissingTimezoneContextReason {
    /// No clock was configured on the [`crate::evaluator::Environment`].
    NotConfigured,
    /// Multiple applicable business calendars disagreed on which timezone
    /// applies (per `business-calendar.md` §7.1).
    MultiCalendarConflict {
        /// Calendar identifiers whose timezones disagreed at the resolution
        /// point. Order is host-defined.
        calendars: Vec<String>,
    },
}

/// Typed error returned by [`crate::evaluator::Environment::current_date`] and
/// [`crate::evaluator::Environment::current_datetime`] when the host has no
/// timezone context configured.
///
/// Per ADR 0069 D-6, this is the ONLY permissible failure mode — silent UTC
/// fallback is forbidden. The evaluator translates this error into a structured
/// [`DiagnosticKind::MissingTimezoneContext`] diagnostic so callers can detect
/// the refusal without parsing message strings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingTimezoneContextError {
    /// Why the timezone context is missing.
    pub reason: MissingTimezoneContextReason,
}

impl MissingTimezoneContextError {
    /// Constructs the common `NotConfigured` case.
    #[must_use]
    pub fn not_configured() -> Self {
        Self {
            reason: MissingTimezoneContextReason::NotConfigured,
        }
    }

    /// Constructs a `MultiCalendarConflict` case carrying the calendars whose
    /// timezones disagreed.
    #[must_use]
    pub fn multi_calendar_conflict(calendars: Vec<String>) -> Self {
        Self {
            reason: MissingTimezoneContextReason::MultiCalendarConflict { calendars },
        }
    }
}

impl fmt::Display for MissingTimezoneContextError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.reason {
            MissingTimezoneContextReason::NotConfigured => f.write_str(
                "timezone context is required for today()/now() but none was configured",
            ),
            MissingTimezoneContextReason::MultiCalendarConflict { calendars } => write!(
                f,
                "timezone context is ambiguous: multiple business calendars disagreed ({})",
                calendars.join(", ")
            ),
        }
    }
}

impl std::error::Error for MissingTimezoneContextError {}

/// Pluralizes the word `argument` for arity diagnostics.
pub(crate) fn arity_argument_word(count: usize) -> &'static str {
    if count == 1 { "argument" } else { "arguments" }
}

/// `{name}: requires exactly {n} argument(s)`.
pub(crate) fn arity_requires_exactly_message(name: &str, n: usize) -> String {
    format!("{name}: requires exactly {n} {}", arity_argument_word(n))
}

/// `{name}: requires at least {min} argument(s)`.
pub(crate) fn arity_requires_at_least_message(name: &str, min: usize) -> String {
    format!(
        "{name}: requires at least {min} {}",
        arity_argument_word(min)
    )
}

/// `{name}: requires at most {max} argument(s)`.
pub(crate) fn arity_requires_at_most_message(name: &str, max: usize) -> String {
    format!(
        "{name}: requires at most {max} {}",
        arity_argument_word(max)
    )
}

/// Human-readable arity mismatch for extensions and builtins.
pub(crate) fn extension_arity_mismatch_message(
    name: &str,
    min_args: usize,
    max_args: Option<usize>,
    got: usize,
) -> String {
    if let Some(max) = max_args {
        if min_args == max && got != min_args {
            return arity_requires_exactly_message(name, min_args);
        }
        if got < min_args {
            return arity_requires_at_least_message(name, min_args);
        }
        if got > max {
            return arity_requires_at_most_message(name, max);
        }
    } else if got < min_args {
        return arity_requires_at_least_message(name, min_args);
    }
    unreachable!("extension_arity_mismatch_message called with valid arity")
}

impl Severity {
    /// Wire string used in JSON diagnostics (`error` / `warning` / `info`).
    pub fn as_wire_str(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Info => "info",
        }
    }
}

impl Diagnostic {
    /// Build an error-severity diagnostic.
    pub fn error(msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Error,
            message: msg.into(),
            code: None,
            kind: None,
            span: None,
        }
    }

    /// Build an error-severity diagnostic with a stable [`Diagnostic::code`].
    pub fn error_coded(code: impl Into<String>, msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Error,
            message: msg.into(),
            code: Some(code.into()),
            kind: None,
            span: None,
        }
    }

    /// Build a warning-severity diagnostic.
    pub fn warning(msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Warning,
            message: msg.into(),
            code: None,
            kind: None,
            span: None,
        }
    }

    /// Build a structured undefined-function diagnostic.
    pub fn undefined_function(name: impl Into<String>) -> Self {
        let name = name.into();
        Diagnostic {
            severity: Severity::Error,
            message: format!("undefined function: {name}"),
            code: None,
            kind: Some(DiagnosticKind::UndefinedFunction { name }),
            span: None,
        }
    }

    /// Build a structured arity-mismatch diagnostic (builtin or extension).
    pub fn arity_mismatch(
        name: impl Into<String>,
        min_args: usize,
        max_args: Option<usize>,
        got: usize,
    ) -> Self {
        let name = name.into();
        let message = extension_arity_mismatch_message(&name, min_args, max_args, got);
        Diagnostic {
            severity: Severity::Error,
            message,
            code: None,
            kind: Some(DiagnosticKind::ArityMismatch {
                name,
                min_args,
                max_args,
                got,
            }),
            span: None,
        }
    }

    /// Build the error diagnostic for a failed host extension call (Core §3.12 totality).
    pub fn extension_failed(name: impl Into<String>, message: impl Into<String>) -> Self {
        Diagnostic::error(format!(
            "{}: extension function failed: {}",
            name.into(),
            message.into()
        ))
    }

    /// Build a structured type-mismatch diagnostic (same message shape as runtime type errors).
    pub fn type_mismatch(
        fn_name: impl Into<String>,
        expected: impl Into<String>,
        got_type: impl Into<String>,
    ) -> Self {
        let fn_name = fn_name.into();
        let expected = expected.into();
        let got_type = got_type.into();
        Diagnostic {
            severity: Severity::Error,
            message: format!("{fn_name}: expected {expected}, got {got_type}"),
            code: None,
            kind: Some(DiagnosticKind::TypeMismatch {
                fn_name: fn_name.clone(),
                expected: expected.clone(),
                got: got_type.clone(),
            }),
            span: None,
        }
    }

    /// Build a structured missing-timezone-context diagnostic (ADR 0069 D-6).
    ///
    /// The message is derived from the [`MissingTimezoneContextError`]
    /// `Display` impl plus the builtin name; the structured [`Self::kind`]
    /// carries the same data for programmatic dispatch.
    pub fn missing_timezone_context(
        fn_name: impl Into<String>,
        err: MissingTimezoneContextError,
    ) -> Self {
        let fn_name = fn_name.into();
        Diagnostic {
            severity: Severity::Error,
            message: format!("{fn_name}(): {err}"),
            code: None,
            kind: Some(DiagnosticKind::MissingTimezoneContext {
                fn_name,
                reason: err.reason,
            }),
            span: None,
        }
    }

    /// Attaches a source span (byte offsets into the FEL source string).
    #[must_use]
    pub fn with_span(mut self, span: Range<usize>) -> Self {
        self.span = Some(span);
        self
    }
}

/// Names from `undefined function: …` diagnostics (host bindings reject these as unsupported).
pub fn undefined_function_names_from_diagnostics(diagnostics: &[Diagnostic]) -> Vec<String> {
    diagnostics
        .iter()
        .filter_map(|d| {
            if let Some(DiagnosticKind::UndefinedFunction { name }) = &d.kind {
                if !name.trim().is_empty() {
                    return Some(name.trim().to_string());
                }
            }
            d.message
                .strip_prefix("undefined function: ")
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
        })
        .collect()
}

/// Returns `true` if any diagnostic has error severity.
pub fn has_error_diagnostics(diagnostics: &[Diagnostic]) -> bool {
    diagnostics.iter().any(|d| d.severity == Severity::Error)
}

/// Returns `Err` when any undefined-function diagnostic is present (WASM / strict hosts).
pub fn reject_undefined_functions(diagnostics: &[Diagnostic]) -> Result<(), String> {
    let names = undefined_function_names_from_diagnostics(diagnostics);
    if names.is_empty() {
        Ok(())
    } else {
        Err(format!("Unsupported FEL function: {}", names.join(", ")))
    }
}

/// Evaluation diagnostics as JSON objects (default `camelCase`).
pub fn fel_diagnostics_to_json_value(diagnostics: &[Diagnostic]) -> serde_json::Value {
    fel_diagnostics_to_json_value_styled(diagnostics, crate::wire_style::JsonWireStyle::JsCamel)
}

/// Serializes the structured diagnostic kind with the selected key style.
fn diagnostic_kind_to_json(
    kind: &DiagnosticKind,
    style: crate::wire_style::JsonWireStyle,
) -> serde_json::Value {
    use crate::wire_style::JsonWireStyle;

    match kind {
        DiagnosticKind::UndefinedFunction { name } => match style {
            JsonWireStyle::JsCamel => serde_json::json!({
                "undefinedFunction": { "name": name }
            }),
            JsonWireStyle::PythonSnake => serde_json::json!({
                "undefined_function": { "name": name }
            }),
        },
        DiagnosticKind::TypeMismatch {
            fn_name,
            expected,
            got,
        } => match style {
            JsonWireStyle::JsCamel => serde_json::json!({
                "typeMismatch": {
                    "fnName": fn_name,
                    "expected": expected,
                    "got": got,
                }
            }),
            JsonWireStyle::PythonSnake => serde_json::json!({
                "type_mismatch": {
                    "fn_name": fn_name,
                    "expected": expected,
                    "got": got,
                }
            }),
        },
        DiagnosticKind::ArityMismatch {
            name,
            min_args,
            max_args,
            got,
        } => match style {
            JsonWireStyle::JsCamel => serde_json::json!({
                "arityMismatch": {
                    "name": name,
                    "minArgs": min_args,
                    "maxArgs": max_args,
                    "got": got,
                }
            }),
            JsonWireStyle::PythonSnake => serde_json::json!({
                "arity_mismatch": {
                    "name": name,
                    "min_args": min_args,
                    "max_args": max_args,
                    "got": got,
                }
            }),
        },
        DiagnosticKind::MissingTimezoneContext { fn_name, reason } => {
            // Reason is a tagged-string + payload to keep value bytes identical
            // across wire styles — only KEY casing differs between camel and
            // snake (mirrors the contract enforced by
            // `diagnostics_json_styled_matches_default_modulo_kind_key` in
            // `tests/json_exports_proptest.rs`).
            let (reason_tag, calendars) = missing_timezone_reason_to_tag(reason);
            match style {
                JsonWireStyle::JsCamel => {
                    let mut inner = serde_json::Map::new();
                    inner.insert("fnName".into(), serde_json::Value::String(fn_name.clone()));
                    inner.insert(
                        "reason".into(),
                        serde_json::Value::String(reason_tag.to_string()),
                    );
                    if let Some(c) = calendars {
                        inner.insert("calendars".into(), serde_json::json!(c));
                    }
                    serde_json::json!({ "missingTimezoneContext": serde_json::Value::Object(inner) })
                }
                JsonWireStyle::PythonSnake => {
                    let mut inner = serde_json::Map::new();
                    inner.insert("fn_name".into(), serde_json::Value::String(fn_name.clone()));
                    inner.insert(
                        "reason".into(),
                        serde_json::Value::String(reason_tag.to_string()),
                    );
                    if let Some(c) = calendars {
                        inner.insert("calendars".into(), serde_json::json!(c));
                    }
                    serde_json::json!({
                        "missing_timezone_context": serde_json::Value::Object(inner)
                    })
                }
            }
        }
    }
}

/// Reduces a [`MissingTimezoneContextReason`] to a stable string tag and the
/// optional `calendars` payload. The tag string is byte-identical across wire
/// styles (the camel/snake casing differs only at the surrounding KEYS).
fn missing_timezone_reason_to_tag(
    reason: &MissingTimezoneContextReason,
) -> (&'static str, Option<&Vec<String>>) {
    match reason {
        MissingTimezoneContextReason::NotConfigured => ("not_configured", None),
        MissingTimezoneContextReason::MultiCalendarConflict { calendars } => {
            ("multi_calendar_conflict", Some(calendars))
        }
    }
}

/// Serializes one diagnostic into its public JSON object shape.
fn diagnostic_to_json_object(
    d: &Diagnostic,
    style: crate::wire_style::JsonWireStyle,
) -> serde_json::Value {
    use serde_json::{Map, Value};

    let mut map = Map::new();
    map.insert("message".to_string(), Value::String(d.message.clone()));
    if let Some(code) = &d.code {
        map.insert("code".to_string(), Value::String(code.clone()));
    }
    map.insert(
        "severity".to_string(),
        Value::String(d.severity.as_wire_str().to_string()),
    );
    if let Some(sp) = &d.span {
        map.insert(
            "span".to_string(),
            serde_json::json!({ "start": sp.start, "end": sp.end }),
        );
    }
    if let Some(kind) = &d.kind {
        map.insert("kind".to_string(), diagnostic_kind_to_json(kind, style));
    }
    Value::Object(map)
}

/// Evaluation diagnostics as JSON objects with configurable key style.
pub fn fel_diagnostics_to_json_value_styled(
    diagnostics: &[Diagnostic],
    style: crate::wire_style::JsonWireStyle,
) -> serde_json::Value {
    serde_json::Value::Array(
        diagnostics
            .iter()
            .map(|d| diagnostic_to_json_object(d, style))
            .collect(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extracts_undefined_function_names() {
        let diagnostics = vec![
            Diagnostic::undefined_function("foo"),
            Diagnostic::warning("other"),
            Diagnostic::undefined_function("bar"),
        ];
        assert_eq!(
            undefined_function_names_from_diagnostics(&diagnostics),
            vec!["foo".to_string(), "bar".to_string()]
        );
    }

    #[test]
    fn detects_error_severity_presence() {
        let diagnostics = vec![Diagnostic::warning("warn"), Diagnostic::error("err")];
        assert!(has_error_diagnostics(&diagnostics));
    }

    #[test]
    fn reject_undefined_functions_returns_error() {
        let diagnostics = vec![Diagnostic::undefined_function("randomFn")];
        let err = reject_undefined_functions(&diagnostics).expect_err("should reject");
        assert!(err.contains("randomFn"));
    }

    #[test]
    fn extracts_undefined_names_from_legacy_message_prefix() {
        let diagnostics = vec![Diagnostic::error("undefined function: legacyFn")];
        assert_eq!(
            undefined_function_names_from_diagnostics(&diagnostics),
            vec!["legacyFn".to_string()]
        );
    }

    #[test]
    fn severity_wire_strings_are_stable() {
        assert_eq!(Severity::Error.as_wire_str(), "error");
        assert_eq!(Severity::Warning.as_wire_str(), "warning");
        assert_eq!(Severity::Info.as_wire_str(), "info");
    }

    #[test]
    fn diagnostic_json_styled_matches_default_shape() {
        use serde_json::json;

        use crate::wire_style::JsonWireStyle;

        let diagnostics = vec![Diagnostic::error("boom")];
        let js = fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::JsCamel);
        let py = fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::PythonSnake);
        let default = fel_diagnostics_to_json_value(&diagnostics);

        let expected = json!([{ "message": "boom", "severity": "error" }]);
        assert_eq!(js, expected);
        assert_eq!(py, expected);
        assert_eq!(default, expected);
    }

    #[test]
    fn diagnostic_json_includes_span_when_set() {
        use serde_json::json;

        let diagnostics = vec![Diagnostic::error("bad").with_span(3..9)];
        assert_eq!(
            fel_diagnostics_to_json_value(&diagnostics),
            json!([{
                "message": "bad",
                "severity": "error",
                "span": { "start": 3, "end": 9 }
            }])
        );
    }

    #[test]
    fn diagnostic_json_includes_kind_arity_mismatch() {
        use serde_json::json;

        let d = Diagnostic::arity_mismatch("needsTwo", 2, Some(2), 1);
        assert_eq!(
            fel_diagnostics_to_json_value(&[d]),
            json!([{
                "message": "needsTwo: requires exactly 2 arguments",
                "severity": "error",
                "kind": {
                    "arityMismatch": {
                        "name": "needsTwo",
                        "minArgs": 2,
                        "maxArgs": 2,
                        "got": 1
                    }
                }
            }])
        );
    }

    #[test]
    fn diagnostic_json_includes_kind_undefined_function_js_camel() {
        use serde_json::json;

        use crate::wire_style::JsonWireStyle;

        let diagnostics = vec![Diagnostic::undefined_function("foo")];
        assert_eq!(
            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::JsCamel),
            json!([{
                "message": "undefined function: foo",
                "severity": "error",
                "kind": { "undefinedFunction": { "name": "foo" } }
            }])
        );
    }

    #[test]
    fn diagnostic_json_includes_kind_and_span_together() {
        use serde_json::json;

        let diagnostics = vec![Diagnostic::undefined_function("bar").with_span(1..5)];
        assert_eq!(
            fel_diagnostics_to_json_value(&diagnostics),
            json!([{
                "message": "undefined function: bar",
                "severity": "error",
                "span": { "start": 1, "end": 5 },
                "kind": { "undefinedFunction": { "name": "bar" } }
            }])
        );
    }

    #[test]
    fn diagnostic_json_snake_style_kind_keys() {
        use serde_json::json;

        use crate::wire_style::JsonWireStyle;

        let diagnostics = vec![Diagnostic::undefined_function("x")];
        assert_eq!(
            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::PythonSnake),
            json!([{
                "message": "undefined function: x",
                "severity": "error",
                "kind": { "undefined_function": { "name": "x" } }
            }])
        );
    }

    #[test]
    fn diagnostic_json_type_mismatch_js_camel() {
        use serde_json::json;

        use crate::wire_style::JsonWireStyle;

        let diagnostics = vec![Diagnostic::type_mismatch("if", "boolean", "number")];
        assert_eq!(
            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::JsCamel),
            json!([{
                "message": "if: expected boolean, got number",
                "severity": "error",
                "kind": { "typeMismatch": { "fnName": "if", "expected": "boolean", "got": "number" } }
            }])
        );
    }

    #[test]
    fn diagnostic_json_type_mismatch_python_snake() {
        use serde_json::json;

        use crate::wire_style::JsonWireStyle;

        let diagnostics = vec![Diagnostic::type_mismatch("sum", "array", "string")];
        assert_eq!(
            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::PythonSnake),
            json!([{
                "message": "sum: expected array, got string",
                "severity": "error",
                "kind": { "type_mismatch": { "fn_name": "sum", "expected": "array", "got": "string" } }
            }])
        );
    }
}