Apply Web2C TCX tables to native byte streams
This commit is contained in:
1 parent
3bb2330676
commit
509f229a52
13 files changed
+393
-38
No files matched your search
@@ -0,0 +1,110 @@
|
||||
//! Web2C character translation and printability for physical TeX byte I/O.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ByteTranslation {
|
||||
input: [[u8; 32]; 8],
|
||||
output: [[u8; 32]; 8],
|
||||
printable: [u64; 4],
|
||||
}
|
||||
|
||||
impl Default for ByteTranslation {
|
||||
fn default() -> Self {
|
||||
let identity =
|
||||
std::array::from_fn(|row| std::array::from_fn(|column| (row * 32 + column) as u8));
|
||||
Self {
|
||||
input: identity,
|
||||
output: identity,
|
||||
printable: [u64::MAX << 32, u64::MAX >> 1, 0, 0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ByteTranslation {
|
||||
pub fn from_tcx(data: &[u8]) -> Result<Self, String> {
|
||||
let mut table = Self::default();
|
||||
for (line, bytes) in data.split(|&b| b == b'\n').enumerate() {
|
||||
let record = bytes.split(|&b| b == b'%').next().unwrap_or_default();
|
||||
let record = std::str::from_utf8(record)
|
||||
.map_err(|_| format!("invalid TCX entry on line {}", line + 1))?;
|
||||
let mut fields = record.split_ascii_whitespace();
|
||||
let Some(field) = fields.next() else {
|
||||
continue;
|
||||
};
|
||||
let parse = |field| {
|
||||
number(field).ok_or_else(|| format!("invalid TCX entry on line {}", line + 1))
|
||||
};
|
||||
let external = parse(field)?;
|
||||
let internal = if let Some(field) = fields.next() {
|
||||
let internal = parse(field)?;
|
||||
table.input[usize::from(external) / 32][usize::from(external) % 32] = internal;
|
||||
table.output[usize::from(internal) / 32][usize::from(internal) % 32] = external;
|
||||
internal
|
||||
} else {
|
||||
external
|
||||
};
|
||||
let printable = match fields.next() {
|
||||
Some(field) => match parse(field)? {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => return Err(format!("invalid TCX printable flag on line {}", line + 1)),
|
||||
},
|
||||
None => true,
|
||||
};
|
||||
let mask = 1_u64 << (internal % 64);
|
||||
let entry = &mut table.printable[usize::from(internal) / 64];
|
||||
if printable || (32..=126).contains(&internal) {
|
||||
*entry |= mask;
|
||||
} else {
|
||||
*entry &= !mask;
|
||||
}
|
||||
}
|
||||
Ok(table)
|
||||
}
|
||||
|
||||
pub(super) fn input(&self, value: u8) -> u8 {
|
||||
self.input[usize::from(value) / 32][usize::from(value) % 32]
|
||||
}
|
||||
|
||||
pub(super) fn output(&self, value: u8) -> u8 {
|
||||
self.output[usize::from(value) / 32][usize::from(value) % 32]
|
||||
}
|
||||
|
||||
pub(super) fn printable(&self, value: u8) -> bool {
|
||||
self.printable[usize::from(value) / 64] & (1_u64 << (value % 64)) != 0
|
||||
}
|
||||
}
|
||||
|
||||
fn number(field: &str) -> Option<u8> {
|
||||
let field = field.strip_prefix('+').unwrap_or(field);
|
||||
if let Some(hex) = field
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| field.strip_prefix("0X"))
|
||||
{
|
||||
u8::from_str_radix(hex, 16).ok()
|
||||
} else if field.len() > 1 && field.starts_with('0') {
|
||||
u8::from_str_radix(field, 8).ok()
|
||||
} else {
|
||||
field.parse().ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn diagnostic_text(bytes: &[u8]) -> String {
|
||||
let mut text = String::new();
|
||||
let mut remaining = bytes;
|
||||
loop {
|
||||
match std::str::from_utf8(remaining) {
|
||||
Ok(valid) => {
|
||||
text.push_str(valid);
|
||||
return text;
|
||||
}
|
||||
Err(error) => {
|
||||
let start = error.valid_up_to();
|
||||
let end = start + error.error_len().unwrap_or(remaining.len() - start);
|
||||
text.push_str(std::str::from_utf8(&remaining[..start]).unwrap());
|
||||
for &byte in &remaining[start..end] {
|
||||
text.push_str(&super::context::encoded_character(char::from(byte)));
|
||||
}
|
||||
remaining = &remaining[end..];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,6 +369,11 @@ impl EntryCheckpoint {
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
pub fn with_byte_translation(mut self, table: ByteTranslation) -> Self {
|
||||
self.state.byte_translation = Some(Arc::new(table));
|
||||
self
|
||||
}
|
||||
|
||||
// Native jobs enforce the no-shell-escape policy for immediate and shipped writes.
|
||||
const SHELL_ESCAPE: i32 = 0;
|
||||
// Compatibility level for the eight-bit native PDF interface.
|
||||
@@ -2919,7 +2924,7 @@ impl Executor {
|
||||
},
|
||||
))?
|
||||
.map(|(offset, value)| xe_encoding::Character {
|
||||
value,
|
||||
value: self.state.translate_input_character(value),
|
||||
start: base + offset,
|
||||
end: base + offset + profile.width(value),
|
||||
})
|
||||
@@ -3155,18 +3160,21 @@ impl Executor {
|
||||
OutputOperation::Write { stream, tokens } => {
|
||||
let expanded = self.fully_expand(tokens.clone(), files)?;
|
||||
let text = self.token_list_text(&expanded);
|
||||
let mut text = self.external_print(&text);
|
||||
let mut bytes = self.external_print_bytes(&text);
|
||||
if *stream == 18 {
|
||||
text = format!("runsystem({text})...disabled.\n");
|
||||
let mut message = b"runsystem(".to_vec();
|
||||
message.extend_from_slice(&bytes);
|
||||
message.extend_from_slice(b")...disabled.\n");
|
||||
bytes = message;
|
||||
} else {
|
||||
text.push('\n');
|
||||
bytes.push(b'\n');
|
||||
}
|
||||
if (0..16).contains(stream) {
|
||||
self.reads.insert(Dependency::OutputStream(*stream as u8));
|
||||
}
|
||||
if (0..16).contains(stream) && self.io.outputs.contains(&(*stream as u8)) {
|
||||
files
|
||||
.write_out(*stream as u8, &text)
|
||||
.write_out_bytes(*stream as u8, &bytes)
|
||||
.map_err(|e| self.error(e, node.span))?;
|
||||
} else {
|
||||
let destination = if matches!(*stream, 17 | 18) {
|
||||
@@ -3175,11 +3183,11 @@ impl Executor {
|
||||
WriteDestination::TerminalAndLog
|
||||
};
|
||||
files
|
||||
.diagnostic(destination, &text)
|
||||
.diagnostic_bytes(destination, &bytes)
|
||||
.map_err(|e| self.error(e, node.span))?;
|
||||
self.events.push(Event::Write {
|
||||
destination,
|
||||
text,
|
||||
text: super::byte_translation::diagnostic_text(&bytes),
|
||||
span: node.span,
|
||||
});
|
||||
}
|
||||
@@ -3261,27 +3269,33 @@ impl Executor {
|
||||
/// terminal/log/file printers encode ASCII controls unless newlinechar
|
||||
/// selects that code as a physical output line break.
|
||||
fn external_print(&mut self, text: &str) -> std::string::String {
|
||||
super::byte_translation::diagnostic_text(&self.external_print_bytes(text))
|
||||
}
|
||||
|
||||
fn external_print_bytes(&mut self, text: &str) -> Vec<u8> {
|
||||
self.reads.insert(Dependency::NewLineChar);
|
||||
let newline = u8::try_from(self.state.newlinechar).ok().map(char::from);
|
||||
let mut printed = std::string::String::new();
|
||||
let byte_mode = self.state.input_profile() == super::InputProfile::TeX8Bit;
|
||||
let table = self.state.byte_translation.as_deref().filter(|_| byte_mode);
|
||||
let mut bytes = Vec::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
if Some(c) == newline {
|
||||
printed.push('\n');
|
||||
} else if self.state.input_profile() == super::InputProfile::TeX8Bit
|
||||
&& (c as u32) >= 128
|
||||
&& (c as u32) <= 255
|
||||
bytes.push(b'\n');
|
||||
} else if let Some(table) = table
|
||||
&& let Ok(value) = u8::try_from(c as u32)
|
||||
{
|
||||
printed.push_str(&super::context::encoded_character(c));
|
||||
} else if c < ' ' {
|
||||
printed.push_str("^^");
|
||||
printed.push(char::from(c as u8 + 64));
|
||||
} else if c == '\u{7f}' {
|
||||
printed.push_str("^^?");
|
||||
if table.printable(value) {
|
||||
bytes.push(table.output(value));
|
||||
} else {
|
||||
bytes.extend(super::context::encoded_character(c).bytes().map(|b| table.output(b)));
|
||||
}
|
||||
} else if c < ' ' || c == '\u{7f}' || (byte_mode && ('\u{80}'..='\u{ff}').contains(&c)) {
|
||||
bytes.extend_from_slice(super::context::encoded_character(c).as_bytes());
|
||||
} else {
|
||||
printed.push(c);
|
||||
bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
|
||||
}
|
||||
}
|
||||
printed
|
||||
bytes
|
||||
}
|
||||
fn meaning_string(&mut self, token: &Token) -> Result<std::string::String, Error> {
|
||||
self.reads.insert(Dependency::EscapeChar);
|
||||
@@ -4174,7 +4188,8 @@ impl Executor {
|
||||
Message | Errmessage => {
|
||||
let expanded = self.scan_expanded_group(files)?;
|
||||
let text = self.token_list_text(&expanded);
|
||||
let text = self.external_print(&text);
|
||||
let bytes = self.external_print_bytes(&text);
|
||||
let text = super::byte_translation::diagnostic_text(&bytes);
|
||||
if primitive == Errmessage {
|
||||
let mut error = self.error(
|
||||
format!("TeX errmessage: {text}"),
|
||||
@@ -4191,7 +4206,7 @@ impl Executor {
|
||||
return Err(error);
|
||||
}
|
||||
files
|
||||
.observe_message(&text)
|
||||
.observe_message_bytes(&bytes)
|
||||
.map_err(|e| self.error(e, token.span))?;
|
||||
self.events.push(Event::Message {
|
||||
text,
|
||||
|
||||
@@ -16,9 +16,9 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 96;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 62] = [
|
||||
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, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, SCHEMA,
|
||||
const SCHEMA: u32 = 97;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 63] = [
|
||||
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, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, SCHEMA,
|
||||
];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Route-D-owned TeX execution. No semantic renderer, source rewriting or VM
|
||||
//! adapter participates in this path. Unsupported commands are errors.
|
||||
mod boxes;
|
||||
mod byte_translation;
|
||||
pub use byte_translation::ByteTranslation;
|
||||
mod cancellation;
|
||||
mod case;
|
||||
mod context;
|
||||
@@ -347,6 +349,9 @@ pub trait SourceProvider {
|
||||
fn observe_message(&mut self, _text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
fn observe_message_bytes(&mut self, text: &[u8]) -> Result<(), String> {
|
||||
self.observe_message(&byte_translation::diagnostic_text(text))
|
||||
}
|
||||
/// Optional live observer for retained engine diagnostics. Unlike an
|
||||
/// explicit write, a pure library consumer can inspect the typed event.
|
||||
fn observe_diagnostic(
|
||||
@@ -422,12 +427,20 @@ pub trait SourceProvider {
|
||||
fn write_out(&mut self, _stream: u8, _text: &str) -> Result<(), String> {
|
||||
Err("host output streams unavailable".into())
|
||||
}
|
||||
/// Hosts that persist byte-mode TeX output must accept arbitrary bytes.
|
||||
fn write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> {
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| "host output stream requires UTF-8")?;
|
||||
self.write_out(stream, text)
|
||||
}
|
||||
fn close_out(&mut self, _stream: u8) -> Result<(), String> {
|
||||
Err("host output streams unavailable".into())
|
||||
}
|
||||
fn diagnostic(&mut self, _destination: WriteDestination, _text: &str) -> Result<(), String> {
|
||||
Err("host diagnostic sink unavailable".into())
|
||||
}
|
||||
fn diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> {
|
||||
self.diagnostic(destination, &byte_translation::diagnostic_text(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoFiles;
|
||||
|
||||
@@ -497,7 +497,11 @@ impl Mouth {
|
||||
self.line = match self.profile.characters(&self.data[start..trimmed]) {
|
||||
Ok(characters) => characters
|
||||
.map(|(index, value)| Character {
|
||||
value,
|
||||
value: if matches!(self.line_breaks, LineBreaks::Generated(_)) {
|
||||
value
|
||||
} else {
|
||||
state.translate_input_character(value)
|
||||
},
|
||||
start: start + index,
|
||||
end: start + index + self.profile.width(value),
|
||||
})
|
||||
|
||||
@@ -748,6 +748,8 @@ pub struct State {
|
||||
initex: bool,
|
||||
#[serde(default)]
|
||||
input_profile: super::InputProfile,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) byte_translation: Option<std::sync::Arc<super::ByteTranslation>>,
|
||||
#[serde(default)]
|
||||
pub(super) xe_default_encoding: super::xe_encoding::Encoding,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -977,6 +979,7 @@ impl Default for State {
|
||||
pdftex_revision: PdftexRevision::R24,
|
||||
initex: false,
|
||||
input_profile: super::InputProfile::default(),
|
||||
byte_translation: None,
|
||||
xe_default_encoding: super::xe_encoding::Encoding::Auto,
|
||||
xe_line_break_locale: None,
|
||||
endlinechar: 13,
|
||||
@@ -1987,6 +1990,15 @@ impl State {
|
||||
pub fn input_profile(&self) -> super::InputProfile {
|
||||
self.input_profile
|
||||
}
|
||||
pub(super) fn translate_input_character(&self, value: char) -> char {
|
||||
if let Some(table) = &self.byte_translation
|
||||
&& self.input_profile == super::InputProfile::TeX8Bit
|
||||
&& let Ok(byte) = u8::try_from(value as u32)
|
||||
{
|
||||
return char::from(table.input(byte));
|
||||
}
|
||||
value
|
||||
}
|
||||
pub fn catcode(&self, character: char) -> CatCode {
|
||||
self.catcodes
|
||||
.get(&character)
|
||||
|
||||
Reference in new issue
Block a user