4931 lines
204 KiB
Rust
4931 lines
204 KiB
Rust
use std::collections::{BTreeSet, HashSet, VecDeque};
|
|
use std::sync::Arc;
|
|
|
|
use super::job::InputStream;
|
|
use super::mouth::Mouth;
|
|
use super::state::{GroupKind, Key, Replacement};
|
|
use super::*;
|
|
mod alignment;
|
|
mod boxes;
|
|
mod case;
|
|
mod device;
|
|
mod diagnostics;
|
|
mod display;
|
|
mod expressions;
|
|
mod fonts;
|
|
mod hyphenation;
|
|
mod input;
|
|
mod interchar;
|
|
mod list_tail;
|
|
mod marks;
|
|
mod math;
|
|
mod math_codes;
|
|
mod nesting;
|
|
mod page;
|
|
mod paragraphs;
|
|
mod pdf_catalog;
|
|
mod pdf_color;
|
|
mod pdf_graphics;
|
|
mod pdf_image;
|
|
mod pdf_form;
|
|
mod pdf_objects;
|
|
mod pdf_links;
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
pub(super) mod pdf_match;
|
|
mod quantities;
|
|
mod restores;
|
|
mod scan_stack;
|
|
mod scanning;
|
|
mod scheduling;
|
|
mod specials;
|
|
mod statistics;
|
|
mod xdv_annotation;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct Limits {
|
|
pub steps: usize,
|
|
pub tokens: usize,
|
|
pub input_depth: usize,
|
|
}
|
|
impl Default for Limits {
|
|
fn default() -> Self {
|
|
Self {
|
|
steps: 100_000,
|
|
tokens: 1_000_000,
|
|
input_depth: 512,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct InputToken {
|
|
token: Token,
|
|
frozen: bool,
|
|
end_write: bool,
|
|
alignment: Option<alignment::Boundary>,
|
|
xe_backed_char: bool,
|
|
}
|
|
impl From<Token> for InputToken {
|
|
fn from(token: Token) -> Self {
|
|
Self {
|
|
token,
|
|
frozen: false,
|
|
end_write: false,
|
|
alignment: None,
|
|
xe_backed_char: false,
|
|
}
|
|
}
|
|
}
|
|
#[derive(Clone)]
|
|
enum InputFrame {
|
|
Source {
|
|
source: usize,
|
|
mouth: Mouth,
|
|
eof_seen: bool,
|
|
pseudo_trace: Option<bool>,
|
|
group_boundary: usize,
|
|
conditional_boundary: usize,
|
|
},
|
|
Tokens {
|
|
tokens: Vec<InputToken>,
|
|
cursor: usize,
|
|
kind: TokenInputKind,
|
|
},
|
|
Macro {
|
|
definition: Arc<Macro>,
|
|
name: CommandName,
|
|
cursor: usize,
|
|
arguments: Vec<Arc<[Token]>>,
|
|
call: Span,
|
|
},
|
|
Argument {
|
|
tokens: Arc<[Token]>,
|
|
cursor: usize,
|
|
call: Span,
|
|
},
|
|
Hook {
|
|
parameter: TokenParameter,
|
|
tokens: Arc<[Token]>,
|
|
cursor: usize,
|
|
},
|
|
Boundary,
|
|
}
|
|
#[derive(Clone, Copy)]
|
|
enum TokenInputKind {
|
|
Inserted,
|
|
BackedUp,
|
|
Write,
|
|
Mark,
|
|
Output,
|
|
XeInterChar,
|
|
}
|
|
enum TheValue {
|
|
Tokens(Vec<Token>),
|
|
Text(std::string::String),
|
|
}
|
|
#[derive(Clone)]
|
|
struct Conditional {
|
|
primitive: Primitive,
|
|
inverted: bool,
|
|
origin: Option<(usize, usize)>,
|
|
limit: ConditionalLimit,
|
|
span: Span,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
enum ConditionalLimit {
|
|
Scanning,
|
|
Fi,
|
|
Else,
|
|
Or,
|
|
}
|
|
|
|
impl ConditionalLimit {
|
|
fn accepts(self, branch: Primitive) -> bool {
|
|
match branch {
|
|
Primitive::Fi => self != Self::Scanning,
|
|
Primitive::Else => matches!(self, Self::Else | Self::Or),
|
|
Primitive::Or => self == Self::Or,
|
|
_ => false,
|
|
}
|
|
}
|
|
}
|
|
|
|
// Closed chunks keep their original order and are shared by entry checkpoints.
|
|
// The live tail is the only part changed while a continuation executes.
|
|
#[derive(Clone, Default)]
|
|
struct ExecutionEvents {
|
|
prefix: Vec<std::sync::Arc<Vec<Event>>>,
|
|
prefix_len: usize,
|
|
tail: Vec<Event>,
|
|
}
|
|
|
|
impl ExecutionEvents {
|
|
fn push(&mut self, event: Event) {
|
|
self.tail.push(event);
|
|
}
|
|
|
|
fn len(&self) -> usize {
|
|
self.prefix_len + self.tail.len()
|
|
}
|
|
|
|
fn iter(&self) -> impl Iterator<Item = &Event> {
|
|
self.prefix
|
|
.iter()
|
|
.flat_map(|chunk| chunk.iter())
|
|
.chain(&self.tail)
|
|
}
|
|
|
|
fn seal_prefix(&mut self) {
|
|
if !self.tail.is_empty() {
|
|
self.prefix_len += self.tail.len();
|
|
self.prefix
|
|
.push(std::sync::Arc::new(std::mem::take(&mut self.tail)));
|
|
}
|
|
}
|
|
|
|
fn into_vec(self) -> Vec<Event> {
|
|
if self.prefix.is_empty() {
|
|
return self.tail;
|
|
}
|
|
let mut events = Vec::with_capacity(self.len());
|
|
for chunk in self.prefix {
|
|
match std::sync::Arc::try_unwrap(chunk) {
|
|
Ok(chunk) => events.extend(chunk),
|
|
Err(chunk) => events.extend_from_slice(&chunk),
|
|
}
|
|
}
|
|
events.extend(self.tail);
|
|
events
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Executor {
|
|
state: State,
|
|
limits: Limits,
|
|
cancellation: Option<Cancellation>,
|
|
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
|
|
interaction_mode: u8,
|
|
inputs: Vec<InputFrame>,
|
|
sources: Vec<SourceFile>,
|
|
stream_sources: BTreeSet<usize>,
|
|
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
|
|
reads: BTreeSet<Dependency>,
|
|
meaning_reads: HashSet<CommandName>,
|
|
reads_tracing_macros: bool,
|
|
conditionals: Vec<Conditional>,
|
|
in_csname: bool,
|
|
command_trace_mode: Option<&'static str>,
|
|
events: ExecutionEvents,
|
|
steps: usize,
|
|
ligature_carry: super::ligature::Carry,
|
|
current: Span,
|
|
expression_depth: usize,
|
|
scanner_depth: usize,
|
|
scanner_status: ScannerStatus,
|
|
expansion_depth: usize,
|
|
io: IoState,
|
|
pdf_colors: crate::pdf_device::PdfColorStacks,
|
|
xdv_colors: crate::pdf_device::xdv_color::ColorState,
|
|
xdv_annotations: crate::pdf_device::xdv_annotation::AnnotationState,
|
|
xdv_text: crate::pdf_device::xdv_document::TextEncoding,
|
|
pdf_link_stack: Vec<pdf_links::ActiveLink>,
|
|
pdf_active_thread: Option<pdf_links::ActiveThread>,
|
|
pdf_navigation_geometry: pdf_links::NavigationGeometry,
|
|
pdf_running_links: bool,
|
|
pdf_interword_spaces: bool,
|
|
pdf_space_font: Option<crate::pdf_device::text_spaces::SpaceFontRequest>,
|
|
pdf_loaded_space_font: Option<Arc<crate::native_font::NativeFont>>,
|
|
pdf_space_probe: Option<Arc<page::PdfSpaceProbe>>,
|
|
pdf_virtual_fonts: Arc<crate::native_font::JobVirtualFonts>,
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
|
|
pdf_catalog_tokens: Vec<Token>,
|
|
pdf_outlines: Vec<crate::pdf_device::catalog::PdfOutline<Vec<Token>>>,
|
|
pdf_outline_payload: usize,
|
|
pdf_info_tokens: Vec<Token>,
|
|
pdf_images: Vec<pdf_image::RegisteredImage>,
|
|
restored_pdf_image_count: usize,
|
|
format_image_warnings: Vec<String>,
|
|
pdf_force_pagebox_warned: bool,
|
|
input_position: Option<(usize, usize)>,
|
|
paragraph: Option<super::paragraph::Builder>,
|
|
vertical: super::boxes::VerticalBuilder,
|
|
box_frames: Vec<boxes::BoxFrame>,
|
|
box_nodes_created: usize,
|
|
material_charge: usize,
|
|
mark_cells_created: usize,
|
|
diagnostic_bytes: usize,
|
|
after_assignment: Option<Token>,
|
|
after_group_tokens: usize,
|
|
math: Vec<super::math::MathBuilder>,
|
|
math_tokens_processed: usize,
|
|
display: Option<display::DisplayFrame>,
|
|
native_page: Option<NativePageState>,
|
|
split_discards: Vec<NativeVerticalNode>,
|
|
output_frame: Option<page::OutputFrame>,
|
|
pending_shipouts: VecDeque<NativeBox>,
|
|
shipped_pages: usize,
|
|
job_ended: bool,
|
|
fresh_job: bool,
|
|
job_name: Option<String>,
|
|
format_loaded: bool,
|
|
format_dumped: bool,
|
|
writing: bool,
|
|
stack_peaks: StackUsage,
|
|
alignments: Vec<alignment::AlignmentFrame>,
|
|
alignment_balance: i64,
|
|
}
|
|
|
|
impl Default for Executor {
|
|
fn default() -> Self {
|
|
Self::new(State::default(), Limits::default())
|
|
}
|
|
}
|
|
|
|
/// A live, in-memory kernel continuation at an entry-file command boundary.
|
|
/// The host must validate dependencies and replay all prefix effects before
|
|
/// resumption. The checkpoint itself validates the entry bytes already loaded.
|
|
pub struct EntryCheckpoint {
|
|
executor: Executor,
|
|
entry: usize,
|
|
initial_depth: usize,
|
|
incoming_state: u64,
|
|
frontier: usize,
|
|
}
|
|
|
|
impl EntryCheckpoint {
|
|
pub fn frontier(&self) -> usize {
|
|
self.frontier
|
|
}
|
|
|
|
pub fn completed_steps(&self) -> usize {
|
|
self.executor.steps
|
|
}
|
|
|
|
pub fn accepts_entry(&self, source: &SourceFile) -> bool {
|
|
self.accepts_entry_bytes(&source.name, &source.data)
|
|
}
|
|
|
|
pub fn accepts_entry_bytes(&self, name: &str, data: &[u8]) -> bool {
|
|
let Some(InputFrame::Source { mouth, .. }) = self.executor.inputs.first() else {
|
|
unreachable!("entry checkpoints start with the physical source frame");
|
|
};
|
|
self.executor.sources[self.entry].name == name && mouth.matches_loaded_prefix(data)
|
|
}
|
|
|
|
pub fn resume_after_host_replay(
|
|
&self,
|
|
source: SourceFile,
|
|
files: &mut impl SourceProvider,
|
|
cancellation: Cancellation,
|
|
) -> Option<Result<Execution, ExecutionFailure>> {
|
|
self.resume_observed(source, files, cancellation, None, None, |_, _, _| {})
|
|
}
|
|
|
|
pub(super) fn resume_capturing_entries_after_host_replay<F: SourceProvider, S>(
|
|
&self,
|
|
source: SourceFile,
|
|
files: &mut F,
|
|
cancellation: Cancellation,
|
|
line_break_cache: std::sync::Arc<super::LineBreakCache>,
|
|
previous: Option<&Execution>,
|
|
select: impl FnMut(usize, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> Option<Result<Execution, ExecutionFailure>> {
|
|
self.resume_observed(
|
|
source,
|
|
files,
|
|
cancellation,
|
|
Some(line_break_cache),
|
|
previous,
|
|
Executor::entry_observer(self.incoming_state, select, capture),
|
|
)
|
|
}
|
|
|
|
fn resume_observed<F: SourceProvider>(
|
|
&self,
|
|
source: SourceFile,
|
|
files: &mut F,
|
|
cancellation: Cancellation,
|
|
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
|
|
previous: Option<&Execution>,
|
|
capture_boundary: impl FnMut(&mut Executor, usize, &mut F),
|
|
) -> Option<Result<Execution, ExecutionFailure>> {
|
|
if !self.accepts_entry(&source) {
|
|
return None;
|
|
}
|
|
let mut executor = self.executor.clone().with_cancellation(cancellation);
|
|
executor.line_break_cache = line_break_cache;
|
|
let Some(InputFrame::Source { mouth, .. }) = executor.inputs.first_mut() else {
|
|
unreachable!("entry checkpoints start with the physical source frame");
|
|
};
|
|
mouth.rebind_loaded_prefix(source.data.clone());
|
|
executor.sources[self.entry] = source;
|
|
let result = executor
|
|
.check_cancellation()
|
|
.and_then(|_| executor.run_active_input(self.initial_depth, files, capture_boundary));
|
|
let result = executor.finish_observed_input(result, files);
|
|
Some(executor.finish_execution(result, self.incoming_state, previous))
|
|
}
|
|
}
|
|
|
|
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.
|
|
// This is independent of the Route-D build version.
|
|
const PDFTEX_VERSION: i32 = 140;
|
|
// The selected XeTeX language and device profile targets this reference.
|
|
// The native binary's build identity remains independent.
|
|
const XETEX_VERSION: i32 = 0;
|
|
const XETEX_REVISION: &'static str = ".999998";
|
|
|
|
pub fn new(state: State, limits: Limits) -> Self {
|
|
Self {
|
|
state,
|
|
limits,
|
|
cancellation: None,
|
|
line_break_cache: None,
|
|
interaction_mode: default_interaction_mode(),
|
|
inputs: Vec::new(),
|
|
sources: Vec::new(),
|
|
stream_sources: BTreeSet::new(),
|
|
generated_inputs: Default::default(),
|
|
reads: BTreeSet::new(),
|
|
meaning_reads: HashSet::new(),
|
|
reads_tracing_macros: false,
|
|
conditionals: Vec::new(),
|
|
in_csname: false,
|
|
command_trace_mode: None,
|
|
events: ExecutionEvents::default(),
|
|
steps: 0,
|
|
ligature_carry: super::ligature::Carry::default(),
|
|
current: Span::default(),
|
|
expression_depth: 0,
|
|
scanner_depth: 0,
|
|
scanner_status: ScannerStatus::Normal,
|
|
expansion_depth: 0,
|
|
io: IoState::default(),
|
|
pdf_colors: Default::default(),
|
|
xdv_colors: Default::default(),
|
|
xdv_annotations: Default::default(),
|
|
xdv_text: Default::default(),
|
|
pdf_link_stack: Vec::new(),
|
|
pdf_active_thread: None,
|
|
pdf_navigation_geometry: Default::default(),
|
|
pdf_running_links: true,
|
|
pdf_interword_spaces: false,
|
|
pdf_space_font: None,
|
|
pdf_loaded_space_font: None,
|
|
pdf_space_probe: None,
|
|
pdf_virtual_fonts: Default::default(),
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
pdf_last_match: None,
|
|
pdf_catalog_tokens: Vec::new(),
|
|
pdf_outlines: Vec::new(),
|
|
pdf_outline_payload: 0,
|
|
pdf_info_tokens: Vec::new(),
|
|
pdf_images: Vec::new(),
|
|
restored_pdf_image_count: 0,
|
|
format_image_warnings: Vec::new(),
|
|
pdf_force_pagebox_warned: false,
|
|
input_position: None,
|
|
paragraph: None,
|
|
vertical: super::boxes::VerticalBuilder::default(),
|
|
box_frames: Vec::new(),
|
|
box_nodes_created: 0,
|
|
material_charge: 0,
|
|
mark_cells_created: 0,
|
|
diagnostic_bytes: 0,
|
|
after_assignment: None,
|
|
after_group_tokens: 0,
|
|
math: Vec::new(),
|
|
math_tokens_processed: 0,
|
|
display: None,
|
|
native_page: None,
|
|
split_discards: Vec::new(),
|
|
output_frame: None,
|
|
pending_shipouts: VecDeque::new(),
|
|
shipped_pages: 0,
|
|
job_ended: false,
|
|
fresh_job: true,
|
|
job_name: None,
|
|
format_loaded: false,
|
|
format_dumped: false,
|
|
writing: false,
|
|
stack_peaks: StackUsage::default(),
|
|
alignments: Vec::new(),
|
|
alignment_balance: 1_000_000,
|
|
}
|
|
}
|
|
/// Continue after bootstrap execution, retaining definition-source identity.
|
|
/// This is not a loader for TeX's binary fmt files or a cache-reuse policy.
|
|
pub fn from_execution(execution: Execution, limits: Limits) -> Self {
|
|
let mut executor = Self::new(execution.state, limits);
|
|
executor.fresh_job = false;
|
|
executor.job_name = execution.job_name;
|
|
executor.interaction_mode = execution.interaction_mode;
|
|
executor.sources = execution.sources;
|
|
executor.stream_sources = execution.stream_sources;
|
|
executor.generated_inputs = execution.generated_inputs;
|
|
executor.split_discards = execution.split_discards;
|
|
executor.io = execution.io;
|
|
executor.after_assignment = execution.after_assignment;
|
|
executor.input_position = execution.input_position;
|
|
executor
|
|
}
|
|
pub(super) fn new_format_job(
|
|
state: State,
|
|
sources: Vec<SourceFile>,
|
|
stream_sources: BTreeSet<usize>,
|
|
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
|
|
limits: Limits,
|
|
) -> Self {
|
|
let mut executor = Self::new(state, limits);
|
|
executor.sources = sources;
|
|
executor.stream_sources = stream_sources;
|
|
executor.generated_inputs = generated_inputs;
|
|
executor.format_loaded = true;
|
|
executor
|
|
}
|
|
/// Attach a job-scoped cooperative cancellation handle.
|
|
pub fn with_line_break_cache(mut self, cache: std::sync::Arc<super::LineBreakCache>) -> Self {
|
|
self.line_break_cache = Some(cache);
|
|
self
|
|
}
|
|
|
|
pub fn with_cancellation(mut self, cancellation: Cancellation) -> Self {
|
|
self.cancellation = Some(cancellation);
|
|
self
|
|
}
|
|
fn check_cancellation(&self) -> Result<(), Error> {
|
|
if self
|
|
.cancellation
|
|
.as_ref()
|
|
.is_some_and(Cancellation::is_cancelled)
|
|
{
|
|
return self.fail("native compilation cancelled");
|
|
}
|
|
Ok(())
|
|
}
|
|
/// Execute a TeX job with online page/output/shipout semantics. The default
|
|
/// constructor remains the explicit list-measurement API used by oracles.
|
|
pub fn with_native_pages(mut self) -> Self {
|
|
self.native_page = Some(NativePageState::default());
|
|
self.state.page_marks.clear();
|
|
self
|
|
}
|
|
fn error(&self, message: impl Into<String>, span: Span) -> Error {
|
|
let mut error = Error::at(&self.sources, self.state.input_profile(), message, span);
|
|
if let Some(generated) = self.generated_inputs.get(&span.source) {
|
|
let data = &self.sources[span.source].data;
|
|
let prefix = &data[..span.start.min(data.len())];
|
|
if let Ok(characters) = self.state.input_profile().characters(prefix) {
|
|
error.line = 1;
|
|
error.column = 1;
|
|
for (_, character) in characters {
|
|
if Some(character) == generated.separator {
|
|
error.line += 1;
|
|
error.column = 1;
|
|
} else {
|
|
error.column += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
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
|
|
}
|
|
fn fail<T>(&self, message: impl Into<String>) -> Result<T, Error> {
|
|
Err(self.error(message, self.current))
|
|
}
|
|
fn tick(&mut self) -> Result<(), Error> {
|
|
self.check_cancellation()?;
|
|
self.steps += 1;
|
|
if self.steps > self.limits.steps {
|
|
return self.fail("native execution step limit exceeded");
|
|
}
|
|
Ok(())
|
|
}
|
|
fn push(&mut self, tokens: Vec<InputToken>) -> Result<(), Error> {
|
|
self.push_kind(tokens, TokenInputKind::Inserted)
|
|
}
|
|
fn push_kind(&mut self, tokens: Vec<InputToken>, kind: TokenInputKind) -> Result<(), Error> {
|
|
if tokens.len() > self.limits.tokens {
|
|
return self.fail("native token limit exceeded");
|
|
}
|
|
if self.inputs.len() >= self.limits.input_depth {
|
|
return self.fail("native input stack limit exceeded");
|
|
}
|
|
if matches!(kind, TokenInputKind::BackedUp) && !self.alignments.is_empty() {
|
|
for token in &tokens {
|
|
self.alignment_balance -= Self::alignment_brace_token(&token.token);
|
|
}
|
|
}
|
|
if !tokens.is_empty() {
|
|
self.inputs.push(InputFrame::Tokens {
|
|
tokens,
|
|
cursor: 0,
|
|
kind,
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
fn unread(&mut self, mut token: InputToken) -> Result<(), Error> {
|
|
token.xe_backed_char = false;
|
|
self.discard_exhausted_tokens();
|
|
self.push_kind(vec![token], TokenInputKind::BackedUp)
|
|
}
|
|
fn push_source(&mut self, file: SourceFile) -> Result<(), Error> {
|
|
if self.inputs.len() >= self.limits.input_depth {
|
|
return self.fail("native input stack limit exceeded");
|
|
}
|
|
let source = self.sources.len();
|
|
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 {
|
|
source,
|
|
mouth,
|
|
eof_seen: false,
|
|
pseudo_trace: None,
|
|
group_boundary: self.state.group_depth(),
|
|
conditional_boundary: self.conditionals.len(),
|
|
});
|
|
Ok(())
|
|
}
|
|
fn required_raw(&mut self, files: &mut impl SourceProvider) -> Result<InputToken, Error> {
|
|
self.raw(files)?
|
|
.ok_or_else(|| self.error("unexpected end of input", self.current))
|
|
}
|
|
fn raw_non_space(&mut self, files: &mut impl SourceProvider) -> Result<InputToken, Error> {
|
|
loop {
|
|
let token = self.required_raw(files)?;
|
|
if !token.token.kind.is_space() {
|
|
return Ok(token);
|
|
}
|
|
}
|
|
}
|
|
fn record_meaning_read(&mut self, name: &CommandName) {
|
|
if !self.meaning_reads.contains(name) {
|
|
self.meaning_reads.insert(name.clone());
|
|
}
|
|
}
|
|
|
|
fn collect_meaning_reads(&mut self) {
|
|
self.reads
|
|
.extend(self.meaning_reads.drain().map(Dependency::Meaning));
|
|
}
|
|
|
|
fn meaning(&mut self, token: &Token) -> Meaning {
|
|
match &token.kind {
|
|
TokenKind::Command(name) => {
|
|
self.record_meaning_read(name);
|
|
self.state.meaning(name)
|
|
}
|
|
kind => Meaning::Character(kind.clone()),
|
|
}
|
|
}
|
|
fn primitive(&mut self, token: &Token) -> Option<Primitive> {
|
|
match self.meaning(token) {
|
|
Meaning::Primitive(p) => Some(p),
|
|
_ => None,
|
|
}
|
|
}
|
|
fn command(&mut self, files: &mut impl SourceProvider) -> Result<CommandName, Error> {
|
|
let token = self.raw_non_space(files)?;
|
|
match token.token.kind {
|
|
TokenKind::Command(CommandName::FrozenRelax) => {
|
|
self.fail("frozen relax cannot be redefined")
|
|
}
|
|
TokenKind::Command(
|
|
CommandName::FrozenPrimitivePrefix | CommandName::FrozenPrimitive(_),
|
|
) => self.fail("frozen primitive cannot be redefined"),
|
|
TokenKind::Command(CommandName::Font(_)) => {
|
|
self.fail("frozen font identifier cannot be redefined")
|
|
}
|
|
TokenKind::Command(name) => Ok(name),
|
|
_ => self.fail("expected a control sequence or active character"),
|
|
}
|
|
}
|
|
fn frozen_primitive(&self, token: &Token) -> Option<(InputToken, bool)> {
|
|
let TokenKind::Command(name) = &token.kind else {
|
|
return None;
|
|
};
|
|
let (name, meaning) = self.state.original_primitive(name)?;
|
|
let expandable = matches!(meaning, Meaning::Primitive(p) if p.expandable());
|
|
let token = Token {
|
|
kind: TokenKind::Command(CommandName::FrozenPrimitive(name.into())),
|
|
..token.clone()
|
|
};
|
|
Some((token.into(), expandable))
|
|
}
|
|
|
|
fn deferred_internal_primitive(
|
|
&mut self,
|
|
prefix: InputToken,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<InputToken, Error> {
|
|
let operand = self.required_raw(files)?;
|
|
Ok(self.frozen_primitive(&operand.token).map_or_else(
|
|
|| Token {
|
|
kind: TokenKind::Command(CommandName::FrozenRelax),
|
|
..prefix.token
|
|
}.into(),
|
|
|(operand, _)| operand,
|
|
))
|
|
}
|
|
|
|
fn expanded(&mut self, files: &mut impl SourceProvider) -> Result<Option<InputToken>, Error> {
|
|
self.expanded_context(files, false)
|
|
}
|
|
fn expanded_context(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
definition: bool,
|
|
) -> Result<Option<InputToken>, Error> {
|
|
while let Some(token) = self.raw(files)? {
|
|
if let Some(token) = self.expand_one(token, files, definition)? {
|
|
return Ok(Some(token));
|
|
}
|
|
}
|
|
Ok(None)
|
|
}
|
|
fn required_expanded(&mut self, files: &mut impl SourceProvider) -> Result<InputToken, Error> {
|
|
self.expanded(files)?
|
|
.ok_or_else(|| self.error("unexpected end of expanded input", self.current))
|
|
}
|
|
fn expanded_non_space(&mut self, files: &mut impl SourceProvider) -> Result<InputToken, Error> {
|
|
loop {
|
|
let token = self.required_expanded(files)?;
|
|
if !self.is_spacer(&token.token) {
|
|
return Ok(token);
|
|
}
|
|
}
|
|
}
|
|
fn is_spacer(&mut self, token: &Token) -> bool {
|
|
matches!(
|
|
self.meaning(token),
|
|
Meaning::Character(TokenKind::Character(_, CatCode::Space))
|
|
)
|
|
}
|
|
fn print_tokens(&mut self, text: &str, origin: &Token) -> Result<(), Error> {
|
|
self.push(
|
|
text.chars()
|
|
.map(|c| {
|
|
Token {
|
|
kind: TokenKind::Character(
|
|
c,
|
|
if c == ' ' {
|
|
CatCode::Space
|
|
} else {
|
|
CatCode::Other
|
|
},
|
|
),
|
|
span: origin.span,
|
|
invocation: origin.invocation,
|
|
}
|
|
.into()
|
|
})
|
|
.collect(),
|
|
)
|
|
}
|
|
// XeTeX scans a 16-bit code for \char in math and a full Unicode
|
|
// character number for shorthand definitions and text character commands.
|
|
fn character_number(
|
|
&mut self,
|
|
command: &str,
|
|
unicode_maximum: i32,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<u32, Error> {
|
|
let number = self.integer(files)?;
|
|
let maximum = if self.state.input_profile() != super::InputProfile::TeX8Bit {
|
|
unicode_maximum
|
|
} else {
|
|
255
|
|
};
|
|
if !(0..=maximum).contains(&number) {
|
|
return self.fail(format!("{command} must be in 0..{maximum}"));
|
|
}
|
|
Ok(number as u32)
|
|
}
|
|
|
|
fn scalar_character(&self, number: u32, span: Span) -> Result<char, Error> {
|
|
char::from_u32(number)
|
|
.ok_or_else(|| self.error(format!("character U+{number:04X} is not a Unicode scalar"), span))
|
|
}
|
|
|
|
fn expand_unicode_character(
|
|
&mut self,
|
|
primitive: Primitive,
|
|
token: &Token,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
use CatCode::*;
|
|
let c = self.character_number("Unicode character", 0x10FFFF, files)?;
|
|
let c = self.scalar_character(c, token.span)?;
|
|
let cat = if primitive == Primitive::Ucharcat {
|
|
let category = self.integer(files)?;
|
|
if !matches!(category, 1..=4 | 6..=8 | 10..=13) {
|
|
return self.fail(format!("invalid category code for Ucharcat: {category}"));
|
|
}
|
|
CatCode::from_number(category).expect("validated category")
|
|
} else if c == ' ' {
|
|
Space
|
|
} else {
|
|
Other
|
|
};
|
|
let kind = if cat == Active {
|
|
TokenKind::Command(CommandName::Active(c))
|
|
} else {
|
|
TokenKind::Character(c, cat)
|
|
};
|
|
self.push(vec![Token {
|
|
kind,
|
|
span: token.span,
|
|
invocation: token.invocation,
|
|
}
|
|
.into()])
|
|
}
|
|
|
|
fn roman_numeral(&self, mut number: usize) -> Result<String, Error> {
|
|
let mut text = String::new();
|
|
for (value, symbol) in [
|
|
(1000, "m"),
|
|
(900, "cm"),
|
|
(500, "d"),
|
|
(400, "cd"),
|
|
(100, "c"),
|
|
(90, "xc"),
|
|
(50, "l"),
|
|
(40, "xl"),
|
|
(10, "x"),
|
|
(9, "ix"),
|
|
(5, "v"),
|
|
(4, "iv"),
|
|
(1, "i"),
|
|
] {
|
|
let repetitions = number / value;
|
|
if text.len() + repetitions * symbol.len() > self.limits.tokens {
|
|
return self.fail("native token limit exceeded");
|
|
}
|
|
text.push_str(&symbol.repeat(repetitions));
|
|
number %= value;
|
|
}
|
|
Ok(text)
|
|
}
|
|
fn expand_one(
|
|
&mut self,
|
|
input: InputToken,
|
|
files: &mut impl SourceProvider,
|
|
definition_context: bool,
|
|
) -> Result<Option<InputToken>, Error> {
|
|
if self.expansion_depth >= scan_stack::limit(self.limits.input_depth) {
|
|
return self.fail("native expansion nesting limit exceeded");
|
|
}
|
|
self.expansion_depth += 1;
|
|
let result = scan_stack::enter(|| {
|
|
self.expand_with_pending_tokens(input, files, definition_context)
|
|
});
|
|
self.expansion_depth -= 1;
|
|
result
|
|
}
|
|
|
|
fn expand_with_pending_tokens(
|
|
&mut self,
|
|
mut input: InputToken,
|
|
files: &mut impl SourceProvider,
|
|
mut definition_context: bool,
|
|
) -> Result<Option<InputToken>, Error> {
|
|
let mut pending = Vec::new();
|
|
let mut first = None;
|
|
let result = loop {
|
|
if input.frozen {
|
|
break Some(input);
|
|
}
|
|
let meaning = self.meaning(&input.token);
|
|
let Meaning::Primitive(command @ (Primitive::Expandafter | Primitive::UsePrimitive)) = meaning else {
|
|
break self.expand_one_inner(input, meaning, files, definition_context)?;
|
|
};
|
|
if self.read_parameter(Parameter::Tracingcommands).width() > 1 {
|
|
self.trace_command(&input.token, files)?;
|
|
}
|
|
if command == Primitive::UsePrimitive {
|
|
let operand = self.normal_raw(files)?;
|
|
let Some((original, expandable)) = self.frozen_primitive(&operand.token) else {
|
|
break None;
|
|
};
|
|
if expandable {
|
|
input = original;
|
|
definition_context = false;
|
|
continue;
|
|
}
|
|
self.unread(operand)?;
|
|
input.token.kind = TokenKind::Command(CommandName::FrozenPrimitivePrefix);
|
|
break Some(input);
|
|
}
|
|
// Expanding the second token is the same dispatch with deferred
|
|
// input. Only a re-entry from a scanner needs a new expansion frame.
|
|
if let Some(outer) = first.replace(self.required_raw(files)?) {
|
|
if pending.len() >= self.limits.input_depth {
|
|
return self.fail("native input stack limit exceeded");
|
|
}
|
|
pending.push(outer);
|
|
}
|
|
input = self.required_raw(files)?;
|
|
definition_context = false;
|
|
};
|
|
let Some(first) = first else {
|
|
return Ok(result);
|
|
};
|
|
if let Some(second) = result {
|
|
self.unread(second)?;
|
|
}
|
|
self.unread(first)?;
|
|
for token in pending.into_iter().rev() {
|
|
self.unread(token)?;
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
fn expand_one_inner(
|
|
&mut self,
|
|
input: InputToken,
|
|
meaning: Meaning,
|
|
files: &mut impl SourceProvider,
|
|
definition_context: bool,
|
|
) -> Result<Option<InputToken>, Error> {
|
|
let token = &input.token;
|
|
use Primitive::*;
|
|
match meaning {
|
|
Meaning::Undefined => {
|
|
return self.fail(format!(
|
|
"undefined native control sequence: {}",
|
|
self.token_string(&token.kind)
|
|
));
|
|
}
|
|
Meaning::Macro(definition) => {
|
|
if definition.protected && definition_context {
|
|
return Ok(Some(input));
|
|
}
|
|
self.call_macro(definition, token, files)?;
|
|
}
|
|
Meaning::Primitive(primitive) => {
|
|
if primitive.expandable()
|
|
&& !primitive.conditional()
|
|
&& !matches!(primitive, Else | Or | Fi)
|
|
&& self.read_parameter(Parameter::Tracingcommands).width() > 1
|
|
{
|
|
self.trace_command(token, files)?;
|
|
}
|
|
match primitive {
|
|
Splitfirstmark | Splitbotmark | Splitfirstmarks | Splitbotmarks | Topmark
|
|
| Firstmark | Botmark | Topmarks | Firstmarks | Botmarks => {
|
|
self.expand_split_mark(primitive, files)?;
|
|
}
|
|
Noexpand => {
|
|
let mut next = self.normal_raw(files)?;
|
|
// A nonexpandable control sequence keeps its command
|
|
// meaning, including a character alias in scan_toks.
|
|
next.frozen |= match self.meaning(&next.token) {
|
|
Meaning::Undefined | Meaning::Macro(_) => true,
|
|
Meaning::Primitive(p) => p.expandable(),
|
|
_ => false,
|
|
};
|
|
return Ok(Some(next));
|
|
}
|
|
Number => {
|
|
let value = self.integer(files)?;
|
|
self.print_tokens(&value.to_string(), token)?;
|
|
}
|
|
Uchar | Ucharcat => self.expand_unicode_character(primitive, token, files)?,
|
|
Romannumeral => {
|
|
let value = self.integer(files)?;
|
|
if value > 0 {
|
|
let text = self.roman_numeral(value as usize)?;
|
|
self.print_tokens(&text, token)?;
|
|
}
|
|
}
|
|
Fontname => {
|
|
let font = self.font_identifier(files)?;
|
|
let text = self
|
|
.state
|
|
.fonts
|
|
.font(font)
|
|
.map_err(|e| self.error(e, self.current))?
|
|
.fontname();
|
|
let text = if self.state.input_profile() == InputProfile::TeX8Bit {
|
|
text.bytes().map(char::from).collect()
|
|
} else {
|
|
text
|
|
};
|
|
self.print_tokens(&text, token)?;
|
|
}
|
|
The => match self.the_value(files)? {
|
|
TheValue::Tokens(tokens) => self.push(
|
|
tokens
|
|
.into_iter()
|
|
.map(|token| InputToken {
|
|
token,
|
|
frozen: definition_context,
|
|
end_write: false,
|
|
alignment: None,
|
|
xe_backed_char: false,
|
|
})
|
|
.collect(),
|
|
)?,
|
|
TheValue::Text(text) => self.print_tokens(&text, token)?,
|
|
},
|
|
String => {
|
|
let next = self.normal_raw(files)?;
|
|
let text = self.string_token(&next.token.kind);
|
|
self.print_tokens(&text, token)?;
|
|
}
|
|
MeaningOf => {
|
|
let next = self.normal_raw(files)?;
|
|
let text = self.meaning_string(&next.token)?;
|
|
self.print_tokens(&text, token)?;
|
|
}
|
|
Unexpanded | Expanded | Detokenize => {
|
|
let body = if primitive == Expanded {
|
|
self.scan_expanded_group(files)?
|
|
} else {
|
|
self.scan_group(files)?
|
|
};
|
|
if primitive == Detokenize {
|
|
let text = self.token_list_text(&body);
|
|
self.print_tokens(&text, token)?;
|
|
} else if primitive == Expanded {
|
|
self.push(body.into_iter().map(InputToken::from).collect())?;
|
|
} else {
|
|
self.push(
|
|
body.into_iter()
|
|
.map(|token| InputToken {
|
|
token,
|
|
frozen: definition_context,
|
|
end_write: false,
|
|
alignment: None,
|
|
xe_backed_char: false,
|
|
})
|
|
.collect(),
|
|
)?;
|
|
}
|
|
}
|
|
Pdfximagebbox => self.expand_pdf_image_bbox(token, files)?,
|
|
Pdfinsertht => self.expand_pdf_insertion_height(token, files)?,
|
|
Pdfstrcmp => {
|
|
let left = self.scan_expanded_group(files)?;
|
|
let left = self.token_list_text(&left);
|
|
let right = self.scan_expanded_group(files)?;
|
|
let right = self.token_list_text(&right);
|
|
let result = match left.cmp(&right) {
|
|
std::cmp::Ordering::Less => "-1",
|
|
std::cmp::Ordering::Equal => "0",
|
|
std::cmp::Ordering::Greater => "1",
|
|
};
|
|
self.print_tokens(result, token)?;
|
|
}
|
|
Pdfmatch | Pdflastmatch => {
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
self.expand_pdf_match(primitive, token, files)?;
|
|
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
|
|
return self
|
|
.fail("pdfTeX regular expressions are unavailable on this host");
|
|
}
|
|
Pdfuniformdeviate => {
|
|
let bound = self.integer(files)?;
|
|
self.reads.insert(Dependency::PdfRandomState);
|
|
let value = self.state.random().uniform(bound);
|
|
self.print_tokens(&value.to_string(), token)?;
|
|
}
|
|
Pdfnormaldeviate => {
|
|
self.reads.insert(Dependency::PdfRandomState);
|
|
let value = loop {
|
|
self.tick()?;
|
|
if let Some(value) = self.state.random().normal_trial() {
|
|
break value;
|
|
}
|
|
};
|
|
self.print_tokens(&value.to_string(), token)?;
|
|
}
|
|
Pdfpageref => {
|
|
let number = self.pdf_page_reference(files)?;
|
|
self.print_tokens(&number.to_string(), token)?;
|
|
}
|
|
Pdffontobjnum => {
|
|
let number = self.pdf_font_object_query(files)?;
|
|
self.print_tokens(&number.to_string(), token)?;
|
|
}
|
|
Leftmarginkern | Rightmarginkern => {
|
|
let register = self.register_index(files)?;
|
|
self.reads.insert(Dependency::BoxRegister(register));
|
|
let Some(NativeBox { content: BoxContent::Horizontal(nodes), .. }) =
|
|
self.state.box_register(register)
|
|
else {
|
|
return self.fail("margin kern requires a non-void horizontal box");
|
|
};
|
|
let width = paragraph::stored_margin_kern(nodes, primitive == Rightmarginkern);
|
|
let value = if width == 0 {
|
|
"0pt".to_owned()
|
|
} else {
|
|
format!("{}pt", registers::print_scaled(width))
|
|
};
|
|
self.print_tokens(&value, token)?;
|
|
}
|
|
Pdfcolorstackinit => {
|
|
let stack = self.init_pdf_color_stack(files)?;
|
|
self.print_tokens(&stack.to_string(), token)?;
|
|
}
|
|
Pdfcreationdate => {
|
|
self.reads.insert(Dependency::PdfCreationDate);
|
|
let date = self.state.pdf_creation_date.clone().ok_or_else(|| {
|
|
self.error("native PDF creation timestamp is unavailable", token.span)
|
|
})?;
|
|
self.print_tokens(&date, token)?;
|
|
}
|
|
Jobname => {
|
|
self.reads.insert(Dependency::JobName);
|
|
let name = self.job_name.as_ref().ok_or_else(|| {
|
|
self.error("native job name is unavailable", token.span)
|
|
})?;
|
|
let text = if self.state.input_profile() == InputProfile::TeX8Bit {
|
|
name.bytes()
|
|
.map(char::from)
|
|
.collect::<std::string::String>()
|
|
} else {
|
|
name.clone()
|
|
};
|
|
self.print_tokens(&text, token)?;
|
|
}
|
|
Pdffilesize | Pdffilemoddate => {
|
|
let body = self.scan_expanded_group(files)?;
|
|
let name = self.token_list_text(&body);
|
|
let name = self.decode_filename(name)?;
|
|
let name = if primitive == Pdffilemoddate {
|
|
name.replace('"', "")
|
|
} else {
|
|
name
|
|
};
|
|
let from = self.source_name(token.span);
|
|
self.reads.insert(Dependency::FileLookup {
|
|
name: name.clone(),
|
|
from: from.clone(),
|
|
});
|
|
let value = if primitive == Pdffilesize {
|
|
files
|
|
.file_size(&name, &from)
|
|
.map_err(|message| self.error(message, token.span))?
|
|
.map(|size| size.to_string())
|
|
} else {
|
|
let value = files
|
|
.file_modification_date(&name, &from)
|
|
.map_err(|message| self.error(message, token.span))?;
|
|
self.reads.insert(Dependency::FileModificationDate {
|
|
name,
|
|
from,
|
|
value: value.clone(),
|
|
});
|
|
value
|
|
};
|
|
if let Some(value) = value {
|
|
self.print_tokens(&value, token)?;
|
|
}
|
|
}
|
|
Pdfmdfivesum => {
|
|
let file = self.keyword("file", files)?;
|
|
let body = self.scan_pdf_tokens(files)?;
|
|
let digest = if file {
|
|
let name = self.token_list_text(&body);
|
|
let name = self.decode_filename(name)?.replace('"', "");
|
|
let from = self.source_name(token.span);
|
|
self.reads.insert(Dependency::FileLookup {
|
|
name: name.clone(),
|
|
from: from.clone(),
|
|
});
|
|
files
|
|
.optional_tex_input(&name, &from)
|
|
.map_err(|message| self.error(message, token.span))?
|
|
.map(|resource| md5::compute(&resource.data))
|
|
} else {
|
|
Some(md5::compute(self.pdf_token_bytes(&body)?))
|
|
};
|
|
if let Some(digest) = digest {
|
|
self.print_tokens(&format!("{digest:X}"), token)?;
|
|
}
|
|
}
|
|
Pdftexrevision => self.print_tokens(self.state.pdftex_revision(), token)?,
|
|
XeTeXrevision => self.print_tokens(Self::XETEX_REVISION, token)?,
|
|
XeTeXglyphname => {
|
|
let name = self.xetex_glyph_name(files)?;
|
|
self.print_tokens(&name, token)?;
|
|
}
|
|
p @ (XeTeXfeaturename | XeTeXselectorname) => {
|
|
self.scan_xetex_graphite_label(p, files)?;
|
|
}
|
|
Etexrevision => self.print_tokens(".6", token)?,
|
|
Csname => {
|
|
let name = self.csname(files)?;
|
|
self.record_meaning_read(&name);
|
|
if self.state.meaning(&name) == Meaning::Undefined {
|
|
self.define_traced(
|
|
name.clone(),
|
|
Meaning::Primitive(Relax),
|
|
false,
|
|
files,
|
|
)?;
|
|
}
|
|
self.unread(
|
|
Token {
|
|
kind: TokenKind::Command(name),
|
|
..token.clone()
|
|
}
|
|
.into(),
|
|
)?;
|
|
}
|
|
Iftrue | Iffalse | Ifx | Ifnum | Ifdefined | If | Ifcat | Ifodd | Ifcsname
|
|
| Ifcase | Ifeof | Ifdim | Ifpdfabsnum | Ifpdfabsdim | Ifvmode | Ifhmode
|
|
| Ifmmode | Ifinner | Ifvoid | Ifhbox | Ifvbox | Iffontchar | Ifincsname
|
|
| Ifprimitive | Ifpdfprimitive => {
|
|
self.evaluate_conditional(primitive, token.span, false, files)?;
|
|
}
|
|
Unless => {
|
|
let next = self.raw_non_space(files)?;
|
|
let Some(p) = self.primitive(&next.token) else {
|
|
return self.fail("unless requires a conditional primitive");
|
|
};
|
|
if !p.conditional() || p == Ifcase {
|
|
return self.fail("unless requires a non-case conditional primitive");
|
|
}
|
|
self.evaluate_conditional(p, token.span, true, files)?;
|
|
}
|
|
Else | Or | Fi => {
|
|
let Some(limit) = self.conditionals.last().map(|frame| frame.limit) else {
|
|
return self.fail(format!(
|
|
"extra {}",
|
|
format!("{primitive:?}").to_ascii_lowercase()
|
|
));
|
|
};
|
|
self.trace_conditional(primitive, false, files)?;
|
|
if limit == ConditionalLimit::Scanning {
|
|
let span = token.span;
|
|
self.unread(input)?;
|
|
return Ok(Some(
|
|
Token::new(TokenKind::Command(CommandName::FrozenRelax), span)
|
|
.into(),
|
|
));
|
|
}
|
|
if !limit.accepts(primitive) {
|
|
return self.fail("unexpected native conditional branch delimiter");
|
|
}
|
|
if primitive != Fi {
|
|
while self.pass_conditional_text(files)? != Fi {}
|
|
}
|
|
self.finish_conditional(files)?;
|
|
}
|
|
Scantokens => self.scan_tokens_input(files)?,
|
|
Input => {
|
|
self.input_file(files, token.span)?;
|
|
}
|
|
_ if primitive.conditional() => {
|
|
return self.fail(format!("unsupported native conditional: {primitive:?}"));
|
|
}
|
|
_ => return Ok(Some(input)),
|
|
}
|
|
}
|
|
_ => return Ok(Some(input)),
|
|
}
|
|
Ok(None)
|
|
}
|
|
fn scan_group(&mut self, files: &mut impl SourceProvider) -> Result<Vec<Token>, Error> {
|
|
self.with_scanner(ScannerStatus::Absorbing, |s| s.scan_group_inner(files))
|
|
}
|
|
fn scan_group_inner(&mut self, files: &mut impl SourceProvider) -> Result<Vec<Token>, Error> {
|
|
let open = self.expanded_non_space(files)?;
|
|
// A character alias to a brace is accepted by TeX's scan_left_brace.
|
|
if !matches!(
|
|
self.meaning(&open.token),
|
|
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
|
|
) {
|
|
return self.fail("expected begin-group token");
|
|
}
|
|
self.after_open(files)
|
|
}
|
|
fn the_value(&mut self, files: &mut impl SourceProvider) -> Result<TheValue, Error> {
|
|
use Primitive::*;
|
|
let mut next = self.expanded_non_space(files)?;
|
|
if self.primitive(&next.token) == Some(DeferredPrimitive) {
|
|
next = self.deferred_internal_primitive(next, files)?;
|
|
}
|
|
let text = match self.meaning(&next.token) {
|
|
Meaning::Font(font) => {
|
|
let mut token = next.token;
|
|
token.kind = TokenKind::Command(CommandName::Font(font));
|
|
return Ok(TheValue::Tokens(vec![token]));
|
|
}
|
|
Meaning::Primitive(
|
|
Font | Letterspacefont | Textfont | Scriptfont | Scriptscriptfont,
|
|
) => {
|
|
let mut token = next.token.clone();
|
|
self.unread(next)?;
|
|
let font = self.font_identifier(files)?;
|
|
token.kind = TokenKind::Command(CommandName::Font(font));
|
|
return Ok(TheValue::Tokens(vec![token]));
|
|
}
|
|
Meaning::TokenParameter(p) => {
|
|
self.reads.insert(Dependency::TokenParameter(p));
|
|
return Ok(TheValue::Tokens(
|
|
self.state
|
|
.token_parameter(p)
|
|
.map_or_else(Vec::new, |t| t.to_vec()),
|
|
));
|
|
}
|
|
Meaning::Toks(index) => {
|
|
self.reads.insert(Dependency::Toks(index));
|
|
return Ok(TheValue::Tokens(self.state.tokens(index)));
|
|
}
|
|
Meaning::Primitive(p @ (Dimexpr | Glueexpr | Muexpr)) => {
|
|
let kind = match p {
|
|
Dimexpr => RegisterKind::Dimen,
|
|
Glueexpr => RegisterKind::Skip,
|
|
_ => RegisterKind::Muskip,
|
|
};
|
|
self.quantity_expression(kind, files)?
|
|
.text(kind == RegisterKind::Muskip)
|
|
}
|
|
Meaning::Primitive(p @ (Lastskip | Lastkern | Lastpenalty | Lastnodetype)) => {
|
|
let (value, kind) = self.last_quantity(p);
|
|
if matches!(p, Lastpenalty | Lastnodetype) {
|
|
value.width().to_string()
|
|
} else {
|
|
value.text(kind == RegisterKind::Muskip)
|
|
}
|
|
}
|
|
Meaning::Primitive(p @ (Gluestretch | Glueshrink)) => {
|
|
RegisterValue::Dimension(self.glue_component(p, files)?).text(false)
|
|
}
|
|
Meaning::Primitive(XeTeXinterchartoks) => {
|
|
let index = self.xe_inter_char_index(files)?;
|
|
let tokens = self
|
|
.read_xe_inter_char_tokens(index)
|
|
.map_or_else(Vec::new, |tokens| tokens.to_vec());
|
|
return Ok(TheValue::Tokens(tokens));
|
|
}
|
|
Meaning::Primitive(Toks) => {
|
|
let index = self.register_index(files)?;
|
|
self.reads.insert(Dependency::Toks(index));
|
|
return Ok(TheValue::Tokens(self.state.tokens(index)));
|
|
}
|
|
Meaning::Register(r) => self.read_register(r).text(r.kind == RegisterKind::Muskip),
|
|
Meaning::Parameter(p) => {
|
|
let value = self.read_parameter(p);
|
|
if p.kind() == Some(RegisterKind::Muskip) {
|
|
match value {
|
|
ParameterValue::Quantity(q) => q.text(true),
|
|
_ => unreachable!(),
|
|
}
|
|
} else {
|
|
value.text()
|
|
}
|
|
}
|
|
Meaning::Primitive(p @ (Dimen | Skip | Muskip)) => {
|
|
let r = self.scan_register(p, files)?;
|
|
self.read_register(r).text(r.kind == RegisterKind::Muskip)
|
|
}
|
|
Meaning::Primitive(p) if p.page_dimension().is_some() => {
|
|
RegisterValue::Dimension(self.page_dimension_value(p)?).text(false)
|
|
}
|
|
Meaning::Primitive(Interactionmode) => self.interaction_mode_value().to_string(),
|
|
Meaning::Primitive(Pdftexversion) => Self::PDFTEX_VERSION.to_string(),
|
|
Meaning::Primitive(Pdfshellescape) => Self::SHELL_ESCAPE.to_string(),
|
|
Meaning::Primitive(Deadcycles) => self.native_page_mut()?.dead_cycles.to_string(),
|
|
Meaning::Primitive(Insertpenalties) => {
|
|
self.native_page_mut()?.insertions.penalties.to_string()
|
|
}
|
|
Meaning::Primitive(p @ (Wd | Ht | Dp | Prevdepth)) => {
|
|
RegisterValue::Dimension(self.dimension_value(p, files)?).text(false)
|
|
}
|
|
Meaning::Primitive(p @ (Parshapeindent | Parshapelength | Parshapedimen)) => {
|
|
RegisterValue::Dimension(self.paragraph_shape_dimension(p, files)?).text(false)
|
|
}
|
|
Meaning::Primitive(
|
|
p @ (Fontdimen | Fontcharwd | Fontcharht | Fontchardp | Fontcharic | XeTeXglyphbounds),
|
|
) => RegisterValue::Dimension(self.font_dimension(p, files)?).text(false),
|
|
_ => self.internal_integer_from(next, files)?.to_string(),
|
|
};
|
|
Ok(TheValue::Text(text))
|
|
}
|
|
fn csname(&mut self, files: &mut impl SourceProvider) -> Result<CommandName, Error> {
|
|
let previous = std::mem::replace(&mut self.in_csname, true);
|
|
let result = self.csname_inner(files);
|
|
self.in_csname = previous;
|
|
result
|
|
}
|
|
fn csname_inner(&mut self, files: &mut impl SourceProvider) -> Result<CommandName, Error> {
|
|
let mut name = std::string::String::new();
|
|
loop {
|
|
let next = self.required_expanded(files)?;
|
|
if self.primitive(&next.token) == Some(Primitive::Endcsname) {
|
|
break;
|
|
}
|
|
match next.token.kind {
|
|
TokenKind::Character(c, _) => name.push(c),
|
|
_ => return self.fail("non-character in csname"),
|
|
}
|
|
}
|
|
Ok(CommandName::Control(name))
|
|
}
|
|
// A suppressed expandable command has TeX's no-expand command flag,
|
|
// distinct from both its original meaning and an ordinary relax.
|
|
fn suppresses_meaning(input: &InputToken, meaning: &Meaning) -> bool {
|
|
input.frozen
|
|
&& (matches!(meaning, Meaning::Macro(_) | Meaning::Undefined)
|
|
|| matches!(meaning, Meaning::Primitive(p) if p.expandable()))
|
|
}
|
|
fn conditional_character(&mut self, input: &InputToken) -> (u32, u32) {
|
|
// TeX normalizes every non-character command to (relax, 256).
|
|
// A noexpanded active token retains the active category/character.
|
|
let meaning = self.meaning(&input.token);
|
|
if input.frozen
|
|
&& !matches!(
|
|
meaning,
|
|
Meaning::Character(_) | Meaning::CharGiven(_) | Meaning::MathCharGiven(_)
|
|
| Meaning::UnicodeMathCharGiven(_)
|
|
)
|
|
&& let TokenKind::Command(CommandName::Active(c)) = input.token.kind
|
|
{
|
|
return (CatCode::Active as u32, c as u32);
|
|
}
|
|
match meaning {
|
|
Meaning::Character(TokenKind::Character(c, cat)) => (cat as u32, c as u32),
|
|
_ => (0, 0x110000),
|
|
}
|
|
}
|
|
fn evaluate_conditional(
|
|
&mut self,
|
|
p: Primitive,
|
|
span: Span,
|
|
invert: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
use Primitive::*;
|
|
let frame_index = self.conditionals.len();
|
|
self.conditionals.push(Conditional {
|
|
primitive: p,
|
|
inverted: invert,
|
|
origin: self.input_position,
|
|
limit: ConditionalLimit::Scanning,
|
|
span,
|
|
});
|
|
self.trace_conditional(p, false, files)?;
|
|
if p == Ifcase {
|
|
let mut remaining = self.integer(files)?;
|
|
if self.read_parameter(Parameter::Tracingcommands).width() > 1 {
|
|
self.trace_command_result(&format!("case {remaining}"), files)?;
|
|
}
|
|
while remaining != 0 {
|
|
let branch = self.pass_conditional_text(files)?;
|
|
if self.conditionals.len() != frame_index + 1 {
|
|
if branch == Fi {
|
|
self.finish_conditional(files)?;
|
|
}
|
|
continue;
|
|
}
|
|
match branch {
|
|
Or => remaining = remaining.saturating_sub(1),
|
|
Else => {
|
|
self.conditionals[frame_index].limit = ConditionalLimit::Fi;
|
|
return Ok(());
|
|
}
|
|
Fi => {
|
|
self.finish_conditional(files)?;
|
|
return Ok(());
|
|
}
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
self.conditionals[frame_index].limit = ConditionalLimit::Or;
|
|
return Ok(());
|
|
}
|
|
let taken = match p {
|
|
Iftrue => true,
|
|
Iffalse => false,
|
|
Ifx => {
|
|
let a = self.normal_raw(files)?;
|
|
let b = self.normal_raw(files)?;
|
|
let a_meaning = self.meaning(&a.token);
|
|
let b_meaning = self.meaning(&b.token);
|
|
match (
|
|
Self::suppresses_meaning(&a, &a_meaning),
|
|
Self::suppresses_meaning(&b, &b_meaning),
|
|
) {
|
|
(true, true) => true,
|
|
(false, false) => Self::same_meaning(&a_meaning, &b_meaning),
|
|
_ => false,
|
|
}
|
|
}
|
|
If | Ifcat => {
|
|
let a = self.required_expanded(files)?;
|
|
let b = self.required_expanded(files)?;
|
|
let a = self.conditional_character(&a);
|
|
let b = self.conditional_character(&b);
|
|
if p == If { a.1 == b.1 } else { a.0 == b.0 }
|
|
}
|
|
Ifvoid | Ifhbox | Ifvbox => {
|
|
let n = self.register_index(files)?;
|
|
self.reads.insert(Dependency::BoxRegister(n));
|
|
let b = self.state.box_register(n);
|
|
match p {
|
|
Ifvoid => b.is_none(),
|
|
Ifhbox => b.is_some_and(|b| b.kind == BoxKind::Horizontal),
|
|
_ => b.is_some_and(|b| matches!(b.kind, BoxKind::Vertical | BoxKind::Vtop)),
|
|
}
|
|
}
|
|
Iffontchar => {
|
|
let font = self.font_identifier(files)?;
|
|
let slot = self.integer(files)?;
|
|
let instance = self.state.fonts.font(font).map_err(|e| self.error(e, self.current))?;
|
|
if let Some(font) = instance.opentype() {
|
|
let character = u32::try_from(slot).ok().and_then(char::from_u32)
|
|
.ok_or_else(|| self.error("font character code requires a Unicode scalar", self.current))?;
|
|
font.face().map_err(|e| self.error(e, self.current))?.glyph_index(character).is_some()
|
|
} else {
|
|
let slot = u8::try_from(slot).map_err(|_| {
|
|
self.error("font character code must be in 0..255", self.current)
|
|
})?;
|
|
self.state.font_has_slot(font, slot)
|
|
}
|
|
}
|
|
Ifodd => self.integer(files)? % 2 != 0,
|
|
Ifvmode | Ifhmode | Ifmmode | Ifinner => {
|
|
self.reads.insert(Dependency::ParagraphMode);
|
|
!self.writing
|
|
&& match p {
|
|
Ifvmode => self.math.is_empty() && self.paragraph.is_none(),
|
|
Ifhmode => self.math.is_empty() && self.paragraph.is_some(),
|
|
Ifmmode => !self.math.is_empty(),
|
|
Ifinner => {
|
|
if !self.math.is_empty() {
|
|
self.display.is_none() || self.math.len() > 1
|
|
} else {
|
|
self.restricted()
|
|
|| (self.paragraph.is_none()
|
|
&& (!self.box_frames.is_empty()
|
|
|| self.output_frame.is_some()
|
|
|| !self.alignments.is_empty()))
|
|
}
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
Ifnum | Ifpdfabsnum => {
|
|
let a = self.integer(files)?;
|
|
let relation = self.expanded_non_space(files)?;
|
|
let b = self.integer(files)?;
|
|
let (a, b) = if p == Ifpdfabsnum {
|
|
(i64::from(a).abs(), i64::from(b).abs())
|
|
} else {
|
|
(i64::from(a), i64::from(b))
|
|
};
|
|
match relation.token.kind {
|
|
TokenKind::Character('<', CatCode::Other) => a < b,
|
|
TokenKind::Character('=', CatCode::Other) => a == b,
|
|
TokenKind::Character('>', CatCode::Other) => a > b,
|
|
_ => return self.fail("ifnum requires <, = or >"),
|
|
}
|
|
}
|
|
Ifdim | Ifpdfabsdim => {
|
|
let a = self.dimension(false, false, files)?.amount;
|
|
let relation = self.expanded_non_space(files)?;
|
|
let b = self.dimension(false, false, files)?.amount;
|
|
let (a, b) = if p == Ifpdfabsdim {
|
|
(a.abs(), b.abs())
|
|
} else {
|
|
(a, b)
|
|
};
|
|
match relation.token.kind {
|
|
TokenKind::Character('<', CatCode::Other) => a < b,
|
|
TokenKind::Character('=', CatCode::Other) => a == b,
|
|
TokenKind::Character('>', CatCode::Other) => a > b,
|
|
_ => return self.fail("ifdim requires <, = or >"),
|
|
}
|
|
}
|
|
Ifdefined => {
|
|
let next = self.normal_raw(files)?.token;
|
|
self.meaning(&next) != Meaning::Undefined
|
|
}
|
|
Ifprimitive | Ifpdfprimitive => {
|
|
let operand = self.normal_raw(files)?;
|
|
let live = self.meaning(&operand.token);
|
|
matches!(
|
|
&operand.token.kind,
|
|
TokenKind::Command(name)
|
|
if !Self::suppresses_meaning(&operand, &live)
|
|
&& self.state.original_primitive(name)
|
|
.is_some_and(|(_, meaning)| *meaning == live)
|
|
)
|
|
}
|
|
Ifcsname => {
|
|
let name = self.csname(files)?;
|
|
self.record_meaning_read(&name);
|
|
self.state.meaning(&name) != Meaning::Undefined
|
|
}
|
|
Ifincsname => self.in_csname,
|
|
Ifeof => {
|
|
let index = self.stream_index(files)?;
|
|
self.reads.insert(Dependency::InputStream(index));
|
|
!self.io.inputs.contains_key(&index)
|
|
}
|
|
_ => return self.fail(format!("unsupported native conditional: {p:?}")),
|
|
} ^ invert;
|
|
if self.read_parameter(Parameter::Tracingcommands).width() > 1 {
|
|
self.trace_command_result(if taken { "true" } else { "false" }, files)?;
|
|
}
|
|
if taken {
|
|
self.conditionals[frame_index].limit = ConditionalLimit::Else;
|
|
} else {
|
|
loop {
|
|
let branch = self.pass_conditional_text(files)?;
|
|
if self.conditionals.len() != frame_index + 1 {
|
|
if branch == Fi {
|
|
self.finish_conditional(files)?;
|
|
}
|
|
continue;
|
|
}
|
|
match branch {
|
|
Else => self.conditionals[frame_index].limit = ConditionalLimit::Fi,
|
|
Fi => {
|
|
self.finish_conditional(files)?;
|
|
}
|
|
Or => return self.fail("extra or outside ifcase"),
|
|
_ => unreachable!(),
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn same_meaning(a: &Meaning, b: &Meaning) -> bool {
|
|
match (a, b) {
|
|
(Meaning::Macro(a), Meaning::Macro(b)) if Arc::ptr_eq(a, b) => true,
|
|
(Meaning::Macro(a), Meaning::Macro(b)) => {
|
|
a.long == b.long
|
|
&& a.protected == b.protected
|
|
&& a.outer == b.outer
|
|
&& a.prefix == b.prefix
|
|
&& a.parameters == b.parameters
|
|
&& a.parameter_chars == b.parameter_chars
|
|
&& a.replacement.len() == b.replacement.len()
|
|
&& a.replacement
|
|
.iter()
|
|
.zip(&b.replacement)
|
|
.all(|(a, b)| match (a, b) {
|
|
(Replacement::Token(a), Replacement::Token(b)) => a.kind == b.kind,
|
|
(Replacement::Parameter(a), Replacement::Parameter(b)) => a == b,
|
|
_ => false,
|
|
})
|
|
}
|
|
_ => a == b,
|
|
}
|
|
}
|
|
/// Find the next branch delimiter at this raw scanner depth.
|
|
fn pass_conditional_text(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Primitive, Error> {
|
|
let branch = self.with_scanner(ScannerStatus::Skipping, |executor| {
|
|
let mut depth = 0;
|
|
loop {
|
|
let token = executor.required_raw(files)?.token;
|
|
match executor.primitive(&token) {
|
|
Some(p) if p.conditional() => depth += 1,
|
|
Some(p @ (Primitive::Fi | Primitive::Else | Primitive::Or)) if depth == 0 => {
|
|
return Ok(p);
|
|
}
|
|
Some(Primitive::Fi) => depth -= 1,
|
|
_ => {}
|
|
}
|
|
}
|
|
})?;
|
|
self.trace_conditional(branch, true, files)?;
|
|
Ok(branch)
|
|
}
|
|
fn after_open(&mut self, files: &mut impl SourceProvider) -> Result<Vec<Token>, Error> {
|
|
let mut depth = 1;
|
|
let mut tokens = Vec::new();
|
|
while depth > 0 {
|
|
let token = self.required_raw(files)?.token;
|
|
if token.kind.begin_group() {
|
|
depth += 1;
|
|
}
|
|
if token.kind.end_group() {
|
|
depth -= 1;
|
|
}
|
|
if depth > 0 {
|
|
tokens.push(token);
|
|
}
|
|
if tokens.len() > self.limits.tokens {
|
|
return self.fail("native token limit exceeded");
|
|
}
|
|
}
|
|
Ok(tokens)
|
|
}
|
|
fn after_open_expanded(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
definition: bool,
|
|
) -> Result<Vec<Token>, Error> {
|
|
let mut depth = 1i32;
|
|
let mut body = Vec::new();
|
|
while depth > 0 {
|
|
let input = self
|
|
.expanded_context(files, definition)?
|
|
.ok_or_else(|| self.error("unexpected end of expanded group", self.current))?;
|
|
let token = input.token;
|
|
if !input.frozen && token.kind.begin_group() {
|
|
depth += 1;
|
|
}
|
|
if !input.frozen && token.kind.end_group() {
|
|
depth -= 1;
|
|
}
|
|
if depth > 0 {
|
|
body.push(token);
|
|
}
|
|
if body.len() > self.limits.tokens {
|
|
return self.fail("native token limit exceeded");
|
|
}
|
|
}
|
|
Ok(body)
|
|
}
|
|
fn scan_expanded_group(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Vec<Token>, Error> {
|
|
self.with_scanner(ScannerStatus::Absorbing, |s| {
|
|
s.scan_expanded_group_mode(files, true)
|
|
})
|
|
}
|
|
fn scan_expanded_group_mode(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
definition: bool,
|
|
) -> Result<Vec<Token>, Error> {
|
|
let open = self.expanded_non_space(files)?;
|
|
if !matches!(
|
|
self.meaning(&open.token),
|
|
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
|
|
) {
|
|
return self.fail("expected begin-group token");
|
|
}
|
|
self.after_open_expanded(files, definition)
|
|
}
|
|
fn fully_expand(
|
|
&mut self,
|
|
tokens: Vec<Token>,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Vec<Token>, Error> {
|
|
// TeX's write scanner owns real brace/endwrite sentinels. They delimit
|
|
// expansion and are consumed below; they are not display-only frames
|
|
// or public control sequences that a document can redefine.
|
|
let depth = self.conditionals.len();
|
|
self.inputs.push(InputFrame::Boundary);
|
|
let span = self.current;
|
|
self.push(vec![
|
|
Token::new(TokenKind::Character('}', CatCode::EndGroup), span).into(),
|
|
InputToken {
|
|
token: Token::new(
|
|
TokenKind::Command(CommandName::Control("endwrite".into())),
|
|
span,
|
|
),
|
|
frozen: true,
|
|
end_write: true,
|
|
alignment: None,
|
|
xe_backed_char: false,
|
|
},
|
|
])?;
|
|
self.push_kind(
|
|
tokens.into_iter().map(InputToken::from).collect(),
|
|
TokenInputKind::Write,
|
|
)?;
|
|
self.push(vec![
|
|
Token::new(TokenKind::Character('{', CatCode::BeginGroup), span).into(),
|
|
])?;
|
|
let previous_writing = std::mem::replace(&mut self.writing, true);
|
|
let expanded = self.scan_expanded_group(files);
|
|
self.writing = previous_writing;
|
|
let expanded = expanded?;
|
|
if !self.required_raw(files)?.end_write {
|
|
return self.fail("unbalanced expanded native write");
|
|
}
|
|
self.discard_exhausted_tokens();
|
|
assert!(matches!(self.inputs.pop(), Some(InputFrame::Boundary)));
|
|
if self.conditionals.len() != depth {
|
|
return self.fail("incomplete conditional in expanded write");
|
|
}
|
|
Ok(expanded)
|
|
}
|
|
fn definition(
|
|
&mut self,
|
|
global: bool,
|
|
long: bool,
|
|
protected: bool,
|
|
outer: bool,
|
|
expanded: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
let name = self.command(files)?;
|
|
self.with_scanner(ScannerStatus::Defining(name.clone()), |s| {
|
|
s.definition_body(name, global, long, protected, outer, expanded, files)
|
|
})
|
|
}
|
|
fn parameter_marker(&mut self, token: &Token) -> Option<char> {
|
|
match self.meaning(token) {
|
|
Meaning::Character(TokenKind::Character(character, CatCode::Parameter)) => {
|
|
Some(character)
|
|
}
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn definition_body(
|
|
&mut self,
|
|
name: CommandName,
|
|
global: bool,
|
|
long: bool,
|
|
protected: bool,
|
|
outer: bool,
|
|
expanded: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
let mut prefix = Vec::new();
|
|
let mut parameters: Vec<Vec<TokenKind>> = Vec::new();
|
|
let mut parameter_chars = Vec::new();
|
|
let mut hash_brace = None;
|
|
loop {
|
|
let token = self.required_raw(files)?.token;
|
|
if token.kind.begin_group() {
|
|
break;
|
|
}
|
|
if let Some(character) = self.parameter_marker(&token) {
|
|
let number = self.required_raw(files)?.token;
|
|
if number.kind.begin_group() {
|
|
if let Some(delimiter) = parameters.last_mut() {
|
|
delimiter.push(number.kind.clone());
|
|
} else {
|
|
prefix.push(number.kind.clone());
|
|
}
|
|
hash_brace = Some(number);
|
|
break;
|
|
}
|
|
let expected = parameters.len() + 1;
|
|
if expected > 9
|
|
|| number.kind
|
|
!= TokenKind::Character(
|
|
char::from_digit(expected as u32, 10).unwrap(),
|
|
CatCode::Other,
|
|
)
|
|
{
|
|
return self
|
|
.fail("macro parameters must be numbered consecutively from #1 to #9");
|
|
}
|
|
parameter_chars.push(character);
|
|
parameters.push(Vec::new());
|
|
} else if let Some(delimiter) = parameters.last_mut() {
|
|
delimiter.push(token.kind);
|
|
} else {
|
|
prefix.push(token.kind);
|
|
}
|
|
}
|
|
let mut replacement = self.scan_replacement(expanded, parameters.len(), files)?;
|
|
if let Some(token) = hash_brace {
|
|
replacement.push(Replacement::Token(token));
|
|
}
|
|
self.define_traced(
|
|
name,
|
|
Meaning::Macro(Arc::new(Macro {
|
|
prefix,
|
|
parameters,
|
|
parameter_chars,
|
|
replacement,
|
|
long,
|
|
outer,
|
|
protected,
|
|
})),
|
|
global,
|
|
files,
|
|
)
|
|
}
|
|
fn scan_replacement(
|
|
&mut self,
|
|
expanded: bool,
|
|
parameters: usize,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Vec<Replacement>, Error> {
|
|
let mut depth = 1i32;
|
|
let mut replacement = Vec::new();
|
|
while depth > 0 {
|
|
let input = if expanded {
|
|
self.expanded_context(files, true)?
|
|
.ok_or_else(|| self.error("unexpected end of macro definition", self.current))?
|
|
} else {
|
|
self.required_raw(files)?
|
|
};
|
|
let token = input.token;
|
|
// the-toks/unexpanded append a literal list to scan_toks. They do
|
|
// not re-interpret parameter markers or alter brace balance.
|
|
if input.frozen {
|
|
replacement.push(Replacement::Token(token));
|
|
} else {
|
|
if token.kind.begin_group() {
|
|
depth += 1;
|
|
}
|
|
if token.kind.end_group() {
|
|
depth -= 1;
|
|
}
|
|
if depth == 0 {
|
|
break;
|
|
}
|
|
if self.parameter_marker(&token).is_some() {
|
|
let next = if expanded {
|
|
// The token that follows a marker uses ordinary
|
|
// expanded scanning even inside an edef body.
|
|
self.expanded(files)?
|
|
.ok_or_else(|| self.error("incomplete macro parameter", token.span))?
|
|
} else {
|
|
self.required_raw(files)?
|
|
};
|
|
if !next.frozen && self.parameter_marker(&next.token).is_some() {
|
|
replacement.push(Replacement::Token(next.token));
|
|
} else {
|
|
match next.token.kind {
|
|
TokenKind::Character(c @ '1'..='9', CatCode::Other)
|
|
if (c as usize - '0' as usize) <= parameters =>
|
|
{
|
|
replacement.push(Replacement::Parameter(c as usize - '1' as usize));
|
|
}
|
|
_ => return self.fail("illegal parameter in macro replacement"),
|
|
}
|
|
}
|
|
} else {
|
|
replacement.push(Replacement::Token(token));
|
|
}
|
|
}
|
|
if replacement.len() > self.limits.tokens {
|
|
return self.fail("native token limit exceeded");
|
|
}
|
|
}
|
|
Ok(replacement)
|
|
}
|
|
fn paragraph_argument(&self, token: &Token, long: bool) -> Result<(), Error> {
|
|
if !long && self.state.is_paragraph_token(&token.kind) {
|
|
return Err(self.error(
|
|
"paragraph ended before non-long macro argument was complete",
|
|
token.span,
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
fn delimiter_overlaps(delimiter: &[TokenKind]) -> Vec<usize> {
|
|
let mut overlaps = vec![0; delimiter.len()];
|
|
for index in 1..delimiter.len() {
|
|
let mut matched = overlaps[index - 1];
|
|
while matched != 0 && delimiter[matched] != delimiter[index] {
|
|
matched = overlaps[matched - 1];
|
|
}
|
|
if delimiter[matched] == delimiter[index] {
|
|
matched += 1;
|
|
}
|
|
overlaps[index] = matched;
|
|
}
|
|
overlaps
|
|
}
|
|
|
|
fn strip_outer_group(mut tokens: Vec<Token>) -> Vec<Token> {
|
|
if tokens.first().is_none_or(|t| !t.kind.begin_group()) {
|
|
return tokens;
|
|
}
|
|
let mut depth = 0;
|
|
for (index, token) in tokens.iter().enumerate() {
|
|
if token.kind.begin_group() {
|
|
depth += 1;
|
|
}
|
|
if token.kind.end_group() {
|
|
depth -= 1;
|
|
}
|
|
if depth == 0 {
|
|
if index + 1 == tokens.len() {
|
|
tokens.pop();
|
|
tokens.remove(0);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
tokens
|
|
}
|
|
fn call_macro(
|
|
&mut self,
|
|
definition: Arc<Macro>,
|
|
call: &Token,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
let TokenKind::Command(name) = &call.kind else {
|
|
unreachable!()
|
|
};
|
|
self.with_scanner(ScannerStatus::Matching(name.clone()), |s| {
|
|
s.call_macro_inner(definition, call, files)
|
|
})
|
|
}
|
|
fn call_macro_inner(
|
|
&mut self,
|
|
definition: Arc<Macro>,
|
|
call: &Token,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
// A macro only scans raw tokens while matching its arguments, so
|
|
// assignments cannot change the trace level during this call.
|
|
if !self.reads_tracing_macros {
|
|
self.reads
|
|
.insert(Dependency::Parameter(Parameter::Tracingmacros));
|
|
self.reads_tracing_macros = true;
|
|
}
|
|
let trace = self.state.parameter(Parameter::Tracingmacros).width() > 0;
|
|
if trace {
|
|
self.trace_macro_call(&definition, call, files)?;
|
|
}
|
|
for expected in &definition.prefix {
|
|
if self.required_raw(files)?.token.kind != *expected {
|
|
return self.fail("macro prefix does not match");
|
|
}
|
|
self.consume_macro_delimiter(expected);
|
|
}
|
|
if !definition.long && !definition.parameters.is_empty() {
|
|
self.reads.insert(Dependency::ParagraphToken);
|
|
}
|
|
let mut arguments = Vec::new();
|
|
for (index, delimiter) in definition.parameters.iter().enumerate() {
|
|
let mut argument = Vec::new();
|
|
if delimiter.is_empty() {
|
|
let next = self.raw_non_space(files)?.token;
|
|
self.paragraph_argument(&next, definition.long)?;
|
|
if next.kind.begin_group() {
|
|
argument = self.after_open(files)?;
|
|
for token in &argument {
|
|
self.paragraph_argument(token, definition.long)?;
|
|
}
|
|
} else if next.kind.end_group() {
|
|
return self.fail("unbalanced macro argument");
|
|
} else {
|
|
argument.push(next);
|
|
}
|
|
} else {
|
|
let mut depth = 0;
|
|
let mut matched = 0;
|
|
let mut overlaps = None;
|
|
loop {
|
|
let next = self.required_raw(files)?.token;
|
|
let delimiter_token = depth == 0 && {
|
|
while matched != 0 && delimiter[matched] != next.kind {
|
|
let overlaps =
|
|
overlaps.get_or_insert_with(|| Self::delimiter_overlaps(delimiter));
|
|
matched = overlaps[matched - 1];
|
|
}
|
|
delimiter[matched] == next.kind
|
|
};
|
|
if delimiter_token {
|
|
// Delimiter tokens, including a final hash brace
|
|
// or \par, are tried before ordinary arguments.
|
|
// TeX also retains any earlier partial match that
|
|
// became argument text when the match shifted.
|
|
matched += 1;
|
|
if matched == delimiter.len() {
|
|
self.consume_macro_delimiter(&next.kind);
|
|
argument.truncate(argument.len() + 1 - matched);
|
|
break;
|
|
}
|
|
} else {
|
|
self.paragraph_argument(&next, definition.long)?;
|
|
if next.kind.begin_group() {
|
|
depth += 1;
|
|
} else if next.kind.end_group() {
|
|
depth -= 1;
|
|
}
|
|
if depth < 0 {
|
|
return self.fail("unbalanced delimited macro argument");
|
|
}
|
|
}
|
|
argument.push(next);
|
|
if argument.len() > self.limits.tokens {
|
|
return self.fail("native token limit exceeded");
|
|
}
|
|
}
|
|
argument = Self::strip_outer_group(argument);
|
|
}
|
|
if trace {
|
|
self.trace_macro_argument(&definition, index, &argument, files)?;
|
|
}
|
|
arguments.push(argument);
|
|
}
|
|
self.discard_exhausted_tokens();
|
|
if self.inputs.len() >= self.limits.input_depth {
|
|
return self.fail("native input stack limit exceeded");
|
|
}
|
|
let TokenKind::Command(name) = &call.kind else {
|
|
unreachable!()
|
|
};
|
|
self.inputs.push(InputFrame::Macro {
|
|
definition,
|
|
name: name.clone(),
|
|
cursor: 0,
|
|
arguments: arguments.into_iter().map(Arc::from).collect(),
|
|
call: call.invocation.unwrap_or(call.span),
|
|
});
|
|
Ok(())
|
|
}
|
|
fn define_shorthand(
|
|
&mut self,
|
|
primitive: Primitive,
|
|
global: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
use Primitive::*;
|
|
let name = self.command(files)?;
|
|
// The new name can be the very next token after the number.
|
|
self.define_traced(name.clone(), Meaning::Primitive(Relax), global, files)?;
|
|
self.optional_equals(files)?;
|
|
let value = match primitive {
|
|
Chardef => Meaning::CharGiven(self.character_number("chardef", 0x10FFFF, files)?),
|
|
Mathchardef => {
|
|
let code = self.integer(files)?;
|
|
if !(0..32768).contains(&code) {
|
|
return self.fail("mathchardef must be in 0..32767");
|
|
}
|
|
Meaning::MathCharGiven(code as u16)
|
|
}
|
|
Umathchardef | Umathcharnumdef => Meaning::UnicodeMathCharGiven(
|
|
self.scan_unicode_math_code(primitive == Umathchardef, files)?,
|
|
),
|
|
Countdef => Meaning::Count(self.register_index(files)?),
|
|
Toksdef => Meaning::Toks(self.register_index(files)?),
|
|
Dimendef | Skipdef | Muskipdef => {
|
|
let kind = match primitive {
|
|
Dimendef => RegisterKind::Dimen,
|
|
Skipdef => RegisterKind::Skip,
|
|
_ => RegisterKind::Muskip,
|
|
};
|
|
Meaning::Register(Register {
|
|
kind,
|
|
index: self.register_index(files)?,
|
|
})
|
|
}
|
|
_ => unreachable!("shorthand definition primitive"),
|
|
};
|
|
self.define_traced(name, value, global, files)
|
|
}
|
|
fn optional_equals(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
|
|
let token = self.expanded_non_space(files)?;
|
|
if !matches!(token.token.kind, TokenKind::Character('=', CatCode::Other)) {
|
|
self.unread(token)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
fn bounded(&self, number: i64) -> Result<i32, Error> {
|
|
if number.abs() > i32::MAX as i64 {
|
|
return self.fail("TeX integer overflow");
|
|
}
|
|
Ok(number as i32)
|
|
}
|
|
fn register_index(&mut self, files: &mut impl SourceProvider) -> Result<u16, Error> {
|
|
let value = self.integer(files)?;
|
|
if value < 0 || value > self.state.register_limit() as i32 {
|
|
return self.fail(format!(
|
|
"register index must be in 0..{}",
|
|
self.state.register_limit()
|
|
));
|
|
}
|
|
Ok(value as u16)
|
|
}
|
|
fn integer_variable(&mut self, files: &mut impl SourceProvider) -> Result<Key, Error> {
|
|
let token = self.expanded_non_space(files)?.token;
|
|
self.integer_variable_from(token, files)
|
|
}
|
|
fn integer_variable_from(
|
|
&mut self,
|
|
token: Token,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Key, Error> {
|
|
match self.meaning(&token) {
|
|
Meaning::Count(index) => Ok(Key::Count(index)),
|
|
Meaning::Primitive(Primitive::Count) => Ok(Key::Count(self.register_index(files)?)),
|
|
Meaning::Primitive(Primitive::Endlinechar) => Ok(Key::Endlinechar),
|
|
Meaning::Primitive(Primitive::Newlinechar) => Ok(Key::Newlinechar),
|
|
Meaning::Primitive(Primitive::Escapechar) => Ok(Key::Escapechar),
|
|
Meaning::Primitive(Primitive::Globaldefs) => Ok(Key::Globaldefs),
|
|
Meaning::Primitive(Primitive::Time) => Ok(Key::Job(JobParameter::Time)),
|
|
Meaning::Primitive(Primitive::Day) => Ok(Key::Job(JobParameter::Day)),
|
|
Meaning::Primitive(Primitive::Month) => Ok(Key::Job(JobParameter::Month)),
|
|
Meaning::Primitive(Primitive::Year) => Ok(Key::Job(JobParameter::Year)),
|
|
Meaning::Parameter(p) if p.kind().is_none() => Ok(Key::Parameter(p)),
|
|
Meaning::Primitive(Primitive::Spacefactor)
|
|
if !self.writing && self.math.is_empty() && self.paragraph.is_some() =>
|
|
{
|
|
Ok(Key::Spacefactor)
|
|
}
|
|
Meaning::Primitive(p @ (Primitive::Lccode | Primitive::Uccode)) => {
|
|
let n = self.integer(files)?;
|
|
let c = self.case_character(n)?;
|
|
Ok(Key::CaseCode(
|
|
if p == Primitive::Lccode {
|
|
CaseCode::Lower
|
|
} else {
|
|
CaseCode::Upper
|
|
},
|
|
c,
|
|
))
|
|
}
|
|
Meaning::Primitive(Primitive::Sfcode) => {
|
|
let c = self.scan_space_factor_code_index(files)?;
|
|
Ok(Key::Sfcode(c))
|
|
}
|
|
Meaning::Primitive(Primitive::Delcode) => {
|
|
Ok(Key::Delcode(self.scan_delimiter_code_index(files)?))
|
|
}
|
|
Meaning::Primitive(Primitive::Udelcodenum) => {
|
|
Ok(Key::Delcodenum(self.scan_delimiter_code_index(files)?))
|
|
}
|
|
Meaning::Primitive(Primitive::Udelcode) => {
|
|
self.scan_delimiter_code_index(files)?;
|
|
self.fail(r"Can't use \Udelcode as a number (try \Udelcodenum)")
|
|
}
|
|
Meaning::Primitive(Primitive::Mathcode) => {
|
|
Ok(Key::Mathcode(self.scan_math_code_index(files)?))
|
|
}
|
|
Meaning::Primitive(Primitive::Umathcodenum) => {
|
|
Ok(Key::Mathcodenum(self.scan_math_code_index(files)?))
|
|
}
|
|
Meaning::Primitive(Primitive::Umathcode) => {
|
|
self.scan_math_code_index(files)?;
|
|
self.fail(r"Can't use \Umathcode as a number (try \Umathcodenum)")
|
|
}
|
|
Meaning::Primitive(Primitive::Catcode) => {
|
|
let number = self.integer(files)?;
|
|
self.check_input_character(number)?;
|
|
let c = u32::try_from(number)
|
|
.ok()
|
|
.and_then(char::from_u32)
|
|
.ok_or_else(|| self.error("invalid catcode character number", self.current))?;
|
|
Ok(Key::Catcode(c))
|
|
}
|
|
_ => self.fail(format!(
|
|
"expected native integer register or parameter, got {}",
|
|
self.token_string(&token.kind)
|
|
)),
|
|
}
|
|
}
|
|
fn scan_space_factor_code_index(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<u32, Error> {
|
|
let maximum = if self.state.input_profile() == InputProfile::XeTeX {
|
|
0x10FFFF
|
|
} else {
|
|
255
|
|
};
|
|
self.character_number("sfcode index", maximum, files)
|
|
}
|
|
|
|
fn read_space_factor_code(&mut self, c: u32) -> u16 {
|
|
let dependency = match u8::try_from(c) {
|
|
Ok(slot) => Dependency::SfCode(slot),
|
|
Err(_) => Dependency::UnicodeSfCode(c),
|
|
};
|
|
self.reads.insert(dependency);
|
|
self.state.space_factor_code(c)
|
|
}
|
|
|
|
fn read_integer(&mut self, key: &Key) -> Result<i32, Error> {
|
|
Ok(match key {
|
|
Key::CaseCode(kind, c) => {
|
|
self.reads.insert(Dependency::CaseCode(*kind, *c));
|
|
self.state.case_code(*kind, *c) as i32
|
|
}
|
|
Key::Sfcode(c) => i32::from(self.read_space_factor_code(*c)),
|
|
Key::Delcode(c) => {
|
|
let code = self.read_delimiter_code(*c);
|
|
if code >= Delimiter::EXTENDED {
|
|
return self.fail("Extended delcode used as delcode");
|
|
}
|
|
code
|
|
}
|
|
Key::Delcodenum(c) => self.read_delimiter_code(*c),
|
|
Key::Mathcode(c) => i32::from(
|
|
self.read_math_code(*c).legacy().ok_or_else(|| {
|
|
self.error("Extended mathchar used as mathchar", self.current)
|
|
})?
|
|
),
|
|
Key::Mathcodenum(c) => self.read_math_code(*c).word(),
|
|
Key::Parameter(p) => self.read_parameter(*p).width(),
|
|
Key::Spacefactor => {
|
|
if self.writing || !self.math.is_empty() {
|
|
return self.fail("spacefactor requires horizontal mode");
|
|
}
|
|
self.paragraph
|
|
.as_ref()
|
|
.ok_or_else(|| {
|
|
self.error("spacefactor requires horizontal mode", self.current)
|
|
})?
|
|
.space_factor
|
|
}
|
|
Key::Count(index) => {
|
|
self.reads.insert(Dependency::Count(*index));
|
|
self.state.count(*index)
|
|
}
|
|
Key::Endlinechar => {
|
|
self.reads.insert(Dependency::EndLineChar);
|
|
self.state.endlinechar
|
|
}
|
|
Key::Newlinechar => {
|
|
self.reads.insert(Dependency::NewLineChar);
|
|
self.state.newlinechar
|
|
}
|
|
Key::Escapechar => {
|
|
self.reads.insert(Dependency::EscapeChar);
|
|
self.state.escapechar
|
|
}
|
|
Key::Globaldefs => {
|
|
self.reads.insert(Dependency::GlobalDefs);
|
|
self.state.globaldefs
|
|
}
|
|
Key::Catcode(c) => {
|
|
self.reads.insert(Dependency::CatCode(*c));
|
|
self.state.catcode(*c) as i32
|
|
}
|
|
Key::Job(parameter) => {
|
|
self.reads.insert(Dependency::JobParameter(*parameter));
|
|
self.state
|
|
.job_parameter(*parameter)
|
|
.ok_or_else(|| self.error("host job time was not provided", self.current))?
|
|
}
|
|
_ => unreachable!(),
|
|
})
|
|
}
|
|
fn interaction_mode_value(&mut self) -> i32 {
|
|
self.reads.insert(Dependency::InteractionMode);
|
|
i32::from(self.interaction_mode)
|
|
}
|
|
|
|
fn change_interaction_mode(
|
|
&mut self,
|
|
mode: u8,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
files
|
|
.set_interaction_mode(mode)
|
|
.map_err(|message| self.error(message, self.current))?;
|
|
self.interaction_mode = mode;
|
|
Ok(())
|
|
}
|
|
|
|
fn font_character_target(
|
|
&mut self, files: &mut impl SourceProvider,
|
|
) -> Result<(FontId, u8), Error> {
|
|
let font = self.font_identifier(files)?;
|
|
let slot = self.integer(files)?;
|
|
let slot = u8::try_from(slot).map_err(|_| {
|
|
self.error("font character code must be in 0..255", self.current)
|
|
})?;
|
|
Ok((font, slot))
|
|
}
|
|
fn internal_integer_from(
|
|
&mut self,
|
|
next: InputToken,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<i32, Error> {
|
|
match self.meaning(&next.token) {
|
|
Meaning::Primitive(
|
|
p @ (Primitive::Gluestretch
|
|
| Primitive::Glueshrink
|
|
| Primitive::Gluestretchorder
|
|
| Primitive::Glueshrinkorder),
|
|
) => self.glue_component(p, files),
|
|
Meaning::Primitive(
|
|
p @ (Primitive::Lastskip
|
|
| Primitive::Lastkern
|
|
| Primitive::Lastpenalty
|
|
| Primitive::Lastnodetype),
|
|
) => {
|
|
let (value, kind) = self.last_quantity(p);
|
|
if kind == RegisterKind::Muskip {
|
|
return self.fail("incompatible mu units in integer scan");
|
|
}
|
|
Ok(value.width())
|
|
}
|
|
Meaning::Primitive(Primitive::Efcode) => {
|
|
let (font, slot) = self.font_character_target(files)?;
|
|
self.reads.insert(Dependency::FontResources);
|
|
Ok(self.state.fonts.expansion_code(font, slot))
|
|
}
|
|
Meaning::Primitive(p @ (Primitive::Knbccode | Primitive::Knaccode)) => {
|
|
let (font, slot) = self.font_character_target(files)?;
|
|
Ok(self.state.fonts.auto_kern_code(font, slot, p == Primitive::Knaccode))
|
|
}
|
|
Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => {
|
|
let (font, slot) = self.protrusion_target(files)?;
|
|
let right = p == Primitive::Rpcode;
|
|
Ok(if self.state.input_profile() == InputProfile::XeTeX {
|
|
self.state.fonts.xe_protrusion_code(font, slot, right)
|
|
} else {
|
|
self.state.fonts.protrusion_code(font, slot as u8, right)
|
|
})
|
|
}
|
|
Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => {
|
|
let font = self.font_identifier(files)?;
|
|
let values = self.state.font_integers(font);
|
|
Ok(if p == Primitive::Hyphenchar {
|
|
values.hyphen
|
|
} else {
|
|
values.skew
|
|
})
|
|
}
|
|
Meaning::CharGiven(c) => Ok(c as i32),
|
|
Meaning::MathCharGiven(c) => Ok(c as i32),
|
|
Meaning::UnicodeMathCharGiven(code) => Ok(code.word()),
|
|
Meaning::Parameter(p) if p.kind() == Some(RegisterKind::Muskip) => {
|
|
self.fail("incompatible mu units in integer scan")
|
|
}
|
|
Meaning::Parameter(p) => Ok(self.read_parameter(p).width()),
|
|
Meaning::Register(register) => self.register_integer(register),
|
|
Meaning::Primitive(p @ (Primitive::Dimen | Primitive::Skip | Primitive::Muskip)) => {
|
|
let register = self.scan_register(p, files)?;
|
|
self.register_integer(register)
|
|
}
|
|
Meaning::Primitive(
|
|
p @ (Primitive::Wd | Primitive::Ht | Primitive::Dp | Primitive::Prevdepth),
|
|
) => self.dimension_value(p, files),
|
|
Meaning::Primitive(Primitive::Parshape) => Ok(self.read_paragraph_shape().len() as i32),
|
|
Meaning::Primitive(Primitive::LinePenalties(kind)) => self.line_penalty_value(kind, files),
|
|
Meaning::Primitive(Primitive::Prevgraf) => {
|
|
if self.writing {
|
|
Ok(0)
|
|
} else {
|
|
self.reads.insert(Dependency::PreviousParagraphLines);
|
|
Ok(self.vertical.previous_lines as i32)
|
|
}
|
|
}
|
|
Meaning::Primitive(
|
|
p @ (Primitive::Parshapeindent
|
|
| Primitive::Parshapelength
|
|
| Primitive::Parshapedimen),
|
|
) => self.paragraph_shape_dimension(p, files),
|
|
Meaning::Primitive(
|
|
p @ (Primitive::Fontdimen
|
|
| Primitive::Fontcharwd
|
|
| Primitive::Fontcharht
|
|
| Primitive::Fontchardp
|
|
| Primitive::Fontcharic
|
|
| Primitive::XeTeXglyphbounds),
|
|
) => self.font_dimension(p, files),
|
|
Meaning::Primitive(p) if p.page_dimension().is_some() => self.page_dimension_value(p),
|
|
Meaning::Primitive(Primitive::Interactionmode) => Ok(self.interaction_mode_value()),
|
|
Meaning::Primitive(Primitive::Pdftexversion) => Ok(Self::PDFTEX_VERSION),
|
|
Meaning::Primitive(Primitive::XeTeXversion) => Ok(Self::XETEX_VERSION),
|
|
Meaning::Primitive(Primitive::XeTeXcharclass) => {
|
|
let character = self.character_number("XeTeXcharclass index", 0x10FFFF, files)?;
|
|
Ok(i32::from(self.read_xe_char_class(character)))
|
|
}
|
|
Meaning::Primitive(Primitive::XeTeXpdfpagecount) => {
|
|
self.xdv_pdf_page_count(&next.token, files)
|
|
}
|
|
Meaning::Primitive(p) if p.xetex_font_query_name().is_some() => {
|
|
self.xetex_font_query(p, files)
|
|
}
|
|
Meaning::Primitive(Primitive::Pdfshellescape) => Ok(Self::SHELL_ESCAPE),
|
|
Meaning::Primitive(Primitive::Pdfrandomseed) => {
|
|
self.reads.insert(Dependency::PdfRandomState);
|
|
Ok(self.state.random_seed())
|
|
}
|
|
Meaning::Primitive(p @ (Primitive::Pdflastxpos | Primitive::Pdflastypos)) => {
|
|
self.reads.insert(Dependency::PdfLastPosition);
|
|
Ok(self.state.pdf_last_position[usize::from(p == Primitive::Pdflastypos)])
|
|
}
|
|
Meaning::Primitive(Primitive::Pdflastannot) => {
|
|
self.reads.insert(Dependency::PdfObjects);
|
|
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last_annotation()))
|
|
}
|
|
Meaning::Primitive(Primitive::Pdflastlink) => {
|
|
self.reads.insert(Dependency::PdfObjects);
|
|
Ok(self
|
|
.state
|
|
.pdf_objects
|
|
.as_deref()
|
|
.map_or(0, |objects| objects.last_link()))
|
|
}
|
|
Meaning::Primitive(Primitive::Pdflastxform) => {
|
|
self.reads.insert(Dependency::PdfObjects);
|
|
Ok(self.state.pdf_forms.last_key_value().map_or(0, |(&number, _)| number as i32))
|
|
}
|
|
Meaning::Primitive(Primitive::Pdflastobj) => {
|
|
self.reads.insert(Dependency::PdfObjects);
|
|
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last()))
|
|
}
|
|
Meaning::Primitive(
|
|
p @ (Primitive::Pdflastximage
|
|
| Primitive::Pdflastximagepages
|
|
| Primitive::Pdflastximagecolordepth),
|
|
) => Ok(self.pdf_image_quantity(p)),
|
|
Meaning::Primitive(Primitive::Deadcycles) => Ok(self.native_page_mut()?.dead_cycles),
|
|
Meaning::Primitive(Primitive::Insertpenalties) => {
|
|
Ok(self.native_page_mut()?.insertions.penalties)
|
|
}
|
|
Meaning::Primitive(Primitive::Badness) => {
|
|
self.reads.insert(Dependency::BoxPackState);
|
|
Ok(self.state.last_badness)
|
|
}
|
|
Meaning::Primitive(Primitive::Inputlineno) => {
|
|
let (source, line) = self.input_position.ok_or_else(|| {
|
|
self.error("no native input position available", self.current)
|
|
})?;
|
|
self.reads.insert(Dependency::InputPosition(source));
|
|
i32::try_from(line)
|
|
.map_err(|_| self.error("input line number overflow", self.current))
|
|
}
|
|
Meaning::Primitive(Primitive::Numexpr) => self.expression(files, 0),
|
|
Meaning::Primitive(p @ (Primitive::Dimexpr | Primitive::Glueexpr)) => {
|
|
let kind = if p == Primitive::Dimexpr {
|
|
RegisterKind::Dimen
|
|
} else {
|
|
RegisterKind::Skip
|
|
};
|
|
Ok(self.quantity_expression(kind, files)?.width())
|
|
}
|
|
Meaning::Primitive(Primitive::Muexpr) => {
|
|
self.fail("incompatible mu units in integer scan")
|
|
}
|
|
Meaning::Primitive(Primitive::Etexversion) => Ok(2),
|
|
Meaning::Primitive(Primitive::Currentgrouplevel) => {
|
|
self.reads.insert(Dependency::GroupState);
|
|
Ok(self.state.group_depth() as i32)
|
|
}
|
|
Meaning::Primitive(Primitive::Currentgrouptype) => {
|
|
self.reads.insert(Dependency::GroupState);
|
|
Ok(self.state.group_type())
|
|
}
|
|
_ => {
|
|
let key = self.integer_variable_from(next.token, files)?;
|
|
self.read_integer(&key)
|
|
}
|
|
}
|
|
}
|
|
fn expression(&mut self, files: &mut impl SourceProvider, depth: usize) -> Result<i32, Error> {
|
|
self.with_expression_scan(|executor| executor.expression_sum(files, depth))
|
|
}
|
|
fn expression_sum(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
depth: usize,
|
|
) -> Result<i32, Error> {
|
|
let mut value = self.expression_term(files, depth)?;
|
|
loop {
|
|
let Some(next) = self.expanded(files)? else {
|
|
return Ok(value);
|
|
};
|
|
match next.token.kind {
|
|
TokenKind::Character(_, CatCode::Space) => continue,
|
|
TokenKind::Character(op @ ('+' | '-'), CatCode::Other) => {
|
|
let term = self.expression_term(files, depth)?;
|
|
value = self.bounded(
|
|
value as i64
|
|
+ if op == '+' {
|
|
term as i64
|
|
} else {
|
|
-(term as i64)
|
|
},
|
|
)?;
|
|
}
|
|
_ if self.primitive(&next.token) == Some(Primitive::Relax) => {
|
|
if depth > 0 {
|
|
return self.fail("missing ) in numexpr");
|
|
}
|
|
return Ok(value);
|
|
}
|
|
_ => {
|
|
self.unread(next)?;
|
|
return Ok(value);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fn expression_operator(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Option<char>, Error> {
|
|
loop {
|
|
let Some(next) = self.expanded(files)? else {
|
|
return Ok(None);
|
|
};
|
|
match next.token.kind {
|
|
TokenKind::Character(_, CatCode::Space) => continue,
|
|
TokenKind::Character(op @ ('*' | '/'), CatCode::Other) => return Ok(Some(op)),
|
|
_ => {
|
|
self.unread(next)?;
|
|
return Ok(None);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fn rounded_divide(&self, a: i64, b: i64) -> Result<i32, Error> {
|
|
if b == 0 {
|
|
return self.fail("division by zero in numexpr");
|
|
}
|
|
let q = (a.abs() + b.abs() / 2) / b.abs();
|
|
self.bounded(if (a < 0) ^ (b < 0) { -q } else { q })
|
|
}
|
|
fn expression_term(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
depth: usize,
|
|
) -> Result<i32, Error> {
|
|
let mut value = self.expression_factor(files, depth)?;
|
|
let mut op = self.expression_operator(files)?;
|
|
while let Some(current) = op {
|
|
let rhs = self.expression_factor(files, depth)?;
|
|
op = self.expression_operator(files)?;
|
|
if current == '*' && op == Some('/') {
|
|
let divisor = self.expression_factor(files, depth)?;
|
|
value = self.rounded_divide(value as i64 * rhs as i64, divisor as i64)?;
|
|
op = self.expression_operator(files)?;
|
|
} else if current == '*' {
|
|
value = self.bounded(value as i64 * rhs as i64)?;
|
|
} else {
|
|
value = self.rounded_divide(value as i64, rhs as i64)?;
|
|
}
|
|
}
|
|
Ok(value)
|
|
}
|
|
fn expression_factor(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
depth: usize,
|
|
) -> Result<i32, Error> {
|
|
let first = self.expanded_non_space(files)?;
|
|
let value = if first.token.kind == TokenKind::Character('(', CatCode::Other) {
|
|
let value = self.expression(files, depth + 1)?;
|
|
let close = self.expanded_non_space(files)?;
|
|
if close.token.kind != TokenKind::Character(')', CatCode::Other) {
|
|
return self.fail("missing ) in numexpr");
|
|
}
|
|
value
|
|
} else {
|
|
self.unread(first)?;
|
|
self.integer(files)?
|
|
};
|
|
Ok(value)
|
|
}
|
|
fn integer(&mut self, files: &mut impl SourceProvider) -> Result<i32, Error> {
|
|
self.with_value_scan(|executor| executor.integer_inner(files))
|
|
}
|
|
|
|
fn with_value_scan<T>(
|
|
&mut self,
|
|
scan: impl FnOnce(&mut Self) -> Result<T, Error>,
|
|
) -> Result<T, Error> {
|
|
if self.scanner_depth >= scan_stack::limit(self.limits.input_depth) {
|
|
return self.fail("native value scanner nesting limit exceeded");
|
|
}
|
|
self.scanner_depth += 1;
|
|
let result = scan_stack::enter(|| scan(self));
|
|
self.scanner_depth -= 1;
|
|
result
|
|
}
|
|
|
|
fn with_expression_scan<T>(
|
|
&mut self,
|
|
scan: impl FnOnce(&mut Self) -> Result<T, Error>,
|
|
) -> Result<T, Error> {
|
|
if self.expression_depth >= scan_stack::limit(self.limits.input_depth) {
|
|
return self.fail("native expression nesting limit exceeded");
|
|
}
|
|
self.expression_depth += 1;
|
|
let result = scan_stack::enter(|| scan(self));
|
|
self.expression_depth -= 1;
|
|
result
|
|
}
|
|
fn integer_inner(&mut self, files: &mut impl SourceProvider) -> Result<i32, Error> {
|
|
let mut sign = 1;
|
|
let first = loop {
|
|
let token = self.expanded_non_space(files)?;
|
|
match token.token.kind {
|
|
TokenKind::Character('+', CatCode::Other) => {}
|
|
TokenKind::Character('-', CatCode::Other) => sign = -sign,
|
|
_ => break token,
|
|
}
|
|
};
|
|
let first = if first.token.kind == TokenKind::Command(CommandName::FrozenPrimitivePrefix) {
|
|
self.deferred_internal_primitive(first, files)?
|
|
} else {
|
|
first
|
|
};
|
|
if let TokenKind::Character('\u{0060}', CatCode::Other) = first.token.kind {
|
|
let next = self.required_raw(files)?;
|
|
let character = match &next.token.kind {
|
|
TokenKind::Character(c, _) | TokenKind::Command(CommandName::Active(c)) => *c,
|
|
TokenKind::Command(CommandName::Control(name)) if name.chars().count() == 1 => {
|
|
name.chars().next().unwrap()
|
|
}
|
|
_ => return self.fail("alphabetic constant needs one character"),
|
|
};
|
|
if !self.alignments.is_empty() {
|
|
// scan_int consumes a literal brace as a character code,
|
|
// undoing get_next's alignment nesting change in scan_int.
|
|
self.alignment_balance -= Self::alignment_brace_token(&next.token);
|
|
}
|
|
// TeX permits one optional space after a character constant.
|
|
if let Some(next) = self.expanded(files)?
|
|
&& !self.is_spacer(&next.token)
|
|
{
|
|
self.unread(next)?;
|
|
}
|
|
return self.bounded(sign * character as i64);
|
|
}
|
|
if matches!(first.token.kind, TokenKind::Command(_)) {
|
|
let value = self.internal_integer_from(first, files)?;
|
|
return if sign > 0 { Ok(value) } else { self.bounded(-i64::from(value)) };
|
|
}
|
|
let radix = match first.token.kind {
|
|
TokenKind::Character('\'', CatCode::Other) => 8,
|
|
TokenKind::Character('"', CatCode::Other) => 16,
|
|
_ => {
|
|
self.unread(first)?;
|
|
10
|
|
}
|
|
};
|
|
let mut number = 0i64;
|
|
let mut digits = 0;
|
|
while let Some(next) = self.expanded(files)? {
|
|
let digit = match next.token.kind {
|
|
TokenKind::Character(c @ '0'..='9', CatCode::Other) => c.to_digit(radix),
|
|
TokenKind::Character(c @ 'A'..='F', CatCode::Other | CatCode::Letter)
|
|
if radix == 16 =>
|
|
{
|
|
c.to_digit(16)
|
|
}
|
|
_ => None,
|
|
};
|
|
if let Some(digit) = digit {
|
|
digits += 1;
|
|
number = number * radix as i64 + digit as i64;
|
|
self.bounded(number)?;
|
|
} else {
|
|
if !self.is_spacer(&next.token) {
|
|
self.unread(next)?;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
if digits == 0 {
|
|
return self.fail("missing integer");
|
|
}
|
|
self.bounded(sign * number)
|
|
}
|
|
fn optional_by(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
|
|
let first = self.expanded_non_space(files)?;
|
|
if matches!(first.token.kind, TokenKind::Character('b' | 'B', _)) {
|
|
let second = self.required_expanded(files)?;
|
|
if matches!(second.token.kind, TokenKind::Character('y' | 'Y', _)) {
|
|
return Ok(());
|
|
}
|
|
self.unread(second)?;
|
|
}
|
|
self.unread(first)
|
|
}
|
|
fn filename(&mut self, files: &mut impl SourceProvider) -> Result<std::string::String, Error> {
|
|
self.filename_with_quoting(files).map(|(name, _)| name)
|
|
}
|
|
fn filename_with_quoting(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(String, bool), Error> {
|
|
self.scan_filename(files, false)
|
|
}
|
|
fn scan_filename(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
allow_empty: bool,
|
|
) -> Result<(String, bool), Error> {
|
|
let first = self.expanded_non_space(files)?;
|
|
let mut used_quotes = false;
|
|
let mut name = std::string::String::new();
|
|
let xetex = self.state.input_profile() == InputProfile::XeTeX;
|
|
if first.token.kind.begin_group() {
|
|
loop {
|
|
let token = self.required_expanded(files)?;
|
|
if token.token.kind.end_group() {
|
|
break;
|
|
}
|
|
match token.token.kind {
|
|
TokenKind::Character(c, _) => name.push(c),
|
|
_ => return self.fail("non-character in input filename"),
|
|
}
|
|
}
|
|
} else {
|
|
let mut next = Some(first);
|
|
let mut quoted = false;
|
|
while let Some(token) = next {
|
|
match token.token.kind {
|
|
TokenKind::Character('"', CatCode::Other) => {
|
|
quoted = !quoted;
|
|
used_quotes = true;
|
|
}
|
|
TokenKind::Character(' ', CatCode::Space) if quoted => name.push(' '),
|
|
TokenKind::Character(_, CatCode::Space) => break,
|
|
TokenKind::Character(c, CatCode::Letter | CatCode::Other) => name.push(c),
|
|
TokenKind::Character(c, CatCode::MathShift | CatCode::Alignment
|
|
| CatCode::Parameter | CatCode::Superscript | CatCode::Subscript) if xetex =>
|
|
{
|
|
name.push(c);
|
|
}
|
|
_ => {
|
|
self.unread(token)?;
|
|
break;
|
|
}
|
|
}
|
|
next = self.expanded(files)?;
|
|
}
|
|
if quoted {
|
|
return self.fail("unclosed quote in filename");
|
|
}
|
|
}
|
|
if name.is_empty() && !allow_empty {
|
|
return self.fail("empty filename");
|
|
}
|
|
self.decode_filename(name).map(|name| (name, used_quotes))
|
|
}
|
|
fn decode_filename(&self, name: String) -> Result<String, Error> {
|
|
if self.state.input_profile() == super::InputProfile::TeX8Bit {
|
|
// Tokens hold character codes, not UTF-8 encodings of those codes.
|
|
// The current World filename API accepts UTF-8 host names. Decode
|
|
// the original filename bytes exactly once at that boundary.
|
|
let bytes = name
|
|
.chars()
|
|
.map(|c| u8::try_from(c as u32))
|
|
.collect::<Result<Vec<_>, _>>()
|
|
.map_err(|_| {
|
|
self.error("filename character outside TeX 8-bit profile", self.current)
|
|
})?;
|
|
return std::string::String::from_utf8(bytes).map_err(|_| {
|
|
self.error(
|
|
"non-UTF-8 filename bytes require a raw host path API",
|
|
self.current,
|
|
)
|
|
});
|
|
}
|
|
Ok(name)
|
|
}
|
|
fn source_name(&self, span: Span) -> std::string::String {
|
|
let current_source = self
|
|
.inputs
|
|
.iter()
|
|
.rev()
|
|
.find_map(|frame| match frame {
|
|
InputFrame::Source { source, .. } => Some(*source),
|
|
_ => None,
|
|
})
|
|
.unwrap_or(span.source);
|
|
let mut source = current_source;
|
|
while let Some(generated) = self.generated_inputs.get(&source) {
|
|
if generated.origin.source >= source {
|
|
break;
|
|
}
|
|
source = generated.origin.source;
|
|
}
|
|
self.sources[source].name.clone()
|
|
}
|
|
fn input_file(&mut self, files: &mut impl SourceProvider, span: Span) -> Result<(), Error> {
|
|
let name = self.filename(files)?;
|
|
let from = self.source_name(span);
|
|
self.reads.insert(Dependency::FileLookup {
|
|
name: name.clone(),
|
|
from: from.clone(),
|
|
});
|
|
let file = files
|
|
.read(&name, &from)
|
|
.map_err(|message| self.error(message, span))?;
|
|
self.push_source(file)
|
|
}
|
|
fn stream_index(&mut self, files: &mut impl SourceProvider) -> Result<u8, Error> {
|
|
let n = self.integer(files)?;
|
|
if !(0..16).contains(&n) {
|
|
return self.fail("stream number must be in 0..15");
|
|
}
|
|
Ok(n as u8)
|
|
}
|
|
fn input_stream(&mut self, open: bool, files: &mut impl SourceProvider) -> Result<(), Error> {
|
|
let index = self.stream_index(files)?;
|
|
if self.io.inputs.remove(&index).is_some() {
|
|
files
|
|
.close_in(index)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
}
|
|
if open {
|
|
self.optional_equals(files)?;
|
|
let name = self.filename(files)?;
|
|
let from = self.source_name(self.current);
|
|
self.reads.insert(Dependency::FileLookup {
|
|
name: name.clone(),
|
|
from: from.clone(),
|
|
});
|
|
if let Some(name) = files
|
|
.open_in(index, &name, &from)
|
|
.map_err(|e| self.error(e, self.current))?
|
|
{
|
|
let source = self.sources.len();
|
|
self.sources.push(SourceFile {
|
|
name,
|
|
data: Vec::new(),
|
|
});
|
|
self.stream_sources.insert(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));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn read_stream(
|
|
&mut self,
|
|
global: bool,
|
|
readline: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
let n = self.integer(files)?;
|
|
// TeX routes invalid/closed streams to terminal input. This host has
|
|
// no interactive reader, so fail instead of inventing an empty line.
|
|
if !(0..16).contains(&n) {
|
|
return self.fail("terminal read is unavailable in native batch execution");
|
|
}
|
|
for c in ['t', 'o'] {
|
|
let t = self.expanded_non_space(files)?;
|
|
if !matches!(t.token.kind, TokenKind::Character(ch, _) if ch.eq_ignore_ascii_case(&c)) {
|
|
return self.fail("read requires the keyword to");
|
|
}
|
|
}
|
|
let name = self.command(files)?;
|
|
self.with_scanner(ScannerStatus::Defining(name.clone()), |s| {
|
|
s.read_stream_body(global, readline, n as u8, name, files)
|
|
})
|
|
}
|
|
fn read_stream_body(
|
|
&mut self,
|
|
global: bool,
|
|
readline: bool,
|
|
index: u8,
|
|
name: CommandName,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
self.reads.insert(Dependency::InputStream(index));
|
|
let Some(stream) = self.io.inputs.get(&index) else {
|
|
return self.fail("terminal read is unavailable for a closed input stream");
|
|
};
|
|
let source = stream.source;
|
|
let mut body = Vec::new();
|
|
let mut depth = 0i32;
|
|
loop {
|
|
self.tick()?;
|
|
let (line, encoding) = self.read_physical_stream_line(index, source, files)?;
|
|
let eof = line.is_none();
|
|
if eof {
|
|
files
|
|
.close_in(index)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
self.io.inputs.remove(&index);
|
|
if depth > 0 {
|
|
return self.fail("file ended within read with unbalanced braces");
|
|
}
|
|
}
|
|
let base = self.sources[source].data.len();
|
|
let line = line.unwrap_or_default();
|
|
self.sources[source].data.extend_from_slice(&line);
|
|
let end = self.sources[source].data.len();
|
|
self.reads.insert(Dependency::EndLineChar);
|
|
if readline {
|
|
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 (chars, warnings) = resolved
|
|
.decode_line(&line[bom..bom + length], base + bom, &self.state, &mut self.reads)
|
|
.map_err(|e| self.error(e, Span { source, start: base + bom, end }))?;
|
|
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()
|
|
+ e.error_len().unwrap_or(length - e.valid_up_to()),
|
|
},
|
|
))?
|
|
.map(|(offset, value)| xe_encoding::Character {
|
|
value: self.state.translate_input_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.value,
|
|
if c.value == ' ' { CatCode::Space } else { CatCode::Other },
|
|
),
|
|
Span { source, start: c.start, end: c.end },
|
|
));
|
|
if body.len() > self.limits.tokens {
|
|
return self.fail("native read token limit exceeded");
|
|
}
|
|
}
|
|
if let Ok(c) = u8::try_from(self.state.endlinechar) {
|
|
body.push(Token::new(
|
|
TokenKind::Character(
|
|
c as char,
|
|
if c == b' ' {
|
|
CatCode::Space
|
|
} else {
|
|
CatCode::Other
|
|
},
|
|
),
|
|
Span {
|
|
source,
|
|
start: end,
|
|
end,
|
|
},
|
|
));
|
|
}
|
|
break;
|
|
}
|
|
// Mouth reads exactly one physical line with the current categories;
|
|
// the virtual EOF line is real TeX read semantics, not host data.
|
|
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)
|
|
.map_err(|(mut s, e)| {
|
|
s.start = (s.start + base).min(end);
|
|
s.end = (s.end + base).min(end);
|
|
self.error(e, s)
|
|
})?
|
|
{
|
|
self.tick()?;
|
|
token.span.start = (base + token.span.start).min(end);
|
|
token.span.end = (base + token.span.end).min(end);
|
|
self.reject_outer(&token, false)?;
|
|
if token.kind.begin_group() {
|
|
depth += 1;
|
|
}
|
|
if token.kind.end_group() {
|
|
depth -= 1;
|
|
}
|
|
if depth < 0 {
|
|
depth = 0;
|
|
break;
|
|
} // TeX discards the rest of this line.
|
|
body.push(token);
|
|
if body.len() > self.limits.tokens {
|
|
return self.fail("native read token limit exceeded");
|
|
}
|
|
}
|
|
self.observe_xe_utf8_warnings(mouth.take_utf8_warnings(), files)?;
|
|
if depth == 0 {
|
|
break;
|
|
}
|
|
}
|
|
self.define_traced(
|
|
name,
|
|
Meaning::Macro(Arc::new(Macro {
|
|
prefix: Vec::new(),
|
|
parameters: Vec::new(),
|
|
parameter_chars: Vec::new(),
|
|
replacement: body.into_iter().map(Replacement::Token).collect(),
|
|
long: false,
|
|
outer: false,
|
|
protected: false,
|
|
})),
|
|
global,
|
|
files,
|
|
)
|
|
}
|
|
fn output_command(
|
|
&mut self,
|
|
mut primitive: Primitive,
|
|
span: Span,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
let immediate = primitive == Primitive::Immediate;
|
|
if immediate {
|
|
let next = self.required_expanded(files)?;
|
|
match self.primitive(&next.token) {
|
|
Some(Primitive::Pdfobj) => return self.scan_pdf_object(true, files),
|
|
Some(Primitive::Pdfxform) => return self.scan_pdf_form(true, files),
|
|
Some(Primitive::Pdfximage) => return self.scan_pdf_image(&next.token, true, files),
|
|
Some(p @ (Primitive::Openout | Primitive::Closeout | Primitive::Write)) => {
|
|
primitive = p
|
|
}
|
|
_ => {
|
|
self.unread(next)?;
|
|
return Ok(());
|
|
} // TeX immediate ignores other commands.
|
|
}
|
|
}
|
|
let operation = match primitive {
|
|
Primitive::Openout => {
|
|
let stream = self.stream_index(files)?;
|
|
self.optional_equals(files)?;
|
|
let name = self.filename(files)?;
|
|
OutputOperation::Open {
|
|
stream,
|
|
name,
|
|
from: self.source_name(span),
|
|
}
|
|
}
|
|
Primitive::Closeout => OutputOperation::Close {
|
|
stream: self.stream_index(files)?,
|
|
},
|
|
Primitive::Write => {
|
|
let n = self.integer(files)?;
|
|
OutputOperation::Write {
|
|
stream: if n == 18 {
|
|
n
|
|
} else if n < 0 {
|
|
17
|
|
} else if n > 15 {
|
|
16
|
|
} else {
|
|
n
|
|
},
|
|
tokens: self.scan_group(files)?,
|
|
}
|
|
}
|
|
_ => unreachable!(),
|
|
};
|
|
let node = OutputNode { operation, span };
|
|
if immediate {
|
|
self.output_node(&node, files)?;
|
|
} else {
|
|
self.defer_output(node)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
fn defer_output(&mut self, node: OutputNode) -> Result<(), Error> {
|
|
if self.native_page.is_some() {
|
|
if let Some(m) = self.math.last_mut() {
|
|
m.nodes.push(MathNode::Output(node));
|
|
} else if let Some(p) = self.paragraph.as_mut() {
|
|
p.nodes.push(TextNode::Output(node));
|
|
} else {
|
|
let start = self.vertical.nodes.len();
|
|
self.vertical.nodes.push(NativeVerticalNode::Output(node));
|
|
self.emit_vertical(start);
|
|
}
|
|
} else {
|
|
if !self.box_frames.is_empty() {
|
|
return self
|
|
.fail("deferred I/O in native boxes requires whatsit/shipout integration");
|
|
}
|
|
self.events.push(Event::DeferredOutput(node));
|
|
}
|
|
Ok(())
|
|
}
|
|
fn output_node(
|
|
&mut self,
|
|
node: &OutputNode,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
self.current = node.span;
|
|
self.tick()?;
|
|
match &node.operation {
|
|
OutputOperation::PdfObject(_) => {
|
|
return self.fail("PDF object reference requires a native PDF shipout");
|
|
}
|
|
OutputOperation::PdfForm { .. } => {
|
|
return self.fail("PDF Form reference requires a positioned shipout");
|
|
}
|
|
OutputOperation::PdfImage { image, .. } => {
|
|
return self.declare_pdf_image(image.id, files);
|
|
}
|
|
OutputOperation::PdfColor { .. } => {
|
|
return self.fail("PDF color operation requires native PDF paint");
|
|
}
|
|
OutputOperation::PdfTextSpace(_) => {
|
|
return self.fail("PDF text space operation requires a positioned shipout");
|
|
}
|
|
OutputOperation::PdfLink(_) => {
|
|
return self.fail("PDF link operation requires a positioned shipout");
|
|
}
|
|
OutputOperation::PdfSavePosition => {
|
|
return self.fail("PDF position requires a positioned shipout");
|
|
}
|
|
OutputOperation::Special { .. } => {
|
|
return self.fail("special requires a positioned shipout");
|
|
}
|
|
OutputOperation::PdfSave
|
|
| OutputOperation::PdfSetMatrix(_)
|
|
| OutputOperation::PdfRestore
|
|
| OutputOperation::PdfLiteral { .. } => {
|
|
return self.fail("PDF graphics operation requires a positioned shipout");
|
|
}
|
|
OutputOperation::Open { stream, name, from } => {
|
|
if self.io.outputs.remove(stream) {
|
|
files
|
|
.close_out(*stream)
|
|
.map_err(|e| self.error(e, node.span))?;
|
|
}
|
|
files
|
|
.open_out(*stream, name, from)
|
|
.map_err(|e| self.error(e, node.span))?;
|
|
self.io.outputs.insert(*stream);
|
|
}
|
|
OutputOperation::Close { stream } => {
|
|
if self.io.outputs.remove(stream) {
|
|
files
|
|
.close_out(*stream)
|
|
.map_err(|e| self.error(e, node.span))?;
|
|
}
|
|
}
|
|
OutputOperation::Write { stream, tokens } => {
|
|
let expanded = self.fully_expand(tokens.clone(), files)?;
|
|
let text = self.token_list_text(&expanded);
|
|
let mut bytes = self.external_print_bytes(&text);
|
|
if *stream == 18 {
|
|
let mut message = b"runsystem(".to_vec();
|
|
message.extend_from_slice(&bytes);
|
|
message.extend_from_slice(b")...disabled.\n");
|
|
bytes = message;
|
|
} else {
|
|
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_bytes(*stream as u8, &bytes)
|
|
.map_err(|e| self.error(e, node.span))?;
|
|
} else {
|
|
let destination = if matches!(*stream, 17 | 18) {
|
|
WriteDestination::Log
|
|
} else {
|
|
WriteDestination::TerminalAndLog
|
|
};
|
|
files
|
|
.diagnostic_bytes(destination, &bytes)
|
|
.map_err(|e| self.error(e, node.span))?;
|
|
self.events.push(Event::Write {
|
|
destination,
|
|
text: super::byte_translation::diagnostic_text(&bytes),
|
|
span: node.span,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
/// Execute only nodes actually shipped, in their list traversal order and
|
|
/// against the state at shipout. No implicit end-of-job flushing occurs.
|
|
/// Open streams require the same live host as the preceding run.
|
|
pub fn shipout_io(
|
|
mut self,
|
|
nodes: &[OutputNode],
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Execution, Error> {
|
|
let incoming_state = self.state.fingerprint();
|
|
self.change_interaction_mode(self.interaction_mode, files)?;
|
|
for node in nodes {
|
|
self.output_node(node, files)?;
|
|
}
|
|
self.collect_meaning_reads();
|
|
let format_pdf_images = self.captured_format_pdf_images();
|
|
Ok(Execution {
|
|
format_dumped: self.format_dumped,
|
|
format_pdf_images,
|
|
job_name: self.job_name,
|
|
interaction_mode: self.interaction_mode,
|
|
native_page: self.native_page,
|
|
split_discards: self.split_discards,
|
|
after_assignment: self.after_assignment,
|
|
incoming_state,
|
|
outgoing_state: self.state.fingerprint(),
|
|
state: self.state,
|
|
io: self.io,
|
|
input_position: self.input_position,
|
|
paragraph_mode: if self.paragraph.is_some() {
|
|
ParagraphMode::Horizontal
|
|
} else {
|
|
ParagraphMode::Vertical
|
|
},
|
|
sources: self.sources,
|
|
stream_sources: self.stream_sources,
|
|
generated_inputs: self.generated_inputs,
|
|
reads: self.reads,
|
|
events: self.events.into_vec(),
|
|
steps: self.steps,
|
|
})
|
|
}
|
|
fn check_input_character(&self, code: i32) -> Result<(), Error> {
|
|
if self.state.input_profile() == super::InputProfile::TeX8Bit && !(0..=255).contains(&code)
|
|
{
|
|
return self.fail("character code must be in 0..255 for TeX 8-bit input profile");
|
|
}
|
|
Ok(())
|
|
}
|
|
fn font_token_name(&self, font: FontId) -> std::string::String {
|
|
self.state
|
|
.fonts
|
|
.font(font)
|
|
.expect("loaded frozen font")
|
|
.identifier_text()
|
|
}
|
|
fn token_string(&self, kind: &TokenKind) -> std::string::String {
|
|
match kind {
|
|
TokenKind::Character(c, _) | TokenKind::Command(CommandName::Active(c)) => {
|
|
c.to_string()
|
|
}
|
|
TokenKind::Command(CommandName::Control(name)) if name.is_empty() => {
|
|
"\\csname\\endcsname".into()
|
|
}
|
|
TokenKind::Command(CommandName::Control(name)) => format!("\\{name}"),
|
|
TokenKind::Command(CommandName::FrozenRelax) => "\\relax".into(),
|
|
TokenKind::Command(CommandName::FrozenPrimitive(name)) => format!("\\{name}"),
|
|
TokenKind::Command(CommandName::FrozenPrimitivePrefix) => {
|
|
format!("\\{}", self.state.primitive_prefix_name())
|
|
}
|
|
TokenKind::Command(CommandName::Font(font)) => {
|
|
format!("\\{}", self.font_token_name(*font))
|
|
}
|
|
}
|
|
}
|
|
/// Internal token-to-string conversions retain character codes. TeX's
|
|
/// 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 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 {
|
|
bytes.push(b'\n');
|
|
} else if let Some(table) = table
|
|
&& let Ok(value) = u8::try_from(c as u32)
|
|
{
|
|
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 {
|
|
bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
|
|
}
|
|
}
|
|
bytes
|
|
}
|
|
fn meaning_string(&mut self, token: &Token) -> Result<std::string::String, Error> {
|
|
self.reads.insert(Dependency::EscapeChar);
|
|
let escape = u8::try_from(self.state.escapechar)
|
|
.ok()
|
|
.map(char::from)
|
|
.map(|c| c.to_string())
|
|
.unwrap_or_default();
|
|
let text = match self.meaning(token) {
|
|
Meaning::Undefined => "undefined".into(),
|
|
Meaning::Primitive(p) => {
|
|
let name = match p {
|
|
Primitive::MeaningOf => "meaning".into(),
|
|
Primitive::Explicitspace => " ".into(),
|
|
Primitive::DiscretionaryHyphen => "-".into(),
|
|
Primitive::ItalicCorrection => "/".into(),
|
|
Primitive::XeTeXversion => "XeTeXversion".into(),
|
|
Primitive::XeTeXrevision => "XeTeXrevision".into(),
|
|
Primitive::XeTeXpdffile => "XeTeXpdffile".into(),
|
|
Primitive::XeTeXpicfile => "XeTeXpicfile".into(),
|
|
Primitive::XeTeXglyph => "XeTeXglyph".into(),
|
|
Primitive::XeTeXglyphbounds => "XeTeXglyphbounds".into(),
|
|
Primitive::XeTeXglyphname => "XeTeXglyphname".into(),
|
|
Primitive::XeTeXfeaturename => "XeTeXfeaturename".into(),
|
|
Primitive::XeTeXselectorname => "XeTeXselectorname".into(),
|
|
Primitive::XeTeXinputencoding => "XeTeXinputencoding".into(),
|
|
Primitive::XeTeXdefaultencoding => "XeTeXdefaultencoding".into(),
|
|
Primitive::XeTeXlinebreaklocale => "XeTeXlinebreaklocale".into(),
|
|
Primitive::XeTeXcharclass => "XeTeXcharclass".into(),
|
|
Primitive::XeTeXinterchartoks => "XeTeXinterchartoks".into(),
|
|
Primitive::BeginL => "beginL".into(),
|
|
Primitive::EndL => "endL".into(),
|
|
Primitive::BeginR => "beginR".into(),
|
|
Primitive::EndR => "endR".into(),
|
|
Primitive::XeTeXpdfpagecount => "XeTeXpdfpagecount".into(),
|
|
p if p.xetex_font_query_name().is_some() => {
|
|
p.xetex_font_query_name().unwrap().into()
|
|
}
|
|
Primitive::Etexversion => "eTeXversion".into(),
|
|
Primitive::Etexrevision => "eTeXrevision".into(),
|
|
Primitive::LinePenalties(kind) => kind.name().into(),
|
|
Primitive::Uchar => "Uchar".into(),
|
|
Primitive::Ucharcat => "Ucharcat".into(),
|
|
Primitive::Umathcode => "Umathcode".into(),
|
|
Primitive::Umathcodenum => "Umathcodenum".into(),
|
|
Primitive::Umathchar => "Umathchar".into(),
|
|
Primitive::Umathcharnum => "Umathcharnum".into(),
|
|
Primitive::Umathchardef => "Umathchardef".into(),
|
|
Primitive::Umathcharnumdef => "Umathcharnumdef".into(),
|
|
_ => self.state
|
|
.profile_primitive_name(p)
|
|
.map(str::to_owned)
|
|
.unwrap_or_else(|| format!("{p:?}").to_ascii_lowercase()),
|
|
};
|
|
format!("{escape}{name}")
|
|
}
|
|
Meaning::Count(n) => format!("{escape}count{n}"),
|
|
Meaning::Toks(n) => format!("{escape}toks{n}"),
|
|
Meaning::TokenParameter(p) => format!("{escape}{}", p.name()),
|
|
Meaning::CharGiven(c) => format!("{escape}char\"{c:X}"),
|
|
Meaning::MathCharGiven(c) => format!("{escape}mathchar\"{c:X}"),
|
|
Meaning::UnicodeMathCharGiven(code) => format!(
|
|
"{escape}Umathchar\"{:X}\"{:X}\"{:X}", code.class(), code.family(), code.slot()
|
|
),
|
|
Meaning::Register(r) => format!("{escape}{}{}", r.kind.name(), r.index),
|
|
Meaning::Parameter(p) => format!("{escape}{}", p.name()),
|
|
Meaning::Font(font) => format!(
|
|
"select font {}",
|
|
self.state.fonts.font(font).expect("loaded font").fontname()
|
|
),
|
|
Meaning::Character(TokenKind::Character(c, code)) => {
|
|
let description = match code {
|
|
CatCode::Letter => "the letter",
|
|
CatCode::Other => "the character",
|
|
CatCode::Space => "blank space",
|
|
CatCode::BeginGroup => "begin-group character",
|
|
CatCode::EndGroup => "end-group character",
|
|
CatCode::Parameter => "macro parameter character",
|
|
CatCode::Alignment => "alignment tab character",
|
|
CatCode::Superscript => "superscript character",
|
|
CatCode::Subscript => "subscript character",
|
|
CatCode::MathShift => "math shift character",
|
|
_ => "unsupported character category",
|
|
};
|
|
format!("{description} {c}")
|
|
}
|
|
Meaning::Macro(m) => {
|
|
let mut text = std::string::String::new();
|
|
if m.protected {
|
|
text.push_str(&format!("{escape}protected"));
|
|
}
|
|
if m.long {
|
|
text.push_str(&format!("{escape}long"));
|
|
}
|
|
if m.outer {
|
|
text.push_str(&format!("{escape}outer"));
|
|
}
|
|
if m.protected || m.long || m.outer {
|
|
text.push(' ');
|
|
}
|
|
text.push_str("macro:");
|
|
text.push_str(&self.macro_token_text(&m, token.span)?);
|
|
text
|
|
}
|
|
_ => "unsupported native meaning".into(),
|
|
};
|
|
if text.len() > self.limits.tokens {
|
|
return self.fail("native diagnostic output limit exceeded");
|
|
}
|
|
Ok(text)
|
|
}
|
|
fn macro_token_text(&mut self, m: &Macro, origin: Span) -> Result<String, Error> {
|
|
let mut text = String::new();
|
|
for t in &m.prefix {
|
|
let piece = self.message_token(&Token::new(t.clone(), origin));
|
|
self.append_diagnostic(&mut text, &piece)?;
|
|
}
|
|
for (i, delimiter) in m.parameters.iter().enumerate() {
|
|
text.push_str(&format!("{}{}", m.parameter_chars[i], i + 1));
|
|
for t in delimiter {
|
|
let piece = self.message_token(&Token::new(t.clone(), origin));
|
|
self.append_diagnostic(&mut text, &piece)?;
|
|
}
|
|
}
|
|
text.push_str("->");
|
|
for replacement in &m.replacement {
|
|
if text.len() + 3 > self.limits.tokens {
|
|
return self.fail("native diagnostic output limit exceeded");
|
|
}
|
|
match replacement {
|
|
Replacement::Parameter(n) => text.push_str(&format!(
|
|
"{}{}",
|
|
m.parameter_chars.last().copied().unwrap_or('#'),
|
|
n + 1
|
|
)),
|
|
Replacement::Token(t) => {
|
|
if let TokenKind::Character(c, CatCode::Parameter) = t.kind {
|
|
text.push(c);
|
|
}
|
|
let piece = self.message_token(t);
|
|
self.append_diagnostic(&mut text, &piece)?;
|
|
}
|
|
}
|
|
}
|
|
Ok(text)
|
|
}
|
|
fn append_diagnostic(&self, text: &mut std::string::String, piece: &str) -> Result<(), Error> {
|
|
if text.len() + piece.len() > self.limits.tokens {
|
|
return self.fail("native diagnostic output limit exceeded");
|
|
}
|
|
text.push_str(piece);
|
|
Ok(())
|
|
}
|
|
fn string_token(&mut self, kind: &TokenKind) -> std::string::String {
|
|
self.reads.insert(Dependency::EscapeChar);
|
|
let escape = u8::try_from(self.state.escapechar)
|
|
.ok()
|
|
.map(char::from)
|
|
.map(|c| c.to_string())
|
|
.unwrap_or_default();
|
|
match kind {
|
|
TokenKind::Command(CommandName::Control(name)) if name.is_empty() => {
|
|
format!("{escape}csname{escape}endcsname")
|
|
}
|
|
TokenKind::Command(CommandName::Control(name)) => format!("{escape}{name}"),
|
|
TokenKind::Command(CommandName::FrozenRelax) => format!("{escape}relax"),
|
|
TokenKind::Command(CommandName::FrozenPrimitive(name)) => format!("{escape}{name}"),
|
|
TokenKind::Command(CommandName::FrozenPrimitivePrefix) => {
|
|
format!("{escape}{}", self.state.primitive_prefix_name())
|
|
}
|
|
TokenKind::Command(CommandName::Font(font)) => {
|
|
self.reads.insert(Dependency::FontResources);
|
|
format!("{escape}{}", self.font_token_name(*font))
|
|
}
|
|
_ => self.token_string(kind),
|
|
}
|
|
}
|
|
// TeX's show_token_list doubles a literal parameter token. Character
|
|
// conversion (e.g. \string) deliberately uses the single-token printer.
|
|
fn token_list_text(&mut self, tokens: &[Token]) -> std::string::String {
|
|
let mut text = std::string::String::new();
|
|
for token in tokens {
|
|
if let TokenKind::Character(c, CatCode::Parameter) = token.kind {
|
|
text.push(c);
|
|
}
|
|
text.push_str(&self.message_token(token));
|
|
}
|
|
text
|
|
}
|
|
fn message_token(&mut self, token: &Token) -> std::string::String {
|
|
if matches!(token.kind, TokenKind::Command(
|
|
CommandName::Font(_) | CommandName::FrozenPrimitivePrefix | CommandName::FrozenPrimitive(_)
|
|
)) {
|
|
return format!("{} ", self.string_token(&token.kind));
|
|
}
|
|
|
|
if let TokenKind::Command(CommandName::Control(name)) = &token.kind {
|
|
let mut chars = name.chars();
|
|
let first = chars.next();
|
|
let space = if chars.next().is_some() || first.is_none() {
|
|
true
|
|
} else {
|
|
let c = first.unwrap();
|
|
self.reads.insert(Dependency::CatCode(c));
|
|
self.state.catcode(c) == CatCode::Letter
|
|
};
|
|
return format!(
|
|
"{}{}",
|
|
self.string_token(&token.kind),
|
|
if space { " " } else { "" }
|
|
);
|
|
}
|
|
self.token_string(&token.kind)
|
|
}
|
|
pub fn run(
|
|
self,
|
|
file: SourceFile,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Execution, Error> {
|
|
self.run_detailed(file, files)
|
|
.map_err(|failure| *failure.error)
|
|
}
|
|
pub fn run_detailed(
|
|
mut self,
|
|
file: SourceFile,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Execution, ExecutionFailure> {
|
|
let incoming_state = self.state.fingerprint();
|
|
let result = self.run_observed(file, files, |_, _, _| {});
|
|
self.finish_execution(result, incoming_state, None)
|
|
}
|
|
/// Capture the first eligible entry command boundary at or beyond the
|
|
/// requested physical byte. The callback captures the matching host state.
|
|
pub fn run_capturing_entry<F: SourceProvider, H>(
|
|
self,
|
|
file: SourceFile,
|
|
files: &mut F,
|
|
minimum_frontier: usize,
|
|
capture_host: impl FnOnce(&mut F) -> H,
|
|
) -> (
|
|
Result<Execution, ExecutionFailure>,
|
|
Option<(EntryCheckpoint, H)>,
|
|
) {
|
|
let mut requested = false;
|
|
let mut capture_host = Some(capture_host);
|
|
let mut captured = None;
|
|
let result = self.run_capturing_entries(
|
|
file,
|
|
files,
|
|
|frontier, _| {
|
|
if requested || frontier < minimum_frontier {
|
|
return None;
|
|
}
|
|
requested = true;
|
|
Some(())
|
|
},
|
|
|(), checkpoint, files| {
|
|
captured = Some((checkpoint, capture_host.take().unwrap()(files)));
|
|
},
|
|
);
|
|
(result, captured)
|
|
}
|
|
|
|
/// Observe eligible boundaries during normal execution. Only clone the
|
|
/// state when the caller selects a boundary, giving it its matching host.
|
|
pub fn run_capturing_entries<F: SourceProvider, S>(
|
|
mut self,
|
|
file: SourceFile,
|
|
files: &mut F,
|
|
select: impl FnMut(usize, usize) -> Option<S>,
|
|
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> Result<Execution, ExecutionFailure> {
|
|
let incoming_state = self.state.fingerprint();
|
|
let result = self.run_observed(
|
|
file,
|
|
files,
|
|
Self::entry_observer(incoming_state, select, capture),
|
|
);
|
|
self.finish_execution(result, incoming_state, None)
|
|
}
|
|
|
|
fn entry_observer<F: SourceProvider, S>(
|
|
incoming_state: u64,
|
|
mut select: impl FnMut(usize, usize) -> Option<S>,
|
|
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
|
) -> impl FnMut(&mut Self, usize, &mut F) {
|
|
move |engine, initial_depth, files| {
|
|
if engine.job_ended {
|
|
return;
|
|
}
|
|
let Some(InputFrame::Source {
|
|
source,
|
|
mouth,
|
|
eof_seen: false,
|
|
pseudo_trace: None,
|
|
..
|
|
}) = engine.inputs.first()
|
|
else {
|
|
return;
|
|
};
|
|
let Some(frontier) = mouth.physical_frontier() else {
|
|
return;
|
|
};
|
|
// Keep the active macro and argument cursors, but a second
|
|
// physical source would have an independent unread frontier.
|
|
if engine.inputs[1..]
|
|
.iter()
|
|
.any(|frame| matches!(frame, InputFrame::Source { .. }))
|
|
{
|
|
return;
|
|
}
|
|
let Some(slot) = select(frontier, engine.shipped_pages) else {
|
|
return;
|
|
};
|
|
if engine.sources.iter().enumerate().any(|(index, other)| {
|
|
index != *source && other.name == engine.sources[*source].name
|
|
}) {
|
|
return;
|
|
}
|
|
let entry = *source;
|
|
engine.events.seal_prefix();
|
|
let mut executor = engine.clone();
|
|
executor.cancellation = None;
|
|
executor.line_break_cache = None;
|
|
let checkpoint = EntryCheckpoint {
|
|
executor,
|
|
entry,
|
|
initial_depth,
|
|
incoming_state,
|
|
frontier,
|
|
};
|
|
capture(slot, checkpoint, files);
|
|
}
|
|
}
|
|
fn finish_execution(
|
|
mut self,
|
|
result: Result<(), Error>,
|
|
incoming_state: u64,
|
|
previous: Option<&Execution>,
|
|
) -> Result<Execution, ExecutionFailure> {
|
|
self.collect_meaning_reads();
|
|
let result = result.and_then(|()| {
|
|
if self.shipped_pages > 0 && !self.format_dumped
|
|
&& let Some(objects) = self.state.pdf_objects.as_deref_mut()
|
|
{
|
|
let compress = self.state.pdf_header_options.is_some_and(|header| header.object_compression > 0);
|
|
objects.finish_threads(compress, self.limits.tokens)
|
|
.map_err(|message| self.error(message, self.current))?;
|
|
}
|
|
Ok(())
|
|
});
|
|
if let Err(error) = result {
|
|
use sha2::{Digest, Sha256};
|
|
let source_versions = self
|
|
.sources
|
|
.iter()
|
|
.map(|s| SourceVersion {
|
|
sha256: format!("{:x}", Sha256::digest(&s.data)),
|
|
bytes: s.data.len() as u64,
|
|
})
|
|
.collect();
|
|
let evidence = ExecutionEvidence {
|
|
sources: self.sources,
|
|
source_versions,
|
|
stream_sources: self.stream_sources,
|
|
generated_inputs: self.generated_inputs,
|
|
reads: self.reads,
|
|
events: self.events.into_vec(),
|
|
input_position: self.input_position,
|
|
incoming_state,
|
|
outgoing_state: self.state.fingerprint(),
|
|
group_depth: self.state.group_depth(),
|
|
paragraph_mode: if !self.math.is_empty() {
|
|
ParagraphMode::Math
|
|
} else if self.paragraph.is_some() {
|
|
ParagraphMode::Horizontal
|
|
} else {
|
|
ParagraphMode::Vertical
|
|
},
|
|
steps: self.steps,
|
|
};
|
|
return Err(ExecutionFailure {
|
|
error: Box::new(error),
|
|
evidence,
|
|
});
|
|
}
|
|
// An identical completed state has the same fingerprint. Compare
|
|
// the entire state, including token source spans and assignments.
|
|
let outgoing_state = previous
|
|
.filter(|last| last.state == self.state)
|
|
.map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state);
|
|
let format_pdf_images = self.captured_format_pdf_images();
|
|
Ok(Execution {
|
|
format_dumped: self.format_dumped,
|
|
format_pdf_images,
|
|
job_name: self.job_name,
|
|
interaction_mode: self.interaction_mode,
|
|
after_assignment: self.after_assignment,
|
|
events: self.events.into_vec(),
|
|
native_page: self.native_page,
|
|
split_discards: self.split_discards,
|
|
outgoing_state,
|
|
state: self.state,
|
|
io: self.io,
|
|
input_position: self.input_position,
|
|
paragraph_mode: ParagraphMode::Vertical,
|
|
sources: self.sources,
|
|
stream_sources: self.stream_sources,
|
|
generated_inputs: self.generated_inputs,
|
|
reads: self.reads,
|
|
incoming_state,
|
|
steps: self.steps,
|
|
})
|
|
}
|
|
fn run_observed<F: SourceProvider>(
|
|
&mut self,
|
|
file: SourceFile,
|
|
files: &mut F,
|
|
capture_boundary: impl FnMut(&mut Self, usize, &mut F),
|
|
) -> Result<(), Error> {
|
|
self.check_cancellation()?;
|
|
self.change_interaction_mode(self.interaction_mode, files)?;
|
|
let result = self.prepare_input(file, files).and_then(|initial_depth| {
|
|
self.emit_format_image_warnings(files)?;
|
|
self.run_active_input(initial_depth, files, capture_boundary)
|
|
});
|
|
self.finish_observed_input(result, files)
|
|
}
|
|
fn finish_observed_input(
|
|
&mut self,
|
|
result: Result<(), Error>,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
if let Err(mut error) = result.and_then(|()| self.finish_pdf_dictionaries()) {
|
|
if let Err(sink) = files.observe_error(&error) {
|
|
error
|
|
.message
|
|
.push_str(&format!("; native error observer: {sink}"));
|
|
}
|
|
if let Err(sink) = self.statistics_end(false, files) {
|
|
error
|
|
.message
|
|
.push_str(&format!("; native statistics: {sink}"));
|
|
}
|
|
return Err(error);
|
|
}
|
|
if let Err(mut error) = self.statistics_end(true, files) {
|
|
if let Err(sink) = files.observe_error(&error) {
|
|
error
|
|
.message
|
|
.push_str(&format!("; native error observer: {sink}"));
|
|
}
|
|
return Err(error);
|
|
}
|
|
self.check_cancellation()?;
|
|
Ok(())
|
|
}
|
|
fn prepare_input(
|
|
&mut self,
|
|
file: SourceFile,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<usize, Error> {
|
|
if self.job_name.is_none() {
|
|
self.job_name = std::path::Path::new(&file.name)
|
|
.file_stem()
|
|
.and_then(std::ffi::OsStr::to_str)
|
|
.map(str::to_owned);
|
|
}
|
|
let initial_depth = self.state.group_depth();
|
|
self.push_source(file)?;
|
|
if !self.format_loaded && !self.state.is_initex() && self.state.fonts.fonts().len() == 1 {
|
|
let defaults = FontIntegers {
|
|
hyphen: self.state.parameter(Parameter::Defaulthyphenchar).width(),
|
|
skew: self.state.parameter(Parameter::Defaultskewchar).width(),
|
|
};
|
|
let from = self.sources[0].name.clone();
|
|
let font = self
|
|
.state
|
|
.fonts
|
|
.load(
|
|
files,
|
|
"cmr10",
|
|
&from,
|
|
crate::tfm::FontSize::Design,
|
|
CommandName::Control("cmr10".into()),
|
|
defaults,
|
|
)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
self.state.text_font = font;
|
|
self.reads.insert(Dependency::FontResources);
|
|
}
|
|
if self.fresh_job {
|
|
self.reads
|
|
.insert(Dependency::TokenParameter(TokenParameter::Everyjob));
|
|
if self
|
|
.state
|
|
.token_parameter(TokenParameter::Everyjob)
|
|
.is_some()
|
|
{
|
|
// TeX loads the first physical line before the job hook, but
|
|
// does not fetch a token from it until the hook has run.
|
|
let Some(InputFrame::Source { source, mouth, .. }) = self.inputs.last_mut() else {
|
|
unreachable!("new job starts with its entry source");
|
|
};
|
|
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)?;
|
|
}
|
|
}
|
|
Ok(initial_depth)
|
|
}
|
|
fn insert_paragraph_token(&mut self, span: Span) -> Result<(), Error> {
|
|
self.reads.insert(Dependency::ParagraphToken);
|
|
self.push(vec![Token::new(self.state.paragraph_token(), span).into()])
|
|
}
|
|
|
|
fn in_unrestricted_horizontal_mode(&self) -> bool {
|
|
self.paragraph.is_some() && self.math.is_empty() && !self.restricted()
|
|
}
|
|
|
|
fn group_end_needs_paragraph_token(&mut self) -> bool {
|
|
let minimum = match self.state.group_kind() {
|
|
Some(GroupKind::Vbox | GroupKind::Vtop | GroupKind::Vcenter) => 1,
|
|
Some(GroupKind::Insertion | GroupKind::Output | GroupKind::NoAlign) => 2,
|
|
_ => return false,
|
|
};
|
|
self.read_parameter(Parameter::Partokencontext).width() >= minimum
|
|
}
|
|
|
|
fn run_active_input<F: SourceProvider>(
|
|
&mut self,
|
|
initial_depth: usize,
|
|
files: &mut F,
|
|
mut capture_boundary: impl FnMut(&mut Self, usize, &mut F),
|
|
) -> Result<(), Error> {
|
|
let xe = self.state.input_profile() == InputProfile::XeTeX;
|
|
loop {
|
|
self.check_box_capacity(None)?;
|
|
capture_boundary(self, initial_depth, files);
|
|
self.process_native_pages(files)?;
|
|
self.check_box_capacity(None)?;
|
|
let Some(input) = self.expanded(files)? else {
|
|
break;
|
|
};
|
|
if let Some(boundary) = input.alignment {
|
|
if xe && self.xe_end_char_run(&input)? {
|
|
continue;
|
|
}
|
|
self.alignment_boundary(boundary, files)?;
|
|
continue;
|
|
}
|
|
let meaning = self.meaning(&input.token);
|
|
let frozen_expandable = Self::suppresses_meaning(&input, &meaning);
|
|
if xe
|
|
&& (frozen_expandable
|
|
|| !matches!(
|
|
&meaning,
|
|
Meaning::Character(TokenKind::Character(
|
|
_,
|
|
CatCode::Letter | CatCode::Other
|
|
)) | Meaning::CharGiven(_)
|
|
| Meaning::Primitive(Primitive::Char | Primitive::Noboundary)
|
|
))
|
|
&& self.xe_end_char_run(&input)?
|
|
{
|
|
continue;
|
|
}
|
|
let xe_backed_char = input.xe_backed_char;
|
|
let token = input.token;
|
|
if self.read_parameter(Parameter::Tracingcommands).width() > 0 {
|
|
if frozen_expandable {
|
|
self.trace_frozen_command(files)?;
|
|
} else {
|
|
self.trace_command(&token, files)?;
|
|
}
|
|
}
|
|
if self.in_unrestricted_horizontal_mode()
|
|
&& (matches!(
|
|
&meaning,
|
|
Meaning::Primitive(
|
|
Primitive::End
|
|
| Primitive::Dump
|
|
| Primitive::Vskip
|
|
| Primitive::Vfil
|
|
| Primitive::Vfill
|
|
| Primitive::Vss
|
|
| Primitive::Vfilneg
|
|
| Primitive::Hrule
|
|
| Primitive::Unvbox
|
|
| Primitive::Unvcopy
|
|
| Primitive::Pagediscards
|
|
| Primitive::Splitdiscards
|
|
| Primitive::Halign
|
|
)
|
|
) || (matches!(
|
|
&meaning,
|
|
Meaning::Character(TokenKind::Character(_, CatCode::EndGroup))
|
|
) && self.group_end_needs_paragraph_token()))
|
|
{
|
|
let span = token.span;
|
|
self.unread(InputToken {
|
|
token,
|
|
frozen: input.frozen,
|
|
end_write: input.end_write,
|
|
alignment: None,
|
|
xe_backed_char: false,
|
|
})?;
|
|
self.insert_paragraph_token(span)?;
|
|
continue;
|
|
}
|
|
if frozen_expandable {
|
|
continue;
|
|
}
|
|
// TeX backs up the triggering command before new_graf, so everypar
|
|
// can change its meaning/font/parameters before that token executes.
|
|
if self.paragraph.is_none()
|
|
&& self.math.is_empty()
|
|
&& matches!(
|
|
&meaning,
|
|
Meaning::Character(TokenKind::Character(
|
|
_,
|
|
CatCode::Letter | CatCode::Other | CatCode::MathShift
|
|
)) | Meaning::CharGiven(_)
|
|
| Meaning::Primitive(
|
|
Primitive::Char
|
|
| Primitive::Accent
|
|
| Primitive::XeTeXglyph
|
|
| Primitive::Hskip
|
|
| Primitive::Hfil
|
|
| Primitive::Hfill
|
|
| Primitive::Hss
|
|
| Primitive::Hfilneg
|
|
| Primitive::DiscretionaryHyphen
|
|
| Primitive::Discretionary
|
|
| Primitive::Noboundary
|
|
| Primitive::Vrule
|
|
| Primitive::Unhbox
|
|
| Primitive::Unhcopy
|
|
| Primitive::Valign
|
|
| Primitive::BeginL
|
|
| Primitive::EndL
|
|
| Primitive::BeginR
|
|
| Primitive::EndR
|
|
)
|
|
)
|
|
{
|
|
self.unread(InputToken {
|
|
token,
|
|
frozen: input.frozen,
|
|
end_write: input.end_write,
|
|
alignment: None,
|
|
xe_backed_char: false,
|
|
})?;
|
|
self.begin_paragraph(self.current, true)?;
|
|
continue;
|
|
}
|
|
if self.math_token(&token, &meaning, files)? {
|
|
continue;
|
|
}
|
|
if !matches!(
|
|
&meaning,
|
|
Meaning::Character(TokenKind::Character(
|
|
_,
|
|
CatCode::Letter | CatCode::Other | CatCode::Space
|
|
)) | Meaning::CharGiven(_)
|
|
| Meaning::Primitive(Primitive::Char | Primitive::Noboundary)
|
|
) {
|
|
self.finish_text(true)?;
|
|
}
|
|
match meaning {
|
|
Meaning::Character(TokenKind::Character(c, code)) => match code {
|
|
CatCode::BeginGroup => self.begin_group(GroupKind::Simple, files)?,
|
|
CatCode::EndGroup => {
|
|
if !self.close_noalign_group(files)?
|
|
&& !self.close_box_group(files)?
|
|
&& !self.close_output_group(files)?
|
|
{
|
|
self.finish_group(GroupKind::Simple, token.span, files)?;
|
|
}
|
|
}
|
|
CatCode::Letter | CatCode::Other | CatCode::Space => {
|
|
if xe
|
|
&& code != CatCode::Space
|
|
&& self.xe_start_character(c, code, &token, xe_backed_char)?
|
|
{
|
|
continue;
|
|
}
|
|
self.text_character(c, code, &token, files)?;
|
|
self.events.push(Event::Character(Token {
|
|
kind: TokenKind::Character(c, code),
|
|
..token
|
|
}));
|
|
}
|
|
_ => return self.fail(format!("unsupported native mode token: {code:?}")),
|
|
},
|
|
Meaning::Primitive(primitive) => {
|
|
use Primitive::*;
|
|
match primitive {
|
|
Noboundary => {
|
|
if xe && self.xe_native_boundary_before_noboundary(&token)? {
|
|
continue;
|
|
}
|
|
self.finish_text(false)?;
|
|
if self.paragraph.is_some() {
|
|
if let Some(next) = self.expanded(files)? {
|
|
let cancel = matches!(
|
|
self.meaning(&next.token),
|
|
Meaning::Character(TokenKind::Character(
|
|
_,
|
|
CatCode::Letter | CatCode::Other
|
|
)) | Meaning::CharGiven(_)
|
|
| Meaning::Primitive(Char)
|
|
);
|
|
let paragraph = self.paragraph.as_mut().unwrap();
|
|
paragraph.cancel_boundary = cancel;
|
|
if xe && cancel {
|
|
paragraph.xe_char_run = None;
|
|
}
|
|
self.unread(next)?;
|
|
}
|
|
}
|
|
}
|
|
Relax => {}
|
|
Halign | Valign => self.start_alignment(primitive, token.span, files)?,
|
|
Cr | Crcr | Span | Omit | Noalign => {
|
|
return self.fail("misplaced native alignment command");
|
|
}
|
|
Explicitspace => {
|
|
if self.paragraph.is_some() {
|
|
let space = self.explicit_space(Some(&token))?;
|
|
self.paragraph.as_mut().unwrap().nodes.push(space);
|
|
}
|
|
}
|
|
DeferredPrimitive => {
|
|
let operand = self.normal_raw(files)?;
|
|
if let Some((original, expandable)) = self.frozen_primitive(&operand.token) {
|
|
if expandable {
|
|
return self.fail(format!(
|
|
"misplaced {}",
|
|
self.token_string(&original.token.kind)
|
|
));
|
|
}
|
|
self.unread(original)?;
|
|
}
|
|
}
|
|
Ignorespaces => {
|
|
while let Some(next) = self.expanded(files)? {
|
|
if !self.is_spacer(&next.token) {
|
|
self.unread(next)?;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
Afterassignment => {
|
|
self.after_assignment = Some(self.required_raw(files)?.token)
|
|
}
|
|
Aftergroup => self.schedule_after_group(files)?,
|
|
Showbox => self.show_box(files)?,
|
|
Showlists | Showgroups | Showifs => self.show_activity(primitive, files)?,
|
|
Show | Showthe | Showtokens => self.show(
|
|
primitive,
|
|
token.invocation.unwrap_or(token.span),
|
|
files,
|
|
)?,
|
|
Partokenname => {
|
|
if let TokenKind::Command(name) = self.required_raw(files)?.token.kind {
|
|
self.state.set_paragraph_token(name);
|
|
}
|
|
}
|
|
Par => {
|
|
if self.paragraph.is_none() {
|
|
self.normal_paragraph(files)?;
|
|
} else {
|
|
self.end_paragraph(files)?;
|
|
}
|
|
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,
|
|
EndL => DirectionBoundary::EndL,
|
|
BeginR => DirectionBoundary::BeginR,
|
|
EndR => DirectionBoundary::EndR,
|
|
_ => unreachable!(),
|
|
};
|
|
if !self.math.is_empty() {
|
|
return self.fail("Missing $ inserted");
|
|
}
|
|
if self.read_parameter(Parameter::TeXXeTstate).width() <= 0 {
|
|
return self.fail(format!("Improper \\{}.", boundary.name()));
|
|
}
|
|
self.finish_text(true)?;
|
|
self.paragraph.as_mut().unwrap().nodes.push(TextNode::Direction(boundary));
|
|
}
|
|
BeginGroup => self.begin_group(GroupKind::SemiSimple, files)?,
|
|
EndGroup => self.finish_group(GroupKind::SemiSimple, token.span, files)?,
|
|
End | Dump => {
|
|
if primitive == Dump {
|
|
if !self.state.is_initex() || !self.fresh_job {
|
|
return self.fail("dump requires a native INITEX job");
|
|
}
|
|
if self.state.group_depth() != 0 || !self.conditionals.is_empty() {
|
|
return self
|
|
.fail("dump requires closed groups and conditionals");
|
|
}
|
|
self.ensure_format_pdf_images()?;
|
|
self.reads.insert(Dependency::FontResources);
|
|
if self.state.fonts.fonts().iter().any(|font| font.opentype().is_some()) {
|
|
return self.fail("cannot dump a format with native OpenType fonts");
|
|
}
|
|
self.format_dumped = true;
|
|
}
|
|
if self.native_page.is_some() {
|
|
if self.end_native_job(token.clone())? {
|
|
self.job_ended = true;
|
|
break;
|
|
}
|
|
continue;
|
|
}
|
|
if !self.box_frames.is_empty() || !self.alignments.is_empty() {
|
|
return self.fail("end inside an unfinished native box");
|
|
}
|
|
self.end_paragraph(files)?;
|
|
self.job_ended = true;
|
|
break;
|
|
}
|
|
Indent | Noindent => {
|
|
if self.paragraph.is_none() {
|
|
self.begin_paragraph(token.span, primitive == Indent)?;
|
|
} else if primitive == Indent {
|
|
let n = self.read_parameter(Parameter::Parindent).width();
|
|
self.paragraph
|
|
.as_mut()
|
|
.unwrap()
|
|
.nodes
|
|
.push(TextNode::Indent(n));
|
|
self.paragraph.as_mut().unwrap().space_factor = 1000;
|
|
}
|
|
}
|
|
Hbox | Vbox | Vtop | Box | Copy | Lastbox | Vsplit => self.box_command(
|
|
primitive,
|
|
boxes::Destination::Append,
|
|
token.span,
|
|
files,
|
|
)?,
|
|
Raise | Lower | Moveleft | Moveright => self.shift_box(primitive, files)?,
|
|
Unhbox | Unhcopy | Unvbox | Unvcopy | Pagediscards | Splitdiscards => {
|
|
self.unpackage(primitive, files)?
|
|
}
|
|
Unskip | Unkern | Unpenalty => self.delete_last(primitive)?,
|
|
ItalicCorrection => self.append_italic_correction()?,
|
|
Accent => self.text_accent(&token, files)?,
|
|
Shipout => self.scan_box(boxes::Destination::Shipout, files)?,
|
|
Leaders | Cleaders | Xleaders => self.scan_leaders(primitive, files)?,
|
|
Vrule => {
|
|
let r = self.scan_rule(false, TokenOrigin::from(&token), files)?;
|
|
let p = self.paragraph.as_mut().unwrap();
|
|
p.nodes.push(TextNode::Rule(r));
|
|
p.space_factor = 1000;
|
|
}
|
|
Vskip | Vfil | Vfill | Vss | Vfilneg | Hrule => {
|
|
self.vertical_command(primitive, TokenOrigin::from(&token), files)?
|
|
}
|
|
Kern | Penalty if self.paragraph.is_none() => {
|
|
self.vertical_command(primitive, TokenOrigin::from(&token), files)?
|
|
}
|
|
Discretionary => self.start_discretionary(token.span, files)?,
|
|
Mark | Marks => self.make_mark(primitive, token.span, files)?,
|
|
Vadjust => self.start_adjustment(token.span, files)?,
|
|
Insert => self.start_insertion(token.span, files)?,
|
|
Hskip | Hfil | Hfill | Hss | Hfilneg | Kern | Penalty
|
|
| DiscretionaryHyphen => {
|
|
self.horizontal_command(primitive, TokenOrigin::from(&token), files)?
|
|
}
|
|
Lowercase | Uppercase => self.change_case(
|
|
if primitive == Lowercase {
|
|
CaseCode::Lower
|
|
} else {
|
|
CaseCode::Upper
|
|
},
|
|
files,
|
|
)?,
|
|
Hyphenation => self.hyphenation(files)?,
|
|
Patterns => self.patterns(files)?,
|
|
Setlanguage => self.set_language(files)?,
|
|
Char => {
|
|
let c = self.character_number("char", 0x10FFFF, files)?;
|
|
let c = self.scalar_character(c, token.span)?;
|
|
if xe
|
|
&& self.xe_start_character(c, CatCode::Other, &token, xe_backed_char)?
|
|
{
|
|
continue;
|
|
}
|
|
self.text_character(c, CatCode::Other, &token, files)?;
|
|
self.events.push(Event::Character(Token {
|
|
kind: TokenKind::Character(c, CatCode::Other),
|
|
..token
|
|
}));
|
|
}
|
|
Endinput => {
|
|
if let Some(InputFrame::Source { mouth, .. }) = self
|
|
.inputs
|
|
.iter_mut()
|
|
.rev()
|
|
.find(|f| matches!(f, InputFrame::Source { .. }))
|
|
{
|
|
mouth.end_input();
|
|
}
|
|
}
|
|
Message | Errmessage => {
|
|
let expanded = self.scan_expanded_group(files)?;
|
|
let text = self.token_list_text(&expanded);
|
|
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}"),
|
|
token.invocation.unwrap_or(token.span),
|
|
);
|
|
self.reads
|
|
.insert(Dependency::TokenParameter(TokenParameter::Errhelp));
|
|
if let Some(help) =
|
|
self.state.token_parameter(TokenParameter::Errhelp).cloned()
|
|
{
|
|
let text = self.token_list_text(&help);
|
|
error.help = Some(self.external_print(&text));
|
|
}
|
|
return Err(error);
|
|
}
|
|
files
|
|
.observe_message_bytes(&bytes)
|
|
.map_err(|e| self.error(e, token.span))?;
|
|
self.events.push(Event::Message {
|
|
text,
|
|
span: token.span,
|
|
});
|
|
}
|
|
Openin | Closein => self.input_stream(primitive == Openin, files)?,
|
|
_ if self.execute_output_extension(primitive, &token, files)? => {}
|
|
_ => {
|
|
self.assignment(Some(primitive), None, files)?;
|
|
}
|
|
}
|
|
}
|
|
Meaning::Count(index) => self.assignment(None, Some(Key::Count(index)), files)?,
|
|
Meaning::Toks(index) => self.assignment(None, Some(Key::Toks(index)), files)?,
|
|
Meaning::TokenParameter(p) => {
|
|
self.assignment(None, Some(Key::TokenParameter(p)), files)?
|
|
}
|
|
Meaning::Register(r) => self.assignment(None, Some(Key::Register(r)), files)?,
|
|
Meaning::Parameter(p) => self.assignment(None, Some(Key::Parameter(p)), files)?,
|
|
Meaning::Font(font) => {
|
|
self.reads.insert(Dependency::GlobalDefs);
|
|
self.select_traced_font(font, self.state.global(false), files)?;
|
|
self.finish_assignment()?;
|
|
}
|
|
Meaning::CharGiven(c) => {
|
|
let c = self.scalar_character(c, token.span)?;
|
|
if xe && self.xe_start_character(c, CatCode::Other, &token, xe_backed_char)? {
|
|
continue;
|
|
}
|
|
self.text_character(c, CatCode::Other, &token, files)?;
|
|
self.events.push(Event::Character(Token {
|
|
kind: TokenKind::Character(c, CatCode::Other),
|
|
..token
|
|
}));
|
|
}
|
|
Meaning::MathCharGiven(_) | Meaning::UnicodeMathCharGiven(_) => {
|
|
return self.fail("native math character execution requires math mode");
|
|
}
|
|
Meaning::Undefined => {
|
|
return self.fail(format!(
|
|
"undefined native control sequence: {}",
|
|
self.token_string(&token.kind)
|
|
));
|
|
}
|
|
_ => return self.fail("unsupported native command meaning"),
|
|
}
|
|
if self.events.len() > self.limits.tokens {
|
|
return self.fail("native output token limit exceeded");
|
|
}
|
|
}
|
|
if !self.math.is_empty() {
|
|
return self.fail("unclosed native math mode at end of input");
|
|
}
|
|
if !self.box_frames.is_empty() {
|
|
return self.fail("unclosed native box at end of input");
|
|
}
|
|
if !self.alignments.is_empty() {
|
|
return self.fail("unclosed native alignment at end of input");
|
|
}
|
|
if self.native_page.is_some() && !self.job_ended {
|
|
return self.fail("native job ended without an end or dump command");
|
|
}
|
|
self.validate_pdf_final_state()?;
|
|
self.end_paragraph(files)?;
|
|
self.check_box_capacity(None)?;
|
|
if self.state.group_depth() != initial_depth {
|
|
return self.fail("unclosed native group at end of input");
|
|
}
|
|
if let Some(conditional) = self.conditionals.last() {
|
|
return Err(self.error("incomplete conditional at end of input", conditional.span));
|
|
}
|
|
if self.job_ended {
|
|
while let Some(frame) = self.inputs.pop() {
|
|
if let InputFrame::Source {
|
|
source,
|
|
pseudo_trace: Some(traced),
|
|
..
|
|
} = frame
|
|
{
|
|
self.pseudo_input_boundary(source, false, traced, files)?;
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn assignment(
|
|
&mut self,
|
|
primitive: Option<Primitive>,
|
|
key: Option<Key>,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
self.assignment_with_box_policy(primitive, key, true, files)
|
|
}
|
|
fn assignment_with_box_policy(
|
|
&mut self,
|
|
primitive: Option<Primitive>,
|
|
key: Option<Key>,
|
|
allow_setbox: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
self.assignment_inner(primitive, key, allow_setbox, files)?;
|
|
self.finish_assignment()
|
|
}
|
|
fn assignment_inner(
|
|
&mut self,
|
|
mut primitive: Option<Primitive>,
|
|
mut key: Option<Key>,
|
|
allow_setbox: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
use Primitive::*;
|
|
let mut global_prefix = false;
|
|
let mut long = false;
|
|
let mut outer = false;
|
|
let mut protected = false;
|
|
let mut selected_font = None;
|
|
loop {
|
|
match primitive {
|
|
Some(Global) => global_prefix = true,
|
|
Some(Long) => long = true,
|
|
Some(Outer) => outer = true,
|
|
Some(Protected) => protected = true,
|
|
_ => break,
|
|
}
|
|
// prefixed_command scans the next nonblank, nonrelax command.
|
|
let next = loop {
|
|
let input = self.expanded_non_space(files)?;
|
|
let meaning = self.meaning(&input.token);
|
|
if !matches!(meaning, Meaning::Primitive(Relax))
|
|
&& !Self::suppresses_meaning(&input, &meaning)
|
|
{
|
|
break input.token;
|
|
}
|
|
};
|
|
primitive = self.primitive(&next);
|
|
let meaning = self.meaning(&next);
|
|
if self.state.profile() == Profile::EtexBootstrap
|
|
&& self.read_parameter(Parameter::Tracingcommands).width() > 2
|
|
{
|
|
self.trace_command(&next, files)?;
|
|
}
|
|
if let Meaning::Font(font) = &meaning {
|
|
selected_font = Some(*font);
|
|
}
|
|
key = match meaning {
|
|
Meaning::Count(index) => Some(Key::Count(index)),
|
|
Meaning::Toks(index) => Some(Key::Toks(index)),
|
|
Meaning::TokenParameter(p) => Some(Key::TokenParameter(p)),
|
|
Meaning::Register(register) => Some(Key::Register(register)),
|
|
Meaning::Parameter(p) => Some(Key::Parameter(p)),
|
|
_ => None,
|
|
};
|
|
}
|
|
self.reads.insert(Dependency::GlobalDefs);
|
|
let global = self
|
|
.state
|
|
.global(global_prefix || matches!(primitive, Some(Gdef | Xdef)));
|
|
if (long || protected || outer) && !matches!(primitive, Some(Def | Gdef | Edef | Xdef)) {
|
|
return self.fail("long/protected/outer prefix requires a macro definition");
|
|
}
|
|
if let Some(font) = selected_font {
|
|
self.select_traced_font(font, global, files)?;
|
|
return Ok(());
|
|
}
|
|
match primitive {
|
|
Some(Futurelet) => {
|
|
let name = self.command(files)?;
|
|
let first = self.required_raw(files)?;
|
|
let second = self.required_raw(files)?;
|
|
let meaning = self.meaning(&second.token);
|
|
self.unread(second)?;
|
|
self.unread(first)?;
|
|
self.define_traced(name, meaning, global, files)?;
|
|
}
|
|
Some(Def | Gdef | Edef | Xdef) => self.definition(
|
|
global,
|
|
long,
|
|
protected,
|
|
outer,
|
|
matches!(primitive, Some(Edef | Xdef)),
|
|
files,
|
|
)?,
|
|
Some(Pdffontexpand) => {
|
|
let span = self.current;
|
|
let font = self.font_identifier(files)?;
|
|
self.optional_equals(files)?;
|
|
let stretch = self.integer(files)?;
|
|
let shrink = self.integer(files)?;
|
|
let step = self.integer(files)?;
|
|
let automatic = self.keyword("autoexpand", files)?;
|
|
if automatic {
|
|
self.optional_space(files)?;
|
|
}
|
|
let from = self.source_name(span);
|
|
let defaults = if automatic {
|
|
self.state.font_defaults()
|
|
} else {
|
|
self.font_defaults()
|
|
};
|
|
if self.state
|
|
.fonts
|
|
.configure_expansion(font, &from, (stretch, shrink, step), automatic, defaults, files)
|
|
.map_err(|message| self.error(message, self.current))?
|
|
{
|
|
self.pdf_virtual_fonts
|
|
.propagate_expansion(font, &mut self.state.fonts, defaults, files)
|
|
.map_err(|message| self.error(message, self.current))?;
|
|
}
|
|
}
|
|
Some(Efcode) => {
|
|
let (font, slot) = self.font_character_target(files)?;
|
|
self.optional_equals(files)?;
|
|
let code = self.integer(files)?;
|
|
self.state.fonts.set_expansion_code(font, slot, code);
|
|
}
|
|
Some(Knbccode | Knaccode) => {
|
|
let (font, slot) = self.font_character_target(files)?;
|
|
self.optional_equals(files)?;
|
|
let code = self.integer(files)?;
|
|
self.state.fonts.set_auto_kern_code(font, slot, primitive == Some(Knaccode), code);
|
|
}
|
|
Some(Lpcode | Rpcode) => {
|
|
let (font, slot) = self.protrusion_target(files)?;
|
|
self.optional_equals(files)?;
|
|
let code = self.integer(files)?;
|
|
let right = primitive == Some(Rpcode);
|
|
if self.state.input_profile() == InputProfile::XeTeX {
|
|
self.state.fonts.set_xe_protrusion_code(font, slot, right, code);
|
|
} else {
|
|
self.state.fonts.set_protrusion_code(font, slot as u8, right, code);
|
|
}
|
|
}
|
|
Some(Hyphenchar | Skewchar) => {
|
|
let font = self.font_identifier(files)?;
|
|
self.optional_equals(files)?;
|
|
let value = self.integer(files)?;
|
|
self.finish_text(true)?;
|
|
let mut values = self.state.font_integers(font);
|
|
if primitive == Some(Hyphenchar) {
|
|
values.hyphen = value;
|
|
} else {
|
|
values.skew = value;
|
|
}
|
|
self.state
|
|
.fonts
|
|
.set_integers(font, values)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
}
|
|
Some(Fontdimen) => {
|
|
let (font, n) = self.font_dimension_target(files)?;
|
|
self.optional_equals(files)?;
|
|
let value = self.dimension(false, false, files)?.amount;
|
|
self.state
|
|
.fonts
|
|
.set_fontdimen(font, n, value)
|
|
.map_err(|e| self.error(e, self.current))?;
|
|
}
|
|
Some(Font) => self.define_font(global, files)?,
|
|
Some(Letterspacefont) => self.define_letterspaced_font(global, files)?,
|
|
Some(Textfont | Scriptfont | Scriptscriptfont) => {
|
|
self.math_font_assignment(primitive.unwrap(), global, files)?
|
|
}
|
|
Some(Lccode | Uccode) => {
|
|
let n = self.integer(files)?;
|
|
let c = self.case_character(n)?;
|
|
self.optional_equals(files)?;
|
|
let value = self.integer(files)?;
|
|
self.case_character(value)?;
|
|
let kind = if primitive == Some(Lccode) {
|
|
CaseCode::Lower
|
|
} else {
|
|
CaseCode::Upper
|
|
};
|
|
let equivalent = self.state.case_code(kind, c) == value as u32;
|
|
self.assign_equivalence(
|
|
Key::CaseCode(kind, c),
|
|
global,
|
|
equivalent,
|
|
files,
|
|
|state| {
|
|
state.assign_case_code(kind, c, value as u32, global);
|
|
},
|
|
)?;
|
|
}
|
|
Some(Sfcode) => {
|
|
self.finish_text(true)?;
|
|
let c = self.scan_space_factor_code_index(files)?;
|
|
self.optional_equals(files)?;
|
|
let value = self.integer(files)?;
|
|
if !(0..32768).contains(&value) {
|
|
return self.fail("sfcode must be in 0..32767");
|
|
}
|
|
let equivalent = self.state.space_factor_code(c) == value as u16;
|
|
self.assign_equivalence(Key::Sfcode(c), global, equivalent, files, |state| {
|
|
state.assign_sfcode(c, value as u16, global);
|
|
})?;
|
|
}
|
|
Some(XeTeXcharclass) => self.assign_xe_char_class(global, files)?,
|
|
Some(XeTeXinterchartoks) => self.assign_xe_inter_char_tokens(global, files)?,
|
|
Some(p @ (Delcode | Udelcode | Udelcodenum)) => {
|
|
self.scan_delimiter_code_assignment(p, global, files)?;
|
|
}
|
|
Some(p @ (Mathcode | Umathcode | Umathcodenum)) => {
|
|
self.scan_math_code_assignment(p, global, files)?;
|
|
}
|
|
Some(Parshape) => self.scan_paragraph_shape(global, files)?,
|
|
Some(LinePenalties(kind)) => self.scan_line_penalties(kind, global, files)?,
|
|
Some(Setbox) => {
|
|
if !allow_setbox {
|
|
return self.fail("improper native setbox in an assignment prefix");
|
|
}
|
|
let n = self.register_index(files)?;
|
|
self.optional_equals(files)?;
|
|
if self
|
|
.display
|
|
.as_ref()
|
|
.is_some_and(display::DisplayFrame::has_alignment)
|
|
{
|
|
return self
|
|
.fail("setbox is not allowed after a native alignment in a display");
|
|
}
|
|
self.scan_box(boxes::Destination::Register(n, global), files)?;
|
|
}
|
|
Some(Wd | Ht | Dp | Prevdepth) => {
|
|
self.assign_box_dimension(primitive.unwrap(), files)?
|
|
}
|
|
Some(Prevgraf) => {
|
|
self.optional_equals(files)?;
|
|
let count = self.integer(files)?;
|
|
self.vertical.previous_lines = usize::try_from(count)
|
|
.map_err(|_| self.error("Bad \\prevgraf", self.current))?;
|
|
}
|
|
Some(p) if p.page_dimension().is_some() => {
|
|
self.optional_equals(files)?;
|
|
let value = self.dimension(false, false, files)?.amount;
|
|
self.native_page_mut()?.dimensions[p.page_dimension().unwrap()] = i64::from(value);
|
|
}
|
|
Some(Batchmode | Nonstopmode | Scrollmode | Errorstopmode) => {
|
|
let mode = match primitive {
|
|
Some(Batchmode) => 0,
|
|
Some(Nonstopmode) => 1,
|
|
Some(Scrollmode) => 2,
|
|
_ => 3,
|
|
};
|
|
self.change_interaction_mode(mode, files)?;
|
|
}
|
|
Some(Interactionmode) => {
|
|
self.optional_equals(files)?;
|
|
let mode = self.integer(files)?;
|
|
if !(0..=3).contains(&mode) {
|
|
return self.fail("interactionmode must be in 0..3");
|
|
}
|
|
self.change_interaction_mode(mode as u8, files)?;
|
|
}
|
|
Some(Deadcycles) => {
|
|
self.optional_equals(files)?;
|
|
let value = self.integer(files)?;
|
|
self.native_page_mut()?.dead_cycles = value;
|
|
}
|
|
Some(Insertpenalties) => {
|
|
self.optional_equals(files)?;
|
|
let value = self.integer(files)?;
|
|
self.native_page_mut()?.insertions.penalties = value;
|
|
}
|
|
None if matches!(key, Some(Key::Parameter(_))) => {
|
|
let Some(Key::Parameter(p)) = key else {
|
|
unreachable!()
|
|
};
|
|
self.optional_equals(files)?;
|
|
let value = if let Some(kind) = p.kind() {
|
|
ParameterValue::Quantity(self.quantity(kind, files)?)
|
|
} else {
|
|
ParameterValue::Integer(self.integer(files)?)
|
|
};
|
|
self.assign_traced_parameter(p, value, global, files)?;
|
|
}
|
|
Some(Let) => {
|
|
let name = self.command(files)?;
|
|
let mut value = self.raw_non_space(files)?;
|
|
if value.token.kind == TokenKind::Character('=', CatCode::Other) {
|
|
value = self.required_raw(files)?;
|
|
if value.token.kind.is_space() {
|
|
value = self.required_raw(files)?;
|
|
}
|
|
}
|
|
let meaning = self.meaning(&value.token);
|
|
self.define_traced(name, meaning, global, files)?;
|
|
}
|
|
Some(Catcode) => {
|
|
let value = self.integer(files)?;
|
|
self.check_input_character(value)?;
|
|
let character = u32::try_from(value)
|
|
.ok()
|
|
.and_then(char::from_u32)
|
|
.ok_or_else(|| self.error("invalid catcode character number", self.current))?;
|
|
self.optional_equals(files)?;
|
|
let code = self.integer(files)?;
|
|
let code = CatCode::from_number(code)
|
|
.ok_or_else(|| self.error("catcode must be in 0..15", self.current))?;
|
|
let equivalent = self.state.catcode(character) == code;
|
|
self.assign_equivalence(
|
|
Key::Catcode(character),
|
|
global,
|
|
equivalent,
|
|
files,
|
|
|state| {
|
|
state.assign_catcode(character, code, global);
|
|
},
|
|
)?;
|
|
}
|
|
Some(
|
|
p @ (Chardef | Mathchardef | Umathchardef | Umathcharnumdef
|
|
| Countdef | Toksdef | Dimendef | Skipdef | Muskipdef),
|
|
) => {
|
|
self.define_shorthand(p, global, files)?;
|
|
}
|
|
Some(Dimen | Skip | Muskip) => {
|
|
let register = self.scan_register(primitive.unwrap(), files)?;
|
|
self.assign_quantity(register, global, files)?;
|
|
}
|
|
None if matches!(key, Some(Key::Register(_))) => {
|
|
let Some(Key::Register(register)) = key else {
|
|
unreachable!()
|
|
};
|
|
self.assign_quantity(register, global, files)?;
|
|
}
|
|
Some(Toks) => {
|
|
let index = self.register_index(files)?;
|
|
self.assign_toks(index, global, files)?;
|
|
}
|
|
None if matches!(key, Some(Key::TokenParameter(_))) => {
|
|
let Some(Key::TokenParameter(p)) = key else {
|
|
unreachable!()
|
|
};
|
|
let (mut tokens, braces) = self.scan_token_list_value_details(files)?;
|
|
if p == TokenParameter::Output && !tokens.is_empty() {
|
|
if let Some((open, close)) = braces {
|
|
tokens.insert(
|
|
0,
|
|
Token::new(TokenKind::Character('{', CatCode::BeginGroup), open),
|
|
);
|
|
tokens.push(Token::new(
|
|
TokenKind::Character('}', CatCode::EndGroup),
|
|
close,
|
|
));
|
|
}
|
|
}
|
|
let equivalent = tokens.is_empty() && self.state.token_parameter(p).is_none();
|
|
self.assign_equivalence(
|
|
Key::TokenParameter(p),
|
|
global,
|
|
equivalent,
|
|
files,
|
|
|state| {
|
|
state.assign_token_parameter(p, tokens, global);
|
|
},
|
|
)?;
|
|
}
|
|
None if matches!(key, Some(Key::Toks(_))) => {
|
|
let Some(Key::Toks(index)) = key else {
|
|
unreachable!()
|
|
};
|
|
self.assign_toks(index, global, files)?;
|
|
}
|
|
Some(Read | Readline) => {
|
|
self.read_stream(global, primitive == Some(Readline), files)?
|
|
}
|
|
Some(Advance | Multiply | Divide) => {
|
|
let next = self.expanded_non_space(files)?;
|
|
if let Meaning::Parameter(p) = self.meaning(&next.token)
|
|
&& p.kind().is_some()
|
|
{
|
|
self.parameter_arithmetic(p, primitive.unwrap(), global, files)?;
|
|
return Ok(());
|
|
}
|
|
let register = match self.meaning(&next.token) {
|
|
Meaning::Register(r) => Some(r),
|
|
Meaning::Primitive(p @ (Dimen | Skip | Muskip)) => {
|
|
Some(self.scan_register(p, files)?)
|
|
}
|
|
_ => {
|
|
self.unread(next)?;
|
|
None
|
|
}
|
|
};
|
|
if let Some(register) = register {
|
|
self.register_arithmetic(register, primitive.unwrap(), global, files)?;
|
|
return Ok(());
|
|
}
|
|
let key = self.integer_variable(files)?;
|
|
if matches!(
|
|
key,
|
|
Key::Catcode(_) | Key::Mathcode(_) | Key::Mathcodenum(_) | Key::Sfcode(_)
|
|
| Key::Delcode(_) | Key::Delcodenum(_) | Key::CaseCode(_, _)
|
|
) {
|
|
return self.fail("expected assignable integer register, not a code table");
|
|
}
|
|
if key == Key::Spacefactor {
|
|
return self.fail(
|
|
"spacefactor is mode state, not an arithmetic register or parameter",
|
|
);
|
|
}
|
|
self.optional_by(files)?;
|
|
let value = self.integer(files)? as i64;
|
|
let old = self.read_integer(&key)? as i64;
|
|
let value = match primitive {
|
|
Some(Advance) => old + value,
|
|
Some(Multiply) => old * value,
|
|
_ if value != 0 => old / value,
|
|
_ => return self.fail("division by zero"),
|
|
};
|
|
let value = self.bounded(value)?;
|
|
self.assign_integer_target(key, value, global, files)?;
|
|
}
|
|
Some(
|
|
Count | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time | Day | Month
|
|
| Year | Spacefactor,
|
|
)
|
|
| None
|
|
if primitive.is_some() || key.is_some() =>
|
|
{
|
|
let key = match primitive {
|
|
Some(Count) => Key::Count(self.register_index(files)?),
|
|
Some(Endlinechar) => Key::Endlinechar,
|
|
Some(Newlinechar) => Key::Newlinechar,
|
|
Some(Escapechar) => Key::Escapechar,
|
|
Some(Globaldefs) => Key::Globaldefs,
|
|
Some(Time) => Key::Job(JobParameter::Time),
|
|
Some(Day) => Key::Job(JobParameter::Day),
|
|
Some(Month) => Key::Job(JobParameter::Month),
|
|
Some(Year) => Key::Job(JobParameter::Year),
|
|
Some(Spacefactor) => Key::Spacefactor,
|
|
_ => key.unwrap(),
|
|
};
|
|
self.optional_equals(files)?;
|
|
let value = self.integer(files)?;
|
|
self.assign_integer_target(key, value, global, files)?;
|
|
}
|
|
_ => {
|
|
return self.fail(format!(
|
|
"unsupported native assignment or primitive: {primitive:?}"
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn scan_token_list_value(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<Vec<Token>, Error> {
|
|
Ok(self.scan_token_list_value_details(files)?.0)
|
|
}
|
|
fn scan_token_list_value_details(
|
|
&mut self,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(Vec<Token>, Option<(Span, Span)>), Error> {
|
|
self.optional_equals(files)?;
|
|
let next = loop {
|
|
let t = self.expanded_non_space(files)?;
|
|
if self.primitive(&t.token) != Some(Primitive::Relax) {
|
|
break t;
|
|
}
|
|
};
|
|
let mut braces = None;
|
|
let body = match self.meaning(&next.token) {
|
|
Meaning::TokenParameter(p) => {
|
|
self.reads.insert(Dependency::TokenParameter(p));
|
|
self.state
|
|
.token_parameter(p)
|
|
.map_or_else(Vec::new, |t| t.to_vec())
|
|
}
|
|
Meaning::Toks(other) => {
|
|
self.reads.insert(Dependency::Toks(other));
|
|
self.state.tokens(other)
|
|
}
|
|
Meaning::Primitive(Primitive::XeTeXinterchartoks) => {
|
|
let index = self.xe_inter_char_index(files)?;
|
|
self.read_xe_inter_char_tokens(index)
|
|
.map_or_else(Vec::new, |tokens| tokens.to_vec())
|
|
}
|
|
Meaning::Primitive(Primitive::Toks) => {
|
|
let other = self.register_index(files)?;
|
|
self.reads.insert(Dependency::Toks(other));
|
|
self.state.tokens(other)
|
|
}
|
|
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup)) => {
|
|
let body = self.with_scanner(ScannerStatus::Absorbing, |s| s.after_open(files))?;
|
|
braces = Some((next.token.span, self.current));
|
|
body
|
|
}
|
|
_ => return self.fail("expected token list or token register"),
|
|
};
|
|
Ok((body, braces))
|
|
}
|
|
fn assign_toks(
|
|
&mut self,
|
|
index: u16,
|
|
global: bool,
|
|
files: &mut impl SourceProvider,
|
|
) -> Result<(), Error> {
|
|
let body = self.scan_token_list_value(files)?;
|
|
self.reads.insert(Dependency::GlobalDefs);
|
|
let global = self.state.global(global);
|
|
let equivalent = body.is_empty() && self.state.tokens(index).is_empty();
|
|
self.assign_equivalence(Key::Toks(index), global, equivalent, files, |state| {
|
|
state.assign_tokens(index, body, global);
|
|
})
|
|
}
|
|
}
|