1use std::fmt;
3use std::ops::Range;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct ParseError {
10 pub message: String,
12 pub span: Option<Range<usize>>,
14}
15
16impl ParseError {
17 #[must_use]
19 pub fn new(message: impl Into<String>) -> Self {
20 Self {
21 message: message.into(),
22 span: None,
23 }
24 }
25
26 #[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#[derive(Debug, Clone)]
44pub enum Error {
45 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#[derive(Debug, Clone)]
61pub struct Diagnostic {
62 pub severity: Severity,
64 pub message: String,
66 pub code: Option<String>,
68 pub kind: Option<DiagnosticKind>,
70 pub span: Option<Range<usize>>,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Severity {
77 Error,
79 Warning,
81 Info,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum DiagnosticKind {
92 UndefinedFunction {
94 name: String,
96 },
97 TypeMismatch {
99 fn_name: String,
101 expected: String,
103 got: String,
105 },
106 ArityMismatch {
108 name: String,
110 min_args: usize,
112 max_args: Option<usize>,
114 got: usize,
116 },
117 MissingTimezoneContext {
125 fn_name: String,
127 reason: MissingTimezoneContextReason,
129 },
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
142pub enum MissingTimezoneContextReason {
143 NotConfigured,
145 MultiCalendarConflict {
148 calendars: Vec<String>,
151 },
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct MissingTimezoneContextError {
164 pub reason: MissingTimezoneContextReason,
166}
167
168impl MissingTimezoneContextError {
169 #[must_use]
171 pub fn not_configured() -> Self {
172 Self {
173 reason: MissingTimezoneContextReason::NotConfigured,
174 }
175 }
176
177 #[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
204pub(crate) fn arity_argument_word(count: usize) -> &'static str {
206 if count == 1 { "argument" } else { "arguments" }
207}
208
209pub(crate) fn arity_requires_exactly_message(name: &str, n: usize) -> String {
211 format!("{name}: requires exactly {n} {}", arity_argument_word(n))
212}
213
214pub(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
222pub(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
230pub(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 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 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 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 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 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 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 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 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 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 #[must_use]
388 pub fn with_span(mut self, span: Range<usize>) -> Self {
389 self.span = Some(span);
390 self
391 }
392}
393
394pub 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
413pub fn has_error_diagnostics(diagnostics: &[Diagnostic]) -> bool {
415 diagnostics.iter().any(|d| d.severity == Severity::Error)
416}
417
418pub 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
428pub 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
433fn 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 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
531fn 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
545fn 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
573pub 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}