forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathre.rs
More file actions
62 lines (52 loc) · 1.77 KB
/
re.rs
File metadata and controls
62 lines (52 loc) · 1.77 KB
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
/*
* Regular expressions.
*
* This module fits the python re interface onto the rust regular expression
* system.
*/
extern crate regex;
use self::regex::Regex;
use super::super::obj::{objstr, objtype};
use super::super::pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol};
use super::super::VirtualMachine;
fn re_match(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
// TODO:
error!("TODO: implement match");
re_search(vm, args)
}
fn re_search(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [
(pattern, Some(vm.ctx.str_type())),
(string, Some(vm.ctx.str_type()))
]
);
let pattern_str = objstr::get_value(&pattern);
let search_text = objstr::get_value(&string);
match Regex::new(&pattern_str) {
Ok(regex) => {
// Now use regex to search:
match regex.find(&search_text) {
None => Ok(vm.get_none()),
Some(result) => {
// Return match object:
// TODO: implement match object
// TODO: how to refer to match object defined in this
// module?
Ok(vm.ctx.new_str(result.as_str().to_string()))
}
}
}
Err(err) => Err(vm.new_value_error(format!("Error in regex: {:?}", err))),
}
}
pub fn mk_module(ctx: &PyContext) -> PyObjectRef {
let py_mod = ctx.new_module("re", ctx.new_scope(None));
let match_type = ctx.new_class("Match", ctx.object());
ctx.set_attr(&py_mod, "Match", match_type);
ctx.set_attr(&py_mod, "match", ctx.new_rustfunc(re_match));
ctx.set_attr(&py_mod, "search", ctx.new_rustfunc(re_search));
py_mod
}