Decode XeTeX input files and streams with original byte spans
This commit is contained in:
1 parent
22e3ba993d
commit
d11ac0cba1
18 files changed
+1040
-109
No files matched your search
@@ -9,6 +9,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D
|
||||
flate2 = "1.1"
|
||||
image = { version = "0.23.12", default-features = false, features = ["bmp"] }
|
||||
lopdf = "0.26"
|
||||
libloading = "=0.8.9"
|
||||
md5 = "0.8"
|
||||
png = "0.18.1"
|
||||
rusttype = "0.8.3"
|
||||
|
||||
@@ -513,6 +513,15 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((line, column)) = self.inputs.iter().rev().find_map(|frame| match frame {
|
||||
InputFrame::Source { source, mouth, .. } if *source == span.source => {
|
||||
mouth.xe_location(span.start)
|
||||
}
|
||||
_ => None,
|
||||
}) {
|
||||
error.line = line;
|
||||
error.column = column;
|
||||
}
|
||||
error.context = self.input_context();
|
||||
error.scanner_status = self.scanner_status.clone();
|
||||
error
|
||||
@@ -561,7 +570,13 @@ impl Executor {
|
||||
return self.fail("native input stack limit exceeded");
|
||||
}
|
||||
let source = self.sources.len();
|
||||
let mouth = Mouth::new(source, file.data.clone(), self.state.input_profile());
|
||||
let profile = self.state.input_profile();
|
||||
if profile == InputProfile::XeTeX {
|
||||
self.reads.insert(Dependency::XeDefaultInputEncoding);
|
||||
}
|
||||
let mouth = Mouth::with_encoding(
|
||||
source, file.data.clone(), profile, &self.state.xe_default_encoding,
|
||||
);
|
||||
self.sources.push(file);
|
||||
self.reads.insert(Dependency::Source(source));
|
||||
self.inputs.push(InputFrame::Source {
|
||||
@@ -2728,7 +2743,11 @@ impl Executor {
|
||||
data: Vec::new(),
|
||||
});
|
||||
self.stream_sources.insert(source);
|
||||
self.io.inputs.insert(index, InputStream { source });
|
||||
let xe_encoding = (self.state.input_profile() == InputProfile::XeTeX).then(|| {
|
||||
self.reads.insert(Dependency::XeDefaultInputEncoding);
|
||||
self.state.xe_default_encoding.clone()
|
||||
});
|
||||
self.io.inputs.insert(index, InputStream { source, xe_encoding, xe_skip_lf: false });
|
||||
self.reads.insert(Dependency::Source(source));
|
||||
}
|
||||
}
|
||||
@@ -2774,9 +2793,7 @@ impl Executor {
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
self.tick()?;
|
||||
let line = files
|
||||
.read_line(index)
|
||||
.map_err(|e| self.error(e, self.current))?;
|
||||
let (line, encoding) = self.read_physical_stream_line(index, source, files)?;
|
||||
let eof = line.is_none();
|
||||
if eof {
|
||||
files
|
||||
@@ -2793,42 +2810,52 @@ impl Executor {
|
||||
let end = self.sources[source].data.len();
|
||||
self.reads.insert(Dependency::EndLineChar);
|
||||
if readline {
|
||||
let mut length = line.len();
|
||||
while length > 0 && matches!(line[length - 1], b'\r' | b'\n' | b' ') {
|
||||
length -= 1;
|
||||
}
|
||||
let characters = self
|
||||
.state
|
||||
.input_profile()
|
||||
.characters(&line[..length])
|
||||
.map_err(|e| {
|
||||
self.error(
|
||||
let chars: Vec<xe_encoding::Character> = if let Some(encoding) = &encoding {
|
||||
let (resolved, bom) = encoding.resolve(&line);
|
||||
let (length, _) = resolved.framing().line_boundary(&line[bom..]);
|
||||
let (mut chars, warnings) = resolved.decode(&line[bom..bom + length], base + bom)
|
||||
.map_err(|e| self.error(e, Span { source, start: base + bom, end }))?;
|
||||
while chars.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) {
|
||||
chars.pop();
|
||||
}
|
||||
if warnings > 0 {
|
||||
self.observe_xe_utf8_warnings(
|
||||
vec![(self.input_position.map_or(1, |(_, line)| line), warnings)],
|
||||
files,
|
||||
)?;
|
||||
}
|
||||
chars
|
||||
} else {
|
||||
let mut length = line.len();
|
||||
while length > 0 && matches!(line[length - 1], b'\r' | b'\n' | b' ') {
|
||||
length -= 1;
|
||||
}
|
||||
let profile = self.state.input_profile();
|
||||
profile.characters(&line[..length])
|
||||
.map_err(|e| self.error(
|
||||
"invalid UTF-8 input for Unicode scalar profile",
|
||||
Span {
|
||||
source,
|
||||
start: base + e.valid_up_to(),
|
||||
end: base
|
||||
+ e.valid_up_to()
|
||||
end: base + e.valid_up_to()
|
||||
+ e.error_len().unwrap_or(length - e.valid_up_to()),
|
||||
},
|
||||
)
|
||||
})?;
|
||||
for (offset, c) in characters {
|
||||
))?
|
||||
.map(|(offset, value)| xe_encoding::Character {
|
||||
value,
|
||||
start: base + offset,
|
||||
end: base + offset + profile.width(value),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
for c in chars {
|
||||
self.tick()?;
|
||||
body.push(Token::new(
|
||||
TokenKind::Character(
|
||||
c,
|
||||
if c == ' ' {
|
||||
CatCode::Space
|
||||
} else {
|
||||
CatCode::Other
|
||||
},
|
||||
c.value,
|
||||
if c.value == ' ' { CatCode::Space } else { CatCode::Other },
|
||||
),
|
||||
Span {
|
||||
source,
|
||||
start: base + offset,
|
||||
end: base + offset + self.state.input_profile().width(c),
|
||||
},
|
||||
Span { source, start: c.start, end: c.end },
|
||||
));
|
||||
if body.len() > self.limits.tokens {
|
||||
return self.fail("native read token limit exceeded");
|
||||
@@ -2855,11 +2882,14 @@ impl Executor {
|
||||
}
|
||||
// Mouth reads exactly one physical line with the current categories;
|
||||
// the virtual EOF line is real TeX read semantics, not host data.
|
||||
let mut mouth = Mouth::new(
|
||||
source,
|
||||
if eof { b"\n".to_vec() } else { line },
|
||||
self.state.input_profile(),
|
||||
);
|
||||
let profile = self.state.input_profile();
|
||||
let mut mouth = if eof {
|
||||
Mouth::generated(source, b"\n".to_vec(), profile, Some('\n'))
|
||||
} else {
|
||||
Mouth::with_encoding(
|
||||
source, line, profile, encoding.as_ref().unwrap_or(&xe_encoding::Encoding::Auto),
|
||||
)
|
||||
};
|
||||
while let Some(mut token) =
|
||||
mouth
|
||||
.next(&self.state, &mut self.reads)
|
||||
@@ -2888,6 +2918,7 @@ impl Executor {
|
||||
return self.fail("native read token limit exceeded");
|
||||
}
|
||||
}
|
||||
self.observe_xe_utf8_warnings(mouth.take_utf8_warnings(), files)?;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -3188,6 +3219,8 @@ impl Executor {
|
||||
Primitive::XeTeXrevision => "XeTeXrevision".into(),
|
||||
Primitive::XeTeXpdffile => "XeTeXpdffile".into(),
|
||||
Primitive::XeTeXpicfile => "XeTeXpicfile".into(),
|
||||
Primitive::XeTeXinputencoding => "XeTeXinputencoding".into(),
|
||||
Primitive::XeTeXdefaultencoding => "XeTeXdefaultencoding".into(),
|
||||
Primitive::BeginL => "beginL".into(),
|
||||
Primitive::EndL => "endL".into(),
|
||||
Primitive::BeginR => "beginR".into(),
|
||||
@@ -3645,6 +3678,8 @@ impl Executor {
|
||||
let line = mouth
|
||||
.load_line(&self.state, &mut self.reads)
|
||||
.map(|_| (*source, mouth.line_number()));
|
||||
let warnings = mouth.take_utf8_warnings();
|
||||
self.observe_xe_utf8_warnings(warnings, files)?;
|
||||
self.input_position =
|
||||
Some(line.map_err(|(span, message)| self.error(message, span))?);
|
||||
self.push_mode_hook(TokenParameter::Everyjob)?;
|
||||
@@ -3872,6 +3907,9 @@ impl Executor {
|
||||
self.request_page();
|
||||
self.events.push(Event::Paragraph(token.span));
|
||||
}
|
||||
XeTeXinputencoding | XeTeXdefaultencoding => {
|
||||
self.change_xe_encoding(primitive, files)?;
|
||||
}
|
||||
BeginL | EndL | BeginR | EndR => {
|
||||
let boundary = match primitive {
|
||||
BeginL => DirectionBoundary::BeginL,
|
||||
|
||||
@@ -38,6 +38,7 @@ impl Executor {
|
||||
let Some(input) = self.inputs.last_mut() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut warnings = Vec::new();
|
||||
let next = match input {
|
||||
InputFrame::Tokens { tokens, cursor, .. } => {
|
||||
let t = tokens.get(*cursor).cloned();
|
||||
@@ -85,41 +86,45 @@ impl Executor {
|
||||
eof_seen,
|
||||
pseudo_trace,
|
||||
..
|
||||
} => match mouth.next(&self.state, &mut self.reads) {
|
||||
Ok(Some(token)) => {
|
||||
self.input_position = Some((*source, mouth.line_number()));
|
||||
Next::Token(Some(token.into()))
|
||||
}
|
||||
Ok(None) => {
|
||||
if self.state.profile() == Profile::EtexBootstrap
|
||||
&& !*eof_seen
|
||||
&& !mouth.forced_eof()
|
||||
{
|
||||
self.reads
|
||||
.insert(Dependency::TokenParameter(TokenParameter::Everyeof));
|
||||
if self
|
||||
.state
|
||||
.token_parameter(TokenParameter::Everyeof)
|
||||
.is_some()
|
||||
} => {
|
||||
let token = mouth.next(&self.state, &mut self.reads);
|
||||
warnings = mouth.take_utf8_warnings();
|
||||
match token {
|
||||
Ok(Some(token)) => {
|
||||
self.input_position = Some((*source, mouth.line_number()));
|
||||
Next::Token(Some(token.into()))
|
||||
}
|
||||
Ok(None) => {
|
||||
if self.state.profile() == Profile::EtexBootstrap
|
||||
&& !*eof_seen
|
||||
&& !mouth.forced_eof()
|
||||
{
|
||||
*eof_seen = true;
|
||||
self.input_position = Some((*source, mouth.enter_eof_line()));
|
||||
Next::EofHook
|
||||
self.reads
|
||||
.insert(Dependency::TokenParameter(TokenParameter::Everyeof));
|
||||
if self
|
||||
.state
|
||||
.token_parameter(TokenParameter::Everyeof)
|
||||
.is_some()
|
||||
{
|
||||
*eof_seen = true;
|
||||
self.input_position = Some((*source, mouth.enter_eof_line()));
|
||||
Next::EofHook
|
||||
} else {
|
||||
Next::EndSource {
|
||||
source: *source,
|
||||
trace: *pseudo_trace,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Next::EndSource {
|
||||
source: *source,
|
||||
trace: *pseudo_trace,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Next::EndSource {
|
||||
source: *source,
|
||||
trace: *pseudo_trace,
|
||||
}
|
||||
}
|
||||
Err((span, text)) => Next::Error(span, text),
|
||||
}
|
||||
Err((span, text)) => Next::Error(span, text),
|
||||
},
|
||||
}
|
||||
InputFrame::Hook { tokens, cursor, .. } => {
|
||||
let t = tokens.get(*cursor).cloned().map(InputToken::from);
|
||||
if t.is_some() {
|
||||
@@ -129,6 +134,7 @@ impl Executor {
|
||||
}
|
||||
InputFrame::Boundary => Next::Boundary,
|
||||
};
|
||||
self.observe_xe_utf8_warnings(warnings, files)?;
|
||||
match next {
|
||||
Next::Token(Some(token)) => {
|
||||
self.current = token.token.invocation.unwrap_or(token.token.span);
|
||||
@@ -169,6 +175,119 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn read_physical_stream_line(
|
||||
&mut self,
|
||||
index: u8,
|
||||
source: usize,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(Option<Vec<u8>>, Option<xe_encoding::Encoding>), Error> {
|
||||
loop {
|
||||
let stream = &self.io.inputs[&index];
|
||||
let Some(encoding) = stream.xe_encoding.clone() else {
|
||||
return files
|
||||
.read_line(index)
|
||||
.map(|line| (line, None))
|
||||
.map_err(|error| self.error(error, self.current));
|
||||
};
|
||||
let Some(line) = files
|
||||
.read_xe_line(index, encoding.framing())
|
||||
.map_err(|error| self.error(error, self.current))?
|
||||
else {
|
||||
return Ok((None, Some(encoding)));
|
||||
};
|
||||
let (resolved, bom) = encoding.resolve(&line);
|
||||
let framing = resolved.framing();
|
||||
let (length, terminator) = framing.line_boundary(&line[bom..]);
|
||||
let empty_after_bom = bom != 0 && line.len() == bom;
|
||||
let skipped_lf = stream.xe_skip_lf && length == 0 && terminator == Some(10);
|
||||
let stream = self.io.inputs.get_mut(&index).unwrap();
|
||||
stream.xe_encoding = Some(resolved);
|
||||
// External providers may deliver an already joined CRLF.
|
||||
stream.xe_skip_lf =
|
||||
terminator == Some(13) && bom + length + framing.unit_width() == line.len();
|
||||
if empty_after_bom || skipped_lf {
|
||||
self.sources[source].data.extend_from_slice(&line);
|
||||
} else {
|
||||
return Ok((Some(line), Some(encoding)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn change_xe_encoding(
|
||||
&mut self,
|
||||
primitive: Primitive,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
use super::super::xe_encoding::Encoding;
|
||||
let name = self.filename(files)?;
|
||||
let encoding = match Encoding::parse(&name).map_err(|e| self.error(e, self.current))? {
|
||||
Some(encoding) => encoding,
|
||||
None => {
|
||||
self.observe_xe_input_warning(
|
||||
&format!("\nUnknown encoding `{name}'; reading as raw bytes\n"),
|
||||
1,
|
||||
files,
|
||||
)?;
|
||||
Encoding::Bytes
|
||||
}
|
||||
};
|
||||
if primitive == Primitive::XeTeXdefaultencoding {
|
||||
self.state.xe_default_encoding = encoding;
|
||||
return Ok(());
|
||||
}
|
||||
if encoding == Encoding::Auto {
|
||||
return self.fail(r"Encoding mode `auto' is not valid for \XeTeXinputencoding");
|
||||
}
|
||||
for frame in self.inputs.iter_mut().rev() {
|
||||
if let InputFrame::Source { mouth, .. } = frame
|
||||
&& mouth.change_encoding(encoding.clone())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
self.fail(r"\XeTeXinputencoding requires a physical input file")
|
||||
}
|
||||
|
||||
pub(super) fn observe_xe_utf8_warnings(
|
||||
&mut self,
|
||||
warnings: Vec<(usize, usize)>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
for (line, count) in warnings {
|
||||
self.observe_xe_input_warning(
|
||||
&format!("\nInvalid UTF-8 byte or sequence at line {line} replaced by U+FFFD.\n"),
|
||||
count,
|
||||
files,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn observe_xe_input_warning(
|
||||
&mut self,
|
||||
message: &str,
|
||||
count: usize,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
self.diagnostic_bytes = self
|
||||
.diagnostic_bytes
|
||||
.saturating_add(message.len().saturating_mul(count));
|
||||
if self.diagnostic_bytes > self.limits.tokens {
|
||||
return self.fail("native diagnostic output limit exceeded");
|
||||
}
|
||||
let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 {
|
||||
WriteDestination::TerminalAndLog
|
||||
} else {
|
||||
WriteDestination::Log
|
||||
};
|
||||
for _ in 0..count {
|
||||
files
|
||||
.observe_diagnostic(destination, message)
|
||||
.map_err(|e| self.error(e, self.current))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_input_position(&mut self) {
|
||||
if let Some(position) = self.inputs.iter().rev().find_map(|frame| match frame {
|
||||
InputFrame::Source { source, mouth, .. } => Some((*source, mouth.line_number())),
|
||||
|
||||
@@ -8,9 +8,9 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 68;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 35] = [
|
||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, SCHEMA,
|
||||
const SCHEMA: u32 = 69;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 36] = [
|
||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, SCHEMA,
|
||||
];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ pub enum InputProfile {
|
||||
TeX8Bit,
|
||||
#[default]
|
||||
UnicodeScalar,
|
||||
/// UTF-8 input, XeTeX primitives and XDV-device semantics.
|
||||
/// Per-file Unicode input encodings, XeTeX primitives and XDV semantics.
|
||||
XeTeX,
|
||||
}
|
||||
impl InputProfile {
|
||||
|
||||
@@ -325,6 +325,10 @@ impl OutputNode {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) struct InputStream {
|
||||
pub source: usize,
|
||||
#[serde(default)]
|
||||
pub xe_encoding: Option<super::xe_encoding::Encoding>,
|
||||
#[serde(default)]
|
||||
pub xe_skip_lf: bool,
|
||||
}
|
||||
|
||||
/// Logical stream metadata only. Live host handles are NOT serialized. A
|
||||
|
||||
@@ -18,6 +18,8 @@ pub use format_image::FormatImage;
|
||||
mod hooks;
|
||||
mod hyphenation;
|
||||
mod input_profile;
|
||||
mod xe_encoding;
|
||||
pub use xe_encoding::XeLineFraming;
|
||||
mod insertions;
|
||||
mod job;
|
||||
mod ligature;
|
||||
@@ -368,6 +370,20 @@ pub trait SourceProvider {
|
||||
fn read_line(&mut self, _stream: u8) -> Result<Option<Vec<u8>>, String> {
|
||||
Err("host input streams unavailable".into())
|
||||
}
|
||||
/// Return original bytes through one delimiter of the requested framing.
|
||||
/// Hosts with byte-framed streams can retain the existing UTF-8 path.
|
||||
fn read_xe_line(&mut self, stream: u8, framing: XeLineFraming) -> Result<Option<Vec<u8>>, String> {
|
||||
if matches!(framing, XeLineFraming::Utf16Le | XeLineFraming::Utf16Be) {
|
||||
return Err("host UTF-16 input streams unavailable".into());
|
||||
}
|
||||
let bytes = self.read_line(stream)?;
|
||||
if framing == XeLineFraming::Auto
|
||||
&& bytes.as_deref().is_some_and(|data| XeLineFraming::detect(data).0.unit_width() == 2)
|
||||
{
|
||||
return Err("host UTF-16 input streams unavailable".into());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
fn close_in(&mut self, _stream: u8) -> Result<(), String> {
|
||||
Err("host input streams unavailable".into())
|
||||
}
|
||||
@@ -459,6 +475,7 @@ pub enum Dependency {
|
||||
value: Option<String>,
|
||||
},
|
||||
InputStream(u8),
|
||||
XeDefaultInputEncoding,
|
||||
InputPosition(usize),
|
||||
OutputStream(u8),
|
||||
ParagraphToken,
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
use super::{CatCode, CommandName, Dependency, Span, State, Token, TokenKind};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Character {
|
||||
value: char,
|
||||
start: usize,
|
||||
end: usize,
|
||||
use super::xe_encoding::{Character, Encoding};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct XePhysical {
|
||||
encoding: Encoding,
|
||||
autodetected: Option<(Encoding, usize)>,
|
||||
skip_lf: bool,
|
||||
terminated: bool,
|
||||
line_start: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -184,6 +188,36 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_utf16_lookahead_preserves_physical_spans_and_rebinding() {
|
||||
use super::super::InputProfile;
|
||||
let utf16 = |text: &str| {
|
||||
[0xff, 0xfe].into_iter()
|
||||
.chain(text.encode_utf16().flat_map(u16::to_le_bytes))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let state = State::default().with_input_profile(InputProfile::XeTeX);
|
||||
let mut reads = BTreeSet::new();
|
||||
let mut mouth = Mouth::new(8, utf16("A\r\n😀\r\n"), InputProfile::XeTeX);
|
||||
let first = mouth.next(&state, &mut reads).unwrap().unwrap();
|
||||
assert_eq!(first.span, Span { source: 8, start: 2, end: 4 });
|
||||
assert_eq!(mouth.physical_frontier(), Some(6));
|
||||
assert!(!mouth.matches_loaded_prefix(&utf16("B\r\n😀\r\n")));
|
||||
let edited = utf16("A\r\nΩ\r\n");
|
||||
assert!(mouth.matches_loaded_prefix(&edited));
|
||||
mouth.rebind_loaded_prefix(edited);
|
||||
let white = mouth.next(&state, &mut reads).unwrap().unwrap();
|
||||
assert!(white.kind.is_space());
|
||||
let next = mouth.next(&state, &mut reads).unwrap().unwrap();
|
||||
assert_eq!(next.kind, TokenKind::Character('Ω', state.catcode('Ω')));
|
||||
assert_eq!(next.span, Span { source: 8, start: 8, end: 10 });
|
||||
|
||||
// With only CR loaded, the second byte still affects Auto detection.
|
||||
let mut first_line = Mouth::new(0, b"\rA".to_vec(), InputProfile::XeTeX);
|
||||
first_line.load_line(&state, &mut reads).unwrap();
|
||||
assert!(!first_line.matches_loaded_prefix(b"\r\0A\0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_line_endings_and_utf8_byte_offsets_are_preserved() {
|
||||
let result = tokens("é界 \r\nB\rC");
|
||||
@@ -224,6 +258,8 @@ pub(super) struct Mouth {
|
||||
end_after_line: bool,
|
||||
line_breaks: LineBreaks,
|
||||
line_number: usize,
|
||||
xe: Option<XePhysical>,
|
||||
invalid_utf8: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Mouth {
|
||||
@@ -236,6 +272,11 @@ impl Mouth {
|
||||
return false;
|
||||
};
|
||||
let loaded = &self.data[..offset];
|
||||
if let Some(xe) = &self.xe {
|
||||
return (xe.terminated || offset == data.len())
|
||||
&& xe.autodetected.as_ref().is_none_or(|old| *old == Encoding::Auto.resolve(data))
|
||||
&& data.starts_with(loaded);
|
||||
}
|
||||
// A CR looks ahead for LF. For an unterminated line, EOF is part
|
||||
// of what has already been observed.
|
||||
let same_boundary = match loaded.last() {
|
||||
@@ -253,17 +294,41 @@ impl Mouth {
|
||||
self.data.len()
|
||||
}
|
||||
pub fn new(source: usize, data: Vec<u8>, profile: super::InputProfile) -> Self {
|
||||
Self::with_encoding(source, data, profile, &Encoding::Auto)
|
||||
}
|
||||
|
||||
pub(super) fn with_encoding(
|
||||
source: usize,
|
||||
data: Vec<u8>,
|
||||
profile: super::InputProfile,
|
||||
encoding: &Encoding,
|
||||
) -> Self {
|
||||
let (xe, offset) = if profile == super::InputProfile::XeTeX {
|
||||
let (resolved, bom) = encoding.resolve(&data);
|
||||
let detected = (*encoding == Encoding::Auto).then(|| (resolved.clone(), bom));
|
||||
(Some(XePhysical {
|
||||
encoding: resolved,
|
||||
autodetected: detected,
|
||||
skip_lf: false,
|
||||
terminated: false,
|
||||
line_start: bom,
|
||||
}), bom)
|
||||
} else {
|
||||
(None, 0)
|
||||
};
|
||||
Self {
|
||||
source,
|
||||
data,
|
||||
profile,
|
||||
offset: 0,
|
||||
offset,
|
||||
line: Vec::new(),
|
||||
cursor: 0,
|
||||
state: LineState::New,
|
||||
end_after_line: false,
|
||||
line_breaks: LineBreaks::Physical,
|
||||
line_number: 0,
|
||||
xe,
|
||||
invalid_utf8: Vec::new(),
|
||||
}
|
||||
}
|
||||
pub(super) fn generated(
|
||||
@@ -274,6 +339,8 @@ impl Mouth {
|
||||
) -> Self {
|
||||
let mut mouth = Self::new(source, data, profile);
|
||||
mouth.line_breaks = LineBreaks::Generated(separator);
|
||||
mouth.xe = None;
|
||||
mouth.offset = 0;
|
||||
mouth
|
||||
}
|
||||
pub(super) fn forced_eof(&self) -> bool {
|
||||
@@ -291,6 +358,24 @@ impl Mouth {
|
||||
pub fn end_input(&mut self) {
|
||||
self.end_after_line = true;
|
||||
}
|
||||
pub(super) fn change_encoding(&mut self, encoding: Encoding) -> bool {
|
||||
if let Some(xe) = &mut self.xe {
|
||||
xe.encoding = encoding;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn xe_location(&self, offset: usize) -> Option<(usize, usize)> {
|
||||
let xe = self.xe.as_ref()?;
|
||||
(xe.line_start <= offset && offset <= self.offset && self.line_number > 0)
|
||||
.then(|| (self.line_number, 1 + self.line.partition_point(|c| c.end <= offset && c.start < offset)))
|
||||
}
|
||||
|
||||
pub(super) fn take_utf8_warnings(&mut self) -> Vec<(usize, usize)> {
|
||||
std::mem::take(&mut self.invalid_utf8)
|
||||
}
|
||||
pub fn line_number(&self) -> usize {
|
||||
self.line_number
|
||||
}
|
||||
@@ -322,6 +407,9 @@ impl Mouth {
|
||||
if self.end_after_line || self.offset == self.data.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
if self.xe.is_some() {
|
||||
return self.load_xe_line(state, reads);
|
||||
}
|
||||
let start = self.offset;
|
||||
self.line_number += 1;
|
||||
let remaining = &self.data[start..];
|
||||
@@ -399,6 +487,57 @@ impl Mouth {
|
||||
));
|
||||
}
|
||||
};
|
||||
self.finish_line(content_end, end, state, reads);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn load_xe_line(
|
||||
&mut self,
|
||||
state: &State,
|
||||
reads: &mut BTreeSet<Dependency>,
|
||||
) -> Result<bool, (Span, String)> {
|
||||
let xe = self.xe.as_mut().unwrap();
|
||||
let framing = xe.encoding.framing();
|
||||
let width = framing.unit_width();
|
||||
if std::mem::take(&mut xe.skip_lf)
|
||||
&& framing.code_unit(&self.data[self.offset..]) == Some(10)
|
||||
{
|
||||
self.offset += width;
|
||||
}
|
||||
let start = self.offset;
|
||||
if start == self.data.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
let (length, terminator) = framing.line_boundary(&self.data[start..]);
|
||||
let content_end = start + length;
|
||||
let end = content_end + if terminator.is_some() { width } else { 0 };
|
||||
xe.line_start = start;
|
||||
xe.skip_lf = terminator == Some(13);
|
||||
xe.terminated = terminator.is_some();
|
||||
self.offset = end;
|
||||
self.line_number += 1;
|
||||
self.line.clear();
|
||||
self.cursor = 0;
|
||||
let (mut chars, invalid_utf8) = xe.encoding.decode(&self.data[start..content_end], start)
|
||||
.map_err(|message| (Span { source: self.source, start, end: content_end }, message))?;
|
||||
while chars.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) {
|
||||
chars.pop();
|
||||
}
|
||||
self.line = chars;
|
||||
if invalid_utf8 > 0 {
|
||||
self.invalid_utf8.push((self.line_number, invalid_utf8));
|
||||
}
|
||||
self.finish_line(content_end, end, state, reads);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn finish_line(
|
||||
&mut self,
|
||||
content_end: usize,
|
||||
end: usize,
|
||||
state: &State,
|
||||
reads: &mut BTreeSet<Dependency>,
|
||||
) {
|
||||
reads.insert(Dependency::EndLineChar);
|
||||
if let Ok(value) = u32::try_from(state.endlinechar)
|
||||
&& value <= 255
|
||||
@@ -412,7 +551,6 @@ impl Mouth {
|
||||
}
|
||||
self.cursor = 0;
|
||||
self.state = LineState::New;
|
||||
Ok(true)
|
||||
}
|
||||
fn catcode(state: &State, reads: &mut BTreeSet<Dependency>, c: char) -> CatCode {
|
||||
reads.insert(Dependency::CatCode(c));
|
||||
|
||||
@@ -385,6 +385,8 @@ pub enum Primitive {
|
||||
EndL,
|
||||
BeginR,
|
||||
EndR,
|
||||
XeTeXinputencoding,
|
||||
XeTeXdefaultencoding,
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
@@ -698,6 +700,8 @@ pub struct State {
|
||||
initex: bool,
|
||||
#[serde(default)]
|
||||
input_profile: super::InputProfile,
|
||||
#[serde(default)]
|
||||
pub(super) xe_default_encoding: super::xe_encoding::Encoding,
|
||||
pub endlinechar: i32,
|
||||
pub newlinechar: i32,
|
||||
pub escapechar: i32,
|
||||
@@ -905,6 +909,7 @@ impl Default for State {
|
||||
pdftex_revision: PdftexRevision::R24,
|
||||
initex: false,
|
||||
input_profile: super::InputProfile::default(),
|
||||
xe_default_encoding: super::xe_encoding::Encoding::Auto,
|
||||
endlinechar: 13,
|
||||
newlinechar: -1,
|
||||
escapechar: 92,
|
||||
@@ -1702,6 +1707,8 @@ impl State {
|
||||
("XeTeXpdffile", Primitive::XeTeXpdffile),
|
||||
("XeTeXpicfile", Primitive::XeTeXpicfile),
|
||||
("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount),
|
||||
("XeTeXinputencoding", Primitive::XeTeXinputencoding),
|
||||
("XeTeXdefaultencoding", Primitive::XeTeXdefaultencoding),
|
||||
] {
|
||||
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! XeTeX physical input encodings. Decoded units retain their source bytes.
|
||||
use std::sync::Arc;
|
||||
|
||||
mod icu;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(super) enum Encoding {
|
||||
#[default]
|
||||
Auto,
|
||||
Utf8,
|
||||
Bytes,
|
||||
Utf16Le,
|
||||
Utf16Be,
|
||||
Legacy(Arc<str>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum XeLineFraming {
|
||||
Bytes,
|
||||
Utf16Le,
|
||||
Utf16Be,
|
||||
Auto,
|
||||
}
|
||||
|
||||
impl XeLineFraming {
|
||||
pub fn detect(data: &[u8]) -> (Self, usize) {
|
||||
match data {
|
||||
[0xfe, 0xff, ..] => (Self::Utf16Be, 2),
|
||||
[0xff, 0xfe, ..] => (Self::Utf16Le, 2),
|
||||
[0, n, ..] if *n != 0 => (Self::Utf16Be, 0),
|
||||
[n, 0, ..] if *n != 0 => (Self::Utf16Le, 0),
|
||||
[0xef, 0xbb, 0xbf, ..] => (Self::Bytes, 3),
|
||||
_ => (Self::Bytes, 0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unit_width(self) -> usize {
|
||||
match self {
|
||||
Self::Utf16Be | Self::Utf16Le => 2,
|
||||
Self::Bytes | Self::Auto => 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code_unit(self, data: &[u8]) -> Option<u16> {
|
||||
match self {
|
||||
Self::Utf16Le => Some(u16::from_le_bytes(data.get(..2)?.try_into().unwrap())),
|
||||
Self::Utf16Be => Some(u16::from_be_bytes(data.get(..2)?.try_into().unwrap())),
|
||||
Self::Bytes | Self::Auto => data.first().map(|b| u16::from(*b)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn line_boundary(self, data: &[u8]) -> (usize, Option<u16>) {
|
||||
let width = self.unit_width();
|
||||
for (index, unit) in data.chunks_exact(width).enumerate() {
|
||||
let code = self.code_unit(unit).unwrap();
|
||||
if matches!(code, 10 | 13) {
|
||||
return (index * width, Some(code));
|
||||
}
|
||||
}
|
||||
(data.len(), None)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Character {
|
||||
pub value: char,
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Encoding {
|
||||
pub fn parse(name: &str) -> Result<Option<Self>, String> {
|
||||
let builtin = match name.to_ascii_lowercase().as_str() {
|
||||
"auto" => Self::Auto,
|
||||
"utf8" => Self::Utf8,
|
||||
"utf16" if cfg!(target_endian = "little") => Self::Utf16Le,
|
||||
"utf16" | "utf16be" => Self::Utf16Be,
|
||||
"utf16le" => Self::Utf16Le,
|
||||
"bytes" => Self::Bytes,
|
||||
_ => {
|
||||
return Ok(icu::recognizes(name)?.then(|| Self::Legacy(Arc::from(name))));
|
||||
}
|
||||
};
|
||||
Ok(Some(builtin))
|
||||
}
|
||||
|
||||
pub fn framing(&self) -> XeLineFraming {
|
||||
match self {
|
||||
Self::Auto => XeLineFraming::Auto,
|
||||
Self::Utf16Le => XeLineFraming::Utf16Le,
|
||||
Self::Utf16Be => XeLineFraming::Utf16Be,
|
||||
_ => XeLineFraming::Bytes,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(&self, data: &[u8]) -> (Self, usize) {
|
||||
if *self != Self::Auto {
|
||||
return (self.clone(), 0);
|
||||
}
|
||||
let (framing, bom) = XeLineFraming::detect(data);
|
||||
let encoding = match framing {
|
||||
XeLineFraming::Utf16Le => Self::Utf16Le,
|
||||
XeLineFraming::Utf16Be => Self::Utf16Be,
|
||||
_ => Self::Utf8,
|
||||
};
|
||||
(encoding, bom)
|
||||
}
|
||||
|
||||
pub fn decode(&self, data: &[u8], base: usize) -> Result<(Vec<Character>, usize), String> {
|
||||
let mut invalid_utf8 = 0;
|
||||
let chars = match self {
|
||||
Self::Auto => unreachable!("resolve the encoding at file open"),
|
||||
Self::Utf8 => {
|
||||
if let Ok(str) = std::str::from_utf8(data) {
|
||||
str.char_indices()
|
||||
.map(|(i, value)| Character {
|
||||
value,
|
||||
start: base + i,
|
||||
end: base + i + value.len_utf8(),
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
let mut chars = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < data.len() {
|
||||
let (value, length, bad) = decode_utf8_character(&data[at..]);
|
||||
invalid_utf8 += usize::from(bad);
|
||||
chars.push(Character {
|
||||
value,
|
||||
start: base + at,
|
||||
end: base + at + length,
|
||||
});
|
||||
at += length;
|
||||
}
|
||||
chars
|
||||
}
|
||||
}
|
||||
Self::Bytes => data
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, byte)| Character {
|
||||
value: char::from(*byte),
|
||||
start: base + i,
|
||||
end: base + i + 1,
|
||||
})
|
||||
.collect(),
|
||||
Self::Utf16Le | Self::Utf16Be => {
|
||||
let framing = self.framing();
|
||||
let mut chars = Vec::new();
|
||||
let mut at = 0;
|
||||
while let Some(first) = framing.code_unit(&data[at..]) {
|
||||
let second = framing.code_unit(&data[at + 2..]);
|
||||
let (value, units) = utf16_character(first, second);
|
||||
let end = at + 2 * units;
|
||||
chars.push(Character {
|
||||
value,
|
||||
start: base + at,
|
||||
end: base + end,
|
||||
});
|
||||
at = end;
|
||||
}
|
||||
if at < data.len() {
|
||||
chars.push(Character {
|
||||
value: char::REPLACEMENT_CHARACTER,
|
||||
start: base + at,
|
||||
end: base + data.len(),
|
||||
});
|
||||
}
|
||||
chars
|
||||
}
|
||||
Self::Legacy(name) => icu::decode(name, data, base)?,
|
||||
};
|
||||
Ok((chars, invalid_utf8))
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_utf8_character(input: &[u8]) -> (char, usize, bool) {
|
||||
let first = input[0];
|
||||
let (mut value, continuation) = match first {
|
||||
0x00..=0xbf => return (char::from(first), 1, false),
|
||||
0xc0..=0xdf => (u32::from(first & 0x1f), 1),
|
||||
0xe0..=0xef => (u32::from(first & 0x0f), 2),
|
||||
0xf0..=0xf7 => (u32::from(first & 0x07), 3),
|
||||
_ => return (char::REPLACEMENT_CHARACTER, 1, true),
|
||||
};
|
||||
for at in 1..=continuation {
|
||||
let Some(&b @ 0x80..=0xbf) = input.get(at) else {
|
||||
return (char::REPLACEMENT_CHARACTER, at, true);
|
||||
};
|
||||
value = (value << 6) | u32::from(b & 0x3f);
|
||||
}
|
||||
match char::from_u32(value) {
|
||||
Some(c) => (c, continuation + 1, false),
|
||||
None => (char::REPLACEMENT_CHARACTER, continuation + 1, true),
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16_character(first: u16, second: Option<u16>) -> (char, usize) {
|
||||
if let (0xd800..=0xdbff, Some(low @ 0xdc00..=0xdfff)) = (first, second) {
|
||||
let value = 0x10000 + ((u32::from(first) - 0xd800) << 10) + u32::from(low) - 0xdc00;
|
||||
return (char::from_u32(value).unwrap(), 2);
|
||||
}
|
||||
(
|
||||
char::from_u32(u32::from(first)).unwrap_or(char::REPLACEMENT_CHARACTER),
|
||||
1,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! The ICU converter used by XeTeX for non-built-in encoding names.
|
||||
use super::{Character, utf16_character};
|
||||
use libloading::Library;
|
||||
use std::{
|
||||
ffi::{CString, c_char, c_void},
|
||||
sync::OnceLock,
|
||||
};
|
||||
|
||||
type Open = unsafe extern "C" fn(*const c_char, *mut i32) -> *mut c_void;
|
||||
type Close = unsafe extern "C" fn(*mut c_void);
|
||||
type ToUnicode = unsafe extern "C" fn(
|
||||
*mut c_void,
|
||||
*mut *mut u16,
|
||||
*const u16,
|
||||
*mut *const c_char,
|
||||
*const c_char,
|
||||
*mut i32,
|
||||
i8,
|
||||
*mut i32,
|
||||
);
|
||||
|
||||
struct Icu {
|
||||
open: Open,
|
||||
close: Close,
|
||||
to_unicode: ToUnicode,
|
||||
_library: Library,
|
||||
}
|
||||
|
||||
fn library() -> Result<&'static Icu, String> {
|
||||
static ICU: OnceLock<Option<Icu>> = OnceLock::new();
|
||||
ICU.get_or_init(load)
|
||||
.as_ref()
|
||||
.ok_or_else(|| "XeTeX legacy input encodings require an ICU4C runtime".into())
|
||||
}
|
||||
|
||||
fn load() -> Option<Icu> {
|
||||
#[cfg(target_os = "windows")]
|
||||
let unversioned = ["icu.dll", "icuuc.dll"];
|
||||
#[cfg(target_os = "macos")]
|
||||
let unversioned = ["libicucore.dylib", "libicuuc.dylib"];
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
let unversioned = ["libicuuc.so"];
|
||||
let versions = (50..=100).rev();
|
||||
// Only the platform loader's library search path is used, never the input
|
||||
// directory or the encoding name supplied by a document.
|
||||
for name in unversioned
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.chain(versions.clone().map(|v| {
|
||||
if cfg!(target_os = "windows") {
|
||||
format!("icuuc{v}.dll")
|
||||
} else if cfg!(target_os = "macos") {
|
||||
format!("libicuuc.{v}.dylib")
|
||||
} else {
|
||||
format!("libicuuc.so.{v}")
|
||||
}
|
||||
}))
|
||||
{
|
||||
#[cfg(target_os = "windows")]
|
||||
let loaded = unsafe {
|
||||
// LOAD_LIBRARY_SEARCH_DEFAULT_DIRS excludes a document's cwd.
|
||||
libloading::os::windows::Library::load_with_flags(name, 0x0000_1000).map(Library::from)
|
||||
};
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let loaded = unsafe { Library::new(name) };
|
||||
let Ok(lib) = loaded else { continue };
|
||||
for suffix in
|
||||
std::iter::once(String::new()).chain(versions.clone().map(|v| format!("_{v}")))
|
||||
{
|
||||
// ICU4C ships these declarations as stable C ABI. All three must
|
||||
// come from this same library and use the same export suffix.
|
||||
let symbols = unsafe {
|
||||
(
|
||||
lib.get::<Open>(format!("ucnv_open{suffix}").as_bytes()),
|
||||
lib.get::<Close>(format!("ucnv_close{suffix}").as_bytes()),
|
||||
lib.get::<ToUnicode>(format!("ucnv_toUnicode{suffix}").as_bytes()),
|
||||
)
|
||||
};
|
||||
if let (Ok(open), Ok(close), Ok(to_unicode)) = symbols {
|
||||
return Some(Icu {
|
||||
open: *open,
|
||||
close: *close,
|
||||
to_unicode: *to_unicode,
|
||||
_library: lib,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct Converter {
|
||||
icu: &'static Icu,
|
||||
value: *mut c_void,
|
||||
}
|
||||
|
||||
impl Converter {
|
||||
fn new(name: &str) -> Result<Option<Self>, String> {
|
||||
let Ok(name) = CString::new(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let icu = library()?;
|
||||
let mut status = 0;
|
||||
// name has a C terminator and only lives for this call.
|
||||
let value = unsafe { (icu.open)(name.as_ptr(), &mut status) };
|
||||
Ok((!value.is_null()).then(|| Self { icu, value }))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Converter {
|
||||
fn drop(&mut self) {
|
||||
// Each converter belongs to a single line conversion.
|
||||
unsafe { (self.icu.close)(self.value) };
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn recognizes(name: &str) -> Result<bool, String> {
|
||||
Converter::new(name).map(|converter| converter.is_some())
|
||||
}
|
||||
|
||||
pub(super) fn decode(name: &str, data: &[u8], base: usize) -> Result<Vec<Character>, String> {
|
||||
if data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut capacity = data.len().saturating_add(4);
|
||||
let (units, offsets) = loop {
|
||||
if capacity > i32::MAX as usize {
|
||||
return Err("XeTeX legacy input line is too long".into());
|
||||
}
|
||||
let converter = Converter::new(name)?
|
||||
.ok_or_else(|| format!("ICU converter for {name} is unavailable"))?;
|
||||
let mut units = vec![0u16; capacity];
|
||||
let mut offsets = vec![0; capacity];
|
||||
let target = units.as_mut_ptr();
|
||||
let source = data.as_ptr().cast::<c_char>();
|
||||
let (mut end, mut read, mut status) = (target, source, 0);
|
||||
// Both limits point one past allocated buffers. ICU writes one offset
|
||||
// per UTF-16 unit and advances end and read within those buffers.
|
||||
let count = unsafe {
|
||||
(converter.icu.to_unicode)(
|
||||
converter.value,
|
||||
&mut end,
|
||||
target.add(capacity),
|
||||
&mut read,
|
||||
source.add(data.len()),
|
||||
offsets.as_mut_ptr(),
|
||||
1,
|
||||
&mut status,
|
||||
);
|
||||
end.offset_from(target) as usize
|
||||
};
|
||||
if status == 15 {
|
||||
// U_BUFFER_OVERFLOW_ERROR
|
||||
capacity *= 2;
|
||||
continue;
|
||||
}
|
||||
if status > 0 {
|
||||
return Err(format!(
|
||||
"Unicode conversion failed (ICU error code = {status})"
|
||||
));
|
||||
}
|
||||
units.truncate(count);
|
||||
offsets.truncate(count);
|
||||
break (units, offsets);
|
||||
};
|
||||
let mut chars = Vec::new();
|
||||
let mut index = 0;
|
||||
let mut start = 0;
|
||||
let mut next_distinct = 0;
|
||||
while index < units.len() {
|
||||
let (value, width) = utf16_character(units[index], units.get(index + 1).copied());
|
||||
if let Ok(offset) = usize::try_from(offsets[index]) {
|
||||
start = offset.min(data.len());
|
||||
}
|
||||
next_distinct = next_distinct.max(index + width);
|
||||
while next_distinct < offsets.len()
|
||||
&& !usize::try_from(offsets[next_distinct]).is_ok_and(|offset| offset > start)
|
||||
{
|
||||
next_distinct += 1;
|
||||
}
|
||||
let end = offsets
|
||||
.get(next_distinct)
|
||||
.map_or(data.len(), |&offset| (offset as usize).min(data.len()));
|
||||
chars.push(Character {
|
||||
value,
|
||||
start: base + start,
|
||||
end: base + end,
|
||||
});
|
||||
index += width;
|
||||
}
|
||||
Ok(chars)
|
||||
}
|
||||
@@ -274,3 +274,40 @@ fn xetex_formats_and_paints_nested_direction_spans() {
|
||||
.unwrap_err();
|
||||
assert!(error.message.contains(r"Improper \beginR"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_default_encoding_survives_dump_and_current_line_is_already_decoded() {
|
||||
let state = State::initex().with_input_profile(InputProfile::XeTeX).with_etex();
|
||||
let mut data = br"\catcode123=1 \catcode125=2".to_vec();
|
||||
data.extend_from_slice("\n\\XeTeXinputencoding \"bytes\" \\message{\\number`é}\n".as_bytes());
|
||||
data.extend_from_slice(b"\\message{\\number`\xe9}\n");
|
||||
data.extend_from_slice(br#"{\XeTeXdefaultencoding "utf16be"}\dump"#);
|
||||
let execution = Executor::new(state, Limits::default())
|
||||
.run(SourceFile { name: "seed.tex".into(), data: data.clone() }, &mut NoFiles)
|
||||
.unwrap();
|
||||
assert_eq!(messages(&execution), ["233", "233"]);
|
||||
let bytes = FormatImage::from_dump(execution, Vec::new(), Vec::new())
|
||||
.unwrap().encode().unwrap();
|
||||
let job = FormatImage::decode(&bytes).unwrap()
|
||||
.new_job(
|
||||
Profile::EtexBootstrap,
|
||||
InputProfile::XeTeX,
|
||||
JobTime::new(2025, 10, 9, 0).unwrap(),
|
||||
Limits::default(),
|
||||
|_| Ok(data.clone()),
|
||||
)
|
||||
.unwrap();
|
||||
let input = r"\def\word{😀}\message{\word}\end";
|
||||
// A UTF-16 source without a BOM must follow the stored mode.
|
||||
let data = input.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<_>>();
|
||||
let result = job.run(SourceFile { name: "next.tex".into(), data: data.clone() }, &mut NoFiles)
|
||||
.unwrap();
|
||||
assert_eq!(messages(&result), ["😀"]);
|
||||
let Meaning::Macro(word) = result.state.meaning(&CommandName::Control("word".into())) else {
|
||||
panic!("expected the real definition");
|
||||
};
|
||||
let [Replacement::Token(token)] = word.replacement.as_slice() else {
|
||||
panic!("expected one scalar token");
|
||||
};
|
||||
assert_eq!(&data[token.span.start..token.span.end], [0xd8, 0x3d, 0xde, 0x00]);
|
||||
}
|
||||
Reference in new issue
Block a user