-
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
Draft
Copilot
wants to merge
6
commits into
main
Choose a base branch
from
copilot/implement-phase-1-rust-migration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a6db450
Initial plan
Copilot 4988ea2
Phase 1 Rust (PyO3) migration for SnakemakeFormatter.parse()
Copilot 78267bf
Address code review: improve surrogate fallback comment and Rust Opti…
Copilot d99205d
Rewrite Rust parser as a clean character-by-character state machine
Copilot 2ad4380
Simplify Rust tuple API and add _core.pyi stub
Copilot f48270b
benchmarks
pvandyken File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| //! 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 4-tuples per parsed segment: | ||
| /// `(literal_text, field_name, squelch_underscore, constraint)` | ||
| /// | ||
| /// - `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 | ||
| /// - `squelch_underscore` – `None` = no change to `_underscore` (empty literal before a field, | ||
| /// or an end-of-string segment); `Some(true)` = set `_underscore = ""` | ||
| /// (literal ends in `'/'` or `'_'`); `Some(false)` = set `_underscore = "_"` | ||
| /// (all other non-empty literals, including doubled-brace segments) | ||
| /// - `constraint` – `None` for non-field segments; `""` for a field with no constraint; | ||
| /// `",<text>"` (starting with `,`) for a field that has a constraint; | ||
| /// Python can derive `_current_field` as `field_name + constraint` | ||
| /// | ||
| /// 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<bool>, Option<String>)>> { | ||
| let mut entries: Vec<(String, Option<String>, Option<bool>, Option<String>)> = 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)); | ||
| } | ||
| 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; always sets _underscore to "_" | ||
| literal.push('{'); | ||
| entries.push((literal, None, Some(false), None)); | ||
| literal = String::new(); | ||
| } | ||
| Some(first) => { | ||
| // `{}` or `{name}` or `{name,constraint}` — a real field. | ||
| // Collect everything up to the matching `}`. | ||
| let mut field_content = String::new(); | ||
| if first != '}' { | ||
| field_content.push(first); | ||
| 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, | ||
| Some(c) => field_content.push(c), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Split field name from constraint at the first `,`. | ||
| let (field_name, constraint) = match field_content.find(',') { | ||
| Some(comma) => { | ||
| let name = field_content[..comma].to_string(); | ||
| let cons = field_content[comma..].to_string(); | ||
| (name, cons) | ||
| } | ||
| None => (field_content, String::new()), | ||
| }; | ||
|
|
||
| // `squelch_underscore`: None when literal is empty (no update needed), | ||
| // Some(true) when literal ends in a squelcher ('/' or '_'), | ||
| // Some(false) otherwise. | ||
| let squelch = literal.chars().last().map(|c| c == '/' || c == '_'); | ||
|
|
||
| entries.push((literal, Some(field_name), squelch, Some(constraint))); | ||
| literal = String::new(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // ---- Closing brace ------------------------------------------ | ||
| Some('}') => { | ||
| match chars.next() { | ||
| Some('}') => { | ||
| // `}}` — escaped close brace; always sets _underscore to "_" | ||
| literal.push('}'); | ||
| entries.push((literal, None, Some(false), None)); | ||
| 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(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| """Type stubs for the optional compiled Rust extension ``snakebids._rust._core``.""" | ||
|
|
||
| def parse_format_string( | ||
| format_string: str, | ||
| ) -> list[tuple[str, str | None, bool | None, str | None]]: | ||
| """Parse a Snakemake-style format string character by character. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| format_string : str | ||
| The format string to parse. | ||
|
|
||
| Returns | ||
| ------- | ||
| list[tuple[str, str | None, bool | None, str | None]] | ||
| A list of ``(literal_text, field_name, squelch_underscore, constraint)`` tuples: | ||
|
|
||
| - ``literal_text`` – literal text before the next field | ||
| - ``field_name`` – ``None`` for non-field segments; the field name otherwise | ||
| - ``squelch_underscore`` – ``None`` = no change to ``_underscore`` (empty literal or | ||
| end-of-string); ``True`` = set ``_underscore = ""``; ``False`` = set ``_underscore = "_"`` | ||
| - ``constraint`` – ``None`` for non-field segments; ``""`` for a field with no | ||
| constraint; ``",<pattern>"`` for a field with a constraint; concatenating | ||
| ``field_name + constraint`` gives the full ``_current_field`` value | ||
|
|
||
| Raises | ||
| ------ | ||
| ValueError | ||
| On malformed input (unexpected ``}`` / ``{`` or missing ``}``). | ||
| """ | ||
| ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.