forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyexpat.rs
More file actions
183 lines (161 loc) · 6.17 KB
/
pyexpat.rs
File metadata and controls
183 lines (161 loc) · 6.17 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/* Pyexpat builtin module
*
*
*/
use crate::vm::{extend_module, PyObjectRef, VirtualMachine};
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
let module = _pyexpat::make_module(vm);
extend_module!(vm, module, {
"errors" => _errors::make_module(vm),
"model" => _model::make_module(vm),
});
module
}
macro_rules! create_property {
($ctx: expr, $attributes: expr, $name: expr, $class: expr, $element: ident) => {
let attr = $ctx.new_getset(
$name,
$class,
move |this: &PyExpatLikeXmlParser| this.$element.read().clone(),
move |this: &PyExpatLikeXmlParser, func: PyObjectRef| *this.$element.write() = func,
);
$attributes.insert($ctx.intern_str($name), attr.into());
};
}
#[pymodule(name = "pyexpat")]
mod _pyexpat {
use crate::vm::{
builtins::{PyStr, PyStrRef, PyType},
function::ArgBytesLike,
function::{IntoFuncArgs, OptionalArg},
Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
};
use rustpython_common::lock::PyRwLock;
use std::io::Cursor;
use xml::reader::XmlEvent;
type MutableObject = PyRwLock<PyObjectRef>;
#[pyattr]
#[pyclass(name = "xmlparser", module = false)]
#[derive(Debug, PyPayload)]
pub struct PyExpatLikeXmlParser {
start_element: MutableObject,
end_element: MutableObject,
character_data: MutableObject,
entity_decl: MutableObject,
buffer_text: MutableObject,
}
type PyExpatLikeXmlParserRef = PyRef<PyExpatLikeXmlParser>;
#[inline]
fn invoke_handler<T>(vm: &VirtualMachine, handler: &MutableObject, args: T)
where
T: IntoFuncArgs,
{
vm.invoke(&handler.read().clone(), args).ok();
}
#[pyclass]
impl PyExpatLikeXmlParser {
fn new(vm: &VirtualMachine) -> PyResult<PyExpatLikeXmlParserRef> {
Ok(PyExpatLikeXmlParser {
start_element: MutableObject::new(vm.ctx.none()),
end_element: MutableObject::new(vm.ctx.none()),
character_data: MutableObject::new(vm.ctx.none()),
entity_decl: MutableObject::new(vm.ctx.none()),
buffer_text: MutableObject::new(vm.ctx.new_bool(false).into()),
}
.into_ref(vm))
}
#[extend_class]
fn extend_class_with_fields(ctx: &Context, class: &'static Py<PyType>) {
let mut attributes = class.attributes.write();
create_property!(ctx, attributes, "StartElementHandler", class, start_element);
create_property!(ctx, attributes, "EndElementHandler", class, end_element);
create_property!(
ctx,
attributes,
"CharacterDataHandler",
class,
character_data
);
create_property!(ctx, attributes, "EntityDeclHandler", class, entity_decl);
create_property!(ctx, attributes, "buffer_text", class, buffer_text);
}
fn create_config(&self) -> xml::ParserConfig {
xml::ParserConfig::new()
.cdata_to_characters(true)
.coalesce_characters(false)
.whitespace_to_characters(true)
}
fn do_parse<T>(&self, vm: &VirtualMachine, parser: xml::EventReader<T>)
where
T: std::io::Read,
{
for e in parser {
match e {
Ok(XmlEvent::StartElement {
name, attributes, ..
}) => {
let dict = vm.ctx.new_dict();
for attribute in attributes {
dict.set_item(
attribute.name.local_name.as_str(),
vm.ctx.new_str(attribute.value).into(),
vm,
)
.unwrap();
}
let name_str = PyStr::from(name.local_name).into_ref(vm);
invoke_handler(vm, &self.start_element, (name_str, dict));
}
Ok(XmlEvent::EndElement { name, .. }) => {
let name_str = PyStr::from(name.local_name).into_ref(vm);
invoke_handler(vm, &self.end_element, (name_str,));
}
Ok(XmlEvent::Characters(chars)) => {
let str = PyStr::from(chars).into_ref(vm);
invoke_handler(vm, &self.character_data, (str,));
}
_ => {}
}
}
}
#[pymethod(name = "Parse")]
fn parse(&self, data: PyStrRef, _isfinal: OptionalArg<bool>, vm: &VirtualMachine) {
let reader = Cursor::<Vec<u8>>::new(data.as_str().as_bytes().to_vec());
let parser = self.create_config().create_reader(reader);
self.do_parse(vm, parser);
}
#[pymethod(name = "ParseFile")]
fn parse_file(&self, file: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
// todo: read chunks at a time
let read_res = vm.call_method(&file, "read", ())?;
let bytes_like = ArgBytesLike::try_from_object(vm, read_res)?;
let buf = bytes_like.borrow_buf().to_vec();
let reader = Cursor::new(buf);
let parser = self.create_config().create_reader(reader);
self.do_parse(vm, parser);
// todo: return value
Ok(())
}
}
#[derive(FromArgs)]
#[allow(dead_code)]
struct ParserCreateArgs {
#[pyarg(any, optional)]
encoding: OptionalArg<PyStrRef>,
#[pyarg(any, optional)]
namespace_separator: OptionalArg<PyStrRef>,
#[pyarg(any, optional)]
intern: OptionalArg<PyStrRef>,
}
#[pyfunction(name = "ParserCreate")]
fn parser_create(
_args: ParserCreateArgs,
vm: &VirtualMachine,
) -> PyResult<PyExpatLikeXmlParserRef> {
PyExpatLikeXmlParser::new(vm)
}
}
#[pymodule(name = "model")]
mod _model {}
#[pymodule(name = "errors")]
mod _errors {}