Skip to content

Commit 622b766

Browse files
authored
Honor native XML encodings and declaration callbacks (#9845)
* Preserve native XML encodings and declaration callbacks Honor explicit encodings, detect BOM-less UTF-16 before starting the backend, and preserve raw declaration metadata without decoding document content outside the XML parser. Restore the three SAX encoding regression tests. Assisted-by: OpenAI Codex:GPT-6.1 * Use slice array chunks for XML declaration decoding Address Rust 1.100 Clippy diagnostics without changing encoding behavior. Assisted-by: OpenAI Codex:GPT-6.1
1 parent 9077f17 commit 622b766

3 files changed

Lines changed: 224 additions & 15 deletions

File tree

‎Lib/test/test_sax.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,6 @@ def test_parse_text(self):
146146
with open(TESTFN, 'r', encoding=encoding) as f:
147147
self.check_parse(f)
148148

149-
@unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing'
150149
def test_parse_bytes(self):
151150
# UTF-8 is default encoding, US-ASCII is compatible with UTF-8,
152151
# UTF-16 is autodetected
@@ -193,7 +192,6 @@ def test_parse_path_object(self):
193192
make_xml_file(self.data, 'utf-8', None)
194193
self.check_parse(FakePath(TESTFN))
195194

196-
@unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing'
197195
def test_parse_InputSource(self):
198196
# accept data without declared but with explicitly specified encoding
199197
make_xml_file(self.data, 'iso-8859-1', None)
@@ -232,7 +230,6 @@ def test_parseString_text(self):
232230
self.check_parseString(xml_str(self.data, encoding))
233231
self.check_parseString(self.data)
234232

235-
@unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing'
236233
def test_parseString_bytes(self):
237234
# UTF-8 is default encoding, US-ASCII is compatible with UTF-8,
238235
# UTF-16 is autodetected

‎crates/stdlib/src/pyexpat.rs‎

Lines changed: 169 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ mod _pyexpat {
175175
},
176176
types::Constructor,
177177
};
178+
use alloc::borrow::Cow;
178179
use alloc::collections::VecDeque;
179180
use alloc::rc::Rc;
180181
use core::cell::RefCell;
@@ -220,6 +221,107 @@ mod _pyexpat {
220221

221222
type MutableObject = PyRwLock<PyObjectRef>;
222223

224+
// Do not use Encoding::from_str here: xml-rs also accepts name prefixes.
225+
fn native_encoding(name: &str) -> Option<xml::Encoding> {
226+
match name.to_ascii_uppercase().as_str() {
227+
"UTF-8" => Some(xml::Encoding::Utf8),
228+
"UTF-16" => Some(xml::Encoding::Utf16),
229+
"UTF-16LE" => Some(xml::Encoding::Utf16Le),
230+
"UTF-16BE" => Some(xml::Encoding::Utf16Be),
231+
"ISO-8859-1" => Some(xml::Encoding::Latin1),
232+
"US-ASCII" => Some(xml::Encoding::Ascii),
233+
_ => None,
234+
}
235+
}
236+
237+
/// xml-rs emits StartDocument even without a declaration and fills in
238+
/// omitted values. Retain only the initial declaration to recover that
239+
/// information; the backend still validates it before any callback.
240+
#[derive(Debug, Default)]
241+
struct DeclarationPrefix {
242+
bytes: Vec<u8>,
243+
complete: bool,
244+
}
245+
246+
impl DeclarationPrefix {
247+
fn text(&self) -> String {
248+
let bytes = &self.bytes;
249+
let (little, offset) = if bytes.starts_with(&[0xff, 0xfe]) {
250+
(true, 2)
251+
} else if bytes.starts_with(&[0xfe, 0xff]) {
252+
(false, 2)
253+
} else if bytes.starts_with(&[b'<', 0]) {
254+
(true, 0)
255+
} else if bytes.starts_with(&[0, b'<']) {
256+
(false, 0)
257+
} else {
258+
return String::from_utf8_lossy(
259+
bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(bytes),
260+
)
261+
.into_owned();
262+
};
263+
let units = bytes[offset..].as_chunks::<2>().0.iter().map(|&pair| {
264+
if little {
265+
u16::from_le_bytes(pair)
266+
} else {
267+
u16::from_be_bytes(pair)
268+
}
269+
});
270+
char::decode_utf16(units)
271+
.map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
272+
.collect()
273+
}
274+
275+
fn record(&mut self, chunk: &[u8]) {
276+
if self.complete {
277+
return;
278+
}
279+
for &byte in chunk {
280+
self.bytes.push(byte);
281+
if self.bytes.len() >= 2
282+
&& self.bytes.len() <= 16
283+
&& ![0xef, 0xbb, 0xbf].starts_with(&self.bytes)
284+
{
285+
let text = self.text();
286+
if (!"<?xml".starts_with(&text) && !text.starts_with("<?xml"))
287+
|| text.strip_prefix("<?xml").is_some_and(|tail| {
288+
!tail.is_empty() && !tail.starts_with([' ', '\t', '\r', '\n'])
289+
})
290+
{
291+
self.bytes.clear();
292+
self.complete = true;
293+
break;
294+
}
295+
}
296+
if self.bytes.ends_with(b"?>")
297+
|| (self.bytes.len().is_multiple_of(2)
298+
&& (self.bytes.ends_with(&[b'?', 0, b'>', 0])
299+
|| self.bytes.ends_with(&[0, b'?', 0, b'>'])))
300+
{
301+
self.complete = true;
302+
break;
303+
}
304+
}
305+
}
306+
307+
fn take(&mut self) -> Option<String> {
308+
let text = self.text();
309+
self.bytes.clear();
310+
self.complete = true;
311+
text.strip_prefix("<?xml")
312+
.filter(|tail| tail.starts_with([' ', '\t', '\r', '\n']))
313+
.map(str::to_owned)
314+
}
315+
}
316+
317+
// Called only after xml-rs validated the declaration's attribute grammar.
318+
fn declaration_value<'a>(text: &'a str, name: &str) -> Option<&'a str> {
319+
let (_, value) = text.split_once(name)?;
320+
let value = value.trim_start().strip_prefix('=')?.trim_start();
321+
let quote = value.chars().next()?;
322+
value.get(1..)?.split(quote).next()
323+
}
324+
223325
#[pyattr(name = "version_info")]
224326
pub(super) const VERSION_INFO: (u32, u32, u32) = (2, 7, 1);
225327

