1use std::borrow::Cow;
10
11use encoding_rs::{DecoderResult, Encoding, UTF_8, UTF_16BE, UTF_16LE};
12use parsec_base::{Diagnostic, LineCol, Span};
13
14use crate::{Document, Error, Options, parse_with};
15
16#[derive(Debug)]
18pub struct Parsed<'b> {
19 pub document: Document,
20 pub encoding: &'static Encoding,
22 pub text: Cow<'b, str>,
25}
26
27fn fail(code: &'static str, message: String) -> Error {
28 Error {
29 diagnostic: Diagnostic::error(code, Span::at(0), message),
30 position: LineCol { line: 1, column: 1 },
31 }
32}
33
34fn declared(bytes: &[u8]) -> Option<&[u8]> {
36 let end = bytes.iter().take(1024).position(|&b| b == b'>')?;
37 let decl = bytes[..end].strip_prefix(b"<?xml")?;
38 let at = decl.windows(8).position(|w| w == b"encoding")?;
39 let rest = &decl[at + 8..];
40 let rest = rest
41 .trim_ascii_start()
42 .strip_prefix(b"=")?
43 .trim_ascii_start();
44 let (&q, rest) = rest.split_first()?;
45 if q != b'"' && q != b'\'' {
46 return None;
47 }
48 Some(&rest[..rest.iter().position(|&b| b == q)?])
49}
50
51fn sniff(bytes: &[u8]) -> Result<(&'static Encoding, usize), Error> {
53 if let Some(found) = Encoding::for_bom(bytes) {
54 return Ok(found);
55 }
56 match bytes.get(..4) {
57 Some([0x3C, 0, 0x3F, 0]) => return Ok((UTF_16LE, 0)),
58 Some([0, 0x3C, 0, 0x3F]) => return Ok((UTF_16BE, 0)),
59 Some([0, 0, 0, 0x3C] | [0x3C, 0, 0, 0] | [0, 0, 0x3C, 0] | [0, 0x3C, 0, 0])
60 | Some([0, 0, 0xFE, 0xFF] | [0xFF, 0xFE, 0, 0]) => {
61 return Err(fail(
62 "unsupported-encoding",
63 "the document is in UCS-4, which Parsec doesn't decode".into(),
64 ));
65 }
66 Some([0x4C, 0x6F, 0xA7, 0x94]) => {
67 return Err(fail(
68 "unsupported-encoding",
69 "the document is in EBCDIC, which Parsec doesn't decode".into(),
70 ));
71 }
72 _ => {}
73 }
74 let Some(label) = declared(bytes) else {
75 return Ok((UTF_8, 0));
76 };
77 let name = String::from_utf8_lossy(label);
78 match Encoding::for_label_no_replacement(label) {
79 Some(e) if e == UTF_16LE || e == UTF_16BE => Err(fail(
82 "encoding-mismatch",
83 format!("the document says it's in {name}, but it has no byte order mark"),
84 )),
85 Some(e) => Ok((e, 0)),
86 None => Err(fail(
87 "unsupported-encoding",
88 format!("`{name}` isn't an encoding Parsec knows"),
89 )),
90 }
91}
92
93pub fn parse_bytes<'b>(bytes: &'b [u8], options: &Options) -> Result<Parsed<'b>, Error> {
102 options.limits.check_input(bytes.len()).map_err(|d| Error {
103 diagnostic: d,
104 position: LineCol { line: 1, column: 1 },
105 })?;
106 let (encoding, bom) = sniff(bytes)?;
107 let body = &bytes[bom..];
108 let text: Cow<'b, str> = if encoding == UTF_8 {
109 match std::str::from_utf8(body) {
110 Ok(s) => Cow::Borrowed(s),
111 Err(e) => {
112 let good = std::str::from_utf8(&body[..e.valid_up_to()]).unwrap_or("");
113 return Err(malformed(good, encoding));
114 }
115 }
116 } else {
117 let mut decoder = encoding.new_decoder_without_bom_handling();
118 let mut out = String::with_capacity(
119 decoder
120 .max_utf8_buffer_length_without_replacement(body.len())
121 .unwrap_or(body.len()),
122 );
123 let (result, _) = decoder.decode_to_string_without_replacement(body, &mut out, true);
124 match result {
125 DecoderResult::InputEmpty => Cow::Owned(out),
126 DecoderResult::Malformed(..) | DecoderResult::OutputFull => {
127 return Err(malformed(&out, encoding));
128 }
129 }
130 };
131 let document = parse_with(&text, options)?;
132 if let Some(decl) = document.xml_decl()
135 && let Some(label) = &decl.encoding
136 && (bom > 0 || encoding == UTF_16LE || encoding == UTF_16BE)
137 {
138 let utf16 = |e: &'static Encoding| e == UTF_16LE || e == UTF_16BE;
139 let agrees = Encoding::for_label(label.as_bytes())
140 .is_some_and(|d| d == encoding || utf16(d) && utf16(encoding));
141 if !agrees {
142 return Err(Error::new(
143 Diagnostic::error(
144 "encoding-mismatch",
145 decl.span,
146 format!(
147 "the document says it's in {label}, but its first bytes say {}",
148 encoding.name()
149 ),
150 ),
151 &text,
152 ));
153 }
154 }
155 Ok(Parsed {
156 document,
157 encoding,
158 text,
159 })
160}
161
162fn malformed(good: &str, encoding: &'static Encoding) -> Error {
164 let at = good.len() as u32;
165 Error::new(
166 Diagnostic::error(
167 "invalid-byte-sequence",
168 Span::at(at),
169 format!("the bytes here aren't {}", encoding.name()),
170 ),
171 good,
172 )
173}