Skip to main content

fel_core/
error.rs

1//! FEL error types and diagnostic messages.
2use std::fmt;
3use std::ops::Range;
4
5/// Lex or parse failure with optional source span (byte offsets into the expression).
6///
7/// [`Error`]'s [`std::fmt::Display`] output uses the `message` field.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct ParseError {
10    /// Human-readable explanation.
11    pub message: String,
12    /// Byte range in the source, when known.
13    pub span: Option<Range<usize>>,
14}
15
16impl ParseError {
17    /// Parse failure with no associated span.
18    #[must_use]
19    pub fn new(message: impl Into<String>) -> Self {
20        Self {
21            message: message.into(),
22            span: None,
23        }
24    }
25
26    /// Parse failure with a source span.
27    #[must_use]
28    pub fn with_span(span: Range<usize>, message: impl Into<String>) -> Self {
29        Self {
30            message: message.into(),
31            span: Some(span),
32        }
33    }
34}
35
36impl fmt::Display for ParseError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.write_str(&self.message)
39    }
40}
41
42/// Failure from [`crate::parse`] or fatal-style evaluation errors surfaced as `Err`.
43#[derive(Debug, Clone)]
44pub enum Error {
45    /// Lex/parse failure (message from lexer or parser).
46    Parse(ParseError),
47}
48
49impl fmt::Display for Error {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Error::Parse(pe) => write!(f, "parse error: {}", pe.message),
53        }
54    }
55}
56
57impl std::error::Error for Error {}
58
59/// A non-fatal diagnostic recorded during evaluation.
60#[derive(Debug, Clone)]
61pub struct Diagnostic {
62    /// Severity for hosts and JSON wire encoding.
63    pub severity: Severity,
64    /// Human-readable explanation.
65    pub message: String,
66    /// Stable machine-readable code for lint/UI (e.g. `FEL_SUM_REJECTS_MONEY`).
67    pub code: Option<String>,
68    /// Machine-readable category for robust downstream handling.
69    pub kind: Option<DiagnosticKind>,
70    /// Byte range in the source expression, when known.
71    pub span: Option<Range<usize>>,
72}
73
74/// Diagnostic severity for tooling and JSON wire format.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Severity {
77    /// Blocking / error-level.
78    Error,
79    /// Warning-level.
80    Warning,
81    /// Informational.
82    Info,
83}
84
85/// Machine-readable diagnostic categories.
86///
87/// Closed-set append-only per `README.md` (FEL 1.0 commitment): consumers may
88/// match exhaustively. Adding a variant is a non-breaking minor revision; removing
89/// or renaming is a breaking change.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum DiagnosticKind {
92    /// Function name could not be resolved in builtins or extension registry.
93    UndefinedFunction {
94        /// The unresolved function identifier as written in the expression.
95        name: String,
96    },
97    /// Builtin or expression context expected a different runtime type.
98    TypeMismatch {
99        /// Builtin name or logical callee (`"if"` for ternary / keyword-if).
100        fn_name: String,
101        /// Expected type phrase as emitted in the human message (e.g. `"boolean"`).
102        expected: String,
103        /// Observed type name from [`crate::types::Value::type_name`].
104        got: String,
105    },
106    /// Extension or builtin invoked with the wrong number of arguments.
107    ArityMismatch {
108        /// Function or extension name.
109        name: String,
110        /// Minimum arguments (inclusive).
111        min_args: usize,
112        /// Maximum arguments (inclusive), if bounded.
113        max_args: Option<usize>,
114        /// Actual argument count supplied.
115        got: usize,
116    },
117    /// A FEL temporal builtin (`today()` / `now()`) was evaluated while the host
118    /// supplied no timezone context.
119    ///
120    /// Pins ADR 0069 D-6: silent UTC / server-timezone fallback is forbidden.
121    /// The host MUST configure a clock (timezone-equivalent context) before
122    /// invoking `today()` or `now()`; otherwise the evaluator returns
123    /// [`crate::Value::Null`] and surfaces this diagnostic.
124    MissingTimezoneContext {
125        /// FEL builtin that hard-refused (`"today"` or `"now"`).
126        fn_name: String,
127        /// Why the timezone context is missing.
128        reason: MissingTimezoneContextReason,
129    },
130}
131
132/// Why a host failed to supply a timezone context to a FEL temporal builtin.
133///
134/// Closed-set per ADR 0069 D-6. The default case is `NotConfigured` (host never
135/// set a clock); `MultiCalendarConflict` carries the conflicting calendar
136/// identifiers when business-calendar resolution (per
137/// `work-spec/specs/sidecars/business-calendar.md` §7.1) cannot pick a single
138/// timezone. Hosts surface their own variant from
139/// [`crate::evaluator::Environment::current_date`] /
140/// [`crate::evaluator::Environment::current_datetime`].
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub enum MissingTimezoneContextReason {
143    /// No clock was configured on the [`crate::evaluator::Environment`].
144    NotConfigured,
145    /// Multiple applicable business calendars disagreed on which timezone
146    /// applies (per `business-calendar.md` §7.1).
147    MultiCalendarConflict {
148        /// Calendar identifiers whose timezones disagreed at the resolution
149        /// point. Order is host-defined.
150        calendars: Vec<String>,
151    },
152}
153
154/// Typed error returned by [`crate::evaluator::Environment::current_date`] and
155/// [`crate::evaluator::Environment::current_datetime`] when the host has no
156/// timezone context configured.
157///
158/// Per ADR 0069 D-6, this is the ONLY permissible failure mode — silent UTC
159/// fallback is forbidden. The evaluator translates this error into a structured
160/// [`DiagnosticKind::MissingTimezoneContext`] diagnostic so callers can detect
161/// the refusal without parsing message strings.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct MissingTimezoneContextError {
164    /// Why the timezone context is missing.
165    pub reason: MissingTimezoneContextReason,
166}
167
168impl MissingTimezoneContextError {
169    /// Constructs the common `NotConfigured` case.
170    #[must_use]
171    pub fn not_configured() -> Self {
172        Self {
173            reason: MissingTimezoneContextReason::NotConfigured,
174        }
175    }
176
177    /// Constructs a `MultiCalendarConflict` case carrying the calendars whose
178    /// timezones disagreed.
179    #[must_use]
180    pub fn multi_calendar_conflict(calendars: Vec<String>) -> Self {
181        Self {
182            reason: MissingTimezoneContextReason::MultiCalendarConflict { calendars },
183        }
184    }
185}
186
187impl fmt::Display for MissingTimezoneContextError {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        match &self.reason {
190            MissingTimezoneContextReason::NotConfigured => f.write_str(
191                "timezone context is required for today()/now() but none was configured",
192            ),
193            MissingTimezoneContextReason::MultiCalendarConflict { calendars } => write!(
194                f,
195                "timezone context is ambiguous: multiple business calendars disagreed ({})",
196                calendars.join(", ")
197            ),
198        }
199    }
200}
201
202impl std::error::Error for MissingTimezoneContextError {}
203
204/// Pluralizes the word `argument` for arity diagnostics.
205pub(crate) fn arity_argument_word(count: usize) -> &'static str {
206    if count == 1 { "argument" } else { "arguments" }
207}
208
209/// `{name}: requires exactly {n} argument(s)`.
210pub(crate) fn arity_requires_exactly_message(name: &str, n: usize) -> String {
211    format!("{name}: requires exactly {n} {}", arity_argument_word(n))
212}
213
214/// `{name}: requires at least {min} argument(s)`.
215pub(crate) fn arity_requires_at_least_message(name: &str, min: usize) -> String {
216    format!(
217        "{name}: requires at least {min} {}",
218        arity_argument_word(min)
219    )
220}
221
222/// `{name}: requires at most {max} argument(s)`.
223pub(crate) fn arity_requires_at_most_message(name: &str, max: usize) -> String {
224    format!(
225        "{name}: requires at most {max} {}",
226        arity_argument_word(max)
227    )
228}
229
230/// Human-readable arity mismatch for extensions and builtins.
231pub(crate) fn extension_arity_mismatch_message(
232    name: &str,
233    min_args: usize,
234    max_args: Option<usize>,
235    got: usize,
236) -> String {
237    if let Some(max) = max_args {
238        if min_args == max && got != min_args {
239            return arity_requires_exactly_message(name, min_args);
240        }
241        if got < min_args {
242            return arity_requires_at_least_message(name, min_args);
243        }
244        if got > max {
245            return arity_requires_at_most_message(name, max);
246        }
247    } else if got < min_args {
248        return arity_requires_at_least_message(name, min_args);
249    }
250    unreachable!("extension_arity_mismatch_message called with valid arity")
251}
252
253impl Severity {
254    /// Wire string used in JSON diagnostics (`error` / `warning` / `info`).
255    pub fn as_wire_str(self) -> &'static str {
256        match self {
257            Self::Error => "error",
258            Self::Warning => "warning",
259            Self::Info => "info",
260        }
261    }
262}
263
264impl Diagnostic {
265    /// Build an error-severity diagnostic.
266    pub fn error(msg: impl Into<String>) -> Self {
267        Diagnostic {
268            severity: Severity::Error,
269            message: msg.into(),
270            code: None,
271            kind: None,
272            span: None,
273        }
274    }
275
276    /// Build an error-severity diagnostic with a stable [`Diagnostic::code`].
277    pub fn error_coded(code: impl Into<String>, msg: impl Into<String>) -> Self {
278        Diagnostic {
279            severity: Severity::Error,
280            message: msg.into(),
281            code: Some(code.into()),
282            kind: None,
283            span: None,
284        }
285    }
286
287    /// Build a warning-severity diagnostic.
288    pub fn warning(msg: impl Into<String>) -> Self {
289        Diagnostic {
290            severity: Severity::Warning,
291            message: msg.into(),
292            code: None,
293            kind: None,
294            span: None,
295        }
296    }
297
298    /// Build a structured undefined-function diagnostic.
299    pub fn undefined_function(name: impl Into<String>) -> Self {
300        let name = name.into();
301        Diagnostic {
302            severity: Severity::Error,
303            message: format!("undefined function: {name}"),
304            code: None,
305            kind: Some(DiagnosticKind::UndefinedFunction { name }),
306            span: None,
307        }
308    }
309
310    /// Build a structured arity-mismatch diagnostic (builtin or extension).
311    pub fn arity_mismatch(
312        name: impl Into<String>,
313        min_args: usize,
314        max_args: Option<usize>,
315        got: usize,
316    ) -> Self {
317        let name = name.into();
318        let message = extension_arity_mismatch_message(&name, min_args, max_args, got);
319        Diagnostic {
320            severity: Severity::Error,
321            message,
322            code: None,
323            kind: Some(DiagnosticKind::ArityMismatch {
324                name,
325                min_args,
326                max_args,
327                got,
328            }),
329            span: None,
330        }
331    }
332
333    /// Build the error diagnostic for a failed host extension call (Core §3.12 totality).
334    pub fn extension_failed(name: impl Into<String>, message: impl Into<String>) -> Self {
335        Diagnostic::error(format!(
336            "{}: extension function failed: {}",
337            name.into(),
338            message.into()
339        ))
340    }
341
342    /// Build a structured type-mismatch diagnostic (same message shape as runtime type errors).
343    pub fn type_mismatch(
344        fn_name: impl Into<String>,
345        expected: impl Into<String>,
346        got_type: impl Into<String>,
347    ) -> Self {
348        let fn_name = fn_name.into();
349        let expected = expected.into();
350        let got_type = got_type.into();
351        Diagnostic {
352            severity: Severity::Error,
353            message: format!("{fn_name}: expected {expected}, got {got_type}"),
354            code: None,
355            kind: Some(DiagnosticKind::TypeMismatch {
356                fn_name: fn_name.clone(),
357                expected: expected.clone(),
358                got: got_type.clone(),
359            }),
360            span: None,
361        }
362    }
363
364    /// Build a structured missing-timezone-context diagnostic (ADR 0069 D-6).
365    ///
366    /// The message is derived from the [`MissingTimezoneContextError`]
367    /// `Display` impl plus the builtin name; the structured [`Self::kind`]
368    /// carries the same data for programmatic dispatch.
369    pub fn missing_timezone_context(
370        fn_name: impl Into<String>,
371        err: MissingTimezoneContextError,
372    ) -> Self {
373        let fn_name = fn_name.into();
374        Diagnostic {
375            severity: Severity::Error,
376            message: format!("{fn_name}(): {err}"),
377            code: None,
378            kind: Some(DiagnosticKind::MissingTimezoneContext {
379                fn_name,
380                reason: err.reason,
381            }),
382            span: None,
383        }
384    }
385
386    /// Attaches a source span (byte offsets into the FEL source string).
387    #[must_use]
388    pub fn with_span(mut self, span: Range<usize>) -> Self {
389        self.span = Some(span);
390        self
391    }
392}
393
394/// Names from `undefined function: …` diagnostics (host bindings reject these as unsupported).
395pub fn undefined_function_names_from_diagnostics(diagnostics: &[Diagnostic]) -> Vec<String> {
396    diagnostics
397        .iter()
398        .filter_map(|d| {
399            if let Some(DiagnosticKind::UndefinedFunction { name }) = &d.kind {
400                if !name.trim().is_empty() {
401                    return Some(name.trim().to_string());
402                }
403            }
404            d.message
405                .strip_prefix("undefined function: ")
406                .map(str::trim)
407                .filter(|s| !s.is_empty())
408                .map(str::to_string)
409        })
410        .collect()
411}
412
413/// Returns `true` if any diagnostic has error severity.
414pub fn has_error_diagnostics(diagnostics: &[Diagnostic]) -> bool {
415    diagnostics.iter().any(|d| d.severity == Severity::Error)
416}
417
418/// Returns `Err` when any undefined-function diagnostic is present (WASM / strict hosts).
419pub fn reject_undefined_functions(diagnostics: &[Diagnostic]) -> Result<(), String> {
420    let names = undefined_function_names_from_diagnostics(diagnostics);
421    if names.is_empty() {
422        Ok(())
423    } else {
424        Err(format!("Unsupported FEL function: {}", names.join(", ")))
425    }
426}
427
428/// Evaluation diagnostics as JSON objects (default `camelCase`).
429pub fn fel_diagnostics_to_json_value(diagnostics: &[Diagnostic]) -> serde_json::Value {
430    fel_diagnostics_to_json_value_styled(diagnostics, crate::wire_style::JsonWireStyle::JsCamel)
431}
432
433/// Serializes the structured diagnostic kind with the selected key style.
434fn diagnostic_kind_to_json(
435    kind: &DiagnosticKind,
436    style: crate::wire_style::JsonWireStyle,
437) -> serde_json::Value {
438    use crate::wire_style::JsonWireStyle;
439
440    match kind {
441        DiagnosticKind::UndefinedFunction { name } => match style {
442            JsonWireStyle::JsCamel => serde_json::json!({
443                "undefinedFunction": { "name": name }
444            }),
445            JsonWireStyle::PythonSnake => serde_json::json!({
446                "undefined_function": { "name": name }
447            }),
448        },
449        DiagnosticKind::TypeMismatch {
450            fn_name,
451            expected,
452            got,
453        } => match style {
454            JsonWireStyle::JsCamel => serde_json::json!({
455                "typeMismatch": {
456                    "fnName": fn_name,
457                    "expected": expected,
458                    "got": got,
459                }
460            }),
461            JsonWireStyle::PythonSnake => serde_json::json!({
462                "type_mismatch": {
463                    "fn_name": fn_name,
464                    "expected": expected,
465                    "got": got,
466                }
467            }),
468        },
469        DiagnosticKind::ArityMismatch {
470            name,
471            min_args,
472            max_args,
473            got,
474        } => match style {
475            JsonWireStyle::JsCamel => serde_json::json!({
476                "arityMismatch": {
477                    "name": name,
478                    "minArgs": min_args,
479                    "maxArgs": max_args,
480                    "got": got,
481                }
482            }),
483            JsonWireStyle::PythonSnake => serde_json::json!({
484                "arity_mismatch": {
485                    "name": name,
486                    "min_args": min_args,
487                    "max_args": max_args,
488                    "got": got,
489                }
490            }),
491        },
492        DiagnosticKind::MissingTimezoneContext { fn_name, reason } => {
493            // Reason is a tagged-string + payload to keep value bytes identical
494            // across wire styles — only KEY casing differs between camel and
495            // snake (mirrors the contract enforced by
496            // `diagnostics_json_styled_matches_default_modulo_kind_key` in
497            // `tests/json_exports_proptest.rs`).
498            let (reason_tag, calendars) = missing_timezone_reason_to_tag(reason);
499            match style {
500                JsonWireStyle::JsCamel => {
501                    let mut inner = serde_json::Map::new();
502                    inner.insert("fnName".into(), serde_json::Value::String(fn_name.clone()));
503                    inner.insert(
504                        "reason".into(),
505                        serde_json::Value::String(reason_tag.to_string()),
506                    );
507                    if let Some(c) = calendars {
508                        inner.insert("calendars".into(), serde_json::json!(c));
509                    }
510                    serde_json::json!({ "missingTimezoneContext": serde_json::Value::Object(inner) })
511                }
512                JsonWireStyle::PythonSnake => {
513                    let mut inner = serde_json::Map::new();
514                    inner.insert("fn_name".into(), serde_json::Value::String(fn_name.clone()));
515                    inner.insert(
516                        "reason".into(),
517                        serde_json::Value::String(reason_tag.to_string()),
518                    );
519                    if let Some(c) = calendars {
520                        inner.insert("calendars".into(), serde_json::json!(c));
521                    }
522                    serde_json::json!({
523                        "missing_timezone_context": serde_json::Value::Object(inner)
524                    })
525                }
526            }
527        }
528    }
529}
530
531/// Reduces a [`MissingTimezoneContextReason`] to a stable string tag and the
532/// optional `calendars` payload. The tag string is byte-identical across wire
533/// styles (the camel/snake casing differs only at the surrounding KEYS).
534fn missing_timezone_reason_to_tag(
535    reason: &MissingTimezoneContextReason,
536) -> (&'static str, Option<&Vec<String>>) {
537    match reason {
538        MissingTimezoneContextReason::NotConfigured => ("not_configured", None),
539        MissingTimezoneContextReason::MultiCalendarConflict { calendars } => {
540            ("multi_calendar_conflict", Some(calendars))
541        }
542    }
543}
544
545/// Serializes one diagnostic into its public JSON object shape.
546fn diagnostic_to_json_object(
547    d: &Diagnostic,
548    style: crate::wire_style::JsonWireStyle,
549) -> serde_json::Value {
550    use serde_json::{Map, Value};
551
552    let mut map = Map::new();
553    map.insert("message".to_string(), Value::String(d.message.clone()));
554    if let Some(code) = &d.code {
555        map.insert("code".to_string(), Value::String(code.clone()));
556    }
557    map.insert(
558        "severity".to_string(),
559        Value::String(d.severity.as_wire_str().to_string()),
560    );
561    if let Some(sp) = &d.span {
562        map.insert(
563            "span".to_string(),
564            serde_json::json!({ "start": sp.start, "end": sp.end }),
565        );
566    }
567    if let Some(kind) = &d.kind {
568        map.insert("kind".to_string(), diagnostic_kind_to_json(kind, style));
569    }
570    Value::Object(map)
571}
572
573/// Evaluation diagnostics as JSON objects with configurable key style.
574pub fn fel_diagnostics_to_json_value_styled(
575    diagnostics: &[Diagnostic],
576    style: crate::wire_style::JsonWireStyle,
577) -> serde_json::Value {
578    serde_json::Value::Array(
579        diagnostics
580            .iter()
581            .map(|d| diagnostic_to_json_object(d, style))
582            .collect(),
583    )
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589
590    #[test]
591    fn extracts_undefined_function_names() {
592        let diagnostics = vec![
593            Diagnostic::undefined_function("foo"),
594            Diagnostic::warning("other"),
595            Diagnostic::undefined_function("bar"),
596        ];
597        assert_eq!(
598            undefined_function_names_from_diagnostics(&diagnostics),
599            vec!["foo".to_string(), "bar".to_string()]
600        );
601    }
602
603    #[test]
604    fn detects_error_severity_presence() {
605        let diagnostics = vec![Diagnostic::warning("warn"), Diagnostic::error("err")];
606        assert!(has_error_diagnostics(&diagnostics));
607    }
608
609    #[test]
610    fn reject_undefined_functions_returns_error() {
611        let diagnostics = vec![Diagnostic::undefined_function("randomFn")];
612        let err = reject_undefined_functions(&diagnostics).expect_err("should reject");
613        assert!(err.contains("randomFn"));
614    }
615
616    #[test]
617    fn extracts_undefined_names_from_legacy_message_prefix() {
618        let diagnostics = vec![Diagnostic::error("undefined function: legacyFn")];
619        assert_eq!(
620            undefined_function_names_from_diagnostics(&diagnostics),
621            vec!["legacyFn".to_string()]
622        );
623    }
624
625    #[test]
626    fn severity_wire_strings_are_stable() {
627        assert_eq!(Severity::Error.as_wire_str(), "error");
628        assert_eq!(Severity::Warning.as_wire_str(), "warning");
629        assert_eq!(Severity::Info.as_wire_str(), "info");
630    }
631
632    #[test]
633    fn diagnostic_json_styled_matches_default_shape() {
634        use serde_json::json;
635
636        use crate::wire_style::JsonWireStyle;
637
638        let diagnostics = vec![Diagnostic::error("boom")];
639        let js = fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::JsCamel);
640        let py = fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::PythonSnake);
641        let default = fel_diagnostics_to_json_value(&diagnostics);
642
643        let expected = json!([{ "message": "boom", "severity": "error" }]);
644        assert_eq!(js, expected);
645        assert_eq!(py, expected);
646        assert_eq!(default, expected);
647    }
648
649    #[test]
650    fn diagnostic_json_includes_span_when_set() {
651        use serde_json::json;
652
653        let diagnostics = vec![Diagnostic::error("bad").with_span(3..9)];
654        assert_eq!(
655            fel_diagnostics_to_json_value(&diagnostics),
656            json!([{
657                "message": "bad",
658                "severity": "error",
659                "span": { "start": 3, "end": 9 }
660            }])
661        );
662    }
663
664    #[test]
665    fn diagnostic_json_includes_kind_arity_mismatch() {
666        use serde_json::json;
667
668        let d = Diagnostic::arity_mismatch("needsTwo", 2, Some(2), 1);
669        assert_eq!(
670            fel_diagnostics_to_json_value(&[d]),
671            json!([{
672                "message": "needsTwo: requires exactly 2 arguments",
673                "severity": "error",
674                "kind": {
675                    "arityMismatch": {
676                        "name": "needsTwo",
677                        "minArgs": 2,
678                        "maxArgs": 2,
679                        "got": 1
680                    }
681                }
682            }])
683        );
684    }
685
686    #[test]
687    fn diagnostic_json_includes_kind_undefined_function_js_camel() {
688        use serde_json::json;
689
690        use crate::wire_style::JsonWireStyle;
691
692        let diagnostics = vec![Diagnostic::undefined_function("foo")];
693        assert_eq!(
694            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::JsCamel),
695            json!([{
696                "message": "undefined function: foo",
697                "severity": "error",
698                "kind": { "undefinedFunction": { "name": "foo" } }
699            }])
700        );
701    }
702
703    #[test]
704    fn diagnostic_json_includes_kind_and_span_together() {
705        use serde_json::json;
706
707        let diagnostics = vec![Diagnostic::undefined_function("bar").with_span(1..5)];
708        assert_eq!(
709            fel_diagnostics_to_json_value(&diagnostics),
710            json!([{
711                "message": "undefined function: bar",
712                "severity": "error",
713                "span": { "start": 1, "end": 5 },
714                "kind": { "undefinedFunction": { "name": "bar" } }
715            }])
716        );
717    }
718
719    #[test]
720    fn diagnostic_json_snake_style_kind_keys() {
721        use serde_json::json;
722
723        use crate::wire_style::JsonWireStyle;
724
725        let diagnostics = vec![Diagnostic::undefined_function("x")];
726        assert_eq!(
727            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::PythonSnake),
728            json!([{
729                "message": "undefined function: x",
730                "severity": "error",
731                "kind": { "undefined_function": { "name": "x" } }
732            }])
733        );
734    }
735
736    #[test]
737    fn diagnostic_json_type_mismatch_js_camel() {
738        use serde_json::json;
739
740        use crate::wire_style::JsonWireStyle;
741
742        let diagnostics = vec![Diagnostic::type_mismatch("if", "boolean", "number")];
743        assert_eq!(
744            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::JsCamel),
745            json!([{
746                "message": "if: expected boolean, got number",
747                "severity": "error",
748                "kind": { "typeMismatch": { "fnName": "if", "expected": "boolean", "got": "number" } }
749            }])
750        );
751    }
752
753    #[test]
754    fn diagnostic_json_type_mismatch_python_snake() {
755        use serde_json::json;
756
757        use crate::wire_style::JsonWireStyle;
758
759        let diagnostics = vec![Diagnostic::type_mismatch("sum", "array", "string")];
760        assert_eq!(
761            fel_diagnostics_to_json_value_styled(&diagnostics, JsonWireStyle::PythonSnake),
762            json!([{
763                "message": "sum: expected array, got string",
764                "severity": "error",
765                "kind": { "type_mismatch": { "fn_name": "sum", "expected": "array", "got": "string" } }
766            }])
767        );
768    }
769}