formatparse-pyo3 0.8.1

PyO3 bindings for formatparse (native _formatparse extension; use PyPI for Python installs)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! formatparse-pyo3: PyO3 bindings for formatparse
//!
//! formatparse-pyo3 provides Python bindings for the formatparse-core library.

use pyo3::exceptions::PyNotImplementedError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
use pyo3::IntoPyObjectExt;
use std::collections::HashMap;

mod datetime;
mod error;
mod match_rs;
mod parser;
mod pattern_cache;
mod pattern_normalize;
mod result;
mod results;
mod types;

pub(crate) use pattern_cache::extract_extra_types_identity;
use pattern_cache::get_or_create_parser;

pub use datetime::FixedTzOffset;
pub use parser::{FindallIter, Format, FormatParser};
pub use result::*;
pub use results::Results;
pub use types::conversion::*;
// Core types come from formatparse-core
pub use formatparse_core::strftime_to_regex;
pub use formatparse_core::{FieldSpec, FieldType};
pub use match_rs::Match;

pub use error::PatternParseMismatch;

/// Parse a string using a format specification
#[pyfunction]
#[pyo3(signature = (pattern, string, extra_types=None, case_sensitive=false, evaluate_result=true))]
fn parse(
    pattern: &str,
    string: &str,
    extra_types: Option<HashMap<String, PyObject>>,
    case_sensitive: bool,
    evaluate_result: bool,
) -> PyResult<Option<PyObject>> {
    // Validate input lengths
    formatparse_core::validate_input_length(string)
        .map_err(pyo3::exceptions::PyValueError::new_err)?;

    // Check for null bytes in inputs
    if string.contains('\0') {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "Input string contains null byte",
        ));
    }

    // Use cached parser if available
    let extra_types_cloned = Python::with_gil(|py| -> Option<HashMap<String, PyObject>> {
        extra_types.as_ref().map(|et| {
            et.iter()
                .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                .collect()
        })
    });
    match get_or_create_parser(pattern, extra_types_cloned) {
        Ok(parser) => parser.parse_internal(
            string,
            case_sensitive,
            extra_types.as_ref(),
            evaluate_result,
        ),
        Err(e) => Python::with_gil(|py| {
            if e.is_instance_of::<PyNotImplementedError>(py) {
                return Err(e);
            }
            if e.is_instance_of::<crate::error::PatternParseMismatch>(py) {
                return Ok(None);
            }
            Err(e)
        }),
    }
}

/// Parse many strings with the same pattern, compiling the pattern once.
///
/// Each input string uses the same semantics as `parse` (including
/// `extra_types`, `case_sensitive`, and `evaluate_result`). Non-matches
/// become Python `None` at that index in the returned list.
#[pyfunction]
#[pyo3(signature = (pattern, strings, extra_types=None, case_sensitive=false, evaluate_result=true))]
fn parse_batch(
    pattern: &str,
    strings: Vec<String>,
    extra_types: Option<HashMap<String, PyObject>>,
    case_sensitive: bool,
    evaluate_result: bool,
) -> PyResult<PyObject> {
    for s in &strings {
        formatparse_core::validate_input_length(s)
            .map_err(pyo3::exceptions::PyValueError::new_err)?;
        if s.contains('\0') {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "Input string contains null byte",
            ));
        }
    }

    let extra_types_cloned = Python::with_gil(|py| -> Option<HashMap<String, PyObject>> {
        extra_types.as_ref().map(|et| {
            et.iter()
                .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                .collect()
        })
    });

    let parser = match get_or_create_parser(pattern, extra_types_cloned) {
        Ok(p) => p,
        Err(e) => {
            return Python::with_gil(|py| -> PyResult<PyObject> {
                if e.is_instance_of::<PyNotImplementedError>(py) {
                    return Err(e);
                }
                if e.is_instance_of::<crate::error::PatternParseMismatch>(py) {
                    let none_obj = py.None().into_py_any(py)?;
                    let mut out: Vec<PyObject> = Vec::with_capacity(strings.len());
                    for _ in 0..strings.len() {
                        out.push(none_obj.clone_ref(py));
                    }
                    let items: Vec<_> = out.iter().map(|o| o.bind(py)).collect();
                    return PyList::new(py, items)?.into_py_any(py);
                }
                Err(e)
            });
        }
    };

    Python::with_gil(|py| -> PyResult<PyObject> {
        let mut out: Vec<PyObject> = Vec::with_capacity(strings.len());
        for s in &strings {
            match parser.parse_internal(s, case_sensitive, extra_types.as_ref(), evaluate_result)? {
                Some(obj) => out.push(obj),
                None => out.push(py.None().into_py_any(py)?),
            }
        }
        let items: Vec<_> = out.iter().map(|o| o.bind(py)).collect();
        PyList::new(py, items)?.into_py_any(py)
    })
}

