-
Notifications
You must be signed in to change notification settings - Fork 16
Phase 1: Rust/PyO3 acceleration for SnakemakeFormatter.parse()
#533
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 4 commits
a6db450
4988ea2
78267bf
d99205d
2ad4380
f48270b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -135,3 +135,8 @@ dmypy.json | |
|
|
||
| # version | ||
| _version.py | ||
|
|
||
| # Rust build artifacts | ||
| target/ | ||
| Cargo.lock | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| [package] | ||
| name = "snakebids-rust" | ||
| version = "0.1.0" | ||
| edition = "2021" | ||
|
|
||
| [lib] | ||
| name = "_core" | ||
| path = "rust/src/lib.rs" | ||
| crate-type = ["cdylib"] | ||
|
|
||
| [dependencies] | ||
| pyo3 = { version = "0.22", features = ["extension-module"] } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # Optional Rust Acceleration | ||
|
|
||
| `snakebids` ships with an optional compiled extension | ||
| (`snakebids._rust._core`) that accelerates `SnakemakeFormatter.parse()`. | ||
| The extension is a private implementation detail—no public API changes | ||
| are required to use it. | ||
|
|
||
| ## How it works | ||
|
|
||
| When the extension is present, `SnakemakeFormatter.parse()` delegates | ||
| its inner loop to a Rust implementation built with | ||
| [PyO3](https://pyo3.rs/). The Python fallback is always available and is | ||
| used automatically when the compiled extension is absent. | ||
|
|
||
| ## Building the extension locally | ||
|
|
||
| You will need [Rust](https://rustup.rs/) and | ||
| [maturin](https://www.maturin.rs/) installed. | ||
|
|
||
| ```bash | ||
| # install maturin once | ||
| pip install maturin | ||
|
|
||
| # build and place the extension inside the source tree | ||
| maturin develop --release | ||
| ``` | ||
|
|
||
| After this, `snakebids._rust._core` is importable and all | ||
| `SnakemakeFormatter` calls benefit from the faster implementation | ||
| transparently. | ||
|
|
||
| ## Verifying the extension is active | ||
|
|
||
| ```python | ||
| from snakebids.utils.snakemake_templates import _HAS_RUST_PARSE | ||
| print(_HAS_RUST_PARSE) # True when the extension is loaded | ||
| ``` | ||
|
|
||
| ## CI / packaging notes | ||
|
|
||
| * Pure-Python installs (`pip install snakebids`) **do not** require | ||
| Rust—the extension is optional. | ||
| * Pre-built wheels distributed on PyPI will include the compiled | ||
| extension for supported platforms. | ||
| * The `[tool.maturin]` section in `pyproject.toml` configures the | ||
| module placement (`snakebids._rust._core`) and Python source root. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| //! Rust-accelerated internals for snakebids. | ||
| //! | ||
| //! This module exposes `parse_format_string`, a fast equivalent of the Python | ||
| //! `SnakemakeFormatter.parse()` parsing loop. | ||
|
|
||
| use pyo3::exceptions::PyValueError; | ||
| use pyo3::prelude::*; | ||
|
|
||
| const UNEXPECTED_CLOSE: &str = "unexpected '}' in string"; | ||
| const MISSING_CLOSE: &str = "expected '}' before end of string"; | ||
| const UNEXPECTED_OPEN: &str = "unexpected '{' in field name"; | ||
|
|
||
| /// Parse a Snakemake-style format string character by character. | ||
| /// | ||
| /// Returns a list of 5-tuples per parsed segment: | ||
| /// `(literal_text, field_name, new_underscore, new_current_field, update_current_field)` | ||
| /// | ||
| /// - `literal_text` – the literal portion before the next field (or at end of string) | ||
| /// - `field_name` – `None` for non-field segments; the field name for field segments | ||
| /// - `new_underscore` – `None` = no change; `Some(s)` = set `_underscore` to `s` | ||
|
||
| /// - `new_current_field` – new `_current_field` value (only meaningful when `update_current_field`) | ||
|
||
| /// - `update_current_field` – whether `_current_field` should be updated | ||
| /// | ||
| /// Raises `ValueError` on malformed input (same conditions as the Python implementation). | ||
| #[pyfunction] | ||
| pub fn parse_format_string( | ||
| format_string: &str, | ||
| ) -> PyResult<Vec<(String, Option<String>, Option<String>, Option<String>, bool)>> { | ||
| let mut entries: Vec<(String, Option<String>, Option<String>, Option<String>, bool)> = | ||
| Vec::new(); | ||
|
|
||
| let mut chars = format_string.chars(); | ||
|
|
||
| // Accumulates literal text between fields. | ||
| let mut literal = String::new(); | ||
|
|
||
| loop { | ||
| match chars.next() { | ||
| // ---- End of string ------------------------------------------ | ||
| None => { | ||
| if !literal.is_empty() { | ||
| entries.push((literal, None, None, None, false)); | ||
| } | ||
| return Ok(entries); | ||
| } | ||
|
|
||
| // ---- Opening brace ------------------------------------------ | ||
| Some('{') => { | ||
| match chars.next() { | ||
| None => { | ||
| // Trailing lone `{` — no closing brace | ||
| return Err(PyValueError::new_err(MISSING_CLOSE)); | ||
| } | ||
| Some('{') => { | ||
| // `{{` — escaped open brace (emits up-to-and-including first `{`) | ||
| literal.push('{'); | ||
| entries.push((literal, None, Some("_".to_string()), None, false)); | ||
| literal = String::new(); | ||
| } | ||
| Some('}') => { | ||
| // `{}` — empty field name | ||
| let new_underscore = literal.chars().last().map(|last| { | ||
| if last == '/' || last == '_' { | ||
| String::new() | ||
| } else { | ||
| "_".to_string() | ||
| } | ||
| }); | ||
| entries.push(( | ||
| literal, | ||
| Some(String::new()), | ||
| new_underscore, | ||
| None, | ||
| true, | ||
| )); | ||
| literal = String::new(); | ||
| } | ||
| Some(first) => { | ||
| // Start of a real field. Collect everything up to the matching `}`. | ||
| let mut field_content = String::new(); | ||
| field_content.push(first); | ||
|
|
||
| let closing = loop { | ||
| match chars.next() { | ||
| None => { | ||
| return Err(PyValueError::new_err(MISSING_CLOSE)); | ||
| } | ||
| Some('{') => { | ||
| // Nested `{` inside a field is not allowed. | ||
| return Err(PyValueError::new_err(UNEXPECTED_OPEN)); | ||
| } | ||
| Some('}') => break field_content, | ||
| Some(c) => field_content.push(c), | ||
| } | ||
| }; | ||
|
|
||
| // Split field name from constraint at the first `,`. | ||
| let (field_name, new_current_field) = | ||
| match closing.find(',') { | ||
| Some(comma) => { | ||
| let name = closing[..comma].to_string(); | ||
| let full = closing.clone(); | ||
| (name, Some(full)) | ||
| } | ||
| None => (closing, None), | ||
| }; | ||
|
|
||
| // `_underscore` update based on the last char of the literal. | ||
| let new_underscore: Option<String> = | ||
| literal.chars().last().map(|last| { | ||
| if last == '/' || last == '_' { | ||
| String::new() | ||
| } else { | ||
| "_".to_string() | ||
| } | ||
| }); | ||
|
|
||
| entries.push(( | ||
| literal, | ||
| Some(field_name), | ||
| new_underscore, | ||
| new_current_field, | ||
| true, | ||
| )); | ||
| literal = String::new(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // ---- Closing brace ------------------------------------------ | ||
| Some('}') => { | ||
| match chars.next() { | ||
| Some('}') => { | ||
| // `}}` — escaped close brace | ||
| literal.push('}'); | ||
| entries.push((literal, None, Some("_".to_string()), None, false)); | ||
| literal = String::new(); | ||
| } | ||
| _ => { | ||
| // Lone `}` outside a field | ||
| return Err(PyValueError::new_err(UNEXPECTED_CLOSE)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // ---- Ordinary character ------------------------------------- | ||
| Some(c) => { | ||
| literal.push(c); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Register this module as `snakebids._rust._core`. | ||
| #[pymodule] | ||
| fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> { | ||
| m.add_function(wrap_pyfunction!(parse_format_string, m)?)?; | ||
| Ok(()) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """Private package for optional Rust-accelerated internals. | ||
|
|
||
| The compiled extension ``_core`` is built separately with maturin. | ||
| If the extension is not available, the pure-Python fallback is used. | ||
| """ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@copilot, it would be much simpler to do a simple loop over each character, check what it is, and respond accordingly (e.g. we have a
{, check the next character, not a{so we're in a field, next character,so we're in the constraint now, etc.I did not do this in the python implementation because python for loops are expensive, better to use the builtin
.find, but rust does not have this problem.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done in d99205d. The implementation is now a straightforward character-by-character loop: match on
{(check next char for{escaped,}empty field, or start accumulating field content),}(check next for}escaped or lone}error), and ordinary characters. Allfind()/index helpers removed.