Skip to main content

jsonata_core/
lib.rs

1// jsonatapy - High-performance Python implementation of JSONata
2// Copyright (c) 2025 jsonatapy contributors
3// Licensed under the MIT License
4
5//! # jsonatapy
6//!
7//! A high-performance Rust implementation of JSONata - the JSON query and
8//! transformation language - with optional Python bindings via PyO3.
9//!
10//! ## Rust API
11//!
12//! ```rust,ignore
13//! use jsonata_core::parser;
14//! use jsonata_core::evaluator::Evaluator;
15//! use jsonata_core::value::JValue;
16//!
17//! let ast = parser::parse("user.name").unwrap();
18//! let data = JValue::from_json_str(r#"{"user":{"name":"Alice"}}"#).unwrap();
19//! let result = Evaluator::new().evaluate(&ast, &data).unwrap();
20//! ```
21//!
22//! ## Architecture
23//!
24//! - `parser` - Expression parser (converts JSONata strings to AST)
25//! - `evaluator` - Expression evaluator (executes AST against data)
26//! - `functions` - Built-in function implementations
27//! - `datetime` - Date/time handling functions
28//! - `signature` - Function signature validation
29//! - `ast` - Abstract Syntax Tree definitions
30//! - `value` - JValue type (the runtime value representation)
31
32pub mod ast;
33pub mod ast_transform;
34mod compiler;
35mod datetime;
36pub mod evaluator;
37pub mod functions;
38pub mod parser;
39mod signature;
40pub mod value;
41mod vm;
42
43// ── Benchmarking facade (only when the "bench" feature is enabled) ────────────
44//
45// Exposes the compiler/VM pipeline for Criterion benchmarks without making
46// the internals part of the permanent public API.
47
48/// Internal benchmarking API — do not use in production code.
49///
50/// Enabled with `--features bench`. Provides access to the bytecode compiler
51/// and VM so that Criterion benchmarks can measure tree-walker vs VM directly.
52#[cfg(feature = "bench")]
53pub mod _bench {
54    use crate::ast::AstNode;
55    pub use crate::evaluator::EvaluatorError;
56    use crate::value::JValue;
57
58    /// An opaque handle to a compiled bytecode program.
59    pub struct CompiledProgram(crate::vm::BytecodeProgram);
60
61    /// Compile an AST node to bytecode.
62    ///
63    /// Returns `None` if the expression contains constructs the compiler
64    /// doesn't handle (e.g. wildcards, `$eval`, higher-order functions at
65    /// the top level). In that case, fall back to `Evaluator::new().evaluate()`.
66    pub fn compile(ast: &AstNode) -> Option<CompiledProgram> {
67        crate::evaluator::try_compile_expr(ast)
68            .map(|ce| CompiledProgram(crate::compiler::BytecodeCompiler::compile(&ce)))
69    }
70
71    /// Execute a compiled program against `data`.
72    pub fn run(prog: &CompiledProgram, data: &JValue) -> Result<JValue, EvaluatorError> {
73        crate::vm::Vm::with_options(&prog.0, crate::evaluator::EvaluatorOptions::default())
74            .run(data, None)
75    }
76}
77
78// ── Python bindings (only when the "python" feature is enabled) ───────────────
79
80/// The JSONata reference implementation version this library targets.
81const JSONATA_REFERENCE_VERSION: &str = "2.1.0";
82
83#[cfg(feature = "python")]
84use crate::value::JValue;
85#[cfg(feature = "python")]
86use indexmap::IndexMap;
87#[cfg(feature = "python")]
88use pyo3::exceptions::{PyTypeError, PyValueError};
89#[cfg(feature = "python")]
90use pyo3::prelude::*;
91#[cfg(feature = "python")]
92use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString};
93
94/// Pre-converted data handle for efficient repeated evaluation.
95///
96/// Convert Python data to an internal representation once, then reuse it
97/// across multiple evaluations to avoid repeated Python↔Rust conversion overhead.
98///
99/// # Examples
100///
101/// ```python
102/// import jsonatapy
103///
104/// data = jsonatapy.JsonataData({"orders": [{"price": 150}, {"price": 50}]})
105/// expr = jsonatapy.compile("orders[price > 100]")
106/// result = expr.evaluate_with_data(data)
107/// ```
108#[cfg(feature = "python")]
109#[pyclass(unsendable)]
110struct JsonataData {
111    data: JValue,
112}
113
114#[cfg(feature = "python")]
115#[pymethods]
116impl JsonataData {
117    /// Create from a Python object (dict, list, etc.)
118    #[new]
119    fn new(py: Python, data: Py<PyAny>) -> PyResult<Self> {
120        let jvalue = python_to_json(py, &data)?;
121        Ok(JsonataData { data: jvalue })
122    }
123
124    /// Create from a JSON string (fastest path).
125    #[staticmethod]
126    fn from_json(json_str: &str) -> PyResult<Self> {
127        let data = JValue::from_json_str(json_str)
128            .map_err(|e| PyValueError::new_err(format!("Invalid JSON: {}", e)))?;
129        Ok(JsonataData { data })
130    }
131}
132
133/// A compiled JSONata expression that can be evaluated against data.
134///
135/// This is the main entry point for using JSONata. Compile an expression once,
136/// then evaluate it multiple times against different data.
137///
138/// # Examples
139///
140/// ```python
141/// import jsonatapy
142///
143/// # Compile once
144/// expr = jsonatapy.compile("orders[price > 100].product")
145///
146/// # Evaluate many times
147/// data1 = {"orders": [{"product": "A", "price": 150}]}
148/// result1 = expr.evaluate(data1)
149///
150/// data2 = {"orders": [{"product": "B", "price": 50}]}
151/// result2 = expr.evaluate(data2)
152/// ```
153#[cfg(feature = "python")]
154#[pyclass(unsendable)]
155struct JsonataExpression {
156    /// The parsed Abstract Syntax Tree
157    ast: ast::AstNode,
158    /// Lazily compiled bytecode — populated on first evaluate() call.
159    /// `Some(bc)` = fast VM path; `None` = must use tree-walker.
160    /// `OnceCell` ensures compilation happens at most once per expression instance.
161    bytecode: std::cell::OnceCell<Option<vm::BytecodeProgram>>,
162    /// Default guardrail options set at `compile()` time. Per-call `evaluate*()`
163    /// kwargs override these on a field-by-field basis (see the `.or(...)` merges
164    /// in the `#[pymethods]` impl below).
165    default_options: evaluator::EvaluatorOptions,
166}
167
168#[cfg(feature = "python")]
169impl JsonataExpression {
170    /// Evaluate the compiled expression against pre-converted data.
171    /// Uses bytecode VM when available, falls back to tree-walker.
172    fn run_eval(
173        &self,
174        py: Python,
175        data: &JValue,
176        bindings: Option<Py<PyAny>>,
177        options: evaluator::EvaluatorOptions,
178    ) -> PyResult<JValue> {
179        if bindings.is_none() {
180            let bytecode = self.bytecode.get_or_init(|| {
181                evaluator::try_compile_expr(&self.ast)
182                    .map(|ce| compiler::BytecodeCompiler::compile(&ce))
183            });
184            if let Some(bc) = bytecode {
185                vm::Vm::with_options(bc, options.clone())
186                    .run(data, None)
187                    .map_err(evaluator_error_to_py)
188            } else {
189                let mut ev = evaluator::Evaluator::with_options(evaluator::Context::new(), options);
190                ev.evaluate(&self.ast, data).map_err(evaluator_error_to_py)
191            }
192        } else {
193            let mut ev = create_evaluator(py, bindings, options)?;
194            ev.evaluate(&self.ast, data).map_err(evaluator_error_to_py)
195        }
196    }
197}
198
199#[cfg(feature = "python")]
200#[pymethods]
201impl JsonataExpression {
202    /// Returns ValueError if evaluation fails
203    #[pyo3(signature = (data, bindings=None, timeout=None, max_stack_depth=None, max_sequence_length=None))]
204    #[allow(clippy::too_many_arguments)]
205    fn evaluate(
206        &self,
207        py: Python,
208        data: Py<PyAny>,
209        bindings: Option<Py<PyAny>>,
210        timeout: Option<u64>,
211        max_stack_depth: Option<usize>,
212        max_sequence_length: Option<usize>,
213    ) -> PyResult<Py<PyAny>> {
214        let json_data = python_to_json(py, &data)?;
215        let options = evaluator::EvaluatorOptions {
216            timeout_ms: timeout.or(self.default_options.timeout_ms),
217            max_stack_depth: max_stack_depth.or(self.default_options.max_stack_depth),
218            max_sequence_length: max_sequence_length.or(self.default_options.max_sequence_length),
219        };
220        json_to_python(py, &self.run_eval(py, &json_data, bindings, options)?)
221    }
222
223    /// Evaluate with a pre-converted data handle (fastest for repeated evaluation).
224    ///
225    /// # Arguments
226    ///
227    /// * `data` - A JsonataData handle (pre-converted from Python to internal format)
228    /// * `bindings` - Optional additional variable bindings
229    ///
230    /// # Returns
231    ///
232    /// The result of evaluating the expression
233    #[pyo3(signature = (data, bindings=None, timeout=None, max_stack_depth=None, max_sequence_length=None))]
234    #[allow(clippy::too_many_arguments)]
235    fn evaluate_with_data(
236        &self,
237        py: Python,
238        data: &JsonataData,
239        bindings: Option<Py<PyAny>>,
240        timeout: Option<u64>,
241        max_stack_depth: Option<usize>,
242        max_sequence_length: Option<usize>,
243    ) -> PyResult<Py<PyAny>> {
244        let options = evaluator::EvaluatorOptions {
245            timeout_ms: timeout.or(self.default_options.timeout_ms),
246            max_stack_depth: max_stack_depth.or(self.default_options.max_stack_depth),
247            max_sequence_length: max_sequence_length.or(self.default_options.max_sequence_length),
248        };
249        json_to_python(py, &self.run_eval(py, &data.data, bindings, options)?)
250    }
251
252    /// Evaluate with a pre-converted data handle, return JSON string (zero-overhead output).
253    ///
254    /// # Arguments
255    ///
256    /// * `data` - A JsonataData handle (pre-converted from Python to internal format)
257    /// * `bindings` - Optional additional variable bindings
258    ///
259    /// # Returns
260    ///
261    /// The result as a JSON string
262    #[pyo3(signature = (data, bindings=None, timeout=None, max_stack_depth=None, max_sequence_length=None))]
263    #[allow(clippy::too_many_arguments)]
264    fn evaluate_data_to_json(
265        &self,
266        py: Python,
267        data: &JsonataData,
268        bindings: Option<Py<PyAny>>,
269        timeout: Option<u64>,
270        max_stack_depth: Option<usize>,
271        max_sequence_length: Option<usize>,
272    ) -> PyResult<String> {
273        let options = evaluator::EvaluatorOptions {
274            timeout_ms: timeout.or(self.default_options.timeout_ms),
275            max_stack_depth: max_stack_depth.or(self.default_options.max_stack_depth),
276            max_sequence_length: max_sequence_length.or(self.default_options.max_sequence_length),
277        };
278        self.run_eval(py, &data.data, bindings, options)?
279            .to_json_string()
280            .map_err(|e| PyValueError::new_err(format!("Failed to serialize result: {}", e)))
281    }
282
283    /// Evaluate the expression with JSON string input/output (faster for large data).
284    ///
285    /// This method avoids Python↔Rust conversion overhead by accepting and returning
286    /// JSON strings directly. This is significantly faster for large datasets.
287    ///
288    /// # Arguments
289    ///
290    /// * `json_str` - Input data as a JSON string
291    /// * `bindings` - Optional dict of variable bindings (default: None)
292    ///
293    /// # Returns
294    ///
295    /// The result as a JSON string
296    ///
297    /// # Errors
298    ///
299    /// Returns ValueError if JSON parsing or evaluation fails
300    #[pyo3(signature = (json_str, bindings=None, timeout=None, max_stack_depth=None, max_sequence_length=None))]
301    #[allow(clippy::too_many_arguments)]
302    fn evaluate_json(
303        &self,
304        py: Python,
305        json_str: &str,
306        bindings: Option<Py<PyAny>>,
307        timeout: Option<u64>,
308        max_stack_depth: Option<usize>,
309        max_sequence_length: Option<usize>,
310    ) -> PyResult<String> {
311        let json_data = JValue::from_json_str(json_str)
312            .map_err(|e| PyValueError::new_err(format!("Invalid JSON: {}", e)))?;
313        let options = evaluator::EvaluatorOptions {
314            timeout_ms: timeout.or(self.default_options.timeout_ms),
315            max_stack_depth: max_stack_depth.or(self.default_options.max_stack_depth),
316            max_sequence_length: max_sequence_length.or(self.default_options.max_sequence_length),
317        };
318        self.run_eval(py, &json_data, bindings, options)?
319            .to_json_string()
320            .map_err(|e| PyValueError::new_err(format!("Failed to serialize result: {}", e)))
321    }
322}
323
324/// Compile a JSONata expression into an executable form.
325///
326/// # Arguments
327///
328/// * `expression` - A JSONata query/transformation expression string
329///
330/// # Returns
331///
332/// A compiled JsonataExpression that can be evaluated
333///
334/// # Errors
335///
336/// Returns ValueError if the expression cannot be parsed
337///
338/// # Examples
339///
340/// ```python
341/// import jsonatapy
342///
343/// expr = jsonatapy.compile("$.name")
344/// result = expr.evaluate({"name": "Alice"})
345/// print(result)  # "Alice"
346/// ```
347#[cfg(feature = "python")]
348#[pyfunction]
349#[pyo3(signature = (expression, timeout=None, max_stack_depth=None, max_sequence_length=None))]
350fn compile(
351    expression: &str,
352    timeout: Option<u64>,
353    max_stack_depth: Option<usize>,
354    max_sequence_length: Option<usize>,
355) -> PyResult<JsonataExpression> {
356    let ast = parser::parse(expression).map_err(parser_error_to_py)?;
357
358    Ok(JsonataExpression {
359        ast,
360        bytecode: std::cell::OnceCell::new(),
361        default_options: build_evaluator_options(timeout, max_stack_depth, max_sequence_length),
362    })
363}
364
365/// Evaluate a JSONata expression against data in one step.
366///
367/// This is a convenience function that compiles and evaluates in one call.
368/// For repeated evaluations of the same expression, use `compile()` instead.
369///
370/// # Arguments
371///
372/// * `expression` - A JSONata query/transformation expression string
373/// * `data` - A Python object (typically dict) to query/transform
374/// * `bindings` - Optional additional variable bindings
375///
376/// # Returns
377///
378/// The result of evaluating the expression
379///
380/// # Errors
381///
382/// Returns ValueError if parsing or evaluation fails
383///
384/// # Examples
385///
386/// ```python
387/// import jsonatapy
388///
389/// result = jsonatapy.evaluate("$uppercase(name)", {"name": "alice"})
390/// print(result)  # "ALICE"
391/// ```
392#[cfg(feature = "python")]
393#[pyfunction]
394#[pyo3(signature = (expression, data, bindings=None, timeout=None, max_stack_depth=None, max_sequence_length=None))]
395#[allow(clippy::too_many_arguments)]
396fn evaluate(
397    py: Python,
398    expression: &str,
399    data: Py<PyAny>,
400    bindings: Option<Py<PyAny>>,
401    timeout: Option<u64>,
402    max_stack_depth: Option<usize>,
403    max_sequence_length: Option<usize>,
404) -> PyResult<Py<PyAny>> {
405    let expr = compile(expression, None, None, None)?;
406    expr.evaluate(
407        py,
408        data,
409        bindings,
410        timeout,
411        max_stack_depth,
412        max_sequence_length,
413    )
414}
415
416/// Convert a Python object to a JValue.
417///
418/// Handles conversion of Python types:
419/// - None -> Null
420/// - bool -> Bool (checked before int since bool is a subclass of int)
421/// - int, float -> Number
422/// - str -> String
423/// - list -> Array
424/// - dict -> Object
425#[cfg(feature = "python")]
426fn python_to_json(py: Python, obj: &Py<PyAny>) -> PyResult<JValue> {
427    python_to_json_bound(obj.bind(py))
428}
429
430/// Inner conversion using Bound API for zero-overhead type checks.
431///
432/// Uses is_instance_of::<T>() which compiles to C-level type pointer comparisons
433/// (PyBool_Check, PyLong_Check, etc.) — single pointer comparison vs qualname()
434/// which allocates a Python string and does string comparison.
435#[cfg(feature = "python")]
436fn python_to_json_bound(obj: &Bound<'_, PyAny>) -> PyResult<JValue> {
437    if obj.is_none() {
438        return Ok(JValue::Null);
439    }
440
441    // Check bool before int — Python bool is a subclass of int
442    if obj.is_instance_of::<PyBool>() {
443        return Ok(JValue::Bool(obj.extract::<bool>()?));
444    }
445    if obj.is_instance_of::<PyInt>() {
446        return Ok(JValue::Number(obj.extract::<i64>()? as f64));
447    }
448    if obj.is_instance_of::<PyFloat>() {
449        return Ok(JValue::Number(obj.extract::<f64>()?));
450    }
451    if obj.is_instance_of::<PyString>() {
452        return Ok(JValue::string(obj.extract::<String>()?));
453    }
454    if let Ok(list) = obj.cast::<PyList>() {
455        let mut result = Vec::with_capacity(list.len());
456        for item in list.iter() {
457            result.push(python_to_json_bound(&item)?);
458        }
459        return Ok(JValue::array(result));
460    }
461    if let Ok(dict) = obj.cast::<PyDict>() {
462        let mut result = IndexMap::with_capacity(dict.len());
463        for (key, value) in dict.iter() {
464            let key_str = key.extract::<String>()?;
465            result.insert(key_str, python_to_json_bound(&value)?);
466        }
467        return Ok(JValue::object(result));
468    }
469
470    // Fallback for subclasses, numpy types, etc.
471    if let Ok(b) = obj.extract::<bool>() {
472        return Ok(JValue::Bool(b));
473    }
474    if let Ok(i) = obj.extract::<i64>() {
475        return Ok(JValue::Number(i as f64));
476    }
477    if let Ok(f) = obj.extract::<f64>() {
478        return Ok(JValue::Number(f));
479    }
480    if let Ok(s) = obj.extract::<String>() {
481        return Ok(JValue::string(s));
482    }
483
484    Err(PyTypeError::new_err(format!(
485        "Cannot convert Python object to JSON: {}",
486        obj.get_type().name()?
487    )))
488}
489
490/// Convert a JValue to a Python object.
491///
492/// Handles conversion of JValue variants to Python types:
493/// - Null/Undefined -> None
494/// - Bool -> bool
495/// - Number -> int (if whole number) or float
496/// - String -> str
497/// - Array -> list (batch-constructed via PyList::new for fewer C API calls)
498/// - Object -> dict
499/// - Lambda/Builtin/Regex -> None
500#[cfg(feature = "python")]
501fn json_to_python(py: Python, value: &JValue) -> PyResult<Py<PyAny>> {
502    match value {
503        JValue::Null | JValue::Undefined => Ok(py.None()),
504
505        JValue::Bool(b) => Ok(b.into_pyobject(py).unwrap().to_owned().into_any().unbind()),
506
507        JValue::Number(n) => {
508            // If it's a whole number that fits in i64, return as Python int
509            if n.fract() == 0.0 && n.is_finite() && *n >= i64::MIN as f64 && *n <= i64::MAX as f64 {
510                Ok((*n as i64).into_pyobject(py).unwrap().into_any().unbind())
511            } else {
512                Ok(n.into_pyobject(py).unwrap().into_any().unbind())
513            }
514        }
515
516        JValue::String(s) => Ok((&**s).into_pyobject(py).unwrap().into_any().unbind()),
517
518        JValue::Array(arr) => {
519            // Array of objects with shared keys: intern first object's keys as
520            // Python strings to avoid repeated UTF-8 -> PyString conversion.
521            let all_objects =
522                arr.len() >= 2 && arr.iter().all(|item| matches!(item, JValue::Object(_)));
523            if all_objects {
524                let first_obj = match arr.first() {
525                    Some(JValue::Object(obj)) => obj,
526                    _ => unreachable!("all_objects guard ensures first element is an object"),
527                };
528
529                // Intern keys: store (&str, Py<PyString>) — no String clone needed
530                // since first_obj borrows from arr which outlives this block
531                let interned_keys: Vec<(&str, Py<PyString>)> = first_obj
532                    .keys()
533                    .map(|k| (k.as_str(), PyString::new(py, k).unbind()))
534                    .collect();
535
536                let items: Vec<Py<PyAny>> = arr
537                    .iter()
538                    .map(|item| {
539                        // Safe to unwrap: all_objects guarantees every element is Object
540                        let obj = match item {
541                            JValue::Object(obj) => obj,
542                            _ => unreachable!(),
543                        };
544                        let dict = PyDict::new(py);
545                        for (key_str, py_key) in &interned_keys {
546                            if let Some(value) = obj.get(*key_str) {
547                                dict.set_item(py_key.bind(py), json_to_python(py, value)?)?;
548                            }
549                        }
550                        // Handle any extra keys not in first object
551                        for (key, value) in obj.iter() {
552                            if !first_obj.contains_key(key) {
553                                dict.set_item(key, json_to_python(py, value)?)?;
554                            }
555                        }
556                        Ok(dict.unbind().into())
557                    })
558                    .collect::<PyResult<Vec<_>>>()?;
559                return Ok(PyList::new(py, &items)?.unbind().into());
560            }
561
562            // General array: batch construction
563            let items: Vec<Py<PyAny>> = arr
564                .iter()
565                .map(|item| json_to_python(py, item))
566                .collect::<PyResult<Vec<_>>>()?;
567            Ok(PyList::new(py, &items)?.unbind().into())
568        }
569
570        JValue::Object(obj) => {
571            let dict = PyDict::new(py);
572            for (key, value) in obj.iter() {
573                dict.set_item(key, json_to_python(py, value)?)?;
574            }
575            Ok(dict.unbind().into())
576        }
577
578        JValue::Lambda { .. } | JValue::Builtin { .. } | JValue::Regex { .. } => Ok(py.None()),
579    }
580}
581
582/// Build an `EvaluatorOptions` from the Python-facing `timeout`/`max_stack_depth`/
583/// `max_sequence_length` kwargs used by `compile()` and the free-standing `evaluate()`.
584#[cfg(feature = "python")]
585fn build_evaluator_options(
586    timeout: Option<u64>,
587    max_stack_depth: Option<usize>,
588    max_sequence_length: Option<usize>,
589) -> evaluator::EvaluatorOptions {
590    evaluator::EvaluatorOptions {
591        timeout_ms: timeout,
592        max_stack_depth,
593        max_sequence_length,
594    }
595}
596
597/// Create an evaluator, optionally configured with Python bindings
598#[cfg(feature = "python")]
599fn create_evaluator(
600    py: Python,
601    bindings: Option<Py<PyAny>>,
602    options: evaluator::EvaluatorOptions,
603) -> PyResult<evaluator::Evaluator> {
604    let mut context = evaluator::Context::new();
605    if let Some(bindings_obj) = bindings {
606        let bindings_json = python_to_json(py, &bindings_obj)?;
607        if let JValue::Object(map) = bindings_json {
608            for (key, value) in map.iter() {
609                context.bind(key.clone(), value.clone());
610            }
611        } else {
612            return Err(PyTypeError::new_err("bindings must be a dictionary"));
613        }
614    }
615    Ok(evaluator::Evaluator::with_options(context, options))
616}
617
618/// Convert an EvaluatorError to a PyErr
619#[cfg(feature = "python")]
620fn evaluator_error_to_py(e: evaluator::EvaluatorError) -> PyErr {
621    match e {
622        evaluator::EvaluatorError::TypeError(msg) => PyValueError::new_err(msg),
623        evaluator::EvaluatorError::ReferenceError(msg) => PyValueError::new_err(msg),
624        evaluator::EvaluatorError::EvaluationError(msg) => PyValueError::new_err(msg),
625    }
626}
627
628/// Format a ParserError's Python-facing message.
629/// Coded errors (e.g., S0214) have their message formatted as "code: message",
630/// so they are passed through directly without an additional "Parse error: " prefix.
631/// Other errors get the "Parse error: " prefix for clarity.
632///
633/// Split out from `parser_error_to_py` so this formatting logic can be unit
634/// tested without constructing a `PyErr` (which requires an initialized
635/// Python interpreter -- fine under `maturin develop`/pytest, but panics
636/// under a plain `cargo test --all-features` with no embedded interpreter).
637fn format_parser_error_message(e: &parser::ParserError) -> String {
638    let msg = e.to_string();
639    if matches!(e, parser::ParserError::Coded { .. }) {
640        // Coded errors already have the format "code: message"
641        msg
642    } else {
643        // Other errors get the "Parse error: " prefix
644        format!("Parse error: {}", msg)
645    }
646}
647
648/// Convert a ParserError to a PyErr
649#[cfg(feature = "python")]
650fn parser_error_to_py(e: parser::ParserError) -> PyErr {
651    PyValueError::new_err(format_parser_error_message(&e))
652}
653
654/// JSONata Python module
655#[cfg(feature = "python")]
656#[pymodule]
657fn _jsonatapy(m: &Bound<'_, PyModule>) -> PyResult<()> {
658    m.add_function(wrap_pyfunction!(compile, m)?)?;
659    m.add_function(wrap_pyfunction!(evaluate, m)?)?;
660    m.add_class::<JsonataExpression>()?;
661    m.add_class::<JsonataData>()?;
662
663    // Add version info
664    m.add("__version__", env!("CARGO_PKG_VERSION"))?;
665    m.add("__jsonata_version__", JSONATA_REFERENCE_VERSION)?;
666
667    Ok(())
668}
669
670#[cfg(test)]
671mod tests {
672    #[test]
673    fn test_module_creation() {
674        // Basic smoke test
675        assert!(!env!("CARGO_PKG_VERSION").is_empty());
676    }
677
678    mod parser_error_handling {
679        use super::super::*;
680
681        // These test format_parser_error_message() directly (a plain string
682        // function) rather than parser_error_to_py(), which constructs a
683        // PyErr -- that requires an initialized Python interpreter, which
684        // isn't available under a bare `cargo test --all-features` run (no
685        // embedded interpreter, unlike the maturin-built extension loaded
686        // into a live Python process). The formatting logic under test is
687        // identical either way.
688
689        #[test]
690        fn test_parser_error_to_py_coded_error_no_prefix() {
691            // Test that coded errors (like S0214) are passed through without "Parse error: " prefix
692            let coded_error = parser::ParserError::Coded {
693                code: "S0214",
694                message: "Expected a variable reference after @".to_string(),
695            };
696            let msg = format_parser_error_message(&coded_error);
697
698            // The message should start with the code, not "Parse error: "
699            assert!(
700                msg.starts_with("S0214:"),
701                "Expected message to start with 'S0214:', got: {}",
702                msg
703            );
704            assert!(
705                !msg.starts_with("Parse error:"),
706                "Expected no 'Parse error:' prefix, got: {}",
707                msg
708            );
709        }
710
711        #[test]
712        fn test_parser_error_to_py_non_coded_error_with_prefix() {
713            // Test that non-coded errors still get the "Parse error: " prefix
714            let non_coded_error = parser::ParserError::UnexpectedToken("foo".to_string());
715            let msg = format_parser_error_message(&non_coded_error);
716
717            // The message should have the "Parse error: " prefix
718            assert!(
719                msg.starts_with("Parse error:"),
720                "Expected message to start with 'Parse error:', got: {}",
721                msg
722            );
723        }
724    }
725}