/// Search for a pattern in a string
#[pyfunction]
#[pyo3(signature = (pattern, string, pos=0, endpos=None, extra_types=None, case_sensitive=true, evaluate_result=true))]
fn search(
    pattern: &str,
    string: &str,
    pos: usize,
    endpos: Option<usize>,
    extra_types: Option<HashMap<String, PyObject>>,
    case_sensitive: bool,
    evaluate_result: bool,
) -> PyResult<Option<PyObject>> {
    // Validate pos parameter
    if pos > string.len() {
        return Ok(None);
    }

    // Validate endpos parameter
    let end = endpos.unwrap_or(string.len());
    if end > string.len() {
        return Ok(None);
    }
    if end < pos {
        return Ok(None);
    }

    // Validate input lengths
    formatparse_core::validate_input_length(string)
        .map_err(pyo3::exceptions::PyValueError::new_err)?;

    // Check for null bytes in inputs
    if string.contains('\0') {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "Input string contains null byte",
        ));
    }

    let extra_types_cloned = Python::with_gil(|py| -> Option<HashMap<String, PyObject>> {
        extra_types.as_ref().map(|et| {
            et.iter()
                .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                .collect()
        })
    });
    let parser = get_or_create_parser(pattern, extra_types_cloned)?;
    let search_string = &string[pos..end];

    if let Some(result) =
        parser.search_pattern(search_string, case_sensitive, extra_types, evaluate_result)?
    {
        // Adjust positions if it's a ParseResult (not Match)
        Python::with_gil(|py| {
            if let Ok(parse_result) = result.bind(py).downcast::<ParseResult>() {
                let result_value = parse_result.borrow();
                let adjusted = result_value.clone().with_offset(pos);
                // Py::new() is already optimized when GIL is held
                Ok(Some(Py::new(py, adjusted)?.into_py_any(py)?))
            } else {
                // It's a Match object - we need to adjust its span
                // For now, just return it as-is (Match spans are relative to search start)
                Ok(Some(result))
            }
        })
    } else {
        Ok(None)
    }
}

/// Find all matches of a pattern in a string
#[pyfunction]
#[pyo3(signature = (pattern, string, extra_types=None, case_sensitive=false, evaluate_result=true))]
fn findall(
    pattern: &str,
    string: &str,
    extra_types: Option<HashMap<String, PyObject>>,
    case_sensitive: bool,
    evaluate_result: bool,
) -> PyResult<PyObject> {
    // Validate input lengths
    formatparse_core::validate_input_length(string)
        .map_err(pyo3::exceptions::PyValueError::new_err)?;

    // Check for null bytes in inputs
    if string.contains('\0') {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "Input string contains null byte",
        ));
    }

    let extra_types_cloned = Python::with_gil(|py| -> Option<HashMap<String, PyObject>> {
        extra_types.as_ref().map(|et| {
            et.iter()
                .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                .collect()
        })
    });
    let parser = get_or_create_parser(pattern, extra_types_cloned)?;
    crate::parser::findall_engine::findall_matches(
        parser,
        string,
        extra_types.as_ref(),
        case_sensitive,
        evaluate_result,
    )
}

/// Iterator over non-overlapping matches (same scan as :func:`findall`, one item per step).
///
/// See :class:`FindallIter` for memory semantics and limitations (issue #13 MVP).
#[pyfunction]
#[pyo3(signature = (pattern, string, extra_types=None, case_sensitive=false, evaluate_result=true))]
fn findall_iter(
    py: Python<'_>,
    pattern: &str,
    string: &str,
    extra_types: Option<HashMap<String, PyObject>>,
    case_sensitive: bool,
    evaluate_result: bool,
) -> PyResult<Py<FindallIter>> {
    formatparse_core::validate_input_length(string)
        .map_err(pyo3::exceptions::PyValueError::new_err)?;

    if string.contains('\0') {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "Input string contains null byte",
        ));
    }

    let extra_types_cloned = Python::with_gil(|py| -> Option<HashMap<String, PyObject>> {
        extra_types.as_ref().map(|et| {
            et.iter()
                .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                .collect()
        })
    });
    let parser = get_or_create_parser(pattern, extra_types_cloned)?;

    let et_map = Python::with_gil(|py| -> HashMap<String, PyObject> {
        extra_types
            .as_ref()
            .map(|et| {
                et.iter()
                    .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                    .collect()
            })
            .unwrap_or_default()
    });

    Py::new(
        py,
        FindallIter::new(
            parser,
            string.to_string(),
            case_sensitive,
            evaluate_result,
            et_map,
        ),
    )
}

