Initial texrra engine
Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture.
This commit is contained in:
commit
bb1d9e0561
147 files changed
+66719
No files matched your search
Vendored
+354
@@ -0,0 +1,354 @@
|
||||
use common::Scaled;
|
||||
|
||||
use super::keyword::parse_keyword;
|
||||
use crate::prelude as txl;
|
||||
use crate::token::Value;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
impl Parsable for Scaled {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(value) = S::scan_dimension(input)? {
|
||||
return Ok(value);
|
||||
}
|
||||
scan_dimen(input, None)
|
||||
}
|
||||
}
|
||||
|
||||
// TeX.2021.448 scan_dimen with:
|
||||
//
|
||||
// - shortcut=false
|
||||
// - the inf parameter is replaced by an optional pointer to a glue order
|
||||
pub(crate) fn scan_dimen<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
glue_order: Option<&mut common::GlueOrder>,
|
||||
) -> txl::Result<common::Scaled> {
|
||||
let negative = match super::integer::parse_optional_signs(input)? {
|
||||
None => 1,
|
||||
Some(_) => -1,
|
||||
};
|
||||
let first_token = input.next_or_err(DimenEndOfInputError {})?;
|
||||
let (negative, integer_part, fractional_part) = match first_token.value() {
|
||||
Value::CommandRef(command_ref) => {
|
||||
// TeX.2021.449
|
||||
use super::integer::InternalNumber;
|
||||
match super::integer::parse_internal_number(input, first_token, command_ref)? {
|
||||
InternalNumber::Integer(i) => (negative * i.signum(), i.abs(), Scaled::ZERO),
|
||||
InternalNumber::Dimen(d) => {
|
||||
return Ok(d * negative);
|
||||
}
|
||||
InternalNumber::Glue(g) => {
|
||||
return Ok(g.width * negative);
|
||||
}
|
||||
InternalNumber::MuGlue(_) => {
|
||||
input.error(parse::Error::new(
|
||||
"a dimension or ordinary glue value",
|
||||
Some(first_token),
|
||||
"a muskip value cannot be used as a dimension",
|
||||
))?;
|
||||
return Ok(Scaled::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let (i, f) = scan_constant_dimen(input, first_token)?;
|
||||
(negative, i, f)
|
||||
}
|
||||
};
|
||||
Ok(scan_and_apply_units(
|
||||
input,
|
||||
first_token,
|
||||
integer_part,
|
||||
fractional_part,
|
||||
glue_order,
|
||||
)? * negative)
|
||||
}
|
||||
|
||||
/// Part of TeX.2021.448
|
||||
pub(crate) fn scan_constant_dimen<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
) -> txl::Result<(i32, common::Scaled)> {
|
||||
Ok(match first_token.value() {
|
||||
Value::Other(',' | '.') => (0, scan_decimal_fraction(input)?),
|
||||
_ => {
|
||||
input.back(first_token);
|
||||
let (_, i, radix) = super::integer::parse_integer(input)?;
|
||||
// We scan for a fractional part if the integer was an decimal constant
|
||||
// and the next token is a period or comma.
|
||||
let fractional_part = if radix == Some(10) {
|
||||
match input.next()? {
|
||||
Some(next) => match next.value() {
|
||||
Value::Other(',' | '.') => scan_decimal_fraction(input)?,
|
||||
_ => {
|
||||
input.back(next);
|
||||
Scaled::ZERO
|
||||
}
|
||||
},
|
||||
None => Scaled::ZERO,
|
||||
}
|
||||
} else {
|
||||
Scaled::ZERO
|
||||
};
|
||||
(i, fractional_part)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// TeX.2021.453
|
||||
pub(crate) fn scan_and_apply_units<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
integer_part: i32,
|
||||
fractional_part: Scaled,
|
||||
glue_order: Option<&mut common::GlueOrder>,
|
||||
) -> txl::Result<common::Scaled> {
|
||||
// todo: scan spaces and non-call tokens
|
||||
|
||||
// First try to scan for infinite units, if this is the stretch
|
||||
// or shrink of a glue.
|
||||
if let Some(glue_order) = glue_order {
|
||||
if parse_keyword(input, "fil")? {
|
||||
*glue_order = common::GlueOrder::Fil;
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Letter('l' | 'L') => match glue_order.next() {
|
||||
None => {
|
||||
input.error(fillll_error(token))?;
|
||||
}
|
||||
Some(o) => *glue_order = o,
|
||||
},
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
super::OptionalSpace::parse(input)?;
|
||||
return match Scaled::from_integer(integer_part) {
|
||||
Ok(integer_part) => Ok(integer_part + fractional_part),
|
||||
Err(_) => handle_overflow(input, first_token, false),
|
||||
};
|
||||
}
|
||||
}
|
||||
// Then try to scan from an internal number.
|
||||
// TeX.2021.455
|
||||
if let Some(next) = input.next()? {
|
||||
let v_or = match next.value() {
|
||||
Value::CommandRef(command_ref) => {
|
||||
use super::integer::InternalNumber;
|
||||
Some(
|
||||
match super::integer::parse_internal_number(input, next, command_ref)? {
|
||||
// TeX silently interprets an integer as sp points in this position
|
||||
InternalNumber::Integer(i) => Scaled(i),
|
||||
InternalNumber::Dimen(scaled) => scaled,
|
||||
InternalNumber::Glue(glue) => glue.width,
|
||||
InternalNumber::MuGlue(_) => {
|
||||
input.error(parse::Error::new(
|
||||
"a dimension or ordinary glue value",
|
||||
Some(next),
|
||||
"a muskip value cannot be used as a dimension",
|
||||
))?;
|
||||
Scaled::ZERO
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
input.back(next);
|
||||
if parse_keyword(input, "em")? {
|
||||
super::OptionalSpace::parse(input)?;
|
||||
Some(input.state().em_width())
|
||||
} else if parse_keyword(input, "ex")? {
|
||||
super::OptionalSpace::parse(input)?;
|
||||
Some(input.state().ex_height())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(v) = v_or {
|
||||
let adjusted_fractional_part = v
|
||||
.xn_over_d(fractional_part.0, Scaled::ONE.0)
|
||||
.expect("n<d=Scaled::ONE, so overflow can't occur");
|
||||
return match v.nx_plus_y(integer_part, adjusted_fractional_part.0) {
|
||||
Ok(s) => Ok(s),
|
||||
Err(_) => handle_overflow(input, first_token, v < Scaled::ZERO),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Potentially adjust for the magnification ratio.
|
||||
if parse_keyword(input, "true")? {
|
||||
// TeX.2021.457
|
||||
// TODO
|
||||
}
|
||||
|
||||
// Finally try to scan unit constants.
|
||||
let scaled_unit = <common::ScaledUnit as Parsable>::parse(input)?;
|
||||
super::OptionalSpace::parse(input)?;
|
||||
match Scaled::new(integer_part, fractional_part, scaled_unit) {
|
||||
Ok(s) => Ok(s),
|
||||
Err(_) => handle_overflow(input, first_token, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_overflow<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
neg: bool,
|
||||
) -> txl::Result<common::Scaled> {
|
||||
input.error(
|
||||
parse::Error::new(
|
||||
"a dimension in the range (-2^14pt,2^14pt)",
|
||||
Some(first_token),
|
||||
"",
|
||||
)
|
||||
.with_got_override("a dimension that's too large"),
|
||||
)?;
|
||||
Ok(if neg {
|
||||
-common::Scaled::MAX_DIMEN
|
||||
} else {
|
||||
common::Scaled::MAX_DIMEN
|
||||
})
|
||||
}
|
||||
|
||||
fn fillll_error(token: token::Token) -> parse::Error {
|
||||
parse::Error::new("an infinite glue stretch or shrink order", Some(token), "")
|
||||
.with_got_override("too many l characters")
|
||||
}
|
||||
|
||||
impl Parsable for common::ScaledUnit {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
use common::ScaledUnit;
|
||||
for (keyword, unit) in [
|
||||
("pt", ScaledUnit::Point),
|
||||
("in", ScaledUnit::Inch),
|
||||
("pc", ScaledUnit::Pica),
|
||||
("cm", ScaledUnit::Centimeter),
|
||||
("mm", ScaledUnit::Millimeter),
|
||||
("bp", ScaledUnit::BigPoint),
|
||||
("dd", ScaledUnit::DidotPoint),
|
||||
("cc", ScaledUnit::Cicero),
|
||||
("sp", ScaledUnit::ScaledPoint),
|
||||
] {
|
||||
if parse_keyword(input, keyword)? {
|
||||
return Ok(unit);
|
||||
}
|
||||
}
|
||||
input.error(error::TODO())?;
|
||||
Ok(common::ScaledUnit::Point)
|
||||
}
|
||||
}
|
||||
|
||||
/// TeX.2021.452
|
||||
fn scan_decimal_fraction<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Scaled> {
|
||||
// We only get up to 17 digits, because further digits won't affect the result given
|
||||
// that the smallest scaled number is 2^(-16). This is very nice because it means
|
||||
// we don't need to allocate a vector to store the digits.
|
||||
let mut digits = [0_u8; 17];
|
||||
let mut i = 0_usize;
|
||||
while let Some(token) = input.next()? {
|
||||
let d: u8 = match token.value() {
|
||||
Value::Other('0') => 0,
|
||||
Value::Other('1') => 1,
|
||||
Value::Other('2') => 2,
|
||||
Value::Other('3') => 3,
|
||||
Value::Other('4') => 4,
|
||||
Value::Other('5') => 5,
|
||||
Value::Other('6') => 6,
|
||||
Value::Other('7') => 7,
|
||||
Value::Other('8') => 8,
|
||||
Value::Other('9') => 9,
|
||||
Value::Space(_) => {
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
};
|
||||
if let Some(digit) = digits.get_mut(i) {
|
||||
*digit = d;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok(Scaled::from_decimal_digits(&digits[0..i]))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DimenEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for DimenEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a dimension".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {}
|
||||
|
||||
parse_success_tests![
|
||||
(zero_pt, "0pt", Scaled::ZERO),
|
||||
(one_pt, "1pt", Scaled::ONE),
|
||||
(one_pt_negative, "-1pt", -Scaled::ONE),
|
||||
(two_pt, "2pt", Scaled::TWO),
|
||||
(empty_point, ".pt", Scaled::ZERO), // TeX.2021.452
|
||||
(fraction_1, "0.5pt", Scaled::from_decimal_digits(&[5])),
|
||||
(fraction_2, "-0.5pt", -Scaled::from_decimal_digits(&[5])),
|
||||
(
|
||||
fraction_3,
|
||||
"1.5pt",
|
||||
Scaled::ONE + Scaled::from_decimal_digits(&[5])
|
||||
),
|
||||
(
|
||||
fraction_4,
|
||||
"-1.5pt",
|
||||
-Scaled::ONE - Scaled::from_decimal_digits(&[5])
|
||||
),
|
||||
(units_in_1, "1in", (Scaled::ONE * 7227) / 100),
|
||||
(units_in_2, "1 in", (Scaled::ONE * 7227) / 100),
|
||||
(units_in_3, "0.075in", Scaled(355207)),
|
||||
(units_pc, "1pc", Scaled::ONE * 12),
|
||||
(units_cm, "1cm", (Scaled::ONE * 7227) / 254),
|
||||
(units_mm, "1mm", (Scaled::ONE * 7227) / 2540),
|
||||
(units_bp, "1bp", (Scaled::ONE * 7227) / 7200),
|
||||
(units_dd, "1dd", (Scaled::ONE * 1238) / 1157),
|
||||
(units_cc, "1cc", (Scaled::ONE * 14856) / 1157),
|
||||
(units_sp_1, "1sp", Scaled(1)),
|
||||
(units_sp_2, "1.999999sp", Scaled(1)),
|
||||
(nearly_overflow_pt, "16383.99998pt", Scaled::MAX_DIMEN,),
|
||||
// (2^30-1) * d / (n * 2^16)
|
||||
// (2^30-1) * d / (n * 2^16)
|
||||
// (nearly_overflow_in, "226.705406in", Scaled::MAX_DIMEN ),
|
||||
(nearly_overflow_sp_1, "1073741823sp", Scaled::MAX_DIMEN,),
|
||||
(
|
||||
nearly_overflow_sp_2,
|
||||
"1073741823.99999999sp",
|
||||
Scaled::MAX_DIMEN,
|
||||
)
|
||||
];
|
||||
|
||||
parse_failure_tests!(
|
||||
Scaled,
|
||||
State,
|
||||
(invalid_unit, "1xy", Scaled::ONE),
|
||||
(overflow_pt, "16384pt", Scaled::MAX_DIMEN),
|
||||
(overflow_pt_neg, "-16384pt", -Scaled::MAX_DIMEN),
|
||||
(overflow_in_1, "300in", Scaled::MAX_DIMEN),
|
||||
(overflow_in_2, "300000000in", Scaled::MAX_DIMEN),
|
||||
(overflow_in_3, "-300in", -Scaled::MAX_DIMEN),
|
||||
(overflow_in_4, "-300000000in", -Scaled::MAX_DIMEN),
|
||||
(overflow_sp, "1073741824sp", Scaled::MAX_DIMEN),
|
||||
(overflow_sp_neg, "-1073741824sp", -Scaled::MAX_DIMEN),
|
||||
);
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
//! File locations
|
||||
//!
|
||||
//! See section 511 of the TeXBook.
|
||||
|
||||
use std::path;
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
/// Representation of a file location in TeX
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
pub struct FileLocation {
|
||||
pub path: String,
|
||||
pub extension: Option<String>,
|
||||
pub area: Option<String>,
|
||||
}
|
||||
|
||||
impl Parsable for FileLocation {
|
||||
// scan_file_name
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let mut raw_string = String::new();
|
||||
let mut area_delimiter = None;
|
||||
let mut ext_delimiter = None;
|
||||
loop {
|
||||
let t = match input.next()? {
|
||||
None => break,
|
||||
Some(t) => t,
|
||||
};
|
||||
if let token::Value::Space(_) = t.value() {
|
||||
break;
|
||||
}
|
||||
let c = match t.char() {
|
||||
None => {
|
||||
input.back(t);
|
||||
break;
|
||||
}
|
||||
Some(c) => c,
|
||||
};
|
||||
match c {
|
||||
'>' | ':' => {
|
||||
area_delimiter = Some(raw_string.len() + 1);
|
||||
ext_delimiter = None;
|
||||
}
|
||||
'.' => {
|
||||
ext_delimiter = Some(raw_string.len());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
raw_string.push(c);
|
||||
}
|
||||
|
||||
Ok(FileLocation {
|
||||
path: raw_string
|
||||
[area_delimiter.unwrap_or(0)..ext_delimiter.unwrap_or(raw_string.len())]
|
||||
.into(),
|
||||
extension: ext_delimiter.map(|j| raw_string[j + 1..].into()),
|
||||
area: area_delimiter.map(|i| raw_string[..i].into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl FileLocation {
|
||||
pub fn determine_full_path(
|
||||
&self,
|
||||
working_directory: Option<&path::Path>,
|
||||
default_extension: &str,
|
||||
) -> path::PathBuf {
|
||||
let mut path: path::PathBuf = match self.area {
|
||||
None => match working_directory {
|
||||
None => Default::default(),
|
||||
Some(working_directory) => working_directory.into(),
|
||||
},
|
||||
Some(_) => {
|
||||
// TODO: support file areas.
|
||||
// Probably we just need to extend the vm::FileSystem trait to accept areas.
|
||||
// Then in production TeX engines, we provide a map of areas to base path for
|
||||
// that area. There is still an error case when an undefined area is referenced.
|
||||
panic!("Texlang does not have support for file areas yet");
|
||||
}
|
||||
};
|
||||
path.push(std::ffi::OsString::from(&self.path));
|
||||
path.set_extension(std::ffi::OsString::from(
|
||||
self.extension.as_deref().unwrap_or(default_extension),
|
||||
));
|
||||
if !path.is_absolute() {
|
||||
panic!("TODO: handle this error (path is relative and no working directory set)");
|
||||
}
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
parse_success_tests![
|
||||
(
|
||||
path_only,
|
||||
"path/to/file",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_only_newline,
|
||||
"path/to/file\n",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_only_control_sequence,
|
||||
r"path/to/file\relax more",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_only_trailing_word,
|
||||
"path/to/file something",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
extension_only,
|
||||
".tex",
|
||||
FileLocation {
|
||||
path: "".to_string(),
|
||||
extension: Some("tex".to_string()),
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
empty,
|
||||
"",
|
||||
FileLocation {
|
||||
path: "".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_extension,
|
||||
"path/to/file.tex",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: Some("tex".to_string()),
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_area_with_langle,
|
||||
"area>path/to/file",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: Some("area>".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_area_with_colon,
|
||||
"area:path/to/file",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: Some("area:".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
area_only,
|
||||
"area:",
|
||||
FileLocation {
|
||||
path: "".to_string(),
|
||||
extension: None,
|
||||
area: Some("area:".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_extension_and_area_with_colon,
|
||||
"area:path/to/file.tex",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: Some("tex".to_string()),
|
||||
area: Some("area:".to_string()),
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
use common::{Glue, Scaled};
|
||||
|
||||
use super::keyword::parse_keyword;
|
||||
use crate::prelude as txl;
|
||||
use crate::token::Value;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
impl Parsable for Glue {
|
||||
// TeX.2021.461
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(value) = S::scan_glue(input)? {
|
||||
return Ok(value);
|
||||
}
|
||||
let negative = match super::integer::parse_optional_signs(input)? {
|
||||
None => 1,
|
||||
Some(_) => -1,
|
||||
};
|
||||
let first_token = input.next_or_err(GlueEndOfInputError {})?;
|
||||
let width = match first_token.value() {
|
||||
Value::CommandRef(command_ref) => {
|
||||
use super::integer::InternalNumber;
|
||||
match super::integer::parse_internal_number(input, first_token, command_ref)? {
|
||||
InternalNumber::Integer(i) => {
|
||||
super::dimen::scan_and_apply_units(
|
||||
input,
|
||||
first_token,
|
||||
i.abs(),
|
||||
Scaled::ZERO,
|
||||
None,
|
||||
)? * negative
|
||||
* i.signum()
|
||||
}
|
||||
InternalNumber::Dimen(d) => d * negative,
|
||||
InternalNumber::Glue(g) => {
|
||||
return Ok(g * negative);
|
||||
}
|
||||
InternalNumber::MuGlue(g) => {
|
||||
input.error(parse::Error::new(
|
||||
"ordinary glue",
|
||||
Some(first_token),
|
||||
"a muskip value cannot be used as an ordinary skip",
|
||||
))?;
|
||||
return Ok(g.0 * 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
input.back(first_token);
|
||||
common::Scaled::parse(input)? * negative
|
||||
}
|
||||
};
|
||||
|
||||
let mut g = Glue {
|
||||
width,
|
||||
..Default::default()
|
||||
};
|
||||
if parse_keyword(input, "plus")? {
|
||||
g.stretch = super::dimen::scan_dimen(input, Some(&mut g.stretch_order))?
|
||||
}
|
||||
if parse_keyword(input, "minus")? {
|
||||
g.shrink = super::dimen::scan_dimen(input, Some(&mut g.shrink_order))?
|
||||
};
|
||||
Ok(g)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GlueEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for GlueEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a glue".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
use common::GlueOrder;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {}
|
||||
|
||||
parse_success_tests![
|
||||
(
|
||||
width_1,
|
||||
"0pt",
|
||||
Glue {
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
width_2,
|
||||
"1pt",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
width_3,
|
||||
"-1pt",
|
||||
Glue {
|
||||
width: -Scaled::ONE,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_1,
|
||||
"1pt plus 1pt",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_fil,
|
||||
"1pt plus 1fil",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
stretch_order: GlueOrder::Fil,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_fill,
|
||||
"1pt plus 1fill",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
stretch_order: GlueOrder::Fill,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_filll,
|
||||
"1pt plus 1filll",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
stretch_order: GlueOrder::Filll,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
];
|
||||
|
||||
parse_failure_tests!(
|
||||
Glue,
|
||||
State,
|
||||
(
|
||||
stretch_overflow_1,
|
||||
"1pt plus 30000000fil",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::MAX_DIMEN,
|
||||
stretch_order: GlueOrder::Fil,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_overflow_2,
|
||||
"1pt plus -30000000fil",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: -Scaled::MAX_DIMEN,
|
||||
stretch_order: GlueOrder::Fil,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_fillll,
|
||||
"1pt plus 2fillll",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE * 2,
|
||||
stretch_order: GlueOrder::Filll,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
);
|
||||
}
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
macro_rules! get_required_element {
|
||||
($stream :expr, $expected: expr, $guidance: expr, $($pat:pat => $result:expr,)+) => {
|
||||
// TODO: probably should call get_optional_element_with_token
|
||||
match ($stream).next()? {
|
||||
Some(token) => match token.value() {
|
||||
$(
|
||||
$pat => {
|
||||
Some($result)
|
||||
},
|
||||
)+
|
||||
_ => {
|
||||
$stream.error(crate::parse::Error::new($expected, Some(token), $guidance))?;
|
||||
$stream.back(token);
|
||||
None
|
||||
},
|
||||
}
|
||||
None => {
|
||||
$stream.error(crate::parse::Error::new($expected, None, $guidance))?;
|
||||
None
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! get_optional_element {
|
||||
($stream :expr, $($pat:pat => $result:expr,)+) => {
|
||||
match ($stream).next()? {
|
||||
None => None,
|
||||
Some(token) => match token.value() {
|
||||
$(
|
||||
$pat => Some($result),
|
||||
)+
|
||||
_ => {
|
||||
$stream.back(token);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! get_optional_element_with_token {
|
||||
($stream :expr, $($pat:pat => $result:expr,)+) => {
|
||||
match ($stream).next()? {
|
||||
None => None,
|
||||
Some(token) => match token.value() {
|
||||
$(
|
||||
$pat => {
|
||||
Some(($result, token))
|
||||
},
|
||||
)+
|
||||
_ => {
|
||||
$stream.back(token);
|
||||
None
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Vendored
+588
@@ -0,0 +1,588 @@
|
||||
//! Number parsing.
|
||||
//!
|
||||
//! The number may be octal, decimal, hexadecimal, cast from a character token, or read
|
||||
//! from an internal registers. The full definition of a number in the TeX grammar
|
||||
//! is given on page X of the TeXBook.
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::token::{CommandRef, Value};
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
impl Parsable for i32 {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(value) = S::scan_integer(input)? {
|
||||
return Ok(value);
|
||||
}
|
||||
let (_, i, _) = parse_integer(input)?;
|
||||
Ok(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for u8 {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let u = Uint::<256>::parse_impl(input)?;
|
||||
Ok(u.0.try_into().expect("smaller than 256 so in range"))
|
||||
}
|
||||
}
|
||||
/// When parsed, this type returns a nonnegative integer with the provided upper bound.
|
||||
///
|
||||
/// This type is used to implement the following parsing logic in TeX:
|
||||
///
|
||||
/// - TeX.2021.433 (scan_eight_bit_int) where N=256.
|
||||
/// - TeX.2021.434 (scan_char_num) where N=256.
|
||||
/// - TeX.2021.435 (scan_four_bit_int) where N=16.
|
||||
/// - TeX.2021.436 (scan_fifteen_bit_int) where N=2^15.
|
||||
/// - TeX.2021.437 (scan_twenty_seven_bit_int) where N=2^27.
|
||||
#[derive(Debug, PartialEq, Eq, Default)]
|
||||
pub struct Uint<const N: usize>(pub usize);
|
||||
|
||||
impl Uint<0> {
|
||||
pub const MAX: usize = i32::MAX as usize;
|
||||
}
|
||||
|
||||
impl<const N: usize> Parsable for Uint<N> {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let (first_token, i, _) = parse_integer(input)?;
|
||||
if i < 0 || i as usize >= N {
|
||||
input.error(OutOfBoundsError::<N> {
|
||||
first_token,
|
||||
got: i,
|
||||
})?;
|
||||
Ok(Uint(0))
|
||||
} else {
|
||||
Ok(Uint(i as usize))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OutOfBoundsError<const N: usize> {
|
||||
first_token: token::Token,
|
||||
got: i32,
|
||||
}
|
||||
|
||||
impl<const N: usize> error::TexError for OutOfBoundsError<N> {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::Token(self.first_token)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
format!(
|
||||
"expected an integer in the range [0, {}), got {}",
|
||||
N, self.got
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for char {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let u1 = Uint::<{ char::MAX as usize }>::parse(input)?;
|
||||
let u2: u32 = u1.0.try_into().unwrap();
|
||||
Ok(char::from_u32(u2).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move to types/catcode.rs
|
||||
impl Parsable for types::CatCode {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let (token, i, _) = parse_integer(input)?;
|
||||
if let Ok(val_u8) = u8::try_from(i) {
|
||||
if let Ok(cat_code) = types::CatCode::try_from(val_u8) {
|
||||
return Ok(cat_code);
|
||||
}
|
||||
}
|
||||
input.error(parse::Error {
|
||||
expected: "a category code number (an integer in the range [0, 15])".into(),
|
||||
got: Some(token),
|
||||
got_override: format!["got the integer {i}"],
|
||||
annotation_override: "this is where the number started".into(),
|
||||
guidance: "".into(),
|
||||
additional_notes: vec![],
|
||||
})?;
|
||||
Ok(types::CatCode::try_from(0).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
const GUIDANCE_BEGINNING: &str =
|
||||
"a number begins with zero or more minus signs followed by one of the following:
|
||||
- A decimal digit (0-9), which begins a decimal number.
|
||||
- The character ', which indicates the beginning of an octal number
|
||||
- The character \", which indicates the beginning of a hexadecimal number
|
||||
- The character `, followed by a character token. The character is converted into its UTF-8 number.
|
||||
- A command that references a variable, like \\year.
|
||||
";
|
||||
|
||||
/// TeX.2021.440 (scan_int)
|
||||
pub(crate) fn parse_integer<S: TexlangState>(
|
||||
stream: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<(token::Token, i32, Option<u8>)> {
|
||||
let sign = parse_optional_signs(stream)?;
|
||||
let first_token = stream.next_or_err(NumberEndOfInputError {})?;
|
||||
let (result, radix) = match first_token.value() {
|
||||
Value::Other('0') => (parse_constant::<S, 10>(stream, 0)?, Some(10_u8)),
|
||||
Value::Other('1') => (parse_constant::<S, 10>(stream, 1)?, Some(10_u8)),
|
||||
Value::Other('2') => (parse_constant::<S, 10>(stream, 2)?, Some(10_u8)),
|
||||
Value::Other('3') => (parse_constant::<S, 10>(stream, 3)?, Some(10_u8)),
|
||||
Value::Other('4') => (parse_constant::<S, 10>(stream, 4)?, Some(10_u8)),
|
||||
Value::Other('5') => (parse_constant::<S, 10>(stream, 5)?, Some(10_u8)),
|
||||
Value::Other('6') => (parse_constant::<S, 10>(stream, 6)?, Some(10_u8)),
|
||||
Value::Other('7') => (parse_constant::<S, 10>(stream, 7)?, Some(10_u8)),
|
||||
Value::Other('8') => (parse_constant::<S, 10>(stream, 8)?, Some(10_u8)),
|
||||
Value::Other('9') => (parse_constant::<S, 10>(stream, 9)?, Some(10_u8)),
|
||||
Value::Other('\'') => (parse_constant::<S, 8>(stream, 0)?, Some(8_u8)),
|
||||
Value::Other('"') => (parse_constant::<S, 16>(stream, 0)?, Some(16_u8)),
|
||||
Value::Other('`') => (parse_character(stream)?, None),
|
||||
Value::CommandRef(command_ref) => (
|
||||
parse_internal_number(stream, first_token, command_ref)?.integer(),
|
||||
None,
|
||||
),
|
||||
// TeX.2021.446
|
||||
_ => {
|
||||
stream.back(first_token);
|
||||
stream.error(parse::Error::new(
|
||||
"the beginning of a number",
|
||||
Some(first_token),
|
||||
GUIDANCE_BEGINNING,
|
||||
))?;
|
||||
(0, None)
|
||||
}
|
||||
};
|
||||
let result = match sign {
|
||||
None => result,
|
||||
// The only i32 that is not safe to multiply by -1 is i32::MIN.
|
||||
// Experimentally we observe in this case that TeX wraps and the result
|
||||
// is i32::MIN again.
|
||||
Some(_) => result.wrapping_mul(-1),
|
||||
};
|
||||
Ok((first_token, result, radix))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum InternalNumber {
|
||||
Integer(i32),
|
||||
Dimen(common::Scaled),
|
||||
Glue(common::Glue),
|
||||
MuGlue(crate::types::MuGlue),
|
||||
}
|
||||
|
||||
impl InternalNumber {
|
||||
pub(crate) fn integer(&self) -> i32 {
|
||||
use InternalNumber::*;
|
||||
match self {
|
||||
Integer(i) => *i,
|
||||
Dimen(scaled) => scaled.0,
|
||||
Glue(glue) => glue.width.0,
|
||||
MuGlue(glue) => glue.0.width.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This function reimplements TeX.2021.413 (scan_something_internal) under the following
|
||||
/// conditions:
|
||||
///
|
||||
/// - level is int_val, dimen_val, glue_val or mu_val; i.e., the call to this function
|
||||
/// is looking for a number, not a token list or font. The token list or font cases
|
||||
/// are handled elsewhere.
|
||||
///
|
||||
/// - negative is false. The negative=true case is handled by the caller to this function.
|
||||
///
|
||||
/// - The logic around casting between types (i.e. TeX.2021.429) is omitted. Instead
|
||||
/// callers of this function perform the casting. The motivation is to make the code
|
||||
/// more explicit and avoid parameters that change logic and/or return types.
|
||||
pub(crate) fn parse_internal_number<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
command_ref: CommandRef,
|
||||
) -> txl::Result<InternalNumber> {
|
||||
let cmd = input.commands_map().get_command(&command_ref);
|
||||
match cmd {
|
||||
Some(command::Command::Variable(cmd)) => {
|
||||
match cmd.clone().value(first_token, input)? {
|
||||
variable::ValueRef::Int(i) => Ok(InternalNumber::Integer(*i)),
|
||||
variable::ValueRef::SmallInt(c) => Ok(InternalNumber::Integer(*c as i32)),
|
||||
variable::ValueRef::CatCode(c) => Ok(InternalNumber::Integer(*c as i32)),
|
||||
variable::ValueRef::MathCode(c) => Ok(InternalNumber::Integer(c.0 as i32)),
|
||||
variable::ValueRef::Dimen(d) => Ok(InternalNumber::Dimen(*d)),
|
||||
variable::ValueRef::Glue(g) => Ok(InternalNumber::Glue(*g)),
|
||||
variable::ValueRef::MuGlue(g) => Ok(InternalNumber::MuGlue(*g)),
|
||||
variable::ValueRef::Font(_) => {
|
||||
// This case behaves identically to the TokenListCase
|
||||
todo!("scan a font into an int?");
|
||||
}
|
||||
variable::ValueRef::TokenList(_) => Err(input.fatal_error(
|
||||
parse::Error::new(
|
||||
"the beginning of a number",
|
||||
Some(first_token),
|
||||
GUIDANCE_BEGINNING,
|
||||
)
|
||||
.with_annotation_override("token list variable"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
Some(command::Command::Character(c)) => Ok(InternalNumber::Integer(*c as i32)),
|
||||
Some(command::Command::MathCharacter(c)) => Ok(InternalNumber::Integer(c.0 as i32)),
|
||||
Some(command::Command::UnicodeMathCharacter {
|
||||
class,
|
||||
family,
|
||||
character,
|
||||
}) => {
|
||||
let packed =
|
||||
(u32::from(*family) << 24) | (u32::from(*class) << 21) | (*character as u32);
|
||||
Ok(InternalNumber::Integer(packed as i32))
|
||||
}
|
||||
None
|
||||
| Some(
|
||||
command::Command::Execution(..)
|
||||
| command::Command::Expansion(..)
|
||||
| command::Command::Macro(..)
|
||||
| command::Command::CharacterTokenAlias(..)
|
||||
| command::Command::Font(..),
|
||||
) => {
|
||||
let err = parse::Error::new(
|
||||
"the beginning of a number",
|
||||
Some(first_token),
|
||||
GUIDANCE_BEGINNING,
|
||||
)
|
||||
.with_annotation_override(match cmd {
|
||||
None => "undefined control sequence".to_string(),
|
||||
Some(cmd) => format!["control sequence referencing {cmd}"],
|
||||
});
|
||||
input.expansions_mut().push(first_token);
|
||||
Err(input.fatal_error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NumberEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for NumberEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a number".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![GUIDANCE_BEGINNING.into()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses optional signs and spaces.
|
||||
///
|
||||
/// If the combination of the signs is positive, [None] is returned.
|
||||
/// Otherwise, the Token corresponding to the last negative sign is returned.
|
||||
///
|
||||
/// This is TeX.2021.441.
|
||||
pub fn parse_optional_signs<S: TexlangState>(
|
||||
stream: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Option<token::Token>> {
|
||||
let mut result = None;
|
||||
while let Some((sign, token)) = get_optional_element_with_token![
|
||||
stream,
|
||||
Value::Other('+') => true,
|
||||
Value::Other('-') => false,
|
||||
Value::Space(_) => true,
|
||||
] {
|
||||
result = match (result, sign) {
|
||||
(None, false) => Some(token),
|
||||
(Some(_), false) => None,
|
||||
(result, true) => result,
|
||||
};
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// TeX.2021.442
|
||||
fn parse_character<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<i32> {
|
||||
// BUG: should be from the unexpanded stream
|
||||
let c = {
|
||||
let token = input.next_or_err(CharacterError {})?;
|
||||
match token.value() {
|
||||
Value::CommandRef(token::CommandRef::ControlSequence(cs_name)) => {
|
||||
let name = input.vm().cs_name_interner().resolve(cs_name).unwrap();
|
||||
let mut iter = name.chars();
|
||||
match (iter.next(), iter.count()) {
|
||||
// (None, 0) => ?! TODO: add a test for this.
|
||||
// Should be something like:
|
||||
// \expandafter \i \expandafter ` \csname\endcsname
|
||||
(Some(c), 0) => c,
|
||||
_ => {
|
||||
input.error(parse::Error::new(
|
||||
"a character",
|
||||
Some(token),
|
||||
"a character is a character token or single-character control sequence like \\a",
|
||||
))?;
|
||||
'0'
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => token.char().unwrap(),
|
||||
}
|
||||
};
|
||||
super::OptionalSpace::parse(input)?;
|
||||
Ok(c as i32)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CharacterError;
|
||||
|
||||
impl error::EndOfInputError for CharacterError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a character".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
r"a character is a character token or single-character control sequence like \a".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// TeX.2021.444-445
|
||||
// TODO: why is the radix a const parameter?
|
||||
fn parse_constant<S: TexlangState, const RADIX: i32>(
|
||||
stream: &mut vm::ExpandedStream<S>,
|
||||
mut result: i32,
|
||||
) -> txl::Result<i32> {
|
||||
let mut started = RADIX == 10;
|
||||
let mut too_big = false;
|
||||
loop {
|
||||
let next = match stream.next()? {
|
||||
None => break,
|
||||
Some(next) => next,
|
||||
};
|
||||
let lsd_or = match next.value() {
|
||||
token::Value::Other(c) => {
|
||||
let d = (c as u32).wrapping_sub('0' as u32);
|
||||
if d < 10 && d < (RADIX as u32) {
|
||||
Some(d as i32)
|
||||
} else if RADIX == 16 {
|
||||
let d = (c as u32).wrapping_sub('A' as u32);
|
||||
if d < 6 {
|
||||
Some(d as i32 + 10)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
token::Value::Letter(c) => {
|
||||
let d = (c as u32).wrapping_sub('A' as u32);
|
||||
if RADIX == 16 && d < 6 {
|
||||
Some(d as i32 + 10)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let lsd = match lsd_or {
|
||||
None => {
|
||||
stream.back(next);
|
||||
break;
|
||||
}
|
||||
Some(lsd) => lsd,
|
||||
};
|
||||
started = true;
|
||||
result = match add_lsd::<RADIX>(result, lsd) {
|
||||
Some(n) => n,
|
||||
None => {
|
||||
if !too_big {
|
||||
stream.error(add_lsd_error::<RADIX>(next, result, lsd))?;
|
||||
too_big = true;
|
||||
}
|
||||
i32::MAX
|
||||
}
|
||||
}
|
||||
}
|
||||
if !started {
|
||||
let (expected, guidance) = match RADIX {
|
||||
8 => {
|
||||
("an octal digit",
|
||||
"an octal digit is a token with value 0-7 and category other")
|
||||
},
|
||||
16 => {
|
||||
("a hexadecimal digit",
|
||||
"a hexadecimal digit is either:\n- A character token with value 0-9 and category other, or\n- A character token with value A-F and category letter or other")
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let got = stream.peek()?;
|
||||
stream.error(parse::Error::new(expected, got, guidance))?;
|
||||
}
|
||||
super::OptionalSpace::parse(stream)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn add_lsd<const RADIX: i32>(n: i32, lsd: i32) -> Option<i32> {
|
||||
match n.checked_mul(RADIX) {
|
||||
None => None,
|
||||
Some(n) => n.checked_add(lsd),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_lsd_error<const RADIX: i32>(token: token::Token, n: i32, lsd: i32) -> parse::Error {
|
||||
let (got, range) = match RADIX {
|
||||
8 => (
|
||||
format!["got '{n:o}{lsd:o}"],
|
||||
format!["'{:o}, '{:o}", i32::MIN, i32::MAX],
|
||||
),
|
||||
10 => (
|
||||
format!["got {n}{lsd}"],
|
||||
format!["{}, {}", i32::MIN, i32::MAX],
|
||||
),
|
||||
16 => (
|
||||
format!["got 0x{n:X}{lsd:X}"],
|
||||
format!["0x{:X}, 0x{:X}", i32::MIN, i32::MAX],
|
||||
),
|
||||
_ => panic!("radix must be 8, 10 or 16"),
|
||||
};
|
||||
parse::Error {
|
||||
expected: format!["a number in the range [{range}]"],
|
||||
got: Some(token),
|
||||
got_override: got,
|
||||
annotation_override: "this digit makes the number too big".into(),
|
||||
guidance: "".into(),
|
||||
additional_notes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
parse_success_tests![
|
||||
(octal_0, "'0", 0),
|
||||
(octal_1, "'1", 1),
|
||||
(octal_2, "'2", 2),
|
||||
(octal_3, "'3", 3),
|
||||
(octal_4, "'4", 4),
|
||||
(octal_5, "'5", 5),
|
||||
(octal_6, "'6", 6),
|
||||
(octal_7, "'7", 7),
|
||||
(octal_8, "'10", 8),
|
||||
(octal_9, "'11", 9),
|
||||
(octal_19, "'12", 10),
|
||||
(octal_11, "'13", 11),
|
||||
(octal_12, "'14", 12),
|
||||
(octal_13, "'15", 13),
|
||||
(octal_14, "'16", 14),
|
||||
(octal_15, "'17", 15),
|
||||
(octal_129, "'201", 129),
|
||||
(octal_max, "'17777777777", 2147483647),
|
||||
(octal_min, "-'17777777777", -2147483647),
|
||||
(decimal_0, "0", 0),
|
||||
(decimal_1, "1", 1),
|
||||
(decimal_2, "2", 2),
|
||||
(decimal_3, "3", 3),
|
||||
(decimal_4, "4", 4),
|
||||
(decimal_5, "5", 5),
|
||||
(decimal_6, "6", 6),
|
||||
(decimal_7, "7", 7),
|
||||
(decimal_8, "8", 8),
|
||||
(decimal_9, "9", 9),
|
||||
(decimal_10, "10", 10),
|
||||
(decimal_11, "11", 11),
|
||||
(decimal_12, "12", 12),
|
||||
(decimal_13, "13", 13),
|
||||
(decimal_14, "14", 14),
|
||||
(decimal_15, "15", 15),
|
||||
(decimal_16, "16", 16),
|
||||
(decimal_17, "17", 17),
|
||||
(decimal_18, "18", 18),
|
||||
(decimal_19, "19", 19),
|
||||
(decimal_1_with_0_padding, "00019", 19),
|
||||
(decimal_201, "201", 201),
|
||||
(decimal_max, "2147483647", 2147483647),
|
||||
(decimal_min, "-2147483647", -2147483647),
|
||||
(hexadecimal_0, "\"0", 0),
|
||||
(hexadecimal_1, "\"1", 1),
|
||||
(hexadecimal_2, "\"2", 2),
|
||||
(hexadecimal_3, "\"3", 3),
|
||||
(hexadecimal_4, "\"4", 4),
|
||||
(hexadecimal_5, "\"5", 5),
|
||||
(hexadecimal_6, "\"6", 6),
|
||||
(hexadecimal_7, "\"7", 7),
|
||||
(hexadecimal_8, "\"8", 8),
|
||||
(hexadecimal_9, "\"9", 9),
|
||||
(hexadecimal_10, "\"A", 10),
|
||||
(hexadecimal_11, "\"B", 11),
|
||||
(hexadecimal_12, "\"C", 12),
|
||||
(hexadecimal_13, "\"D", 13),
|
||||
(hexadecimal_14, "\"E", 14),
|
||||
(hexadecimal_15, "\"F", 15),
|
||||
(hexadecimal_16, "\"10", 16),
|
||||
(hexadecimal_17, "\"11", 17),
|
||||
(hexadecimal_18, "\"12", 18),
|
||||
(hexadecimal_19, "\"13", 19),
|
||||
(hexadecimal_20, "\"14", 20),
|
||||
(hexadecimal_21, "\"15", 21),
|
||||
(hexadecimal_22, "\"16", 22),
|
||||
(hexadecimal_23, "\"17", 23),
|
||||
(hexadecimal_24, "\"18", 24),
|
||||
(hexadecimal_25, "\"19", 25),
|
||||
(hexadecimal_26, "\"1A", 26),
|
||||
(hexadecimal_27, "\"1B", 27),
|
||||
(hexadecimal_28, "\"1C", 28),
|
||||
(hexadecimal_29, "\"1D", 29),
|
||||
(hexadecimal_30, "\"1E", 30),
|
||||
(hexadecimal_31, "\"1F", 31),
|
||||
(hexadecimal_513, "\"201", 513),
|
||||
(hexadecimal_max, "\"7FFFFFFF", 2147483647),
|
||||
(hexadecimal_min, "-\"7FFFFFFF", -2147483647),
|
||||
(number_from_character, "`A", 65),
|
||||
(number_from_length_1_control_sequence, r"`\A", 65),
|
||||
(number_from_character_non_ascii, "`ö", 0x00F6),
|
||||
(
|
||||
number_from_length_1_control_sequence_non_ascii,
|
||||
r"`\ö",
|
||||
0x00F6
|
||||
),
|
||||
(signs_plus, r"+4", 4),
|
||||
(signs_minus, r"-4", -4),
|
||||
(signs_plus_minus, r"+-4", -4),
|
||||
(signs_minus_minus, r"--4", 4),
|
||||
(signs_minus_minus_spaces, r" - - 4", 4),
|
||||
];
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {
|
||||
fn cat_code(&self, c: char) -> types::CatCode {
|
||||
if c == '9' {
|
||||
return types::CatCode::Letter;
|
||||
}
|
||||
types::CatCode::PLAIN_TEX_DEFAULTS
|
||||
.get(c as usize)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
parse_failure_tests![
|
||||
i32,
|
||||
State,
|
||||
(number_with_letter_catcode, "9"),
|
||||
(octal_too_big, "'177777777770", i32::MAX),
|
||||
(octal_empty, "'"),
|
||||
(decimal_too_big_1, "2147483648", i32::MAX),
|
||||
(decimal_too_big_2, "500000000000000", i32::MAX),
|
||||
(decimal_too_negative_1, "-2147483648", -1 * i32::MAX),
|
||||
(decimal_too_negative_2, "-5000000000000", -1 * i32::MAX),
|
||||
(hexadecimal_too_big, "\"7FFFFFFF0", i32::MAX),
|
||||
(hexadecimal_empty, "\""),
|
||||
(character, "A"),
|
||||
// TODO: the test is messed up because a space gets appended to the input
|
||||
// (character_missing, r"`", '0' as i32),
|
||||
(control_sequence_too_big, r"`\BC", '0' as i32),
|
||||
];
|
||||
|
||||
parse_failure_tests![
|
||||
Uint::<16>,
|
||||
State,
|
||||
(number_too_big, "16"),
|
||||
(number_is_negative, "-1"),
|
||||
];
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
use crate::prelude as txl;
|
||||
use crate::token;
|
||||
use crate::traits::*;
|
||||
use crate::vm;
|
||||
|
||||
/// Parses a keyword from the input stream.
|
||||
///
|
||||
/// TeX.2021.407 scan_keyword
|
||||
pub fn parse_keyword<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
keyword: &str,
|
||||
) -> txl::Result<bool> {
|
||||
let Some(c) = keyword.chars().next() else {
|
||||
// keyword is empty
|
||||
return Ok(true);
|
||||
};
|
||||
let Some(token) = input.next()? else {
|
||||
// input ended, keyword does not match
|
||||
return Ok(false);
|
||||
};
|
||||
if token.value() != token::Value::Letter(c.to_ascii_lowercase())
|
||||
&& token.value() != token::Value::Letter(c.to_ascii_uppercase())
|
||||
{
|
||||
input.back(token);
|
||||
return Ok(false);
|
||||
}
|
||||
// this character matched; now try to match the result of keyword
|
||||
let result = parse_keyword(input, &keyword[c.len_utf8()..]);
|
||||
if let Ok(false) = result {
|
||||
// some later character did not match, reverse consuming the token.
|
||||
input.back(token);
|
||||
}
|
||||
result
|
||||
}
|
||||
Vendored
+370
@@ -0,0 +1,370 @@
|
||||
//! Logic for parsing elements of the TeX grammar from token streams.
|
||||
//!
|
||||
//! This parsing module is based around the [Parsable] trait, which is the most important type in the module.
|
||||
//! This trait is implemented by Rust types that correspond to elements of the TeX grammar.
|
||||
//! The trait implementation provides a way to parse grammar elements out of the input stream.
|
||||
//!
|
||||
//! The module contains implementations of [Parsable] for tuples where each element is parsable.
|
||||
//! This allows expressions like `<integer><relation><integer>` to be parsed by one invocation
|
||||
//! of [Parsable::parse], in this case on the type `(i32, std::cmp::Ordering, i32)`.
|
||||
//!
|
||||
//! The second most important thing is the collection of custom Rust types like [OptionalEquals] and
|
||||
//! [FileLocation] which correspond to Rust grammar elements.
|
||||
//!
|
||||
//! Finally this module contains some functions for special situation like parsing lists of tokens.
|
||||
|
||||
#[macro_use]
|
||||
mod helpers;
|
||||
|
||||
mod dimen;
|
||||
mod filelocation;
|
||||
mod glue;
|
||||
mod integer;
|
||||
mod keyword;
|
||||
mod muglue;
|
||||
mod relation;
|
||||
#[cfg(test)]
|
||||
mod testing;
|
||||
mod variable;
|
||||
|
||||
pub use filelocation::FileLocation;
|
||||
pub use integer::Uint;
|
||||
pub use keyword::parse_keyword;
|
||||
pub use relation::Ordering;
|
||||
pub use variable::OptionalEquals;
|
||||
pub use variable::OptionalEqualsUnexpanded;
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::types::CatCode;
|
||||
use crate::*;
|
||||
|
||||
/// Implementations of this trait are elements of the TeX grammar than can be parsed from a stream of tokens.
|
||||
pub trait Parsable: Sized {
|
||||
/// Parses a value from an input stream.
|
||||
///
|
||||
/// This method just delegates to [Parsable::parse_impl].
|
||||
#[inline]
|
||||
fn parse<S: TexlangState, I>(input: &mut I) -> txl::Result<Self>
|
||||
where
|
||||
I: AsMut<vm::ExpandedStream<S>>,
|
||||
{
|
||||
Parsable::parse_impl(input.as_mut())
|
||||
}
|
||||
|
||||
/// Parses a value from the [vm::ExpandedStream].
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error {
|
||||
pub expected: String,
|
||||
pub got: Option<token::Token>,
|
||||
pub got_override: String,
|
||||
pub annotation_override: String,
|
||||
pub guidance: String,
|
||||
pub additional_notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl error::TexError for Error {
|
||||
fn kind(&self) -> error::Kind {
|
||||
match self.got {
|
||||
None => error::Kind::EndOfInput,
|
||||
Some(token) => error::Kind::Token(token),
|
||||
}
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
let got = if self.got_override.is_empty() {
|
||||
match self.got {
|
||||
None => "the input ended".to_string(),
|
||||
Some(token) => match token.value() {
|
||||
token::Value::Letter(c) => format!["found the letter {c}"],
|
||||
token::Value::Other(c) => format!["found a non-letter character {c}"],
|
||||
_ => match (token.char(), token.cat_code()) {
|
||||
(Some(c), Some(code)) => {
|
||||
format!["found a token with value {c} and category code {code}"]
|
||||
}
|
||||
_ => "found a control sequence".to_string(),
|
||||
},
|
||||
},
|
||||
}
|
||||
} else {
|
||||
self.got_override.clone()
|
||||
};
|
||||
format!["expected {}, instead {}", self.expected, got]
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![self.guidance.clone().into()]
|
||||
}
|
||||
|
||||
fn source_annotation(&self) -> String {
|
||||
if !self.annotation_override.is_empty() {
|
||||
return self.annotation_override.clone();
|
||||
}
|
||||
error::TexError::default_source_annotation(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
pub fn new<T: Into<String>, R: Into<String>>(
|
||||
expected: T,
|
||||
got: Option<token::Token>,
|
||||
guidance: R,
|
||||
) -> Self {
|
||||
Error {
|
||||
expected: expected.into(),
|
||||
got,
|
||||
got_override: "".into(),
|
||||
annotation_override: "".into(),
|
||||
guidance: guidance.into(),
|
||||
additional_notes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_got_override<T: Into<String>>(mut self, got_override: T) -> Self {
|
||||
self.got_override = got_override.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_annotation_override<T: Into<String>>(mut self, annotation_override: T) -> Self {
|
||||
self.annotation_override = annotation_override.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! generate_tuple_impls {
|
||||
( $first: ident ) => {};
|
||||
( $first: ident, $( $name: ident ),+ ) => {
|
||||
generate_tuple_impls![ $( $name ),+];
|
||||
|
||||
impl<$first : Parsable, $( $name : Parsable ),+> Parsable for ($first, $( $name ),+) {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
Ok(($first::parse(input)?, $( $name::parse(input)? ),+))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
generate_tuple_impls![T1, T2, T3, T4, T5];
|
||||
|
||||
impl Parsable for Option<token::CommandRef> {
|
||||
// TeX.2021.get_r_token
|
||||
// TeX.2021.1215
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// Implements get_r_token
|
||||
while let Some(found_equals) = get_optional_element![
|
||||
input.unexpanded(),
|
||||
token::Value::Space(_) => true,
|
||||
] {
|
||||
if found_equals {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ref_or = get_required_element![
|
||||
input.unexpanded(),
|
||||
"a control sequence or active character",
|
||||
"a command must be a control sequence or an active character",
|
||||
token::Value::CommandRef(command_ref) => command_ref,
|
||||
];
|
||||
Ok(ref_or)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LeftBrace;
|
||||
|
||||
impl Parsable for LeftBrace {
|
||||
// TeX.2021.403 scan_left_brace
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
get_required_element![
|
||||
input.unexpanded(),
|
||||
"an opening brace",
|
||||
"a balanced token list must start with an opening brace",
|
||||
token::Value::BeginGroup(_) => (),
|
||||
];
|
||||
Ok(LeftBrace {})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UnexpandedTokenList(pub Vec<token::Token>);
|
||||
|
||||
impl Parsable for UnexpandedTokenList {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let mut result = input.checkout_token_buffer();
|
||||
LeftBrace::parse(input)?;
|
||||
finish_parsing_balanced_tokens(input.unexpanded(), &mut result)?;
|
||||
Ok(UnexpandedTokenList(result))
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for Vec<token::Token> {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let mut result = input.checkout_token_buffer();
|
||||
let first_token = input.next_or_err(TokenStreamEndOfInputError {})?;
|
||||
let got = match first_token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match input.commands_map().get_command(&command_ref) {
|
||||
Some(command::Command::Variable(cmd)) => {
|
||||
if let crate::variable::ValueRef::TokenList(token_list) =
|
||||
cmd.clone().value(first_token, input)?
|
||||
{
|
||||
result.extend(token_list.iter());
|
||||
return Ok(result);
|
||||
};
|
||||
"a variable command of the wrong type (wanted a token list)"
|
||||
}
|
||||
Some(_) => "a command that is not a variable command",
|
||||
None => "an undefined command",
|
||||
}
|
||||
}
|
||||
token::Value::BeginGroup(_) => {
|
||||
finish_parsing_balanced_tokens(input, &mut result)?;
|
||||
return Ok(result);
|
||||
}
|
||||
_ => "a non-command, non-opening brace token",
|
||||
};
|
||||
input.return_token_buffer(result);
|
||||
Err(input.fatal_error(
|
||||
parse::Error::new(
|
||||
"an opening brace or a variable of type token list",
|
||||
Some(first_token),
|
||||
"",
|
||||
)
|
||||
.with_got_override(format!("got {got}"))
|
||||
.with_annotation_override(got),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TokenStreamEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for TokenStreamEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a token list".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses balanced tokens from the stream.
|
||||
///
|
||||
/// This function assumes the the initial opening brace has ready been consumed.
|
||||
/// It returns false if the input ends before balanced tokens completed.
|
||||
///
|
||||
/// This function is somewhat analogous to `scan_toks` in Knuth's TeX.
|
||||
/// For us the `xpand` parameter can be controlled by providing a different token stream.
|
||||
pub fn finish_parsing_balanced_tokens<S: vm::TokenStream>(
|
||||
stream: &mut S,
|
||||
result: &mut Vec<token::Token>,
|
||||
) -> txl::Result<()> {
|
||||
let mut scope_depth = 0;
|
||||
loop {
|
||||
let token = stream.next_or_err(TokenStreamEndOfInputError {})?;
|
||||
match token.value() {
|
||||
token::Value::BeginGroup(_) => {
|
||||
scope_depth += 1;
|
||||
}
|
||||
token::Value::EndGroup(_) => {
|
||||
if scope_depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
scope_depth -= 1;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
result.push(token);
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an arbitrary number of spaces from the input stream
|
||||
///
|
||||
/// TODO: we should audit all places Knuth uses this, and ensure we're using it too.
|
||||
///
|
||||
/// TeX.2021.406
|
||||
pub struct Spaces;
|
||||
|
||||
impl Parsable for Spaces {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Space(_) => {
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Spaces {})
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an arbitrary number of spaces from the unexpanded input stream
|
||||
pub struct SpacesUnexpanded;
|
||||
|
||||
impl Parsable for SpacesUnexpanded {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let input = input.unexpanded();
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Space(_) => {
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(SpacesUnexpanded {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for Option<char> {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let Some(token) = input.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let c = match token.value() {
|
||||
token::Value::BeginGroup(_)
|
||||
| token::Value::EndGroup(_)
|
||||
| token::Value::MathShift(_)
|
||||
| token::Value::AlignmentTab(_)
|
||||
| token::Value::Parameter(_)
|
||||
| token::Value::Superscript(_)
|
||||
| token::Value::Subscript(_)
|
||||
| token::Value::Space(_) => {
|
||||
input.back(token);
|
||||
return Ok(None);
|
||||
}
|
||||
token::Value::Letter(c) => c,
|
||||
token::Value::Other(c) => c,
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match input.commands_map().get_command(&command_ref) {
|
||||
Some(command::Command::Character(c)) => *c,
|
||||
_ => {
|
||||
input.back(token);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(Some(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an optional space from the token stream.
|
||||
pub struct OptionalSpace;
|
||||
|
||||
impl Parsable for OptionalSpace {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// TeX.2021.443
|
||||
if let Some(next) = input.next()? {
|
||||
if next.cat_code() != Some(CatCode::Space) {
|
||||
input.back(next);
|
||||
}
|
||||
}
|
||||
Ok(OptionalSpace {})
|
||||
}
|
||||
}
|
||||
Vendored
+136
@@ -0,0 +1,136 @@
|
||||
use common::{Glue, GlueOrder, Scaled, ScaledUnit};
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
use super::keyword::parse_keyword;
|
||||
|
||||
impl Parsable for types::MuGlue {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(glue) = S::scan_mu_glue(input)? {
|
||||
return Ok(glue);
|
||||
}
|
||||
let negative = super::integer::parse_optional_signs(input)?.is_some();
|
||||
if let Some(first_token) = input.next()? {
|
||||
if let token::Value::CommandRef(command_ref) = first_token.value() {
|
||||
if let super::integer::InternalNumber::MuGlue(glue) =
|
||||
super::integer::parse_internal_number(input, first_token, command_ref)?
|
||||
{
|
||||
return Ok(if negative {
|
||||
types::MuGlue(glue.0 * -1)
|
||||
} else {
|
||||
glue
|
||||
});
|
||||
}
|
||||
}
|
||||
input.back(first_token);
|
||||
}
|
||||
let width = scan_mu_dimen(input, None)?;
|
||||
let mut glue = Glue {
|
||||
width,
|
||||
..Glue::default()
|
||||
};
|
||||
if parse_keyword(input, "plus")? {
|
||||
glue.stretch = scan_mu_dimen(input, Some(&mut glue.stretch_order))?;
|
||||
}
|
||||
if parse_keyword(input, "minus")? {
|
||||
glue.shrink = scan_mu_dimen(input, Some(&mut glue.shrink_order))?;
|
||||
}
|
||||
if negative {
|
||||
glue = glue * -1;
|
||||
}
|
||||
Ok(types::MuGlue(glue))
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_mu_dimen<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
mut glue_order: Option<&mut GlueOrder>,
|
||||
) -> txl::Result<Scaled> {
|
||||
let negative = super::integer::parse_optional_signs(input)?.is_some();
|
||||
let first_token = input.next_or_err(MuGlueEndOfInputError {})?;
|
||||
let (integer_part, fractional_part) = match first_token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match super::integer::parse_internal_number(input, first_token, command_ref)? {
|
||||
super::integer::InternalNumber::MuGlue(glue) => {
|
||||
let width = glue.0.width;
|
||||
return Ok(if negative { -width } else { width });
|
||||
}
|
||||
super::integer::InternalNumber::Integer(value) => (value.abs(), Scaled::ZERO),
|
||||
_ => {
|
||||
input.error(parse::Error::new(
|
||||
"a math glue value",
|
||||
Some(first_token),
|
||||
"math glue assignments require values measured in mu",
|
||||
))?;
|
||||
return Ok(Scaled::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => super::dimen::scan_constant_dimen(input, first_token)?,
|
||||
};
|
||||
|
||||
let unit_found = match glue_order.as_deref_mut() {
|
||||
Some(order) if parse_keyword(input, "fil")? => {
|
||||
*order = GlueOrder::Fil;
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Letter('l' | 'L') => match order.next() {
|
||||
Some(next) => *order = next,
|
||||
None => {
|
||||
input.error(parse::Error::new(
|
||||
"an infinite glue order",
|
||||
Some(token),
|
||||
"too many l characters in the glue order",
|
||||
))?;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
super::OptionalSpace::parse(input)?;
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
let found = parse_keyword(input, "mu")?;
|
||||
if found {
|
||||
super::OptionalSpace::parse(input)?;
|
||||
}
|
||||
found
|
||||
}
|
||||
};
|
||||
if !unit_found {
|
||||
input.error(parse::Error::new(
|
||||
"a math unit (mu)",
|
||||
Some(first_token),
|
||||
"muskip values require mu units",
|
||||
))?;
|
||||
return Ok(Scaled::ZERO);
|
||||
}
|
||||
|
||||
let value = match Scaled::new(integer_part, fractional_part, ScaledUnit::Point) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
input.error(parse::Error::new(
|
||||
"a math glue value in TeX's supported range",
|
||||
Some(first_token),
|
||||
"the value is too large",
|
||||
))?;
|
||||
Scaled::MAX_DIMEN
|
||||
}
|
||||
};
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MuGlueEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for MuGlueEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing math glue".into()
|
||||
}
|
||||
}
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
//! Parsing of relations (<, = and >)
|
||||
//!
|
||||
//! A relation is defined on p209 of the TeXBook to be a character token with
|
||||
//! catcode 12 (other) and value <, = or >.
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::{token, types, vm};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Ordering(pub std::cmp::Ordering);
|
||||
|
||||
impl Default for Ordering {
|
||||
fn default() -> Self {
|
||||
Ordering(std::cmp::Ordering::Equal)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for Ordering {
|
||||
// TeX.2021.503
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
super::Spaces::parse(input)?;
|
||||
let ordering_or = get_required_element![
|
||||
input,
|
||||
"a relation",
|
||||
format!["a relation is a token with character code {} and one of the following values: <, =, >", types::CatCode::Other],
|
||||
token::Value::Other('<') => Ordering(std::cmp::Ordering::Less),
|
||||
token::Value::Other('=') => Ordering(std::cmp::Ordering::Equal),
|
||||
token::Value::Other('>') => Ordering(std::cmp::Ordering::Greater),
|
||||
];
|
||||
Ok(ordering_or.unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
parse_success_tests![
|
||||
(less_than_1, r"<a", Ordering(std::cmp::Ordering::Less)),
|
||||
(less_than_2, r"<a", Ordering(std::cmp::Ordering::Less)),
|
||||
(equals, r"=a", Ordering(std::cmp::Ordering::Equal)),
|
||||
(greater_than, r">a", Ordering(std::cmp::Ordering::Greater)),
|
||||
];
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {
|
||||
fn cat_code(&self, c: char) -> types::CatCode {
|
||||
if c == '<' {
|
||||
return types::CatCode::Letter;
|
||||
}
|
||||
types::CatCode::PLAIN_TEX_DEFAULTS
|
||||
.get(c as usize)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
parse_failure_tests![
|
||||
Ordering,
|
||||
State,
|
||||
(empty_input, ""),
|
||||
(letter, "a"),
|
||||
(control_sequence, r"\A"),
|
||||
(incorrect_catcode, "<"),
|
||||
];
|
||||
}
|
||||
Vendored
+121
@@ -0,0 +1,121 @@
|
||||
use crate::traits::*;
|
||||
use crate::types;
|
||||
use crate::vm;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub(crate) fn run_parse_success_test<S: TexlangState + Default, T: Parsable + Debug + Eq>(
|
||||
source: &str,
|
||||
want: T,
|
||||
) {
|
||||
let mut vm = vm::VM::<S>::new_with_built_in_commands(HashMap::new());
|
||||
vm.push_source("".to_string(), source.to_string()).unwrap();
|
||||
let input = vm::ExecutionInput::new(&mut vm);
|
||||
let got = T::parse(input).unwrap();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
pub(crate) fn run_parse_failure_test<S: TexlangState + Default, T: Parsable + Debug>(source: &str) {
|
||||
let mut vm = vm::VM::<S>::new_with_built_in_commands(HashMap::new());
|
||||
vm.push_source("".to_string(), source.to_string()).unwrap();
|
||||
let input = vm::ExecutionInput::new(&mut vm);
|
||||
let result = T::parse(input);
|
||||
if let Ok(value) = result {
|
||||
panic![
|
||||
"Successfully parsed a value '{value:?}' of type '{}' from invalid input '{source}'",
|
||||
std::any::type_name::<T>()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_parse_failure_recovery_test<
|
||||
S: TexlangState + Default,
|
||||
T: Parsable + Debug + Eq,
|
||||
>(
|
||||
source: &str,
|
||||
want: T,
|
||||
) {
|
||||
let mut vm = vm::VM::<WrappedState<S>>::new_with_built_in_commands(HashMap::new());
|
||||
vm.state.recover_from_errors = true;
|
||||
vm.push_source("".to_string(), source.to_string()).unwrap();
|
||||
let input = vm::ExecutionInput::new(&mut vm);
|
||||
let got = T::parse(input).unwrap();
|
||||
assert_eq!(got, want);
|
||||
let got_num_errors = *vm.state.num_errors.borrow();
|
||||
assert_eq!(
|
||||
got_num_errors, 1,
|
||||
"expected 1 TeX error, found {} TeX errors",
|
||||
got_num_errors
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WrappedState<S> {
|
||||
inner: S,
|
||||
recover_from_errors: bool,
|
||||
num_errors: RefCell<usize>,
|
||||
}
|
||||
|
||||
impl<S: TexlangState> TexlangState for WrappedState<S> {
|
||||
fn cat_code(&self, c: char) -> types::CatCode {
|
||||
self.inner.cat_code(c)
|
||||
}
|
||||
fn end_line_char(&self) -> Option<char> {
|
||||
self.inner.end_line_char()
|
||||
}
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: crate::error::TracedTexError,
|
||||
) -> Result<(), Box<dyn crate::error::TexError>> {
|
||||
let mut num_errors = self.num_errors.borrow_mut();
|
||||
*num_errors = *num_errors + 1;
|
||||
if self.recover_from_errors {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(recoverable_error.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! parse_success_tests {
|
||||
($( ($name: ident, $input: expr, $expected: expr $(,)? ) ),+ $(,)? ) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
let source = $input;
|
||||
let want = $expected;
|
||||
run_parse_success_test::<(), _>(&source, want);
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use parse_success_tests;
|
||||
|
||||
macro_rules! parse_failure_tests {
|
||||
( $parsable_type: ty, $state: ty, $( ($name: ident, $input: expr $( , $want: expr )? ), )+) => {
|
||||
$(
|
||||
mod $name {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn recovery_disabled() {
|
||||
let input = $input;
|
||||
run_parse_failure_test::<$state, $parsable_type>(&input);
|
||||
}
|
||||
#[test]
|
||||
fn recovery_enabled() {
|
||||
let source = $input;
|
||||
#[allow(unused_mut,unused_assignments)]
|
||||
let mut want: $parsable_type = Default::default();
|
||||
$(
|
||||
want = $want;
|
||||
)?
|
||||
run_parse_failure_recovery_test::<$state, $parsable_type>(&source, want);
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use parse_failure_tests;
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
/// When parsed, this type consumes an optional equals from the token stream.
|
||||
pub struct OptionalEquals;
|
||||
|
||||
impl Parsable for OptionalEquals {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// scan_optional_equals
|
||||
parse_optional_equals(input)?;
|
||||
Ok(OptionalEquals {})
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an optional equals from the token stream without performing expansion.
|
||||
pub struct OptionalEqualsUnexpanded;
|
||||
|
||||
impl Parsable for OptionalEqualsUnexpanded {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
parse_optional_equals(input.unexpanded())?;
|
||||
Ok(OptionalEqualsUnexpanded {})
|
||||
}
|
||||
}
|
||||
|
||||
// Corresponds to the `scan_optional_equals` procedure in Knuth's TeX (405)
|
||||
fn parse_optional_equals<S: TexlangState, I: TokenStream<S = S>>(input: &mut I) -> txl::Result<()> {
|
||||
while let Some(found_equals) = get_optional_element![
|
||||
input,
|
||||
token::Value::Other('=') => true,
|
||||
token::Value::Space(_) => false,
|
||||
] {
|
||||
if found_equals {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// TODO: this is not correct: this function should not scan spaces after the equals.
|
||||
// A separate routine corresponding to Knuth TeX 404 needs to be added and used instead
|
||||
// at the right call sites.
|
||||
while get_optional_element![
|
||||
input,
|
||||
token::Value::Space(_) => (),
|
||||
]
|
||||
.is_some()
|
||||
{}
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user