Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Lib/test/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,6 @@ def test_groupdict(self):
'first second').groupdict(),
{'first':'first', 'second':'second'})

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_expand(self):
self.assertEqual(re.match("(?P<first>first) (?P<second>second)",
"first second")
Expand Down
47 changes: 34 additions & 13 deletions crates/vm/src/stdlib/_sre.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,15 +471,7 @@ mod _sre {
}
FilterType::Template(template) => {
let m = Match::new(&mut iter.state, zelf.clone(), string.clone());
// template.expand(m)?
// let mut list = vec![template.literal.clone()];
sub_list.push(template.literal.clone());
for (index, literal) in template.items.iter().cloned() {
if let Some(item) = m.get_slice(index, s, vm) {
sub_list.push(item);
}
sub_list.push(literal);
}
m.expand_template(template, s, &mut sub_list, vm);
}
};

Expand Down Expand Up @@ -702,10 +694,19 @@ mod _sre {
}

#[pymethod]
fn expand(zelf: PyRef<Self>, template: PyStrRef, vm: &VirtualMachine) -> PyResult {
let re = vm.import("re", 0)?;
let func = re.get_attr("_expand", vm)?;
func.call((zelf.pattern.clone(), zelf, template), vm)
fn expand(zelf: PyRef<Self>, template: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let template = Template::compile(zelf.pattern.clone(), template, vm)?;
with_sre_str!(zelf.pattern, &zelf.string, vm, |s| {
let mut list: Vec<PyObjectRef> = Vec::new();
zelf.expand_template(&template, s, &mut list, vm);

let join_type: PyObjectRef = if zelf.pattern.isbytes {
vm.ctx.new_bytes(vec![]).into()
} else {
vm.ctx.new_str(ascii!("")).into()
};
vm.call_method(&join_type, "join", (PyList::from(list).into_pyobject(vm),))
})
}

#[pymethod]
Expand Down Expand Up @@ -820,6 +821,26 @@ mod _sre {
Some(str_drive.slice(start as usize, end as usize, vm))
}

/// Expand an already-compiled template against this match, appending the
/// resulting literal/group segments to `list`. Shared by `expand` and
/// `Pattern.sub` so the template-filling logic lives in one place; the
/// caller is responsible for compiling the template (once) beforehand.
fn expand_template<S: SreStr>(
&self,
template: &Template,
str_drive: S,
list: &mut Vec<PyObjectRef>,
vm: &VirtualMachine,
) {
list.push(template.literal.clone());
for (index, literal) in template.items.iter().cloned() {
if let Some(item) = self.get_slice(index, str_drive, vm) {
list.push(item);
}
list.push(literal);
}
}

#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
Expand Down
Loading