/// Compile a pattern into a FormatParser for reuse.
///
/// Uses the same LRU cache as the `parse`, `search`, and `findall` bindings:
/// `compile` with the same pattern and equivalent `extra_types` keys avoids
/// rebuilding compiled regexes (see GitHub issue #29).
#[pyfunction]
#[pyo3(signature = (pattern, extra_types=None))]
fn compile(
    pattern: &str,
    extra_types: Option<HashMap<String, PyObject>>,
) -> PyResult<FormatParser> {
    let extra_types_cloned = Python::with_gil(|py| -> Option<HashMap<String, PyObject>> {
        extra_types.as_ref().map(|et| {
            et.iter()
                .map(|(k, v)| (k.clone(), v.clone_ref(py)))
                .collect()
        })
    });
    let arc = get_or_create_parser(pattern, extra_types_cloned)?;
    Ok((*arc).clone())
}

/// Extract format specification components from a format string
#[pyfunction]
#[pyo3(signature = (format_string, _match_dict=None))]
fn extract_format(
    format_string: &str,
    _match_dict: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyObject> {
    use crate::types::FieldSpec;

    // Parse the format spec string
    let mut spec = FieldSpec::new();
    formatparse_core::parser::pattern::parse_format_spec(format_string, &mut spec)
        .map_err(crate::parser::pattern::pattern_compile_error_to_py)?;
    formatparse_core::parser::pattern::validate_multiline_mvp(&spec)
        .map_err(crate::parser::pattern::pattern_compile_error_to_py)?;

    // Extract type from the original format_string (preserve original type chars like 'o', 'x', 'b')
    // Parse the format spec to extract the type characters that come after width/precision/alignment
    let type_str: String = if format_string == "%" {
        "%".to_string()
    } else {
        // Parse format spec to find where type starts
        // Format: [[fill]align][sign][#][0][width][,][.precision][type]
        let chars: Vec<char> = format_string.chars().collect();
        let mut i = 0;
        let len = chars.len();

        // Skip fill and align
        if i < len && (chars[i] == '<' || chars[i] == '>' || chars[i] == '^' || chars[i] == '=') {
            i += 1;
        } else if i + 1 < len {
            let ch = chars[i];
            let next_ch = chars[i + 1];
            if (next_ch == '<' || next_ch == '>' || next_ch == '^' || next_ch == '=')
                && ch != next_ch
            {
                i += 2; // Skip fill + align
            }
        }

        // Skip sign
        if i < len && (chars[i] == '+' || chars[i] == '-' || chars[i] == ' ') {
            i += 1;
        }

        // Skip #
        if i < len && chars[i] == '#' {
            i += 1;
        }

        // Skip 0
        if i < len && chars[i] == '0' {
            i += 1;
        }

        // Skip width (digits)
        while i < len && chars[i].is_ascii_digit() {
            i += 1;
        }

        // Skip comma
        if i < len && chars[i] == ',' {
            i += 1;
        }

        // Skip precision (.digits)
        if i < len && chars[i] == '.' {
            i += 1;
            while i < len && chars[i].is_ascii_digit() {
                i += 1;
            }
        }

        // Type is the rest
        if i < len {
            format_string[i..].to_string()
        } else {
            "s".to_string() // Default
        }
    };

    // Build result dictionary
    Python::with_gil(|py| {
        let result = PyDict::new(py);
        result.set_item("type", type_str)?;

        // Extract width
        if let Some(width) = spec.width {
            result.set_item("width", width.to_string())?;
        }

        // Extract precision
        if let Some(precision) = spec.precision {
            result.set_item("precision", precision.to_string())?;
        }

        // Extract alignment
        if let Some(align) = spec.alignment {
            result.set_item("align", align.to_string())?;
        }

        // Extract fill
        if let Some(fill) = spec.fill {
            result.set_item("fill", fill.to_string())?;
        }

        // Extract zero padding
        if spec.zero_pad {
            result.set_item("zero", true)?;
        }

        result.into_py_any(py)
    })
}

/// Python module definition
#[pymodule]
fn _formatparse(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add(
        "PatternParseMismatch",
        py.get_type::<crate::error::PatternParseMismatch>(),
    )?;
    m.add_function(wrap_pyfunction!(parse, m)?)?;
    m.add_function(wrap_pyfunction!(parse_batch, m)?)?;
    m.add_function(wrap_pyfunction!(search, m)?)?;
    m.add_function(wrap_pyfunction!(findall, m)?)?;
    m.add_function(wrap_pyfunction!(findall_iter, m)?)?;
    m.add_function(wrap_pyfunction!(compile, m)?)?;
    m.add_function(wrap_pyfunction!(extract_format, m)?)?;
    m.add_class::<ParseResult>()?;
    m.add_class::<FormatParser>()?;
    m.add_class::<Format>()?;
    m.add_class::<FixedTzOffset>()?;
    m.add_class::<Match>()?;
    m.add_class::<Results>()?;
    m.add_class::<FindallIter>()?;
    Ok(())
}