Skip to content

Commit d04318e

Browse files
authored
_sre: drive an all-ASCII str subject over its bytes (#8520)
* sre_engine: document that StrDrive positions are character indices StrDrive carried no documentation, so nothing recorded that a cursor's position is a character index rather than a byte offset. Every implementation satisfies it -- skip(n) advances position by exactly n in all three -- and the engine depends on it: _count bounds a repeat with position + max_count and reports the repeat length as a difference of positions, ASSERT compares position against a lookbehind width, and search_info recovers a match start as position - (len - 1). A drive over a variable-width encoding that stored byte offsets would leave those type-correct and wrong, and would index a lookbehind out of bounds. Write the invariant down on StringCursor and on each trait method. Also walk the group's own cursor in GROUPREF instead of counting to the group's width, so the loop bound is the thing being stepped. Generated machine code is unchanged. Assisted-by: Claude * _sre: drive an all-ASCII str subject over its bytes with_sre_str handed every str subject to the &Wtf8 drive, which answers count() by counting every code point and create_cursor(n) by stepping over the first n. Both run once per Request, so a scan that restarts at successive positions walked the subject again on every call: finditer over an ASCII subject of n tokens was quadratic in n. PyStr already records whether it is ASCII -- StrKind is decided when the string is built -- and for ASCII a character index is a byte index, so the &[u8] drive's cursor arithmetic already applies: count() is the byte length and create_cursor() is a pointer offset. Add AsciiStr, which delegates every StrDrive method to that impl and differs only in slice(), which reslices the span and returns str rather than bytes. Matching is unaffected: StrDrive carries no unicode semantics, because the engine keys every unicode decision on the compiled pattern's opcode rather than on the subject type. Also bind the subject once in with_sre_str, so callers passing a temporary (`&x.clone()`) build it once rather than per arm. finditer over an ASCII subject, n tokens, this machine: n before after 5000 41.60ms 1.37ms 10000 217.30ms 2.68ms 20000 1206.28ms 5.17ms 40000 5016.65ms 10.31ms Per-doubling x5.22/x5.55/x4.16 becomes x1.95/x1.93/x1.99. Collecting m.group(0) for every match goes 5061.02ms -> 17.80ms at n=40000. test.test_re is unchanged at 166 tests, OK (skipped=14, expected failures=6), and a 2731-line differential over the is_ascii() boundary -- findall, finditer spans and groups, sub, split, match, search, fullmatch across subjects that are empty, ASCII, non-ASCII, or mixed -- is byte-identical to CPython 3.14.6. Introducing an off-by-one in AsciiStr::slice moves 1224 of those lines, so the comparison reaches the new code. Assisted-by: Claude
1 parent b109723 commit d04318e

3 files changed

Lines changed: 137 additions & 6 deletions

File tree

‎crates/sre_engine/src/engine.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,11 @@ fn _match<S: StrDrive>(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo
581581
..ctx
582582
};
583583

584-
for _ in group_start..group_end {
584+
// Walk the group itself rather than counting to its
585+
// width: `g_ctx` is already stepping over exactly
586+
// the characters being compared, so its own cursor
587+
// is the loop bound.
588+
while g_ctx.cursor.position < group_end {
585589
#[allow(clippy::redundant_closure_call)]
586590
if ctx.at_end(req)
587591
|| $f(ctx.peek_char::<S>()) != $f(g_ctx.peek_char::<S>())

‎crates/sre_engine/src/string.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
use rustpython_wtf8::Wtf8;
22

3+
/// A position in the subject, paired with the byte pointer it resolves to.
4+
///
5+
/// `position` is a **character index**, never a byte offset. The engine does
6+
/// arithmetic on it directly — it subtracts two positions to get a character
7+
/// count, adds a repeat count to get a bound, and compares one against a
8+
/// lookbehind width — so the unit is part of the [`StrDrive`] contract rather
9+
/// than a detail each implementation may pick.
310
#[derive(Debug, Clone, Copy)]
411
pub struct StringCursor {
512
pub(crate) ptr: *const u8,
@@ -15,15 +22,43 @@ impl Default for StringCursor {
1522
}
1623
}
1724

25+
/// Random access over the subject being matched.
26+
///
27+
/// An implementation chooses how a character is spelled in memory — one byte
28+
/// for `&[u8]`, one code point for `&str` and `&Wtf8` — but **not** how
29+
/// positions are counted. Every position this trait produces or consumes is a
30+
/// character index: `count` is the subject's length in characters, and
31+
/// `skip(n)` advances a cursor's `position` by exactly `n`.
32+
///
33+
/// That is load-bearing, not incidental. The engine reads position arithmetic
34+
/// as character arithmetic in several places — `_count` bounds a repeat with
35+
/// `position + max_count` and reports the repeat's length as a difference of
36+
/// positions, `ASSERT` tests `position < back` against a lookbehind width, and
37+
/// `search_info` recovers a match start as `position - (len - 1)`. A drive
38+
/// that stored byte offsets here would leave all of those type-correct and
39+
/// silently wrong, and would index a lookbehind out of bounds.
40+
///
41+
/// So a drive over a variable-width encoding pays for the mapping: `count`
42+
/// and `create_cursor` have to resolve character indices, and cannot simply
43+
/// hand back byte lengths and byte offsets.
1844
pub trait StrDrive: Copy {
45+
/// The subject's length, in characters.
1946
fn count(&self) -> usize;
47+
/// A cursor at character index `n`.
2048
fn create_cursor(&self, n: usize) -> StringCursor;
49+
/// Move `cursor` to character index `n`, from wherever it is now.
2150
fn adjust_cursor(&self, cursor: &mut StringCursor, n: usize);
51+
/// Consume one character, returning it; `position` grows by one.
2252
fn advance(cursor: &mut StringCursor) -> u32;
53+
/// The character at `cursor`, without moving it.
2354
fn peek(cursor: &StringCursor) -> u32;
55+
/// Skip `n` characters, so `position` grows by exactly `n`.
2456
fn skip(cursor: &mut StringCursor, n: usize);
57+
/// Step back over one character, returning it; `position` shrinks by one.
2558
fn back_advance(cursor: &mut StringCursor) -> u32;
59+
/// The character before `cursor`, without moving it.
2660
fn back_peek(cursor: &StringCursor) -> u32;
61+
/// Step back `n` characters, so `position` shrinks by exactly `n`.
2762
fn back_skip(cursor: &mut StringCursor, n: usize);
2863
}
2964

‎crates/vm/src/stdlib/_sre.rs‎

Lines changed: 97 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ mod _sre {
2222
use itertools::Itertools;
2323
use num_traits::ToPrimitive;
2424
use rustpython_sre_engine::{
25-
Request, SearchIter, SreFlag, State, StrDrive,
25+
Request, SearchIter, SreFlag, State, StrDrive, StringCursor,
2626
string::{lower_ascii, lower_unicode},
2727
};
2828

@@ -83,6 +83,72 @@ mod _sre {
8383
}
8484
}
8585

86+
/// An all-ASCII `str` subject, driven over its bytes.
87+
///
88+
/// For ASCII a character index *is* a byte index, so `&[u8]`'s cursor
89+
/// arithmetic is already the right arithmetic: `count` is the byte length
90+
/// and `create_cursor` is a pointer offset. The `&Wtf8` drive has to count
91+
/// code points from the start of the subject to answer either, once per
92+
/// `Request`, which makes a scan that restarts at successive positions --
93+
/// `finditer`, or `re` module functions called in a loop -- walk the
94+
/// subject again on every call.
95+
///
96+
/// Matching is unaffected: `StrDrive` carries no unicode semantics of its
97+
/// own, because the engine keys every unicode decision on the compiled
98+
/// pattern's opcode rather than on the subject type. Only `slice` differs
99+
/// from the `&[u8]` impl, to hand back `str` instead of `bytes`.
100+
#[derive(Clone, Copy)]
101+
struct AsciiStr<'a>(&'a [u8]);
102+
103+
impl StrDrive for AsciiStr<'_> {
104+
fn count(&self) -> usize {
105+
<&[u8] as StrDrive>::count(&self.0)
106+
}
107+
108+
fn create_cursor(&self, n: usize) -> StringCursor {
109+
<&[u8] as StrDrive>::create_cursor(&self.0, n)
110+
}
111+
112+
fn adjust_cursor(&self, cursor: &mut StringCursor, n: usize) {
113+
<&[u8] as StrDrive>::adjust_cursor(&self.0, cursor, n)
114+
}
115+
116+
fn advance(cursor: &mut StringCursor) -> u32 {
117+
<&[u8] as StrDrive>::advance(cursor)
118+
}
119+
120+
fn peek(cursor: &StringCursor) -> u32 {
121+
<&[u8] as StrDrive>::peek(cursor)
122+
}
123+
124+
fn skip(cursor: &mut StringCursor, n: usize) {
125+
<&[u8] as StrDrive>::skip(cursor, n)
126+
}
127+
128+
fn back_advance(cursor: &mut StringCursor) -> u32 {
129+
<&[u8] as StrDrive>::back_advance(cursor)
130+
}
131+
132+
fn back_peek(cursor: &StringCursor) -> u32 {
133+
<&[u8] as StrDrive>::back_peek(cursor)
134+
}
135+
136+
fn back_skip(cursor: &mut StringCursor, n: usize) {
137+
<&[u8] as StrDrive>::back_skip(cursor, n)
138+
}
139+
}
140+
141+
impl SreStr for AsciiStr<'_> {
142+
fn slice(&self, start: usize, end: usize, vm: &VirtualMachine) -> PyObjectRef {
143+
let end = end.min(self.0.len());
144+
let start = start.min(end);
145+
// The subject is ASCII, so any span of it is valid UTF-8 and the
146+
// span is a reslice rather than a walk from the subject's start.
147+
let s = str::from_utf8(&self.0[start..end]).expect("ascii subject");
148+
vm.ctx.new_str(s).into()
149+
}
150+
}
151+
86152
#[pyfunction]
87153
fn compile(
88154
pattern: PyObjectRef,
@@ -200,13 +266,18 @@ mod _sre {
200266
}
201267

202268
macro_rules! with_sre_str {
203-
($pattern:expr, $string:expr, $vm:expr, $f:expr) => {
269+
($pattern:expr, $string:expr, $vm:expr, $f:expr) => {{
270+
// Bind once: the branches only borrow the subject, and callers pass
271+
// a temporary (`&x.clone()`) that would otherwise be rebuilt per arm.
272+
let subject = $string;
204273
if $pattern.isbytes {
205-
Pattern::with_bytes($string, $vm, $f)
274+
Pattern::with_bytes(subject, $vm, $f)
275+
} else if Pattern::is_ascii_str(subject) {
276+
Pattern::with_ascii_str(subject, $vm, $f)
206277
} else {
207-
Pattern::with_str($string, $vm, $f)
278+
Pattern::with_str(subject, $vm, $f)
208279
}
209-
};
280+
}};
210281
}
211282

212283
#[pyclass(with(Hashable, Comparable, Representable), flags(HAS_WEAKREF))]
@@ -221,6 +292,27 @@ mod _sre {
221292
f(string.as_wtf8())
222293
}
223294

295+
/// Whether a `str` subject can take the [`AsciiStr`] drive.
296+
///
297+
/// `PyStr` already knows: `StrKind` is decided when the string is
298+
/// built, so this is a field load rather than a scan. A non-`str`
299+
/// argument answers `false` and is reported by [`Self::with_str`].
300+
fn is_ascii_str(string: &PyObject) -> bool {
301+
string
302+
.downcast_ref::<PyStr>()
303+
.is_some_and(|s| s.kind().is_ascii())
304+
}
305+
306+
fn with_ascii_str<F, R>(string: &PyObject, vm: &VirtualMachine, f: F) -> PyResult<R>
307+
where
308+
F: FnOnce(AsciiStr<'_>) -> PyResult<R>,
309+
{
310+
let string = string.downcast_ref::<PyStr>().ok_or_else(|| {
311+
vm.new_type_error(format!("expected string got '{}'", string.class()))
312+
})?;
313+
f(AsciiStr(string.as_wtf8().as_bytes()))
314+
}
315+
224316
fn with_bytes<F, R>(string: &PyObject, vm: &VirtualMachine, f: F) -> PyResult<R>
225317
where
226318
F: FnOnce(&[u8]) -> PyResult<R>,

0 commit comments

Comments
 (0)