use std::fmt;
use std::ops::Range;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
pub message: String,
pub span: Option<Range<usize>>,
}
impl ParseError {
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
span: None,
}
}
#[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)
}
}
#[derive(Debug, Clone)]
pub enum Error {
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 {}
#[derive(Debug, Clone)]
pub struct Diagnostic {
pub severity: Severity,
pub message: String,
pub code: Option<String>,
pub kind: Option<DiagnosticKind>,
pub span: Option<Range<usize>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Error,
Warning,
Info,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagnosticKind {
UndefinedFunction {
name: String,
},
TypeMismatch {
fn_name: String,
expected: String,
got: String,
},
ArityMismatch {
name: String,
min_args: usize,
max_args: Option<usize>,
got: usize,
},
MissingTimezoneContext {
fn_name: String,
reason: MissingTimezoneContextReason,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MissingTimezoneContextReason {
NotConfigured,
MultiCalendarConflict {
calendars: Vec<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingTimezoneContextError {
pub reason: MissingTimezoneContextReason,
}
impl MissingTimezoneContextError {
#[must_use]
pub fn not_configured() -> Self {
Self {
reason: MissingTimezoneContextReason::NotConfigured,
}
}
#[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 {}
pub(crate) fn arity_argument_word(count: usize) -> &'static str {
if count == 1 { "argument" } else { "arguments" }
}
pub(crate) fn arity_requires_exactly_message(name: &str, n: usize) -> String {
format!("{name}: requires exactly {n} {}", arity_argument_word(n))
}
pub(crate) fn arity_requires_at_least_message(name: &str, min: usize) -> String {
format!(
"{name}: requires at least {min} {}",
arity_argument_word(min)
)
}
pub(crate) fn arity_requires_at_most_message(name: &str, max: usize) -> String {
format!(
"{name}: requires at most {max} {}",
arity_argument_word(max)
)
}
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 {
pub fn as_wire_str(self) -> &'static str {
match self {
Self::Error => "error",
Self::Warning => "warning",
Self::Info => "info",
}
}
}
impl Diagnostic {
pub fn error(msg: impl Into<String>) -> Self {
Diagnostic {
severity: Severity::Error,
message: msg.into(),
code: None,
kind: None,
span: None,
}
}
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,
}
}
pub fn warning(msg: impl Into<String>) -> Self {
Diagnostic {
severity: Severity::Warning,
message: msg.into(),
code: None,
kind: None,
span: None,
}
}
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,
}
}
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,
}
}
pub fn extension_failed(name: impl Into<String>, message: impl Into<String>) -> Self {
Diagnostic::error(format!(
"{}: extension function failed: {}",
name.into(),
message.into()
))
}
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,
}
}
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,
}
}
#[must_use]
pub fn with_span(mut self, span: Range<usize>) -> Self {
self.span = Some(span);
self
}
}
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()
}
pub fn has_error_diagnostics(diagnostics: &[Diagnostic]) -> bool {
diagnostics.iter().any(|d| d.severity == Severity::Error)
}
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(", ")))
}
}
pub fn fel_diagnostics_to_json_value(diagnostics: &[Diagnostic]) -> serde_json::Value {
fel_diagnostics_to_json_value_styled(diagnostics, crate::wire_style::JsonWireStyle::JsCamel)
}
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 } => {
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)
})
}
}
}
}
}
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))
}
}
}
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)
}
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" } }
}])
);
}
}