Skip to main content

fel_core/
trace.rs

1//! Structured evaluation traces for FEL.
2//!
3//! A [`Trace`] is an ordered sequence of [`TraceStep`]s that records what the
4//! evaluator did while producing a result. Traces are opt-in: the hot-path
5//! [`crate::evaluate`] function does not allocate or emit any steps. Use
6//! [`crate::evaluate_with`] with [`crate::EvaluatorOptions::trace`] set (and optionally [`crate::EvaluatorOptions::extensions`] when host
7//! extensions must appear in the trace) to capture one.
8//!
9//! Traces are designed for human and LLM consumption, not for re-evaluation.
10//! Values are projected to `serde_json::Value` — losing FEL type fidelity
11//! (money, date) but gaining universal readability. Add new variants as the
12//! need arises; this v0 set covers field resolution, function calls, binary
13//! ops, conditional branches, and short-circuit skips.
14use serde::Serialize;
15
16/// A single recorded event during FEL evaluation.
17///
18/// The variant set is intentionally narrow: only events that help explain
19/// *why* an expression produced its result. Non-covered AST nodes omit steps
20/// rather than emitting noise — correctness over completeness.
21#[derive(Debug, Clone, Serialize)]
22#[serde(tag = "kind")]
23pub enum TraceStep {
24    /// A `$field` reference was resolved against the environment.
25    FieldResolved {
26        /// Dotted path as written in source (e.g. `foo`, `items[2].amount`).
27        path: String,
28        /// Value returned by the environment, projected to JSON.
29        value: serde_json::Value,
30    },
31    /// A function call completed and returned a value.
32    ///
33    /// Emitted only for functions that eagerly evaluate all arguments. Lazy
34    /// or short-circuiting functions (`if`, `countWhere`, `every`, `some`,
35    /// etc.) rely on other step kinds to explain themselves.
36    FunctionCalled {
37        /// Function name as written in source.
38        name: String,
39        /// Argument values, in order.
40        args: Vec<serde_json::Value>,
41        /// Return value.
42        result: serde_json::Value,
43    },
44    /// A binary operator produced a result from two operand values.
45    ///
46    /// Covers arithmetic (`+ - * /`), comparison (`< <= == != > >=`), and
47    /// `and`/`or` when both sides were actually evaluated. Short-circuited
48    /// `and`/`or` emit [`TraceStep::ShortCircuit`] instead.
49    BinaryOp {
50        /// Operator symbol (`+`, `==`, `and`, ...).
51        op: String,
52        /// Left-hand value.
53        lhs: serde_json::Value,
54        /// Right-hand value.
55        rhs: serde_json::Value,
56        /// Result value.
57        result: serde_json::Value,
58    },
59    /// A conditional (`if(...)` call or `if-then-else` / ternary) selected a branch.
60    IfBranch {
61        /// The evaluated condition value.
62        condition_value: serde_json::Value,
63        /// Which branch was taken: `"then"` or `"else"`.
64        branch_taken: &'static str,
65    },
66    /// A logical operator short-circuited; the right-hand side was not evaluated.
67    ShortCircuit {
68        /// Operator symbol (`and` or `or`).
69        op: String,
70        /// Human-readable reason (e.g. `"left of 'and' was false, skipped right"`).
71        reason: String,
72    },
73}
74
75/// An ordered record of everything the evaluator emitted during one run.
76///
77/// Steps are appended in evaluation order. A consumer (linter, MCP tool,
78/// error-explainer) can render the sequence top-to-bottom to reconstruct
79/// *why* the expression produced its result.
80#[derive(Debug, Clone, Default, Serialize)]
81pub struct Trace {
82    /// Steps in evaluation order.
83    pub steps: Vec<TraceStep>,
84}
85
86impl Trace {
87    /// Create an empty trace.
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    /// Append a step.
93    pub fn push(&mut self, step: TraceStep) {
94        self.steps.push(step);
95    }
96
97    /// Number of recorded steps.
98    pub fn len(&self) -> usize {
99        self.steps.len()
100    }
101
102    /// True when no steps have been recorded.
103    pub fn is_empty(&self) -> bool {
104        self.steps.is_empty()
105    }
106}