@@ -238,6 +340,14 @@ mod _pyexpat {
238340
#[pytraverse(skip)]
239341
namespace_separator: Option<String>,
240342
#[pytraverse(skip)]
343+
encoding: Option<String>,
344+
#[pytraverse(skip)]
345+
declaration: PyRwLock<DeclarationPrefix>,
346+
#[pytraverse(skip)]
347+
initial_bytes: PyRwLock<Vec<u8>>,
348+
#[pytraverse(skip)]
349+
input_unicode: PyRwLock<Option<bool>>,
350+
#[pytraverse(skip)]
241351
base: PyRwLock<Option<String>>,
242352
// Position of the last event produced, exposed as CurrentLineNumber /
243353
// CurrentColumnNumber / CurrentByteIndex (mirrors libexpat's
@@ -928,6 +1038,7 @@ mod _pyexpat {
9281038
#[pyclass]
9291039
impl PyExpatLikeXmlParser {
9301040
fn new(
1041+
encoding: Option<String>,
9311042
namespace_separator: Option<String>,
9321043
intern: OptionalOption<PyObjectRef>,
9331044
parent: Option<PyExpatLikeXmlParserRef>,
@@ -940,6 +1051,10 @@ mod _pyexpat {
9401051
OptionalArg::Present(None) => vm.ctx.none(),
9411052
};
9421053
Self {
1054+
encoding,
1055+
declaration: PyRwLock::new(DeclarationPrefix::default()),
1056+
initial_bytes: PyRwLock::new(Vec::new()),
1057+
input_unicode: PyRwLock::new(None),
9431058
namespace_separator,
9441059
base: PyRwLock::new(None),
9451060
current_line: PyRwLock::new(1),
@@ -1128,10 +1243,24 @@ mod _pyexpat {
11281243
);
11291244
}
11301245

1131-
fn create_config(&self, unicode_input: bool) -> xml::ParserConfig {
1246+
fn create_config(
1247+
&self,
1248+
unicode_input: bool,
1249+
sniffed: Option<xml::Encoding>,
1250+
) -> xml::ParserConfig {
1251+
let encoding = if unicode_input {
1252+
Some(xml::Encoding::Utf8)
1253+
} else {
1254+
self.encoding
1255+
.as_deref()
1256+
.and_then(native_encoding)
1257+
.or(sniffed)
1258+
};
11321259
xml::ParserConfig::new()
1133-
.override_encoding(unicode_input.then_some(xml::Encoding::Utf8))
1134-
.ignore_invalid_encoding_declarations(unicode_input)
1260+
.override_encoding(encoding)
1261+
.ignore_invalid_encoding_declarations(
1262+
unicode_input || self.encoding.as_deref().and_then(native_encoding).is_some(),
1263+
)
11351264
.cdata_to_characters(false)
11361265
.coalesce_characters(false)
11371266
.ignore_comments(false)
@@ -1195,6 +1324,7 @@ mod _pyexpat {
11951324
return Err(vm.new_value_error("embedded null character"));
11961325
}
11971326
let child = Self::new(
1327+
encoding.clone(),
11981328
zelf.namespace_separator.clone(),
11991329
OptionalArg::Present(Some(zelf.intern.clone())),
12001330
Some(zelf.clone()),
@@ -1321,6 +1451,18 @@ mod _pyexpat {
13211451
XmlEvent::StartDocument { standalone, .. } => {
13221452
self.standalone
13231453
.store(standalone == Some(true), Ordering::Relaxed);
1454+
let declaration = self.declaration.write().take();
1455+
if let Some(declaration) = declaration {
1456+
invoke_handler(
1457+
vm,
1458+
&self.xml_decl,
1459+
(
1460+
declaration_value(&declaration, "version"),
1461+
declaration_value(&declaration, "encoding"),
1462+
standalone.map_or(-1, i32::from),
1463+
),
1464+
)?;
1465+
}
13241466
Ok(())
13251467
}
13261468
XmlEvent::Doctype { .. } => {
@@ -1824,17 +1966,34 @@ mod _pyexpat {
18241966
}
18251967
self.started.store(true, Ordering::Relaxed);
18261968
self.check_completed(vm)?;
1969+
self.declaration.write().record(chunk);
18271970
if self.finished.load(Ordering::SeqCst) {
18281971
return Ok(());
18291972
}
1830-
{
1831-
let mut guard = self.backend.write();
1832-
if guard.is_none() {
1833-
// CPython selects UTF-8 for str input with XML_SetEncoding;
1834-
// that call cannot change the encoding after parsing starts.
1835-
*guard = Some(Backend::new(self.create_config(unicode_input)));
1973+
let mut input = Cow::Borrowed(chunk);
1974+
if self.backend.read().is_none() {
1975+
let unicode_input = *self.input_unicode.write().get_or_insert(unicode_input);
1976+
// xml-rs detects a UTF-16 BOM, but unlike Expat does not
1977+
// recognize UTF-16 XML without one. Two initial bytes suffice
1978+
// to distinguish the endian form; retain only a split prefix.
1979+
let mut initial = self.initial_bytes.write();
1980+
if !initial.is_empty() {
1981+
initial.extend_from_slice(chunk);
1982+
input = Cow::Owned(core::mem::take(&mut *initial));
1983+
}
1984+
if !unicode_input && self.encoding.is_none() && input.len() < 2 && !isfinal {
1985+
initial.extend_from_slice(&input);
1986+
return Ok(());
18361987
}
1988+
let sniffed = match input.as_ref() {
1989+
[0, _, ..] => Some(xml::Encoding::Utf16Be),
1990+
[_, 0, ..] => Some(xml::Encoding::Utf16Le),
1991+
_ => None,
1992+
};
1993+
*self.backend.write() =
1994+
Some(Backend::new(self.create_config(unicode_input, sniffed)));
18371995
}
1996+
let chunk = input.as_ref();
18381997
#[cfg(not(target_arch = "wasm32"))]
18391998
{
18401999
let is_threaded = matches!(*self.backend.read(), Some(Backend::Threaded(_)));
@@ -1969,10 +2128,8 @@ mod _pyexpat {
19692128
return Err(vm.new_type_error("intern must be a dictionary"));
19702129
}
19712130

1972-
// Encoding selection is still handled by the xml-rs backend.
1973-
let _ = encoding;
1974-
19752131
Ok(PyExpatLikeXmlParser::new(
2132+
encoding.map(|encoding| encoding.as_str().to_owned()),
19762133
ns_sep.map(|sep| sep.as_str().to_owned()),
19772134
args.intern,
19782135
None,

‎extra_tests/snippets/stdlib_pyexpat.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,58 @@ def check_position_aliases(parser):
9696
parser.Parse(first, False)
9797
parser.Parse(tail, True)
9898
assert "".join(text) == expected
99+
100+
# Declaration metadata is not the parser's effective encoding: omitted
101+
# encoding stays None, spelling is preserved, and no declaration means no event.
102+
for encoding in ("UTF-8", "UTF-16", "UTF-16LE", "UTF-16BE", "ISO-8859-1", "US-ASCII"):
103+
for declaration, expected in (
104+
("", []),
105+
('<?xml version="1.0"?>', [("1.0", None, -1)]),
106+
('<?xml version="1.7" standalone="yes"?>', [("1.7", None, 1)]),
107+
(
108+
'<?xml version="1.0" encoding="uTf-8" standalone="no"?>',
109+
[("1.0", "uTf-8", 0)],
110+
),
111+
):
112+
# An explicit encoding wins over a conflicting declaration, even when
113+
# BOMs, code units, and the declaration terminator cross Parse calls.
114+
document = (declaration + "<r>abc</r>").encode(encoding)
115+
for chunk_size in (1, len(document)):
116+
parser = expat.ParserCreate(encoding)
117+
declarations = []
118+
text = []
119+
parser.XmlDeclHandler = lambda *args: declarations.append(args)
120+
parser.CharacterDataHandler = text.append
121+
for offset in range(0, len(document), chunk_size):
122+
parser.Parse(document[offset : offset + chunk_size], False)
123+
parser.Parse(b"", True)
124+
assert declarations == expected, (encoding, declaration, declarations)
125+
assert "".join(text) == "abc"
126+
127+
# Native byte decoding must be used rather than UTF-8 preprocessing.
128+
for encoding, character in (("ISO-8859-1", "£"), ("UTF-16LE", "𝄞"), ("UTF-16BE", "𝄞")):
129+
parser = expat.ParserCreate(encoding)
130+
text = []
131+
parser.CharacterDataHandler = text.append
132+
for byte in ("<r>" + character + "</r>").encode(encoding):
133+
parser.Parse(bytes([byte]), False)
134+
parser.Parse(b"", True)
135+
assert "".join(text) == character
136+
137+
# No declaration callback is allowed before the whole declaration is valid.
138+
for declaration in (
139+
'<?xml encoding="UTF-8"?>',
140+
'<?xml version="1.0" standalone="maybe"?>',
141+
):
142+
parser = expat.ParserCreate()
143+
declarations = []
144+
parser.XmlDeclHandler = lambda *args: declarations.append(args)
145+
try:
146+
for byte in (declaration + "<r/>").encode():
147+
parser.Parse(bytes([byte]), False)
148+
parser.Parse(b"", True)
149+
except expat.ExpatError:
150+
pass
151+
else:
152+
raise AssertionError("malformed declaration accepted")
153+
assert not declarations

0 commit comments

Comments
 (0)