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
+54
@@ -0,0 +1,54 @@
|
||||
[package]
|
||||
name = "texlang-stdlib"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
description = "The Texlang standard library of TeX primitives"
|
||||
homepage = "https://texcraft.dev"
|
||||
repository = "https://github.com/jamespfennell/texcraft"
|
||||
keywords = ["tex", "texcraft"]
|
||||
|
||||
[[bin]]
|
||||
name = "texlang-all-errors"
|
||||
path = "bin/errors.rs"
|
||||
|
||||
[dependencies]
|
||||
# Texcraft
|
||||
common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
|
||||
texcraft-stdext = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
|
||||
texlang = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
|
||||
texlang-common = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
|
||||
|
||||
# This should be a dev-dependency, but this breaks `cargo t`
|
||||
# I think there's actually a bug in cargo.
|
||||
# The problem is that it invokes `rustc` on texlang_testing with
|
||||
# the serde feature enabled but without passing serde as a dependency.
|
||||
texlang-testing = { git = "https://github.com/jamespfennell/texcraft", rev = "c1dbf5dfe3a480daf73972c394ac8231e0c6ebd0" }
|
||||
|
||||
# Third-party
|
||||
|
||||
## In the time module, for getting the current time on startup.
|
||||
chrono = {version="0.4.19", default-features = false, features = ["clock"], optional = true}
|
||||
|
||||
## In the REPL module, for reading terminal input in a nice way
|
||||
linefeed = {version = "0.6", optional = true }
|
||||
|
||||
## The usual suspects
|
||||
serde = {version="^1.0", optional = true}
|
||||
serde_json = {version="1.0", optional = true}
|
||||
rmp-serde = {version="^1.0", optional = true}
|
||||
bincode = {version="2.0.0-rc.3", default-features = false, features = ["alloc", "serde"], optional = true}
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
[features]
|
||||
default = ["time"]
|
||||
color = ["texcraft-stdext/color"]
|
||||
repl = ["dep:linefeed"]
|
||||
serde = [
|
||||
"dep:serde", "dep:serde_json", "dep:rmp-serde",
|
||||
"dep:bincode", "texcraft-stdext/serde", "texlang/serde",
|
||||
"texlang-testing/serde"
|
||||
]
|
||||
time = ["dep:chrono"]
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
# The Texlang standard library of TeX primitives
|
||||
|
||||
This crate contains a collection of standard non-typesetting
|
||||
TeX primitives that can be used in any Texlang VM.
|
||||
|
||||
See the Texcraft homepage or the GitHub repo for more information.
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
use texlang::*;
|
||||
use texlang_stdlib::*;
|
||||
|
||||
fn main() {
|
||||
println!("# All Texlang errors\n");
|
||||
for case in ErrorCase::all_error_cases() {
|
||||
let result = run(case);
|
||||
println!(
|
||||
"## {}\n\nInput:\n```\n{}\n```\nOutput:\n```\n{}```\n\n",
|
||||
result.case.description, result.case.source_code, result.err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct RunResult {
|
||||
case: ErrorCase,
|
||||
err: Box<error::TracedTexError>,
|
||||
}
|
||||
|
||||
fn run(case: ErrorCase) -> RunResult {
|
||||
let mut vm = vm::VM::<StdLibState>::new();
|
||||
vm.push_source("input.tex", case.source_code).unwrap();
|
||||
let err = match vm.run::<vm::DefaultHandlers>() {
|
||||
Ok(_) => panic!(
|
||||
"successfully ran {} (`{}`) but expected an error",
|
||||
case.description, case.source_code
|
||||
),
|
||||
Err(err) => err,
|
||||
};
|
||||
RunResult { case, err }
|
||||
}
|
||||
Vendored
+138
@@ -0,0 +1,138 @@
|
||||
//! `\let` aliasing command
|
||||
|
||||
use crate::prefix;
|
||||
use texlang::parse::OptionalEqualsUnexpanded;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
pub const LET_DOC: &str = "Assign a command or character to a control sequence";
|
||||
|
||||
/// Get the `\let` command.
|
||||
pub fn get_let<S: HasComponent<prefix::Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(let_primitive_fn)
|
||||
.with_tag(let_tag())
|
||||
.with_doc(LET_DOC)
|
||||
}
|
||||
|
||||
static LET_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
pub fn let_tag() -> command::Tag {
|
||||
LET_TAG.get()
|
||||
}
|
||||
|
||||
fn let_primitive_fn<S: HasComponent<prefix::Component>>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
// TeX.2021.1221
|
||||
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
let cmd_ref_or = Option::<token::CommandRef>::parse(input)?;
|
||||
OptionalEqualsUnexpanded::parse(input)?;
|
||||
let token = input.unexpanded().next_or_err(LetEndOfInputError {})?;
|
||||
if let Some(cmd_ref) = cmd_ref_or {
|
||||
match token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
input
|
||||
.commands_map_mut()
|
||||
.alias_control_sequence(cmd_ref, &command_ref, scope);
|
||||
}
|
||||
_ => {
|
||||
input.commands_map_mut().alias_token(cmd_ref, token, scope);
|
||||
}
|
||||
};
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct LetEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for LetEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"parsing the right hand side of a \let assignment".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use crate::def;
|
||||
use crate::the;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct State {
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
implement_has_component![State {
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
impl the::TheCompatible for State {}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn variable_assignment_scope_hook(
|
||||
state: &mut Self,
|
||||
) -> texcraft_stdext::collections::groupingmap::Scope {
|
||||
prefix::variable_assignment_scope_hook(state)
|
||||
}
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
TestingComponent::recoverable_error_hook(self, recoverable_error)
|
||||
}
|
||||
}
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("def", def::get_def()),
|
||||
("global", prefix::get_global()),
|
||||
("integer", TestingComponent::get_integer()),
|
||||
("let", get_let()),
|
||||
("the", the::get_the()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(let_for_macro, r"\def\A{abc}\let\B\A\B", "abc"),
|
||||
(let_for_macro_active_char, r"\def\A{abc}\let~\A~", "abc"),
|
||||
(local, r"\def\A{a}\def\B{b}\let\C=\A{\let\C=\B \C}\C", "ba"),
|
||||
(
|
||||
global,
|
||||
r"\def\A{a}\def\B{b}\let\C=\A{\global\let\C=\B \C}\C",
|
||||
"bb"
|
||||
),
|
||||
(let_for_macro_equals, r"\def\A{abc}\let\B=\A\B", "abc"),
|
||||
(let_character, r"\let\A=B\A", "B"),
|
||||
(let_unknown_cs_name, r"\let \B=\undefined", ""),
|
||||
),
|
||||
recoverable_failure_tests((missing_cs, r"\def\B{Hello}\let A=\B World", "=HelloWorld"),),
|
||||
serde_tests(
|
||||
(
|
||||
alias_execution_primitive,
|
||||
r"\let\defNew=\def",
|
||||
r"\defNew\A{abc}\A"
|
||||
),
|
||||
(
|
||||
alias_expansion_primitive,
|
||||
r"\let\theNew=\the",
|
||||
r"\integer=3\theNew\integer"
|
||||
),
|
||||
(
|
||||
alias_variable_singleton,
|
||||
r"\let\integerNew=\integer",
|
||||
r"\integerNew=3\the\integer"
|
||||
),
|
||||
(serde_macro, r"\def\A{Hello World}\let\B=\A ", r"\A \B",),
|
||||
(serde_character, r"\let\A=B ", r"\A",),
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+268
@@ -0,0 +1,268 @@
|
||||
//! Dynamic allocation of variables and arrays
|
||||
//!
|
||||
//! This module contains implementations of brand new Texcraft commands
|
||||
//! `\newInt` and `\newIntArray` which perform dynamic memory allocation.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use texcraft_stdext::collections::groupingmap;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
pub const NEWINT_DOC: &str = r"Allocate a new integer
|
||||
|
||||
Usage: `\newInt <control sequence>`
|
||||
|
||||
The `\newInt` command allocates a new integer
|
||||
that is referenced using the provided control sequence.
|
||||
Simple example:
|
||||
|
||||
```
|
||||
\newInt \myvariable
|
||||
\myvariable = 4
|
||||
\advance \myvariable by 5
|
||||
\asserteq{\the \myvariable}{9}
|
||||
```
|
||||
|
||||
You can think of `\newInt` as being a replacement for
|
||||
Plain TeX's `\newcount` macro (TeXBook p346).
|
||||
The benefit of `\newInt` is that different callers of the command
|
||||
do not share the underlying memory; the allocated memory is unique
|
||||
to the caller.
|
||||
Under the hood `\newInt` works by allocating new memory on the TeX engine's heap.
|
||||
";
|
||||
|
||||
pub const NEWINTARRAY_DOC: &str = r"Allocate a new integer array
|
||||
|
||||
Usage: `\newIntArray <control sequence> <array length>`
|
||||
|
||||
The `\newIntArray` command allocates a new array of integers that
|
||||
is referenced using the provided control sequence.
|
||||
This new control sequence works pretty much like `\count`, but you can create
|
||||
as many arrays as you like and don't need to worry about other
|
||||
TeX code reusing the memory.
|
||||
Unlike `\count`, the size of the array is not fixed by
|
||||
the engine.
|
||||
The only constraint on the size is that you have enough RAM
|
||||
on the machine to store it.
|
||||
Simple example:
|
||||
|
||||
```
|
||||
\newIntArray \myarray 3
|
||||
\myarray 0 = 4
|
||||
\asserteq{\the \myarray 0}{4}
|
||||
\myarray 1 = 5
|
||||
\asserteq{\the \myarray 1}{5}
|
||||
\myarray 2 = 6
|
||||
\asserteq{\the \myarray 2}{6}
|
||||
```
|
||||
|
||||
The new control sequence can *not* be aliased using \let.
|
||||
";
|
||||
|
||||
/// Component required for the alloc commands.
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
singletons: Vec<i32>,
|
||||
arrays: Vec<i32>,
|
||||
#[cfg_attr(feature = "serde", serde(with = "texcraft_stdext::serde_tools::iter"))]
|
||||
array_refs: HashMap<token::CommandRef, (usize, usize)>,
|
||||
}
|
||||
|
||||
/// Get the `\newInt` execution command.
|
||||
pub fn get_newint<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(newint_primitive_fn)
|
||||
}
|
||||
|
||||
fn newint_primitive_fn<S: HasComponent<Component>>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let command_ref = Option::<token::CommandRef>::parse(input)?;
|
||||
let Some(command_ref) = command_ref else {
|
||||
return Ok(());
|
||||
};
|
||||
let component = input.state_mut().component_mut();
|
||||
let index = component.singletons.len();
|
||||
component.singletons.push(Default::default());
|
||||
input.commands_map_mut().insert_variable_command(
|
||||
command_ref,
|
||||
variable::Command::new_array(
|
||||
singleton_ref_fn,
|
||||
singleton_mut_ref_fn,
|
||||
variable::IndexResolver::Static(variable::Index(index)),
|
||||
),
|
||||
groupingmap::Scope::Local,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn singleton_ref_fn<S: HasComponent<Component>>(state: &S, index: variable::Index) -> &i32 {
|
||||
&state.component().singletons[index.0]
|
||||
}
|
||||
|
||||
fn singleton_mut_ref_fn<S: HasComponent<Component>>(
|
||||
state: &mut S,
|
||||
index: variable::Index,
|
||||
) -> &mut i32 {
|
||||
&mut state.component_mut().singletons[index.0]
|
||||
}
|
||||
|
||||
/// Return a getter provider for the `\newInt` command.
|
||||
///
|
||||
/// The built-in commands for a VM must include this command in order for
|
||||
/// the allocation component to be serializable.
|
||||
pub fn get_newint_getter_provider<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_getter_provider(singleton_ref_fn, singleton_mut_ref_fn).into()
|
||||
}
|
||||
|
||||
/// Get the `\newIntArray` execution command.
|
||||
pub fn get_newintarray<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(newintarray_primitive_fn)
|
||||
}
|
||||
|
||||
fn newintarray_primitive_fn<S: HasComponent<Component>>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let command_ref = Option::<token::CommandRef>::parse(input)?;
|
||||
let len = parse::Uint::<{ parse::Uint::MAX }>::parse(input)?.0;
|
||||
let Some(command_ref) = command_ref else {
|
||||
return Ok(());
|
||||
};
|
||||
let component = input.state_mut().component_mut();
|
||||
let start = component.arrays.len();
|
||||
component.arrays.resize(start + len, Default::default());
|
||||
component.array_refs.insert(command_ref, (start, len));
|
||||
input.commands_map_mut().insert_variable_command(
|
||||
command_ref,
|
||||
variable::Command::new_array(
|
||||
array_element_ref_fn,
|
||||
array_element_mut_ref_fn,
|
||||
variable::IndexResolver::Dynamic(resolve),
|
||||
),
|
||||
groupingmap::Scope::Local,
|
||||
);
|
||||
// TODO: Return the arraydef version
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve<S: HasComponent<Component>>(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<variable::Index> {
|
||||
let command_ref = match token.value() {
|
||||
token::Value::CommandRef(command_ref) => command_ref,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let (array_index, array_len) = *input
|
||||
.state()
|
||||
.component()
|
||||
.array_refs
|
||||
.get(&command_ref)
|
||||
.unwrap();
|
||||
let inner_index = parse::Uint::<{ parse::Uint::MAX }>::parse(input)?.0;
|
||||
if inner_index >= array_len {
|
||||
return Err(input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
format![
|
||||
"Array out of bounds: cannot access index {inner_index} of array with length {array_len}"
|
||||
],
|
||||
)
|
||||
));
|
||||
}
|
||||
Ok(variable::Index(array_index + inner_index))
|
||||
}
|
||||
|
||||
fn array_element_ref_fn<S: HasComponent<Component>>(state: &S, index: variable::Index) -> &i32 {
|
||||
&state.component().arrays[index.0]
|
||||
}
|
||||
|
||||
fn array_element_mut_ref_fn<S: HasComponent<Component>>(
|
||||
state: &mut S,
|
||||
index: variable::Index,
|
||||
) -> &mut i32 {
|
||||
&mut state.component_mut().arrays[index.0]
|
||||
}
|
||||
|
||||
/// Return a getter provider for the `\newIntArray` command.
|
||||
///
|
||||
/// The built-in commands for a VM must include this command in order to support
|
||||
/// the allocation component to be serializable.
|
||||
pub fn get_newintarray_getter_provider<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_array(
|
||||
array_element_ref_fn,
|
||||
array_element_mut_ref_fn,
|
||||
variable::IndexResolver::Dynamic(resolve),
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::the;
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct State {
|
||||
alloc: Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {}
|
||||
|
||||
implement_has_component![State {
|
||||
alloc: Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
impl the::TheCompatible for State {}
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("newInt", get_newint()),
|
||||
("newInt_getter_provider_\u{0}", get_newint_getter_provider()),
|
||||
("newIntArray", get_newintarray()),
|
||||
(
|
||||
"newIntArray_getter_provider_\u{0}",
|
||||
get_newintarray_getter_provider(),
|
||||
),
|
||||
("the", the::get_the()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(newint_base_case, r"\newInt\a \a=3 \the\a", "3"),
|
||||
(
|
||||
newintarray_base_case_0,
|
||||
r"\newIntArray \a 3 \a 0 = 2 \the\a 0",
|
||||
"2"
|
||||
),
|
||||
(newint_active_char, r"\newInt~~=3 \the~", "3"),
|
||||
(
|
||||
newintarray_base_case_1,
|
||||
r"\newIntArray \a 3 \a 1 = 2 \the\a 1",
|
||||
"2"
|
||||
),
|
||||
(
|
||||
newintarray_base_case_2,
|
||||
r"\newIntArray \a 3 \a 2 = 5 \the\a 2",
|
||||
"5"
|
||||
),
|
||||
(newintarray_active_char, r"\newIntArray~3~2=5 \the~2", "5"),
|
||||
),
|
||||
serde_tests(
|
||||
(serde_singleton, r"\newInt\a \a=-1 ", r"\the\a"),
|
||||
(serde_array, r"\newIntArray\a 20 \a 3=-1 ", r"\the\a 3"),
|
||||
),
|
||||
fatal_error_tests(
|
||||
(newintarray_out_of_bounds, r"\newIntArray \a 3 \a 3 = 2"),
|
||||
(newintarray_negative_index, r"\newIntArray \a 3 \a -3 = 2"),
|
||||
(newintarray_negative_length, r"\newIntArray \a -3"),
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
//! The `\chardef` primitive.
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
/// Get the `\chardef` command.
|
||||
pub fn get_chardef<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(chardef_primitive_fn)
|
||||
}
|
||||
|
||||
fn chardef_primitive_fn<S: TexlangState>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
let (cmd_ref_or, _, c) =
|
||||
<(Option<token::CommandRef>, parse::OptionalEquals, char)>::parse(input)?;
|
||||
if let Some(cmd_ref) = cmd_ref_or {
|
||||
input
|
||||
.commands_map_mut()
|
||||
.insert(cmd_ref, command::Command::Character(c), scope);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::the;
|
||||
use std::collections::HashMap;
|
||||
use texlang_testing::*;
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("chardef", get_chardef()),
|
||||
("the", the::get_the()),
|
||||
("i", TestingComponent::get_integer()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(basic_case, r"\chardef\Hello = `\+ \Hello", "+"),
|
||||
(
|
||||
basic_case_with_the,
|
||||
r"\chardef\Hello = 123 \the\Hello",
|
||||
"123"
|
||||
),
|
||||
(
|
||||
parsable_as_number,
|
||||
r"\chardef\Hello = 13 \i=\Hello x\the\i",
|
||||
"x13"
|
||||
),
|
||||
(
|
||||
parsable_as_number_negative,
|
||||
r"\chardef\Hello = 13 \i=-\Hello x\the\i",
|
||||
"x-13"
|
||||
),
|
||||
),
|
||||
serde_tests((basic_case, r"\chardef\Hello = `\+ ", r"\Hello"),),
|
||||
];
|
||||
}
|
||||
Vendored
+225
@@ -0,0 +1,225 @@
|
||||
//! Primitives for setting codes (`\catcode`, `\mathcode`, etc.)
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::types::CatCode;
|
||||
use texlang::*;
|
||||
|
||||
pub trait Code: Copy + Debug + Default + variable::SupportedType {
|
||||
const COMMAND_DOC: &'static str;
|
||||
fn default_low_values() -> [Self; 128] {
|
||||
[Self::default(); 128]
|
||||
}
|
||||
}
|
||||
|
||||
impl Code for CatCode {
|
||||
const COMMAND_DOC: &'static str = "Get or set a cat code register";
|
||||
fn default_low_values() -> [Self; 128] {
|
||||
CatCode::PLAIN_TEX_DEFAULTS
|
||||
}
|
||||
}
|
||||
|
||||
impl Code for types::MathCode {
|
||||
const COMMAND_DOC: &'static str = "Get or set a math code register";
|
||||
// TODO: default_low_values
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component<T: Code> {
|
||||
#[cfg_attr(feature = "serde", serde(with = "texcraft_stdext::serde_tools::array"))]
|
||||
low: [T; 128],
|
||||
high: HashMap<usize, T>,
|
||||
default: T,
|
||||
}
|
||||
|
||||
impl<T: Code> Component<T> {
|
||||
#[inline]
|
||||
pub fn get(&self, u: usize) -> &T {
|
||||
match self.low.get(u) {
|
||||
None => self.high.get(&u).unwrap_or(&self.default),
|
||||
Some(cat_code) => cat_code,
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_mut(&mut self, u: usize) -> &mut T {
|
||||
match self.low.get_mut(u) {
|
||||
None => self.high.entry(u).or_insert(self.default),
|
||||
Some(cat_code) => cat_code,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Code> Default for Component<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
low: T::default_low_values(),
|
||||
high: Default::default(),
|
||||
default: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the currently defined cat code of a character.
|
||||
#[inline]
|
||||
pub fn cat_code<S: HasComponent<Component<CatCode>>>(state: &S, c: char) -> CatCode {
|
||||
get_value(state, c)
|
||||
}
|
||||
|
||||
/// Get the `\catcode` command.
|
||||
pub fn get_catcode<S: HasComponent<Component<CatCode>>>() -> command::BuiltIn<S> {
|
||||
get_command::<CatCode, S>()
|
||||
}
|
||||
|
||||
/// Return the currently defined math code of a character.
|
||||
#[inline]
|
||||
pub fn math_code<S: HasComponent<Component<types::MathCode>>>(
|
||||
state: &S,
|
||||
c: char,
|
||||
) -> types::MathCode {
|
||||
get_value(state, c)
|
||||
}
|
||||
|
||||
/// Get the `\mathcode` command.
|
||||
pub fn get_mathcode<S: HasComponent<Component<types::MathCode>>>() -> command::BuiltIn<S> {
|
||||
get_command::<types::MathCode, S>()
|
||||
}
|
||||
|
||||
/// Return the currently defined math code of a character.
|
||||
#[inline]
|
||||
fn get_value<T: Code, S: HasComponent<Component<T>>>(state: &S, c: char) -> T {
|
||||
*state.component().get(c as usize)
|
||||
}
|
||||
|
||||
fn get_command<T: Code, S: HasComponent<Component<T>>>() -> command::BuiltIn<S> {
|
||||
let cmd: command::BuiltIn<S> = variable::Command::new_array(
|
||||
|state: &S, index: variable::Index| -> &T { state.component().get(index.0) },
|
||||
|state: &mut S, index: variable::Index| -> &mut T {
|
||||
state.component_mut().get_mut(index.0)
|
||||
},
|
||||
variable::IndexResolver::Dynamic(
|
||||
|_: token::Token, input: &mut vm::ExpandedStream<S>| -> txl::Result<variable::Index> {
|
||||
let c = char::parse(input)?;
|
||||
let u = c as usize;
|
||||
Ok(u.into())
|
||||
},
|
||||
),
|
||||
)
|
||||
.into();
|
||||
cmd.with_doc(T::COMMAND_DOC)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::the;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct State {
|
||||
catcode: Component<CatCode>,
|
||||
math_code: Component<types::MathCode>,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
TestingComponent::recoverable_error_hook(self, recoverable_error)
|
||||
}
|
||||
}
|
||||
impl the::TheCompatible for State {}
|
||||
|
||||
implement_has_component![State {
|
||||
catcode: Component<CatCode>,
|
||||
math_code: Component<types::MathCode>,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("the", the::get_the()),
|
||||
("catcode", get_catcode()),
|
||||
("mathcode", get_mathcode()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(catcode_base_case, r"\catcode 48 11 \the\catcode 48", r"11"),
|
||||
(
|
||||
catcode_grouping,
|
||||
r"{\catcode 48 11 \the\catcode 48}-\the\catcode 48",
|
||||
r"11-12"
|
||||
),
|
||||
(catcode_default, r"\the\catcode 48", r"12"),
|
||||
(
|
||||
mathcode_base_case,
|
||||
r"\mathcode 48 11 \the\mathcode 48",
|
||||
r"11"
|
||||
),
|
||||
(
|
||||
mathcode_grouping,
|
||||
r"{\mathcode 48 11 \the\mathcode 48}-\the\mathcode 48",
|
||||
r"11-0"
|
||||
),
|
||||
(mathcode_default, r"\the\mathcode 48", r"0"),
|
||||
(
|
||||
mathcode_math_active,
|
||||
r#"\mathcode 48 "8000 \the\mathcode 48"#,
|
||||
r"32768"
|
||||
),
|
||||
),
|
||||
serde_tests(
|
||||
(catcode_serde_low, r"\catcode 48 11 ", r"\the\catcode 48"),
|
||||
(catcode_serde_high, r"\catcode 480 11 ", r"\the\catcode 480"),
|
||||
(
|
||||
catcode_serde_group,
|
||||
r"\catcode 65 7 {r\catcode 65 8 ",
|
||||
r"\the\catcode 65 } \the\catcode 65"
|
||||
),
|
||||
(mathcode_serde_low, r"\mathcode 48 11 ", r"\the\mathcode 48"),
|
||||
(
|
||||
mathcode_serde_high,
|
||||
r"\mathcode 480 11 ",
|
||||
r"\the\mathcode 480"
|
||||
),
|
||||
(
|
||||
mathcode_serde_group,
|
||||
r"\mathcode 65 7 {r\mathcode 65 8 ",
|
||||
r"\the\mathcode 65 } \the\mathcode 65"
|
||||
),
|
||||
),
|
||||
recoverable_failure_tests(
|
||||
(
|
||||
catcode_value_too_large,
|
||||
r"\catcode 48 16 \the\catcode 48",
|
||||
"0"
|
||||
),
|
||||
(
|
||||
catcode_value_is_negative,
|
||||
r"\catcode 48 -1 \the\catcode 48",
|
||||
"0"
|
||||
),
|
||||
(
|
||||
mathcode_value_too_large,
|
||||
r"\mathcode 48 33000 \the\mathcode 48",
|
||||
"0"
|
||||
),
|
||||
(
|
||||
mathcode_value_just_too_large,
|
||||
r#"\mathcode 48 "8001 \the\mathcode 48"#,
|
||||
"0"
|
||||
),
|
||||
(
|
||||
mathcode_value_is_negative,
|
||||
r"\mathcode 48 -1 \the\mathcode 48",
|
||||
"0"
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
+652
@@ -0,0 +1,652 @@
|
||||
//! Control flow primitives (if, else, switch)
|
||||
//!
|
||||
//! This module contains implementations of generic conditional commands,
|
||||
//! as well as a mechanism for adding new conditional commands outside
|
||||
//! of this module.
|
||||
//! See the [Condition] trait for information on adding new commands.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use texlang::parse::Ordering;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
const ELSE_DOC: &str = "Start the else branch of a conditional or switch statement";
|
||||
const IFCASE_DOC: &str = "Begin a switch statement";
|
||||
const IFNUM_DOC: &str = "Compare two variables";
|
||||
const IFODD_DOC: &str = "Check if a variable is odd";
|
||||
const IFTRUE_DOC: &str = "Evaluate the true branch";
|
||||
const IFFALSE_DOC: &str = "Evaluate the false branch";
|
||||
const FI_DOC: &str = "End a conditional or switch statement";
|
||||
const OR_DOC: &str = "Begin the next branch of a switch statement";
|
||||
|
||||
/// A component for keeping track of conditional branches as they are expanded.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Default)]
|
||||
pub struct Component {
|
||||
// Branches is a stack where each element corresponds to a conditional that is currently
|
||||
// expanding. A nested conditional is further up the stack than the conditional it is
|
||||
// nested in.
|
||||
//
|
||||
// This stack is used to
|
||||
// verify that \else and \fi tokens are valid; i.e., if a \else is encountered, the current
|
||||
// conditional must be true otherwise the \else is invalid. For correct TeX code, the stack
|
||||
// is never actually used.
|
||||
//
|
||||
// Because the conditional commands are expansion commands, they cannot get a mutable reference
|
||||
// to the state. We thus wrap the branches in a ref cell to support mutating them through
|
||||
// an immutable reference.
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
serde(
|
||||
serialize_with = "serialize_branches",
|
||||
deserialize_with = "deserialize_branches"
|
||||
)
|
||||
)]
|
||||
branches: RefCell<Vec<Branch>>,
|
||||
|
||||
// We cache the tag values inside the component for performance reasons.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
tags: Tags,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn serialize_branches<S>(input: &RefCell<Vec<Branch>>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
use serde::Serialize;
|
||||
let slice: &[Branch] = &input.borrow();
|
||||
slice.serialize(serializer)
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn deserialize_branches<'de, D>(deserializer: D) -> Result<RefCell<Vec<Branch>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
use serde::Deserialize;
|
||||
let vec = Vec::<Branch>::deserialize(deserializer)?;
|
||||
Ok(RefCell::new(vec))
|
||||
}
|
||||
|
||||
struct Tags {
|
||||
if_tag: command::Tag,
|
||||
else_tag: command::Tag,
|
||||
or_tag: command::Tag,
|
||||
fi_tag: command::Tag,
|
||||
}
|
||||
|
||||
impl Default for Tags {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
if_tag: IF_TAG.get(),
|
||||
else_tag: ELSE_TAG.get(),
|
||||
or_tag: OR_TAG.get(),
|
||||
fi_tag: FI_TAG.get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
enum BranchKind {
|
||||
// The true branch of an if conditional.
|
||||
True,
|
||||
// The false branch of an if conditional, or the default branch of a switch statement.
|
||||
Else,
|
||||
// A regular case brach of a switch statement.
|
||||
Switch,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct Branch {
|
||||
_token: token::Token,
|
||||
kind: BranchKind,
|
||||
}
|
||||
|
||||
fn push_branch<S: HasComponent<Component>>(input: &mut vm::ExpansionInput<S>, branch: Branch) {
|
||||
input.state().component().branches.borrow_mut().push(branch)
|
||||
}
|
||||
|
||||
fn pop_branch<S: HasComponent<Component>>(input: &mut vm::ExpansionInput<S>) -> Option<Branch> {
|
||||
input.state().component().branches.borrow_mut().pop()
|
||||
}
|
||||
|
||||
static IF_TAG: command::StaticTag = command::StaticTag::new();
|
||||
static ELSE_TAG: command::StaticTag = command::StaticTag::new();
|
||||
static OR_TAG: command::StaticTag = command::StaticTag::new();
|
||||
static FI_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
// The `true_case` function is executed whenever a conditional evaluates to true.
|
||||
fn true_case<S: HasComponent<Component>>(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
push_branch(
|
||||
input,
|
||||
Branch {
|
||||
_token: token,
|
||||
kind: BranchKind::True,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The `false_case` function is executed whenever a conditional evaluates to false.
|
||||
//
|
||||
// The function scans forward in the input stream, discarding all tokens, until it encounters
|
||||
// either a \else or \fi command.
|
||||
fn false_case<S: HasComponent<Component>>(
|
||||
original_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let token = input
|
||||
.unexpanded()
|
||||
.next_or_err(FalseBranchEndOfInputError {})?;
|
||||
if let token::Value::CommandRef(command_ref) = &token.value() {
|
||||
let tag = input.commands_map().get_tag(command_ref);
|
||||
if tag == Some(input.state().component().tags.else_tag) && depth == 0 {
|
||||
push_branch(
|
||||
input,
|
||||
Branch {
|
||||
_token: original_token,
|
||||
kind: BranchKind::Else,
|
||||
},
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if tag == Some(input.state().component().tags.if_tag) {
|
||||
depth += 1;
|
||||
}
|
||||
if tag == Some(input.state().component().tags.fi_tag) {
|
||||
depth -= 1;
|
||||
if depth < 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FalseBranchEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for FalseBranchEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"skipping the true branch of an conditional command".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
"each `if` command must be terminated by a `fi` command, with an optional `else` in between".into(),
|
||||
"this `if` command evaluated to false, and the input ended while skipping the true branch".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Logical condition used to build `if` conditional commands.
|
||||
///
|
||||
/// This trait can be used to build new conditional commands outside of this module.
|
||||
/// To do this, just create a new type (generally a ZST)
|
||||
/// and implement the [`evaluate`](Condition::evaluate) method of the trait for the type.
|
||||
/// A conditional command that uses the condition can then be obtained
|
||||
/// using the [`build_if_command`](Condition::build_if_command) method.
|
||||
pub trait Condition<S: HasComponent<Component>> {
|
||||
/// Optional documentation for the command built using this condition.
|
||||
const DOC: Option<&'static str> = None;
|
||||
|
||||
/// Evaluate the condition.
|
||||
///
|
||||
/// Returns `true` if the condition is true, `false` if it is false,
|
||||
/// and an error otherwise.
|
||||
fn evaluate(input: &mut vm::ExpansionInput<S>) -> txl::Result<bool>;
|
||||
|
||||
/// Build an `if` conditional command that uses this condition.
|
||||
fn build_if_command() -> command::BuiltIn<S> {
|
||||
let primitive_fn =
|
||||
|token: token::Token, input: &mut vm::ExpansionInput<S>| -> txl::Result<()> {
|
||||
match Self::evaluate(input)? {
|
||||
true => true_case(token, input),
|
||||
false => false_case(token, input),
|
||||
}
|
||||
};
|
||||
let mut cmd = command::BuiltIn::new_expansion(primitive_fn).with_tag(IF_TAG.get());
|
||||
if let Some(doc) = Self::DOC {
|
||||
cmd = cmd.with_doc(doc)
|
||||
};
|
||||
cmd
|
||||
}
|
||||
}
|
||||
|
||||
struct IfTrue;
|
||||
|
||||
impl<S: HasComponent<Component>> Condition<S> for IfTrue {
|
||||
const DOC: Option<&'static str> = Some(IFTRUE_DOC);
|
||||
|
||||
fn evaluate(_: &mut vm::ExpansionInput<S>) -> txl::Result<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\iftrue` primitive.
|
||||
pub fn get_iftrue<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
IfTrue::build_if_command()
|
||||
}
|
||||
|
||||
struct IfFalse;
|
||||
|
||||
impl<S: HasComponent<Component>> Condition<S> for IfFalse {
|
||||
const DOC: Option<&'static str> = Some(IFFALSE_DOC);
|
||||
|
||||
fn evaluate(_: &mut vm::ExpansionInput<S>) -> txl::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\iffalse` primitive.
|
||||
pub fn get_iffalse<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
IfFalse::build_if_command()
|
||||
}
|
||||
|
||||
struct IfNum;
|
||||
|
||||
impl<S: HasComponent<Component>> Condition<S> for IfNum {
|
||||
const DOC: Option<&'static str> = Some(IFNUM_DOC);
|
||||
|
||||
fn evaluate(input: &mut vm::ExpansionInput<S>) -> txl::Result<bool> {
|
||||
let (a, o, b) = <(i32, Ordering, i32)>::parse(input)?;
|
||||
Ok(a.cmp(&b) == o.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\ifnum` primitive.
|
||||
pub fn get_ifnum<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
IfNum::build_if_command()
|
||||
}
|
||||
|
||||
struct IfOdd;
|
||||
|
||||
impl<S: HasComponent<Component>> Condition<S> for IfOdd {
|
||||
const DOC: Option<&'static str> = Some(IFODD_DOC);
|
||||
|
||||
fn evaluate(input: &mut vm::ExpansionInput<S>) -> txl::Result<bool> {
|
||||
let n = i32::parse(input)?;
|
||||
Ok((n % 2) == 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\ifodd` primitive.
|
||||
pub fn get_ifodd<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
IfOdd::build_if_command()
|
||||
}
|
||||
|
||||
fn if_case_primitive_fn<S: HasComponent<Component>>(
|
||||
ifcase_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
// TODO: should we reading the number from the unexpanded stream? Probably!
|
||||
let total_cases_to_skip = i32::parse(input)?;
|
||||
if total_cases_to_skip == 0 {
|
||||
push_branch(
|
||||
input,
|
||||
Branch {
|
||||
_token: ifcase_token,
|
||||
kind: BranchKind::Switch,
|
||||
},
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let mut cases_left_to_skip = total_cases_to_skip;
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let token = input.unexpanded().next_or_err(IfCaseEndOfInputError {
|
||||
total_cases_to_skip,
|
||||
cases_left_to_skip,
|
||||
})?;
|
||||
if let token::Value::CommandRef(command_ref) = &token.value() {
|
||||
let tag = input.commands_map().get_tag(command_ref);
|
||||
if tag == Some(input.state().component().tags.or_tag) && depth == 0 {
|
||||
cases_left_to_skip -= 1;
|
||||
if cases_left_to_skip == 0 {
|
||||
push_branch(
|
||||
input,
|
||||
Branch {
|
||||
_token: ifcase_token,
|
||||
kind: BranchKind::Switch,
|
||||
},
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if tag == Some(input.state().component().tags.else_tag) && depth == 0 {
|
||||
push_branch(
|
||||
input,
|
||||
Branch {
|
||||
_token: ifcase_token,
|
||||
kind: BranchKind::Else,
|
||||
},
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if tag == Some(input.state().component().tags.if_tag) {
|
||||
depth += 1;
|
||||
}
|
||||
if tag == Some(input.state().component().tags.fi_tag) {
|
||||
depth -= 1;
|
||||
if depth < 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IfCaseEndOfInputError {
|
||||
total_cases_to_skip: i32,
|
||||
cases_left_to_skip: i32,
|
||||
}
|
||||
|
||||
impl error::EndOfInputError for IfCaseEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"skipping cases in an `ifcase` command".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
"each `ifcase` command must be matched by a `or`, `else` or `fi` command".into(),
|
||||
format![
|
||||
"this `ifcase` case evaluated to {}",
|
||||
self.total_cases_to_skip
|
||||
]
|
||||
.into(),
|
||||
format![
|
||||
"the input ended while skipping case {}",
|
||||
self.total_cases_to_skip + 1 - self.cases_left_to_skip
|
||||
]
|
||||
.into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\ifcase` primitive.
|
||||
pub fn get_ifcase<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(if_case_primitive_fn)
|
||||
.with_tag(IF_TAG.get())
|
||||
.with_doc(IFCASE_DOC)
|
||||
}
|
||||
|
||||
fn or_primitive_fn<S: HasComponent<Component>>(
|
||||
ifcase_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let branch = pop_branch(input);
|
||||
// For an or command to be valid, we must be in a switch statement
|
||||
let is_valid = match branch {
|
||||
None => false,
|
||||
Some(branch) => matches!(branch.kind, BranchKind::Switch),
|
||||
};
|
||||
if !is_valid {
|
||||
input.error(error::SimpleTokenError::new(
|
||||
ifcase_token,
|
||||
"unexpected `or` command",
|
||||
))?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let token = input.unexpanded().next_or_err(OrEndOfInputError {})?;
|
||||
if let token::Value::CommandRef(command_ref) = &token.value() {
|
||||
let tag = input.commands_map().get_tag(command_ref);
|
||||
if tag == Some(input.state().component().tags.if_tag) {
|
||||
depth += 1;
|
||||
}
|
||||
if tag == Some(input.state().component().tags.fi_tag) {
|
||||
depth -= 1;
|
||||
if depth < 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OrEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for OrEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"skipping cases in an `ifcase` command".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
"each `or` command must be terminated by a `fi` command".into(),
|
||||
"this `or` corresponds to an `ifcase` command that evaluated to %d, and the input ended while skipping the remaining cases".into(),
|
||||
"this is the `ifcase` command involved in the error:".into(),
|
||||
"this is the `or` command involved in the error:".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\or` primitive.
|
||||
pub fn get_or<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(or_primitive_fn)
|
||||
.with_tag(OR_TAG.get())
|
||||
.with_doc(OR_DOC)
|
||||
}
|
||||
|
||||
fn else_primitive_fn<S: HasComponent<Component>>(
|
||||
else_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let branch = pop_branch(input);
|
||||
// For else token to be valid, we must be in the true branch of a conditional
|
||||
let is_valid = match branch {
|
||||
None => false,
|
||||
Some(branch) => matches!(branch.kind, BranchKind::True | BranchKind::Switch),
|
||||
};
|
||||
if !is_valid {
|
||||
input.error(error::SimpleTokenError::new(
|
||||
else_token,
|
||||
"unexpected `else` command",
|
||||
))?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Now consume all of the tokens until the next \fi
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let token = input.unexpanded().next_or_err(ElseEndOfInputError {})?;
|
||||
if let token::Value::CommandRef(command_ref) = &token.value() {
|
||||
let tag = input.commands_map().get_tag(command_ref);
|
||||
if tag == Some(input.state().component().tags.if_tag) {
|
||||
depth += 1;
|
||||
}
|
||||
if tag == Some(input.state().component().tags.fi_tag) {
|
||||
depth -= 1;
|
||||
if depth < 0 {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ElseEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for ElseEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"skipping the false branch of an conditional command".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
"each `else` command must be terminated by a `fi` command".into(),
|
||||
"this `else` corresponds to an `if` command that evaluated to true, and the input ended while skipping the false branch".into(),
|
||||
"this is the `if` command involved in the error:".into(),
|
||||
"this is the `else` command involved in the error:".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\else` primitive.
|
||||
pub fn get_else<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(else_primitive_fn)
|
||||
.with_tag(ELSE_TAG.get())
|
||||
.with_doc(ELSE_DOC)
|
||||
}
|
||||
|
||||
/// Get the `\fi` primitive.
|
||||
fn fi_primitive_fn<S: HasComponent<Component>>(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let branch = pop_branch(input);
|
||||
// For a \fi primitive to be valid, we must be in a conditional.
|
||||
// Note that we could be in the false branch: \iftrue\else\fi
|
||||
// Or in the true branch: \iftrue\fi
|
||||
// Or in a switch statement.
|
||||
if branch.is_none() {
|
||||
input.error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"unexpected `fi` command",
|
||||
))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the `\fi` primitive.
|
||||
pub fn get_fi<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(fi_primitive_fn)
|
||||
.with_tag(FI_TAG.get())
|
||||
.with_doc(FI_DOC)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct State {
|
||||
conditional: Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
TestingComponent::recoverable_error_hook(self, error)
|
||||
}
|
||||
}
|
||||
|
||||
implement_has_component![State {
|
||||
conditional: Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("else", get_else()),
|
||||
("fi", get_fi()),
|
||||
("ifcase", get_ifcase()),
|
||||
("iffalse", get_iffalse()),
|
||||
("ifnum", get_ifnum()),
|
||||
("ifodd", get_ifodd()),
|
||||
("iftrue", get_iftrue()),
|
||||
("or", get_or()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(iftrue_base_case, r"\iftrue a\else b\fi c", r"ac"),
|
||||
(iftrue_no_else, r"\iftrue a\fi c", r"ac"),
|
||||
(
|
||||
iftrue_skip_nested_ifs,
|
||||
r"\iftrue a\else b\iftrue \else c\fi d\fi e",
|
||||
r"ae"
|
||||
),
|
||||
(iffalse_base_case, r"\iffalse a\else b\fi c", r"bc"),
|
||||
(iffalse_no_else, r"\iffalse a\fi c", r"c"),
|
||||
(
|
||||
iffalse_skip_nested_ifs,
|
||||
r"\iffalse \iftrue a\else b\fi c\else d\fi e",
|
||||
r"de"
|
||||
),
|
||||
(
|
||||
iffalse_and_iftrue_1,
|
||||
r"\iffalse a\else b\iftrue c\else d\fi e\fi f",
|
||||
r"bcef"
|
||||
),
|
||||
(
|
||||
iffalse_and_iftrue_2,
|
||||
r"\iftrue a\iffalse b\else c\fi d\else e\fi f",
|
||||
r"acdf"
|
||||
),
|
||||
(ifnum_less_than_true, r"\ifnum 4<5a\else b\fi c", r"ac"),
|
||||
(ifnum_less_than_false, r"\ifnum 5<4a\else b\fi c", r"bc"),
|
||||
(ifnum_equal_true_1, r"\ifnum 4=4a\else b\fi c", r"ac"),
|
||||
(ifnum_equal_true_2, r"\ifnum 4=4a\else b\fi c", r"ac"),
|
||||
(ifnum_equal_false, r"\ifnum 5=4a\else b\fi c", r"bc"),
|
||||
(ifnum_greater_than_true, r"\ifnum 5>4a\else b\fi c", r"ac"),
|
||||
(ifnum_greater_than_false, r"\ifnum 4>5a\else b\fi c", r"bc"),
|
||||
(ifodd_odd, r"\ifodd 3a\else b\fi c", r"ac"),
|
||||
(ifodd_even, r"\ifodd 4a\else b\fi c", r"bc"),
|
||||
(ifcase_zero_no_ors, r"\ifcase 0 a\else b\fi c", r"ac"),
|
||||
(ifcase_zero_one_or, r"\ifcase 0 a\or b\else c\fi d", r"ad"),
|
||||
(ifcase_one, r"\ifcase 1 a\or b\else c\fi d", r"bd"),
|
||||
(
|
||||
ifcase_one_more_cases,
|
||||
r"\ifcase 1 a\or b\or c\else d\fi e",
|
||||
r"be"
|
||||
),
|
||||
(ifcase_else_no_ors, r"\ifcase 1 a\else b\fi c", r"bc"),
|
||||
(ifcase_else_one_or, r"\ifcase 2 a\or b\else c\fi d", r"cd"),
|
||||
(ifcase_no_matching_case, r"\ifcase 3 a\or b\or c\fi d", r"d"),
|
||||
(
|
||||
ifcase_nested,
|
||||
r"\ifcase 1 a\or b\ifcase 1 c\or d\or e\else f\fi g\or h\fi i",
|
||||
r"bdgi"
|
||||
),
|
||||
),
|
||||
serde_tests(
|
||||
(serde_if, r"\iftrue true ", r"branch \else false branch \fi"),
|
||||
(
|
||||
serde_ifcase,
|
||||
r"\ifcase 2 a\or b\or executed ",
|
||||
r"case \or d \fi"
|
||||
),
|
||||
),
|
||||
recoverable_failure_tests(
|
||||
(
|
||||
missing_op_1,
|
||||
r"\ifnum 3 3 equal \else not equal \fi",
|
||||
"equal",
|
||||
),
|
||||
(
|
||||
missing_op_2,
|
||||
r"\ifnum 3 4 equal \else not equal \fi",
|
||||
"not equal",
|
||||
),
|
||||
(else_not_expected, r"a\else b", "ab"),
|
||||
(fi_not_expected, r"a\fi b", "ab"),
|
||||
(or_not_expected, r"a\or b", "ab"),
|
||||
),
|
||||
fatal_error_tests(
|
||||
(iftrue_end_of_input, r"\iftrue a\else b"),
|
||||
(iffalse_end_of_input, r"\iffalse a"),
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+620
@@ -0,0 +1,620 @@
|
||||
//! User-defined macros (`\def` and friends)
|
||||
|
||||
use texcraft_stdext::algorithms::substringsearch::Matcher;
|
||||
use texcraft_stdext::collections::groupingmap;
|
||||
use texcraft_stdext::collections::nevec::Nevec;
|
||||
use texcraft_stdext::nevec;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
pub const DEF_DOC: &str = "Define a custom macro";
|
||||
|
||||
/// Get the `\def` command.
|
||||
pub fn get_def<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(def_primitive_fn).with_tag(def_tag())
|
||||
}
|
||||
|
||||
/// Get the `\gdef` command.
|
||||
pub fn get_gdef<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(gdef_primitive_fn).with_tag(def_tag())
|
||||
}
|
||||
|
||||
static DEF_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
pub fn def_tag() -> command::Tag {
|
||||
DEF_TAG.get()
|
||||
}
|
||||
|
||||
fn def_primitive_fn<S: TexlangState>(
|
||||
def_token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
parse_and_set_macro(def_token, input, false)
|
||||
}
|
||||
|
||||
fn gdef_primitive_fn<S: TexlangState>(
|
||||
def_token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
parse_and_set_macro(def_token, input, true)
|
||||
}
|
||||
|
||||
fn parse_and_set_macro<S: TexlangState>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
set_globally_override: bool,
|
||||
) -> txl::Result<()> {
|
||||
let mut scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
if set_globally_override {
|
||||
scope = groupingmap::Scope::Global;
|
||||
}
|
||||
let cmd_ref_or = Option::<token::CommandRef>::parse(input)?;
|
||||
let PrefixAndParameters {
|
||||
prefix,
|
||||
raw_parameters,
|
||||
replacement_end_token,
|
||||
skip_replacement_scan,
|
||||
} = parse_prefix_and_parameters(input.unexpanded())?;
|
||||
let parameters: Vec<texmacro::Parameter> = raw_parameters
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
RawParameter::Undelimited => texmacro::Parameter::Undelimited,
|
||||
RawParameter::Delimited(vec) => texmacro::Parameter::Delimited(Matcher::new(vec)),
|
||||
})
|
||||
.collect();
|
||||
let replacement = if skip_replacement_scan {
|
||||
vec![]
|
||||
} else {
|
||||
let mut rs =
|
||||
parse_replacement_text(input.unexpanded(), replacement_end_token, parameters.len())?;
|
||||
for r in rs.iter_mut() {
|
||||
if let texmacro::Replacement::Tokens(tokens) = r {
|
||||
tokens.reverse();
|
||||
}
|
||||
}
|
||||
rs
|
||||
};
|
||||
let user_defined_macro = texmacro::Macro::new(prefix, parameters, replacement);
|
||||
if let Some(cmd_ref) = cmd_ref_or {
|
||||
input
|
||||
.commands_map_mut()
|
||||
.insert_macro(cmd_ref, user_defined_macro, scope);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum RawParameter {
|
||||
Undelimited,
|
||||
Delimited(Nevec<token::Value>),
|
||||
}
|
||||
|
||||
impl RawParameter {
|
||||
fn push(&mut self, t: token::Token) {
|
||||
match self {
|
||||
RawParameter::Undelimited => {
|
||||
*self = RawParameter::Delimited(nevec![t.value()]);
|
||||
}
|
||||
RawParameter::Delimited(vec) => {
|
||||
vec.push(t.value());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn char_to_parameter_index(c: char) -> Option<usize> {
|
||||
match c {
|
||||
'1' => Some(0),
|
||||
'2' => Some(1),
|
||||
'3' => Some(2),
|
||||
'4' => Some(3),
|
||||
'5' => Some(4),
|
||||
'6' => Some(5),
|
||||
'7' => Some(6),
|
||||
'8' => Some(7),
|
||||
'9' => Some(8),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
struct PrefixAndParameters {
|
||||
prefix: Vec<token::Token>,
|
||||
raw_parameters: Vec<RawParameter>,
|
||||
// For the weird #{ edge case
|
||||
replacement_end_token: Option<token::Token>,
|
||||
skip_replacement_scan: bool,
|
||||
}
|
||||
|
||||
/// TeX.2021.474
|
||||
fn parse_prefix_and_parameters<S: TexlangState>(
|
||||
input: &mut vm::UnexpandedStream<S>,
|
||||
) -> txl::Result<PrefixAndParameters> {
|
||||
let mut prefix = Vec::new();
|
||||
let mut raw_parameters: Vec<RawParameter> = Vec::new();
|
||||
let mut replacement_end_token = None;
|
||||
let mut skip_replacement_scan = false;
|
||||
loop {
|
||||
let token = input.next_or_err(ParameterPartEndOfInputError {})?;
|
||||
match token.value() {
|
||||
token::Value::BeginGroup(_) => {
|
||||
break;
|
||||
}
|
||||
token::Value::EndGroup(_) => {
|
||||
input.error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"unexpected end group token while parsing the parameter of a macro definition",
|
||||
))?;
|
||||
skip_replacement_scan = true;
|
||||
break;
|
||||
}
|
||||
token::Value::Parameter(_) => {
|
||||
// TeX.2021.476
|
||||
let parameter_token = input.next_or_err(ParameterPartEndOfInputError {})?;
|
||||
// "parsing a parameter")?;
|
||||
match parameter_token.value() {
|
||||
token::Value::BeginGroup(_) => {
|
||||
// In this case we end the group according to the special #{ rule
|
||||
replacement_end_token = Some(parameter_token);
|
||||
match raw_parameters.last_mut() {
|
||||
None => {
|
||||
prefix.push(parameter_token);
|
||||
}
|
||||
Some(spec) => {
|
||||
spec.push(parameter_token);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
if raw_parameters.len() == 9 {
|
||||
input.error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"Too many parameters; you already have 9",
|
||||
))?;
|
||||
continue;
|
||||
}
|
||||
let parameter_index_correct = match parameter_token.char() {
|
||||
// control sequence
|
||||
None => false,
|
||||
// character token
|
||||
Some(c) => {
|
||||
match char_to_parameter_index(c) {
|
||||
// non-numeric character token
|
||||
None => false,
|
||||
// numeric character token
|
||||
Some(n) => n == raw_parameters.len(),
|
||||
}
|
||||
}
|
||||
};
|
||||
if !parameter_index_correct {
|
||||
input.error(InvalidParameterNumberError {
|
||||
parameter_number_token: parameter_token,
|
||||
parameters_so_far: raw_parameters.len(),
|
||||
})?;
|
||||
input.back(parameter_token);
|
||||
}
|
||||
raw_parameters.push(RawParameter::Undelimited);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => match raw_parameters.last_mut() {
|
||||
None => {
|
||||
prefix.push(token);
|
||||
}
|
||||
Some(parameter) => {
|
||||
parameter.push(token);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
// We may end up here because the input ended in which case we should error.
|
||||
// However this case will be handled when we try to scan the replacement
|
||||
// text.
|
||||
Ok(PrefixAndParameters {
|
||||
prefix,
|
||||
raw_parameters,
|
||||
replacement_end_token,
|
||||
skip_replacement_scan,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ParameterPartEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for ParameterPartEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"parsing the parameter part of a macro being defined by \def".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ReplacementPartEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for ReplacementPartEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"parsing the replacement part of a macro being defined by \def".into()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_replacement_text<S: TexlangState>(
|
||||
input: &mut vm::UnexpandedStream<S>,
|
||||
opt_final_token: Option<token::Token>,
|
||||
num_parameters: usize,
|
||||
) -> txl::Result<Vec<texmacro::Replacement>> {
|
||||
// TODO: could we use a pool of vectors to avoid some of the allocations here?
|
||||
let mut result = vec![];
|
||||
let mut scope_depth = 0;
|
||||
let push = |result: &mut Vec<texmacro::Replacement>, token| match result.last_mut() {
|
||||
Some(texmacro::Replacement::Tokens(tokens)) => {
|
||||
tokens.push(token);
|
||||
}
|
||||
_ => {
|
||||
result.push(texmacro::Replacement::Tokens(vec![token]));
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
let token = input.next_or_err(ReplacementPartEndOfInputError {})?;
|
||||
// "parsing the replacement text of a macro")?;
|
||||
match token.value() {
|
||||
token::Value::BeginGroup(_) => {
|
||||
scope_depth += 1;
|
||||
}
|
||||
token::Value::EndGroup(_) => {
|
||||
if scope_depth == 0 {
|
||||
if let Some(final_token) = opt_final_token {
|
||||
push(&mut result, final_token);
|
||||
}
|
||||
return Ok(result);
|
||||
}
|
||||
scope_depth -= 1;
|
||||
}
|
||||
token::Value::Parameter(_) => {
|
||||
let parameter_token = input.next_or_err(ReplacementPartEndOfInputError {})?;
|
||||
let c = match parameter_token.value() {
|
||||
token::Value::Parameter(_) => {
|
||||
// ## case
|
||||
push(&mut result, parameter_token);
|
||||
continue;
|
||||
}
|
||||
_ => parameter_token.char(),
|
||||
};
|
||||
let valid_index_or = match c {
|
||||
// control sequence
|
||||
None => None,
|
||||
// character
|
||||
Some(c) => char_to_parameter_index(c).filter(|&n| n < num_parameters),
|
||||
};
|
||||
match valid_index_or {
|
||||
None => {
|
||||
// TeX.2021.479
|
||||
input.error(error::SimpleTokenError::new(
|
||||
parameter_token,
|
||||
"illegal parameter number",
|
||||
))?;
|
||||
// Fallback to the ## case
|
||||
input.back(parameter_token);
|
||||
push(&mut result, token);
|
||||
}
|
||||
Some(valid_index) => {
|
||||
result.push(texmacro::Replacement::Parameter(valid_index));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
push(&mut result, token);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InvalidParameterNumberError {
|
||||
parameter_number_token: token::Token,
|
||||
parameters_so_far: usize,
|
||||
}
|
||||
|
||||
impl error::TexError for InvalidParameterNumberError {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::Token(self.parameter_number_token)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"unexpected parameter".to_string()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![format![
|
||||
"this macro has {} parameter(s) so far, so parameter number #{} was expected.",
|
||||
self.parameters_so_far,
|
||||
self.parameters_so_far + 1
|
||||
]
|
||||
.into()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use crate::prefix;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct State {
|
||||
prefix: prefix::Component,
|
||||
testing: texlang_testing::TestingComponent,
|
||||
}
|
||||
|
||||
implement_has_component![State {
|
||||
prefix: prefix::Component,
|
||||
testing: texlang_testing::TestingComponent,
|
||||
}];
|
||||
|
||||
impl TexlangState for State {
|
||||
fn variable_assignment_scope_hook(
|
||||
state: &mut Self,
|
||||
) -> texcraft_stdext::collections::groupingmap::Scope {
|
||||
prefix::variable_assignment_scope_hook(state)
|
||||
}
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
texlang_testing::TestingComponent::recoverable_error_hook(self, recoverable_error)
|
||||
}
|
||||
}
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("def", get_def()),
|
||||
("gdef", get_gdef()),
|
||||
("global", prefix::get_global()),
|
||||
("assertGlobalIsFalse", prefix::get_assert_global_is_false()),
|
||||
])
|
||||
}
|
||||
|
||||
texlang_testing::test_suite![
|
||||
@option(texlang_testing::TestOption::BuiltInCommands(built_in_commands)),
|
||||
@option(texlang_testing::TestOption::AllowUndefinedCommands(true)),
|
||||
expansion_equality_tests(
|
||||
(def_parsed_successfully, r"\def\A{abc}", ""),
|
||||
(output_is_correct, r"\def\A{abc}\A", "abc"),
|
||||
(active_char, r"\def~{abc}~", "abc"),
|
||||
(output_twice, "\\def\\A{abc}\\A\\A", "abcabc"),
|
||||
(parse_one_parameter, "\\def\\A#1{a-#1-b}", ""),
|
||||
(one_undelimited_parameter, "\\def\\A#1{a-#1-b}\\A1", "a-1-b"),
|
||||
(
|
||||
one_undelimited_parameter_multiple_times,
|
||||
"\\def\\A#1{#1 #1 #1}\\A1",
|
||||
"1 1 1"
|
||||
),
|
||||
(
|
||||
one_undelimited_parameter_multiple_tokens,
|
||||
"\\def\\A#1{a-#1-b}\\A{123}",
|
||||
"a-123-b"
|
||||
),
|
||||
(
|
||||
two_undelimited_parameters,
|
||||
"\\def\\A#1#2{#2-#1}\\A56",
|
||||
"6-5"
|
||||
),
|
||||
(
|
||||
two_undelimited_parameters_multiple_token_inputs,
|
||||
"\\def\\A#1#2{#2-#1}\\A{abc}{xyz}",
|
||||
"xyz-abc"
|
||||
),
|
||||
(
|
||||
consume_prefix_correctly,
|
||||
"\\def\\A fgh{567}\\A fghi",
|
||||
"567i"
|
||||
),
|
||||
(
|
||||
one_undelimited_parameter_with_prefix,
|
||||
"\\def\\A abc#1{y#1z}\\A abcdefg",
|
||||
"ydzefg"
|
||||
),
|
||||
(
|
||||
one_undelimited_parameter_with_prefix_multiple_tokens,
|
||||
"\\def\\A abc#1{y#1z}\\A abcdefg",
|
||||
"ydzefg"
|
||||
),
|
||||
(
|
||||
one_delimited_parameter,
|
||||
"\\def\\A #1xxx{y#1z}\\A abcxxx",
|
||||
"yabcz"
|
||||
),
|
||||
(
|
||||
one_delimited_parameter_empty,
|
||||
"\\def\\A #1xxx{y#1z}\\A xxx",
|
||||
"yz"
|
||||
),
|
||||
(
|
||||
one_delimited_parameter_with_scope,
|
||||
"\\def\\A #1xxx{#1}\\A abc{123xxx}xxx",
|
||||
"abc{123xxx}"
|
||||
),
|
||||
(
|
||||
one_delimited_parameter_with_prefix,
|
||||
"\\def\\A a#1c{x#1y}\\A abcdef",
|
||||
"xbydef"
|
||||
),
|
||||
(
|
||||
two_delimited_parameters_with_prefix,
|
||||
r"\def\A a#1c#2e{x#2y#1z}\A abcdef",
|
||||
"xdybzf"
|
||||
),
|
||||
(
|
||||
one_delimited_parameter_grouped_value,
|
||||
r"\def\A #1c{x#1y}\A {Hello}c",
|
||||
"xHelloy"
|
||||
),
|
||||
(
|
||||
parameter_brace_special_case,
|
||||
r"\def\A #{Mint says }\A{hello}",
|
||||
"Mint says {hello}"
|
||||
),
|
||||
(
|
||||
grouping,
|
||||
r"\def\A{Hello}\A{\def\A{World}\A}\A",
|
||||
r"HelloWorldHello"
|
||||
),
|
||||
(
|
||||
grouping_global,
|
||||
r"\def\A{Hello}\A{\global\def\A{World}\A}\A",
|
||||
r"HelloWorldWorld"
|
||||
),
|
||||
(
|
||||
gdef,
|
||||
r"\def\A{Hello}\A{\gdef\A{World}\A}\A",
|
||||
r"HelloWorldWorld"
|
||||
),
|
||||
(
|
||||
gdef_global,
|
||||
r"\def\A{Hello}\A{\global\gdef\A{World}\A}\A",
|
||||
r"HelloWorldWorld"
|
||||
),
|
||||
(
|
||||
def_takes_global,
|
||||
r"\global\def\A{Hello}\assertGlobalIsFalse",
|
||||
r""
|
||||
),
|
||||
(
|
||||
gdef_takes_global,
|
||||
r"\global\gdef\A{Hello}\assertGlobalIsFalse",
|
||||
r""
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_1,
|
||||
r"\def\mustnt{I must not talk in class.}%
|
||||
\def\five{\mustnt\mustnt\mustnt\mustnt\mustnt}%
|
||||
\def\twenty{\five\five\five\five}%
|
||||
\def\punishment{\twenty\twenty\twenty\twenty\twenty}%
|
||||
\punishment",
|
||||
"I must not talk in class.".repeat(100)
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_2,
|
||||
r"\def\a{\b}%
|
||||
\def\b{A\def\a{B\def\a{C\def\a{\b}}}}%
|
||||
\def\puzzle{\a\a\a\a\a}%
|
||||
\puzzle",
|
||||
"ABCAB"
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_3_part_1,
|
||||
"\\def\\row#1{(#1_1,\\ldots,#1_n)}\\row{\\bf x}",
|
||||
"(\\bf x_1,\\ldots,\\bf x_n)"
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_3_part_2,
|
||||
"\\def\\row#1{(#1_1,\\ldots,#1_n)}\\row{{\\bf x}}",
|
||||
"({\\bf x}_1,\\ldots,{\\bf x}_n)"
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_4_part_1,
|
||||
r#"\def\mustnt#1#2{I must not #1 in #2.}%
|
||||
\def\five#1#2{\mustnt{#1}{#2}\mustnt{#1}{#2}\mustnt{#1}{#2}\mustnt{#1}{#2}\mustnt{#1}{#2}}%
|
||||
\def\twenty#1#2{\five{#1}{#2}\five{#1}{#2}\five{#1}{#2}\five{#1}{#2}}%
|
||||
\def\punishment#1#2{\twenty{#1}{#2}\twenty{#1}{#2}\twenty{#1}{#2}\twenty{#1}{#2}\twenty{#1}{#2}}%
|
||||
\punishment{run}{the halls}"#,
|
||||
"I must not run in the halls.".repeat(100)
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_4_part_2,
|
||||
r#"\def\mustnt{I must not \doit\ in \thatplace.}%
|
||||
\def\five{\mustnt\mustnt\mustnt\mustnt\mustnt}%
|
||||
\def\twenty{\five\five\five\five}%
|
||||
\def\punishment#1#2{\def\doit{#1}\def\thatplace{#2}\twenty\twenty\twenty\twenty\twenty}%
|
||||
\punishment{run}{the halls}"#,
|
||||
r"I must not run\ in the halls.".repeat(100)
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_5,
|
||||
r"\def\a#1{\def\b##1{##1#1}}\a!\b{Hello}",
|
||||
"Hello!"
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_5_temp,
|
||||
r"\def\b#1{#1!}\b{Hello}",
|
||||
"Hello!"
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_5_example_below,
|
||||
"\\def\\a#1#{\\hbox to #1}\\a3pt{x}",
|
||||
"\\hbox to 3pt{x}"
|
||||
),
|
||||
(
|
||||
texbook_exercise_20_6,
|
||||
r"\def\b#1{And #1, World!}\def\a#{\b}\a{Hello}",
|
||||
"And Hello, World!"
|
||||
),
|
||||
(
|
||||
space_in_undelimited_param_1,
|
||||
r"\def\Hello#1#2{Hello-#1-#2-World}\Hello A B C",
|
||||
r"Hello-A-B-World C",
|
||||
),
|
||||
(
|
||||
space_in_undelimited_param_2,
|
||||
r"\def\Space{ }\def\Hello#1#2{Hello-#1-#2-World}\Hello\Space B C",
|
||||
r"Hello- -B-World C",
|
||||
),
|
||||
),
|
||||
serde_tests((
|
||||
serde_basic,
|
||||
r"\def\helloWorld{Hello World} ",
|
||||
r"\helloWorld"
|
||||
),),
|
||||
end_of_input_error_tests(
|
||||
(end_of_input_scanning_target, r"\def"),
|
||||
(end_of_input_scanning_argument_text, r"\def\A"),
|
||||
(end_of_input_scanning_replacement, r"\def\A{"),
|
||||
(end_of_input_scanning_nested_replacement, r"\def\A{{}"),
|
||||
// TODO (end_of_input_reading_parameter_number, r"\def\A#"),
|
||||
(end_of_input_scanning_argument, r"\def\A#1{X-#1-Z}\A Y{}\A"),
|
||||
(
|
||||
end_of_input_reading_value_for_parameter,
|
||||
r"\def\A#1{#1}\A{correct}\A{this {is parameter 1 but it never ends}",
|
||||
),
|
||||
// TODO (end_of_input_reading_prefix, r"\def\A abc{def}\A abc\A ab"),
|
||||
(
|
||||
end_of_input_reading_delimiter,
|
||||
r"\def\A #1abc{#1}\A xyzabc\A {first parameter}ab",
|
||||
),
|
||||
),
|
||||
recoverable_failure_tests(
|
||||
(bad_token_target, r"\def a other stuff{}Hello", "Hello"),
|
||||
(unexpected_token_argument, r"\def\A{Hello}\def\A }\A", ""),
|
||||
(wrong_parameter_number_1, r"\def\A #2X{-#1-}\A Y2X", "-Y-"),
|
||||
(wrong_parameter_number_2, r"\def\A #GX{-#1-}\A YGX", "-Y-"),
|
||||
(wrong_parameter_number_3, r"\def\A #\def{-#1-}\A Y\def", "-Y-"),
|
||||
(unexpected_end_group, r"\def\A{M}\def\A X}\A XY", r"Y"),
|
||||
(too_many_parameters, r"\def\A#1#2#3#4#5#6#7#8#9#0{#9#8#7#6#5#4#3#2#1}\A abcdefghi", "ihgfedcba"),
|
||||
(
|
||||
invalid_parameter_in_replacement_1,
|
||||
// invalid #1 becomes ##1
|
||||
r"\def\A{\def\B##1{-#1-}}\A{}\B C",
|
||||
"-C-",
|
||||
),
|
||||
(
|
||||
invalid_parameter_in_replacement_2,
|
||||
// invalid #A becomes ##A
|
||||
// we don't invoke the macro because this would output #A which is invalid.
|
||||
// We instead just verify that the macro definition ends where it should.
|
||||
r"\def\A{\def\B##1{-#A-}}Hello",
|
||||
"Hello",
|
||||
),
|
||||
(
|
||||
invalid_parameter_in_replacement_3,
|
||||
// invalid #\cs becomes ##\cs
|
||||
// we don't invoke the macro because this would output #A which is invalid.
|
||||
// We instead just verify that the macro definition ends where it should.
|
||||
r"\def\A{\def\B##1{-#\cs-}}Hello",
|
||||
"Hello",
|
||||
),
|
||||
(prefix_does_not_match, r"\def\A abc{d}\A abdef", "ef"),
|
||||
),
|
||||
];
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
//! The `\endlinechar` primitive
|
||||
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
end_line_char_raw: i32,
|
||||
}
|
||||
|
||||
impl Default for Component {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
end_line_char_raw: ('\r' as u32).try_into().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\endlinechar` command.
|
||||
pub fn get_endlinechar<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _: variable::Index| -> &i32 { &state.component().end_line_char_raw },
|
||||
|state: &mut S, _: variable::Index| -> &mut i32 {
|
||||
&mut state.component_mut().end_line_char_raw
|
||||
},
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn end_line_char<S: HasComponent<Component>>(state: &S) -> Option<char> {
|
||||
let raw = state.component().end_line_char_raw;
|
||||
if (0..128).contains(&raw) {
|
||||
// All of the conversions are guaranteed to succeed because
|
||||
// raw is in the ASCII range.
|
||||
Some(char::try_from(u32::try_from(raw).unwrap()).unwrap())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use crate::{def, prefix};
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
conditional: Component,
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn end_line_char(&self) -> Option<char> {
|
||||
end_line_char(self)
|
||||
}
|
||||
}
|
||||
|
||||
implement_has_component![State {
|
||||
conditional: Component,
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([("def", def::get_def()), ("endlinechar", get_endlinechar())])
|
||||
}
|
||||
|
||||
test_suite![expansion_equality_tests(
|
||||
(
|
||||
case_1,
|
||||
"\\endlinechar=`\\A Hello\nWorld\nMundo\n",
|
||||
"Hello WorldAMundoA"
|
||||
),
|
||||
(
|
||||
case_2,
|
||||
"\\endlinechar=-1 Hello\nWorld\nMundo\n",
|
||||
"Hello WorldMundo"
|
||||
),
|
||||
(
|
||||
case_3,
|
||||
"\\endlinechar=-1 Hello\nWorld \nMundo\n",
|
||||
"Hello WorldMundo"
|
||||
),
|
||||
(case_4, "\\endlinechar=`\\A\nHello\nWorld\n", "Hello WorldA"),
|
||||
),];
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
//! Commands that control what to do when errors occur
|
||||
//!
|
||||
//! The commands in this module have ownership both over the recoverable error
|
||||
//! handler and the input terminal.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
use texlang_common as common;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
mode: Mode,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
default_terminal: DefaultTerminal,
|
||||
errors: RefCell<Vec<error::TracedTexError>>,
|
||||
}
|
||||
|
||||
impl Component {
|
||||
/// Set the default terminal.
|
||||
pub fn set_default_terminal(&mut self, default_terminal: Rc<RefCell<dyn common::TerminalIn>>) {
|
||||
self.default_terminal = DefaultTerminal(default_terminal);
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper type so we can implement the default trait.
|
||||
struct DefaultTerminal(Rc<RefCell<dyn common::TerminalIn>>);
|
||||
|
||||
impl Default for DefaultTerminal {
|
||||
fn default() -> Self {
|
||||
Self(Rc::new(RefCell::new(std::io::stdin())))
|
||||
}
|
||||
}
|
||||
|
||||
impl common::HasTerminalIn for Component {
|
||||
fn terminal_in(&self) -> Rc<RefCell<dyn common::TerminalIn>> {
|
||||
match self.mode {
|
||||
Mode::ErrorStop | Mode::Scroll => self.default_terminal.0.clone(),
|
||||
Mode::Batch | Mode::NonStop => Rc::new(RefCell::new(DisabledTerminalIn {})),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, PartialEq, Eq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
enum Mode {
|
||||
#[default]
|
||||
ErrorStop,
|
||||
Scroll,
|
||||
NonStop,
|
||||
Batch,
|
||||
}
|
||||
|
||||
/// Get the `\errorstopmode` command.
|
||||
pub fn get_errorstopmode<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(|_, input: &mut vm::ExecutionInput<S>| {
|
||||
set_mode(input, Mode::ErrorStop);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the `\scrollmode` command.
|
||||
pub fn get_scrollmode<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(|_, input: &mut vm::ExecutionInput<S>| {
|
||||
set_mode(input, Mode::Scroll);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the `\nonstopmode` command.
|
||||
pub fn get_nonstopmode<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(|_, input: &mut vm::ExecutionInput<S>| {
|
||||
set_mode(input, Mode::NonStop);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the `\batchmode` command.
|
||||
pub fn get_batchmode<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(|_, input: &mut vm::ExecutionInput<S>| {
|
||||
set_mode(input, Mode::Batch);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn recoverable_error_hook<S: HasComponent<Component> + common::HasLogging>(
|
||||
state: &S,
|
||||
recoverable_error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
match &state.component().mode {
|
||||
Mode::ErrorStop => {
|
||||
return Err(recoverable_error.error);
|
||||
}
|
||||
Mode::Scroll | Mode::NonStop => {
|
||||
writeln!(state.terminal_out().borrow_mut(), "{recoverable_error}").unwrap();
|
||||
}
|
||||
Mode::Batch => {}
|
||||
}
|
||||
writeln!(state.log_file().borrow_mut(), "{recoverable_error}").unwrap();
|
||||
state
|
||||
.component()
|
||||
.errors
|
||||
.borrow_mut()
|
||||
.push(recoverable_error);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_mode<S: HasComponent<Component>>(input: &mut vm::ExecutionInput<S>, mode: Mode) {
|
||||
input.state_mut().component_mut().mode = mode;
|
||||
}
|
||||
|
||||
struct DisabledTerminalIn;
|
||||
|
||||
impl common::TerminalIn for DisabledTerminalIn {
|
||||
fn read_line(&mut self, _: Option<&str>, _: &mut String) -> std::io::Result<()> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
//! Examples from the TeX literature for use in testing.
|
||||
//!
|
||||
//! This module contains testable exercises and examples of TeX snippets from the literature (right now the TeXBook).
|
||||
//! The documentation for each exercise shows the input and the correct output.
|
||||
//!
|
||||
//! This collection is intended for testing and for verifying a TeX distribution
|
||||
//! is conformant with the language.
|
||||
//! This module's test module runs the exercises as tests for the primitives implemented in the
|
||||
//! [Texcraft primitives library](super::library).
|
||||
|
||||
/// Data structure representing a testable TeX example.
|
||||
pub struct Example {
|
||||
pub input: &'static str,
|
||||
pub solution: &'static str,
|
||||
}
|
||||
|
||||
macro_rules! exercises {
|
||||
( $ ( ($ name : ident , $page: expr, $input : expr, $solution: expr, ), ) * ) => {
|
||||
$(
|
||||
#[allow(non_upper_case_globals)]
|
||||
#[doc = $page]
|
||||
#[doc= ".\n\nInput:\n\n```text"]
|
||||
#[doc = $input]
|
||||
#[doc = "```\n\nExpected output:\n\n```text"]
|
||||
#[doc = $solution]
|
||||
#[doc = "```\n\n"]
|
||||
pub const $name: Example = Example{
|
||||
input: $input,
|
||||
solution: $solution,
|
||||
};
|
||||
)*
|
||||
|
||||
#[doc="A static array containing all exercises in this module"]
|
||||
pub const ALL_EXERCISES: &[&Example] = &[
|
||||
$(
|
||||
&$name,
|
||||
)*
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests{
|
||||
use crate::driver;
|
||||
use crate::state::Base;
|
||||
use crate::command::library::*;
|
||||
use crate::types::CatCode;
|
||||
|
||||
struct State;
|
||||
fn new_state() -> State {
|
||||
State{}
|
||||
}
|
||||
|
||||
fn built_in_commands(s: &mut Base<State>) {
|
||||
s.set_command("catcode", catcodecmd::get_catcode());
|
||||
s.set_command("def", def::get_def());
|
||||
}
|
||||
|
||||
$(
|
||||
expansion_test![$name, $input, $solution];
|
||||
)*
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exercises![
|
||||
(
|
||||
texbook_chap_20_exercise_4_pt_2,
|
||||
"TexBook p203",
|
||||
r#"
|
||||
\def\mustnt{I must not \doit\ in \thatplace.}%
|
||||
\def\five{\mustnt\mustnt\mustnt\mustnt\mustnt}%
|
||||
\def\twenty{\five\five\five\five}%
|
||||
\def\punishment#1#2{\def\doit{#1}\def\thatplace{#2}\twenty\twenty\twenty\twenty\twenty}%
|
||||
\punishment{run}{the halls}"#,
|
||||
r"
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.%
|
||||
I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.I must not run\ in the halls.",
|
||||
),
|
||||
(
|
||||
texbook_chap_20_exercise_7,
|
||||
"TeXBook p205",
|
||||
r"
|
||||
\catcode`!=6 \catcode`[=1 \catcode`]=2
|
||||
\def\!!1#2![{!#]#!!2}\! x{[y]][z}",
|
||||
r"
|
||||
\catcode`!=6 \catcode`[=1 \catcode`]=2
|
||||
{#]![y][z}",
|
||||
),
|
||||
];
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
//! Commands that alter the expansion process
|
||||
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
/// Get the `\noexpand` command.
|
||||
pub fn get_noexpand<S>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(noexpand_fn).with_tag(NO_EXPAND_TAG.get())
|
||||
}
|
||||
|
||||
static NO_EXPAND_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
fn noexpand_fn<S>(_: token::Token, _: &mut vm::ExpansionInput<S>) -> txl::Result<()> {
|
||||
panic!(
|
||||
"The \\noexpand expansion function is never invoked directly. \
|
||||
Instead, the primitive operates through the \\noexpand hook, \
|
||||
which is a method on the `TexlangState` trait. \
|
||||
Ensure your Texcraft VM is configured to use this hook."
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn noexpand_hook<S: TexlangState>(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
tag: Option<command::Tag>,
|
||||
) -> txl::Result<Option<token::Token>> {
|
||||
// Fast path: this is not the \noexpand command.
|
||||
// We want this check to be inlined into the VM functions that perform expansion.
|
||||
if tag != Some(NO_EXPAND_TAG.get()) {
|
||||
return Ok(None);
|
||||
}
|
||||
// Slow path: this is the \noexpand command.
|
||||
// We don't want this check to be inlined into the VM because it will take up space in the instruction cache.
|
||||
noexpand_hook_finish(token, input)
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn noexpand_hook_finish<S: TexlangState>(
|
||||
_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<Option<token::Token>> {
|
||||
Ok(Some(
|
||||
input.unexpanded().next_or_err(NoExpandEndOfInputError {})?,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NoExpandEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for NoExpandEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"determining which token to suppress expansion for".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the simple `\expandafter` command.
|
||||
///
|
||||
/// This is the simplest implementation of the command, and the
|
||||
/// same implementation as in the original TeX.
|
||||
pub fn get_expandafter_simple<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(expandafter_simple_fn)
|
||||
}
|
||||
|
||||
/// Get the optimized `\expandafter` command.
|
||||
///
|
||||
/// This is a more complex implementation of `\expandafter` that is optimized for handling
|
||||
/// repeated `\expandafter` tokens.
|
||||
/// It contains two optimizations, as described below.
|
||||
/// These optimizations where developed "theoretically" and with no benchmarking, so it
|
||||
/// remains to be seen if they actually make expansion faster.
|
||||
/// For this reason both the optimized and simple `\expandafter` implementations are maintained.
|
||||
///
|
||||
/// We now describe the two optimizations.
|
||||
///
|
||||
/// **First**, `\expandafter` control sequences are often linked together in the following format:
|
||||
///
|
||||
/// ```tex
|
||||
/// \expandafter<token 1>\expandafter<token 2>...\expandafter<token n><token n+1>
|
||||
/// ```
|
||||
///
|
||||
/// Here, to expand the first `\expandafter` we just need to expand `<token n+1>`.
|
||||
/// In the original implementation of TeX this works via recursion: the ith `\expandafter`
|
||||
/// requests expansion of the second-to-next token, which is the (i+1)th `\expandafter`.
|
||||
/// After n recursions, the last token is finally expanded.
|
||||
/// In the optimized implementation here, the token stream is scanned ahead for as long as the pattern
|
||||
/// `\expandafter<token i>` repeats.
|
||||
/// The token `<token n+1>` is expanded and the intermediate `\expandafter` tokens are dropped from the input.
|
||||
/// This is still an O(n) operation, but results in only 1 Rust function stack being used, rather than n.
|
||||
///
|
||||
/// **Second**, `\expandafter` commands are often grouped together like this:
|
||||
///
|
||||
/// ```tex
|
||||
/// \expandafter\expandafter\expandafter\A\expandafter\B\C
|
||||
/// ```
|
||||
///
|
||||
/// This TeX code causes `\C` to be expanded first, then `\B\` and finally `\A`.
|
||||
/// When the leading `\expandafter` is expanded, the first optimization kicks in and `\C` will be expanded, leaving:
|
||||
///
|
||||
/// ```tex
|
||||
/// \expandafter\A\B\Cexpanded
|
||||
/// ```
|
||||
///
|
||||
/// The second optimization is that the leading `\expandafter` that is left over will also be expanded
|
||||
/// without yielding control to the main expansion loop.
|
||||
/// If, after this pass, the leading token is again an `\expandafter` token, it will be expanded too.
|
||||
/// This process continues repeatedly until no `\expandafter` tokens are left at the start of the token stream.
|
||||
pub fn get_expandafter_optimized<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(expandafter_optimized_fn)
|
||||
}
|
||||
|
||||
fn expandafter_simple_fn<S: TexlangState>(
|
||||
_expandafter_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let first = input
|
||||
.unexpanded()
|
||||
.next_or_err(EndOfInputError { first: true })?;
|
||||
let second = input
|
||||
.unexpanded()
|
||||
.next_or_err(EndOfInputError { first: false })?;
|
||||
input.back(second);
|
||||
input.expanded().expand_once()?;
|
||||
input.back(first);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expandafter_optimized_fn<S: TexlangState>(
|
||||
expandafter_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let mut buffer: Vec<token::Token> = input.checkout_token_buffer();
|
||||
// The optimization implemented here is that if we have the following input:
|
||||
// \xa <token 1> \xa <token 2> ... \xa <token N> <token N+1>
|
||||
// we expand <token N+1> once.
|
||||
loop {
|
||||
let first = input
|
||||
.unexpanded()
|
||||
.next_or_err(EndOfInputError { first: true })?;
|
||||
buffer.push(first);
|
||||
let second = input
|
||||
.unexpanded()
|
||||
.next_or_err(EndOfInputError { first: false })?;
|
||||
if second.value() != expandafter_token.value() {
|
||||
input.back(second);
|
||||
break;
|
||||
}
|
||||
}
|
||||
input.expanded().expand_once()?;
|
||||
input.expansions_mut().extend(buffer.iter().rev());
|
||||
input.return_token_buffer(buffer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct EndOfInputError {
|
||||
first: bool,
|
||||
}
|
||||
impl error::EndOfInputError for EndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
format![
|
||||
r"reading the {} token after \expandafter",
|
||||
if self.first { "first" } else { "second" }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\relax` command.
|
||||
pub fn get_relax<S>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(|_, _| Ok(()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::prefix;
|
||||
use std::collections::HashMap;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct State {
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn expansion_override_hook(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpansionInput<Self>,
|
||||
tag: Option<command::Tag>,
|
||||
) -> txl::Result<Option<token::Token>> {
|
||||
noexpand_hook(token, input, tag)
|
||||
}
|
||||
}
|
||||
|
||||
implement_has_component![State {
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands(optimized: bool) -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("def", crate::def::get_def()),
|
||||
("let", crate::alias::get_let()),
|
||||
("noexpand", get_noexpand()),
|
||||
("integer", TestingComponent::get_integer()),
|
||||
(
|
||||
"xa",
|
||||
match optimized {
|
||||
true => get_expandafter_optimized(),
|
||||
false => get_expandafter_simple(),
|
||||
},
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
@option(TestOption::BuiltInCommandsDyn(Box::new(|| { built_in_commands(true) }))),
|
||||
@option(TestOption::AllowUndefinedCommands(true)),
|
||||
expansion_equality_tests(
|
||||
(simple_case, r"\def\a{Hello}\noexpand\a", r"\a"),
|
||||
(
|
||||
expandafter_and_noexpand_1,
|
||||
r"\def\a#1\b{Hello '#1'}\def\b{World}\a\b",
|
||||
"Hello ''"
|
||||
),
|
||||
(
|
||||
expandafter_and_noexpand_2,
|
||||
r"\def\a#1\b{Hello '#1'}\def\b{World}\a\b\b",
|
||||
"Hello ''World"
|
||||
),
|
||||
(
|
||||
expandafter_and_noexpand_3,
|
||||
r"\def\a#1\b{Hello '#1'}\def\b{World}\xa\a\b\b",
|
||||
"Hello 'World'"
|
||||
),
|
||||
(
|
||||
expandafter_and_noexpand_4,
|
||||
r"\def\a#1\b{Hello '#1'}\def\b{World}\xa\a\noexpand\b\b",
|
||||
"Hello ''World"
|
||||
),
|
||||
(
|
||||
only_expands_once,
|
||||
r"\def\A{\B}\def\B{Hello}\xa\noexpand\A",
|
||||
r"\B",
|
||||
),
|
||||
(
|
||||
peek_consumes_noexpand_1,
|
||||
r"\def\A{\B}\def\B{Hello}\integer = 1 \noexpand\A",
|
||||
r"\A",
|
||||
),
|
||||
(
|
||||
peek_consumes_noexpand_2,
|
||||
r"\def\A{\B}\def\B{Hello}\integer = 1\noexpand\A",
|
||||
r"Hello",
|
||||
),
|
||||
// peek
|
||||
),
|
||||
fatal_error_tests((end_of_input, r"\noexpand"),),
|
||||
];
|
||||
|
||||
static PREFIX: &str = r"\def\mk#1#2{\def#1##1\notes##2\end{##1\notes##2#2\end}}\mk\a a\mk\b b\mk\c c\mk\d d\def\notes#1\end{#1}";
|
||||
static POSTFIX: &str = r"\notes\end";
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! expandafter_test {
|
||||
( $( ( $name: ident, $lhs: expr, $rhs: expr ) ),* $(,)? ) => {
|
||||
mod expandafter_simple {
|
||||
use super::*;
|
||||
test_suite![
|
||||
@option(TestOption::BuiltInCommandsDyn(Box::new(|| { built_in_commands(false) }))),
|
||||
expansion_equality_tests(
|
||||
$(
|
||||
( $name, format!("{}{}{}", PREFIX, $lhs, POSTFIX), $rhs ),
|
||||
)*
|
||||
),
|
||||
];
|
||||
}
|
||||
mod expandafter_optimized {
|
||||
use super::*;
|
||||
test_suite![
|
||||
@option(TestOption::BuiltInCommandsDyn(Box::new(|| { built_in_commands(true) }))),
|
||||
expansion_equality_tests(
|
||||
$(
|
||||
( $name, format!("{}{}{}", PREFIX, $lhs, POSTFIX), $rhs ),
|
||||
)*
|
||||
),
|
||||
];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
expandafter_test![
|
||||
// In the following test we alias \xa to \other so that the \expandafter optimizations don't kick in.
|
||||
// This makes \other behave like the unoptimized \expandafter.
|
||||
// It then triggers the case when the optimized \expandafter is only supposed to expand the input
|
||||
// once, rather the repeatedly expanding to remove the \expandafter's at the front.
|
||||
(
|
||||
expandafter_only_once,
|
||||
r"\let\other=\xa \other\noexpand\xa\xa\xa\a\b",
|
||||
r"\noexpand\xa ba"
|
||||
),
|
||||
(texbook_p374_3, r"\xa\a\b", r"ba"),
|
||||
(texbook_p374_4, r"\xa\xa\xa\a\xa\b\c", "cba"),
|
||||
(
|
||||
texbook_p374_5,
|
||||
r"\xa\xa\xa\xa\xa\xa\xa\a\xa\xa\xa\b\xa\c\d",
|
||||
"dcba"
|
||||
),
|
||||
/*
|
||||
All of the following permutation cases were generated by hand, but there's actually
|
||||
an algorithmic way to generate them. For each macro, count the number of \expandafter=\xa
|
||||
tokens that come before. Then calculate the shift:
|
||||
- if #\xa is 0, the shift is 0.
|
||||
- if #\xa is 1, the shift is 1.
|
||||
- if #\xa is 3, the shift is 2.
|
||||
- if #\xa is 7, the shift is 3.
|
||||
(In general if #\xa is 2^n-1, the shift is n-1.)
|
||||
Now work backwards through the tokens `\a\b\c\d`. For each token, move it right by the associated
|
||||
shift. You then get the result of the expansion.
|
||||
|
||||
For example: `\xa\xa\xa\a\xa\b\c\d`.
|
||||
The #\xa numbers are: 3 1 0 0
|
||||
The shifts are: 2 1 0 0
|
||||
Then
|
||||
- start: `\a\b\c\d`
|
||||
- shift \d by 0: `\a\b\c\d`
|
||||
- shift \c by 0: `\a\b\c\d`
|
||||
- shift \b by 1: `\a\c\b\d`
|
||||
- shift \a by 2: `\c\b\a\d` <- this is the expansion
|
||||
*/
|
||||
(permutation_abcd, r"\a\b\c\d", "abcd"),
|
||||
(permutation_abdc, r"\a\b\xa\c\d", "abdc"),
|
||||
(permutation_acbd, r"\a\xa\b\c\d", "acbd"),
|
||||
(permutation_acdb, r"\a\xa\xa\xa\b\c\d", "acdb"),
|
||||
(permutation_adbc, r"\a\xa\b\xa\c\d", "adbc"),
|
||||
(permutation_adcb, r"\a\xa\xa\xa\b\xa\c\d", "adcb"),
|
||||
(permutation_bacd, r"\xa\a\b\c\d", "bacd"),
|
||||
(permutation_badc, r"\xa\a\b\xa\c\d", "badc"),
|
||||
(permutation_bcad, r"\xa\xa\xa\a\b\c\d", "bcad"),
|
||||
(permutation_bcda, r"\xa\xa\xa\xa\xa\xa\xa\a\b\c\d", "bcda"),
|
||||
(permutation_bdac, r"\xa\xa\xa\a\b\xa\c\d", "bdac"),
|
||||
(
|
||||
permutation_bdca,
|
||||
r"\xa\xa\xa\xa\xa\xa\xa\a\b\xa\c\d",
|
||||
"bdca"
|
||||
),
|
||||
(permutation_cabd, r"\xa\a\xa\b\c\d", "cabd"),
|
||||
(permutation_cadb, r"\xa\a\xa\xa\xa\b\c\d", "cadb"),
|
||||
(permutation_cbad, r"\xa\xa\xa\a\xa\b\c\d", "cbad"),
|
||||
(
|
||||
permutation_cbda,
|
||||
r"\xa\xa\xa\xa\xa\xa\xa\a\xa\xa\xa\b\c\d",
|
||||
"cdba"
|
||||
),
|
||||
(permutation_cdab, r"\xa\xa\xa\a\xa\xa\xa\b\c\d", "cdab"),
|
||||
(
|
||||
permutation_cdba,
|
||||
r"\xa\xa\xa\xa\xa\xa\xa\a\xa\xa\xa\b\c\d",
|
||||
"cdba"
|
||||
),
|
||||
(permutation_dabc, r"\xa\a\xa\b\xa\c\d", "dabc"),
|
||||
(permutation_dacb, r"\xa\a\xa\xa\xa\b\xa\c\d", "dacb"),
|
||||
(permutation_dbac, r"\xa\xa\xa\a\xa\b\xa\c\d", "dbac"),
|
||||
(
|
||||
permutation_dbca,
|
||||
r"\xa\xa\xa\xa\xa\xa\xa\a\xa\b\xa\c\d",
|
||||
"dbca"
|
||||
),
|
||||
(permutation_dcab, r"\xa\xa\xa\a\xa\xa\xa\b\xa\c\d", "dcab"),
|
||||
(
|
||||
permutation_dcba,
|
||||
r"\xa\xa\xa\xa\xa\xa\xa\a\xa\xa\xa\b\xa\c\d",
|
||||
"dcba"
|
||||
),
|
||||
(
|
||||
expandafter_last_after_first_pass,
|
||||
r"\xa\xa\xa\a\xa\xa\b\c\d",
|
||||
"bdac"
|
||||
),
|
||||
];
|
||||
|
||||
fn run_expandafter_failure_test(input: &str, optimized: bool) {
|
||||
let options = vec![TestOption::BuiltInCommandsDyn(Box::new(|| {
|
||||
built_in_commands(optimized)
|
||||
}))];
|
||||
run_fatal_error_test(input, &options, false);
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! expandafter_fatal_error_test {
|
||||
($( ( $name: ident, $input: expr), )+) => {
|
||||
$(
|
||||
mod $name {
|
||||
#[test]
|
||||
fn simple() {
|
||||
super::run_expandafter_failure_test($input, false);
|
||||
}
|
||||
#[test]
|
||||
fn optimized() {
|
||||
super::run_expandafter_failure_test($input, true);
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
expandafter_fatal_error_test![
|
||||
(expandafter_missing_1st_token, r"\xa"),
|
||||
(expandafter_missing_2nd_token, r"\xa\a"),
|
||||
(expandafter_missing_1st_token_nested, r"\xa\xa\xa\a\xa\xa\b"),
|
||||
(
|
||||
expandafter_missing_2nd_token_nested,
|
||||
r"\def\A{}\xa\xa\xa\A\A"
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+581
@@ -0,0 +1,581 @@
|
||||
//! Primitives for inputting source code from files and the terminal
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use texlang::parse::{FileLocation, OptionalEquals};
|
||||
use texlang::prelude as txl;
|
||||
use texlang::token::lexer;
|
||||
use texlang::token::trace;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
use texlang_common as common;
|
||||
|
||||
use crate::conditional::{self, Condition};
|
||||
|
||||
/// Get the `\input` expansion primitive.
|
||||
pub fn get_input<S: TexlangState + common::HasFileSystem>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(input_fn)
|
||||
}
|
||||
|
||||
fn input_fn<S: TexlangState + common::HasFileSystem>(
|
||||
input_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let file_location = FileLocation::parse(input)?;
|
||||
let (file_path, source_code) =
|
||||
match texlang_common::read_file_to_string(input.vm(), file_location, "tex") {
|
||||
Ok(ok) => ok,
|
||||
Err(err) => {
|
||||
return Err(input.fatal_error(err));
|
||||
}
|
||||
};
|
||||
if input.vm().num_current_sources() > 100 {
|
||||
return Err(input.fatal_error(TooManyInputs {}));
|
||||
}
|
||||
input.push_source(input_token, file_path, source_code)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TooManyInputs {}
|
||||
|
||||
impl error::TexError for TooManyInputs {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::FailedPrecondition
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"too many input levels (100)".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\endinput` expansion primitive.
|
||||
pub fn get_endinput<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(endinput_fn)
|
||||
}
|
||||
|
||||
fn endinput_fn<S: TexlangState>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
input.end_current_file();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component<const N: usize> {
|
||||
#[cfg_attr(feature = "serde", serde(with = "texcraft_stdext::serde_tools::array"))]
|
||||
files: [Option<Box<lexer::Lexer>>; N],
|
||||
}
|
||||
|
||||
impl<const N: usize> Component<N> {
|
||||
fn take_file(&mut self, index: i32) -> Option<Box<lexer::Lexer>> {
|
||||
let u: usize = match index.try_into() {
|
||||
Ok(u) => u,
|
||||
Err(_) => return None,
|
||||
};
|
||||
match self.files.get_mut(u) {
|
||||
None => None,
|
||||
Some(file_or) => file_or.take(),
|
||||
}
|
||||
}
|
||||
|
||||
fn return_file(&mut self, index: i32, file: Box<lexer::Lexer>) {
|
||||
let u: usize = index.try_into().unwrap();
|
||||
*self.files.get_mut(u).unwrap() = Some(file);
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Default for Component<N> {
|
||||
fn default() -> Self {
|
||||
// We construct the array as a vector first because the element type
|
||||
// cannot be cloned and so we can't use the standard array constructor.
|
||||
// But note that this isn't inefficient, because the array will
|
||||
// simply use the vector's buffer.
|
||||
let v: Vec<Option<Box<lexer::Lexer>>> = (0..N).map(|_| None).collect();
|
||||
Self {
|
||||
files: v.try_into().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\openin` execution primitive.
|
||||
pub fn get_openin<const N: usize, S: HasComponent<Component<N>> + common::HasFileSystem>(
|
||||
) -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(openin_fn)
|
||||
}
|
||||
|
||||
fn openin_fn<const N: usize, S: HasComponent<Component<N>> + common::HasFileSystem>(
|
||||
openin_token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let (u, _, file_location) = <(parse::Uint<N>, OptionalEquals, FileLocation)>::parse(input)?;
|
||||
let lexer_or = match texlang_common::read_file_to_string(input.vm(), file_location, "tex") {
|
||||
// If the file fails to open TeX does not error out.
|
||||
// Instead, TeX users are expected to test the result with \ifeof.
|
||||
Err(_) => None,
|
||||
Ok((file_path, source_code)) => {
|
||||
let source_code = ensure_ends_in_newline(source_code);
|
||||
let trace_key_range = input.tracer_mut().register_source_code(
|
||||
Some(openin_token),
|
||||
trace::Origin::File(file_path),
|
||||
&source_code,
|
||||
);
|
||||
Some(Box::new(lexer::Lexer::new(source_code, trace_key_range)))
|
||||
}
|
||||
};
|
||||
*input
|
||||
.state_mut()
|
||||
.component_mut()
|
||||
.files
|
||||
.get_mut(u.0)
|
||||
.unwrap() = lexer_or;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_ends_in_newline(mut s: String) -> String {
|
||||
if !s.ends_with('\n') {
|
||||
s.push('\n')
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Get the `\closein` execution primitive.
|
||||
pub fn get_closein<const N: usize, S: HasComponent<Component<N>>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(closein_fn)
|
||||
}
|
||||
|
||||
fn closein_fn<const N: usize, S: HasComponent<Component<N>>>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let u = parse::Uint::<N>::parse(input)?;
|
||||
*input
|
||||
.state_mut()
|
||||
.component_mut()
|
||||
.files
|
||||
.get_mut(u.0)
|
||||
.unwrap() = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the `\read` execution primitive.
|
||||
pub fn get_read<const N: usize, S: HasComponent<Component<N>> + common::HasTerminalIn>(
|
||||
) -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(read_fn)
|
||||
}
|
||||
|
||||
fn read_fn<const N: usize, S: HasComponent<Component<N>> + common::HasTerminalIn>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
let (index, _, cmd_ref_or) = <(i32, To, Option<token::CommandRef>)>::parse(input)?;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
File,
|
||||
Terminal,
|
||||
}
|
||||
|
||||
let terminal_in = input.state().terminal_in().clone();
|
||||
let (mut lexer, mode, prompt) = match input.state_mut().component_mut().take_file(index) {
|
||||
Some(file) => (file, Mode::File, None),
|
||||
None => {
|
||||
let prompt = if index < 0 {
|
||||
None
|
||||
} else {
|
||||
Some(format!(
|
||||
r"{}=",
|
||||
match cmd_ref_or {
|
||||
None => "unreachable".to_string(),
|
||||
Some(cmd_ref) => cmd_ref.to_string(input.vm().cs_name_interner()),
|
||||
}
|
||||
))
|
||||
};
|
||||
(
|
||||
read_from_terminal(&terminal_in, input, &prompt)?,
|
||||
Mode::Terminal,
|
||||
prompt,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let mut tokens = vec![];
|
||||
let mut more_lines_exist = true;
|
||||
let mut braces: Vec<token::Token> = vec![];
|
||||
loop {
|
||||
let vm::Parts {
|
||||
state,
|
||||
cs_name_interner,
|
||||
..
|
||||
} = input.vm_parts();
|
||||
match (lexer.next(state, cs_name_interner, true), mode) {
|
||||
(lexer::Result::Token(token), _) => {
|
||||
match token.cat_code() {
|
||||
Some(types::CatCode::BeginGroup) => {
|
||||
braces.push(token);
|
||||
}
|
||||
Some(types::CatCode::EndGroup) => {
|
||||
if braces.pop().is_none() {
|
||||
more_lines_exist = drain_line(&mut lexer, state, cs_name_interner);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
};
|
||||
tokens.push(token);
|
||||
}
|
||||
(lexer::Result::InvalidCharacter(c, trace_key), _) => {
|
||||
return Err(input.fatal_error(lexer::InvalidCharacterError::new(
|
||||
input.vm(),
|
||||
c,
|
||||
trace_key,
|
||||
)))
|
||||
}
|
||||
(lexer::Result::EndOfLine, Mode::File) => {
|
||||
if braces.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(lexer::Result::EndOfInput, Mode::File) => {
|
||||
if let Some(unmatched_brace) = braces.pop() {
|
||||
return Err(input.fatal_error(UnmatchedBracesError { unmatched_brace }));
|
||||
}
|
||||
more_lines_exist = false;
|
||||
break;
|
||||
}
|
||||
(lexer::Result::EndOfLine | lexer::Result::EndOfInput, Mode::Terminal) => {
|
||||
if !braces.is_empty() {
|
||||
lexer = read_from_terminal(&terminal_in, input, &prompt)?;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if mode == Mode::File && more_lines_exist {
|
||||
input.state_mut().component_mut().return_file(index, lexer);
|
||||
}
|
||||
tokens.reverse();
|
||||
let user_defined_macro =
|
||||
texmacro::Macro::new(vec![], vec![], vec![texmacro::Replacement::Tokens(tokens)]);
|
||||
if let Some(cmd_ref) = cmd_ref_or {
|
||||
input
|
||||
.commands_map_mut()
|
||||
.insert_macro(cmd_ref, user_defined_macro, scope);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drain_line<S: TexlangState>(
|
||||
file: &mut lexer::Lexer,
|
||||
state: &S,
|
||||
cs_name_interner: &mut token::CsNameInterner,
|
||||
) -> bool {
|
||||
loop {
|
||||
match file.next(state, cs_name_interner, true) {
|
||||
lexer::Result::Token(_) | lexer::Result::InvalidCharacter(_, _) => {}
|
||||
lexer::Result::EndOfLine => {
|
||||
return true;
|
||||
}
|
||||
lexer::Result::EndOfInput => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_from_terminal<S: TexlangState>(
|
||||
terminal_in: &Rc<RefCell<dyn common::TerminalIn>>,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
prompt: &Option<String>,
|
||||
) -> txl::Result<Box<lexer::Lexer>> {
|
||||
let mut buffer = String::new();
|
||||
if let Err(err) = terminal_in
|
||||
.borrow_mut()
|
||||
.read_line(prompt.as_deref(), &mut buffer)
|
||||
{
|
||||
return Err(input.fatal_error(IoError {
|
||||
title: "failed to read from the terminal".into(),
|
||||
underlying_error: err,
|
||||
}));
|
||||
}
|
||||
let trace_key_range =
|
||||
input
|
||||
.tracer_mut()
|
||||
.register_source_code(None, trace::Origin::Terminal, &buffer);
|
||||
Ok(Box::new(lexer::Lexer::new(buffer, trace_key_range)))
|
||||
}
|
||||
|
||||
/// Get the `\ifeof` conditional expansion primitive.
|
||||
pub fn get_ifeof<const N: usize, S>() -> command::BuiltIn<S>
|
||||
where
|
||||
S: HasComponent<Component<N>> + HasComponent<conditional::Component>,
|
||||
{
|
||||
IsEof::build_if_command()
|
||||
}
|
||||
|
||||
struct IsEof<const N: usize>;
|
||||
|
||||
impl<const N: usize, S> conditional::Condition<S> for IsEof<N>
|
||||
where
|
||||
S: HasComponent<Component<N>> + HasComponent<conditional::Component>,
|
||||
{
|
||||
fn evaluate(input: &mut vm::ExpansionInput<S>) -> txl::Result<bool> {
|
||||
let u = parse::Uint::<N>::parse(input)?;
|
||||
Ok(HasComponent::<Component<N>>::component(input.state())
|
||||
.files
|
||||
.get(u.0)
|
||||
.unwrap()
|
||||
.is_none())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IoError {
|
||||
title: String,
|
||||
underlying_error: std::io::Error,
|
||||
}
|
||||
|
||||
impl error::TexError for IoError {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::FailedPrecondition
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
self.title.clone()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![format!("underlying filesystem error: {}", self.underlying_error).into()]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct UnmatchedBracesError {
|
||||
unmatched_brace: token::Token,
|
||||
}
|
||||
|
||||
impl error::TexError for UnmatchedBracesError {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::Token(self.unmatched_brace)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"file has an unmatched opening brace".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![r"files being read with the \read primitive must match all opening braces with closing braces".into()]
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes a required `to` keyword from the input stream.
|
||||
struct To;
|
||||
|
||||
impl Parsable for To {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
texlang::parse::parse_keyword(input, "to")?;
|
||||
Ok(To {})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{def, expansion, prefix};
|
||||
use std::collections::HashMap;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct State {
|
||||
conditional: conditional::Component,
|
||||
input: Component<16>,
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
file_system: Rc<RefCell<common::InMemoryFileSystem>>,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
terminal_in: Rc<RefCell<common::MockTerminalIn>>,
|
||||
}
|
||||
|
||||
impl TexlangState for State {}
|
||||
|
||||
impl common::HasFileSystem for State {
|
||||
fn file_system(&self) -> Rc<RefCell<dyn common::FileSystem>> {
|
||||
self.file_system.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl common::HasTerminalIn for State {
|
||||
fn terminal_in(&self) -> Rc<RefCell<dyn common::TerminalIn>> {
|
||||
self.terminal_in.clone()
|
||||
}
|
||||
}
|
||||
|
||||
implement_has_component![State{
|
||||
conditional: conditional::Component,
|
||||
input: Component<16>,
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("closein", get_closein()),
|
||||
("def", def::get_def()),
|
||||
("else", conditional::get_else()),
|
||||
("endinput", get_endinput()),
|
||||
("fi", conditional::get_fi()),
|
||||
("ifeof", get_ifeof()),
|
||||
("input", get_input()),
|
||||
("openin", get_openin()),
|
||||
("read", get_read()),
|
||||
("relax", expansion::get_relax()),
|
||||
])
|
||||
}
|
||||
|
||||
fn custom_vm_initialization(vm: &mut vm::VM<State>) {
|
||||
let mut fs = common::InMemoryFileSystem::new(vm.working_directory.as_ref().unwrap());
|
||||
fs.add_string_file("file1.tex", "content1\n");
|
||||
fs.add_string_file("file2.tex", "content2%\n");
|
||||
fs.add_string_file("file3.tex", r"\input nested/file4");
|
||||
fs.add_string_file("nested/file4.tex", "content4");
|
||||
fs.add_string_file("file5.tex", "file1.tex");
|
||||
fs.add_string_file("recursive.tex", r"\input recursive.tex content");
|
||||
vm.state.file_system = Rc::new(RefCell::new(fs));
|
||||
}
|
||||
|
||||
test_suite!(
|
||||
@options(
|
||||
TestOption::BuiltInCommands(built_in_commands),
|
||||
TestOption::CustomVMInitialization(custom_vm_initialization),
|
||||
),
|
||||
expansion_equality_tests(
|
||||
(basic_case, r"\input file1 hello", "content1 hello"),
|
||||
(input_together, r"\input file2 hello", r"content2hello"),
|
||||
(basic_case_with_ext, r"\input file1.tex", r"content1 "),
|
||||
(nested, r"\input file3", r"content4"),
|
||||
(nested_2, r"\input \input file5", r"content1 "),
|
||||
),
|
||||
fatal_error_tests(
|
||||
(file_does_not_exist, r"\input doesNotExist"),
|
||||
(recursive_input, r"\input recursive s"),
|
||||
),
|
||||
);
|
||||
|
||||
fn end_input_vm_initialization(vm: &mut vm::VM<State>) {
|
||||
let mut fs = common::InMemoryFileSystem::new(vm.working_directory.as_ref().unwrap());
|
||||
fs.add_string_file(
|
||||
"file1.tex",
|
||||
"Hello\\def\\Macro{Hola\\endinput Mundo}\\Macro World\n",
|
||||
);
|
||||
vm.state.file_system = Rc::new(RefCell::new(fs));
|
||||
}
|
||||
|
||||
test_suite!(
|
||||
@option(TestOption::BuiltInCommands(built_in_commands)),
|
||||
@option(TestOption::CustomVMInitialization(end_input_vm_initialization)),
|
||||
expansion_equality_tests(
|
||||
(end_input_simple, r"Hello\endinput World", "Hello",),
|
||||
(
|
||||
end_input_in_second_file,
|
||||
r"Before\input file1 After",
|
||||
"BeforeHelloHolaMundoAfter"
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
fn read_vm_initialization(vm: &mut vm::VM<State>) {
|
||||
let mut fs = common::InMemoryFileSystem::new(vm.working_directory.as_ref().unwrap());
|
||||
fs.add_string_file("file1.tex", "1\n2%\n3");
|
||||
fs.add_string_file("file2.tex", "1{\n2\n3}");
|
||||
fs.add_string_file("file3.tex", "1}1\n2");
|
||||
fs.add_string_file("file4.tex", "");
|
||||
fs.add_string_file("file5.tex", "hello { world");
|
||||
vm.state.file_system = Rc::new(RefCell::new(fs));
|
||||
|
||||
let mut terminal_in: common::MockTerminalIn = Default::default();
|
||||
terminal_in.add_line("first-line");
|
||||
terminal_in.add_line("second-line {");
|
||||
terminal_in.add_line("third-line }");
|
||||
terminal_in.add_line("fourth}line");
|
||||
vm.state.terminal_in = Rc::new(RefCell::new(terminal_in));
|
||||
}
|
||||
|
||||
test_suite!(
|
||||
@options(
|
||||
TestOption::BuiltInCommands(built_in_commands),
|
||||
TestOption::CustomVMInitialization(read_vm_initialization),
|
||||
),
|
||||
expansion_equality_tests(
|
||||
(
|
||||
ifeof_nothing_open,
|
||||
r"\ifeof 0 Closed\else Open\fi",
|
||||
"Closed",
|
||||
),
|
||||
(
|
||||
ifeof_non_existent_file,
|
||||
r"\openin 0 doesNotExist \ifeof 0 Closed\else Open\fi",
|
||||
"Closed",
|
||||
),
|
||||
(
|
||||
ifeof_file_exists,
|
||||
r"\openin 0 file1 \ifeof 0 Closed\else Open\fi",
|
||||
"Open",
|
||||
),
|
||||
(
|
||||
ifeof_non_existent_file_2,
|
||||
r"\openin 0 file1 \openin 0 doesNotExist \ifeof 0 Closed\else Open\fi",
|
||||
"Closed",
|
||||
),
|
||||
(
|
||||
ifeof_file_closed,
|
||||
r"\openin 0 file1 \closein 0 \ifeof 0 Closed\else Open\fi",
|
||||
"Closed",
|
||||
),
|
||||
(
|
||||
read_1,
|
||||
r"\openin 0 file1\read 0 to \line line1='\line'\read 0 to \line line2='\line'\read 0 to \line line3='\line'\ifeof 0 Closed\else Open\fi",
|
||||
"line1='1 'line2='2'line3='3 'Closed",
|
||||
),
|
||||
(
|
||||
read_2,
|
||||
r"\openin 0 file2\read 0 to ~line1='~'\ifeof 0 Closed\else Open\fi",
|
||||
"line1='1{ 2 3} 'Closed",
|
||||
),
|
||||
(
|
||||
read_3,
|
||||
r"\openin 0 file3\read 0 to \line line1='\line'\read 0 to \line line2='\line'",
|
||||
"line1='1'line2='2 '",
|
||||
),
|
||||
(
|
||||
read_4,
|
||||
r"\def\par{par}\openin 0 file4\read 0 to \line line1='\line'\ifeof 0 Closed\else Open\fi",
|
||||
"line1='par'Closed",
|
||||
),
|
||||
(
|
||||
read_from_terminal,
|
||||
r"\read 0 to \line line1='\line'\read 0 to \line line2='\line'\read 0 to \line line3='\line'",
|
||||
"line1='first-line 'line2='second-line { third-line } 'line3='fourth'",
|
||||
),
|
||||
),
|
||||
serde_tests((
|
||||
ifeof_file_exists_serde,
|
||||
r"\openin 0 file1 ",
|
||||
r"\ifeof 0 Closed\else Open\fi"
|
||||
),),
|
||||
fatal_error_tests(
|
||||
(
|
||||
file_has_unmatched_braces,
|
||||
r"\openin 0 file5 \read 0 to \X (\X)",
|
||||
),
|
||||
(
|
||||
failed_to_read_from_terminal,
|
||||
r"\read 0 to \X \read 0 to \X \read 0 to \X \read 0 to \X",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
Vendored
+183
@@ -0,0 +1,183 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
ffi::OsString,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
use texlang_common as common;
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
job_name: Option<PathBuf>,
|
||||
default_job_name: PathBuf,
|
||||
dump_format: i32,
|
||||
dump_validate: i32,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
num_dumps: usize,
|
||||
}
|
||||
|
||||
impl Default for Component {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
job_name: None,
|
||||
default_job_name: "jobname".into(),
|
||||
dump_format: 0,
|
||||
dump_validate: 0,
|
||||
num_dumps: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Component {
|
||||
pub fn job_name(&self) -> &Path {
|
||||
match &self.job_name {
|
||||
None => &self.default_job_name,
|
||||
Some(job_name) => job_name,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this should be called after the first \input.
|
||||
// Probably should add a hook to the VM for this case.
|
||||
// TODO: maybe this should be bundled with \input
|
||||
/// Set the job name based on the provided file path.
|
||||
pub fn set_job_name(&mut self, file_path: &Path) {
|
||||
if let Some(file_stem) = file_path.file_stem() {
|
||||
self.job_name = Some(file_stem.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\jobname` primitive.
|
||||
pub fn get_jobname<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(|token, input| {
|
||||
let job_name: String = input
|
||||
.state()
|
||||
.component()
|
||||
.job_name()
|
||||
.to_string_lossy()
|
||||
.into();
|
||||
input.push_string_tokens(token, &job_name);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the `\dump` primitive.
|
||||
#[cfg(feature = "serde")]
|
||||
pub fn get_dump<
|
||||
S: HasComponent<Component>
|
||||
+ serde::Serialize
|
||||
+ serde::de::DeserializeOwned
|
||||
+ common::HasFileSystem,
|
||||
>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(dump_primitive_fn)
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn dump_primitive_fn<
|
||||
S: HasComponent<Component>
|
||||
+ serde::Serialize
|
||||
+ serde::de::DeserializeOwned
|
||||
+ common::HasFileSystem,
|
||||
>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let component = input.state().component();
|
||||
let mut job_name: OsString = component.job_name().into();
|
||||
let num_dumps = component.num_dumps;
|
||||
if num_dumps > 0 {
|
||||
job_name.push(format!["-{}", num_dumps + 1]);
|
||||
}
|
||||
let mut output_file: PathBuf = job_name.into();
|
||||
output_file.set_extension(match component.dump_format {
|
||||
1 => "fmt.json",
|
||||
2 => "fmt.bincode",
|
||||
_ => "fmt.mp",
|
||||
});
|
||||
|
||||
// TODO: error handle all these serialization errors.
|
||||
let serialized = match component.dump_format {
|
||||
0 => rmp_serde::encode::to_vec(input.vm()).unwrap(),
|
||||
1 => serde_json::to_vec_pretty(input.vm()).unwrap(),
|
||||
2 => bincode::serde::encode_to_vec(input.vm(), bincode::config::standard()).unwrap(),
|
||||
i => {
|
||||
return Err(input.fatal_error(
|
||||
error::SimpleFailedPreconditionError::new(format![
|
||||
r"\dumpFormat has invalid value {i}",
|
||||
])
|
||||
.with_note(r"\dumpFormat must be either 0 (message pack), 1 (json) or 2 (bincode)"),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
if component.dump_validate != 0 {
|
||||
let built_in_commands: HashMap<&str, command::BuiltIn<S>> = input
|
||||
.vm()
|
||||
.commands_map
|
||||
.built_in_commands()
|
||||
.iter()
|
||||
.map(|(cs_name, command)| {
|
||||
(
|
||||
input.vm().cs_name_interner().resolve(*cs_name).unwrap(),
|
||||
command.clone(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
match component.dump_format {
|
||||
0 => {
|
||||
let mut deserializer = rmp_serde::decode::Deserializer::from_read_ref(&serialized);
|
||||
// TODO: this shouldn't panic if the deserialization fails!
|
||||
vm::VM::<S>::deserialize_with_built_in_commands(
|
||||
&mut deserializer,
|
||||
built_in_commands,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
1 => {
|
||||
let mut deserializer = serde_json::Deserializer::from_slice(&serialized);
|
||||
vm::VM::<S>::deserialize_with_built_in_commands(
|
||||
&mut deserializer,
|
||||
built_in_commands,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
2 => {
|
||||
let deserialized: Box<vm::serde::DeserializedVM<S>> =
|
||||
bincode::serde::decode_from_slice(&serialized, bincode::config::standard())
|
||||
.unwrap()
|
||||
.0;
|
||||
vm::serde::finish_deserialization(deserialized, built_in_commands);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: error handle file write
|
||||
input
|
||||
.state()
|
||||
.file_system()
|
||||
.borrow_mut()
|
||||
.write_bytes(&output_file, &serialized)
|
||||
.unwrap();
|
||||
input.state_mut().component_mut().num_dumps += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_dumpformat<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _| &state.component().dump_format,
|
||||
|state: &mut S, _| &mut state.component_mut().dump_format,
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn get_dumpvalidate<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _| &state.component().dump_validate,
|
||||
|state: &mut S, _| &mut state.component_mut().dump_validate,
|
||||
)
|
||||
.into()
|
||||
}
|
||||
Vendored
+574
@@ -0,0 +1,574 @@
|
||||
//! # The Texlang standard library
|
||||
//!
|
||||
//! This module contains implementations of TeX primitives for Texlang.
|
||||
|
||||
extern crate texcraft_stdext;
|
||||
extern crate texlang;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use texlang::command;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::token;
|
||||
use texlang::traits::*;
|
||||
use texlang::types;
|
||||
use texlang::types::CatCode;
|
||||
use texlang::vm;
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_common::HasFileSystem;
|
||||
use texlang_common::HasLogging;
|
||||
use texlang_common::HasTerminalIn;
|
||||
|
||||
pub mod alias;
|
||||
pub mod alloc;
|
||||
pub mod chardef;
|
||||
pub mod codes;
|
||||
pub mod conditional;
|
||||
pub mod def;
|
||||
pub mod endlinechar;
|
||||
pub mod errormode;
|
||||
pub mod expansion;
|
||||
pub mod input;
|
||||
pub mod job;
|
||||
pub mod math;
|
||||
pub mod mathchardef;
|
||||
pub mod prefix;
|
||||
pub mod registers;
|
||||
pub mod repl;
|
||||
pub mod script;
|
||||
pub mod sleep;
|
||||
pub mod texcraft;
|
||||
pub mod the;
|
||||
pub mod time;
|
||||
pub mod tracingmacros;
|
||||
|
||||
/// A state struct that is compatible with every primitive in the Texlang standard library.
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct StdLibState {
|
||||
pub alloc: alloc::Component,
|
||||
pub codes_cat_code: codes::Component<CatCode>,
|
||||
pub codes_math_code: codes::Component<types::MathCode>,
|
||||
pub conditional: conditional::Component,
|
||||
pub end_line_char: endlinechar::Component,
|
||||
pub error_mode: errormode::Component,
|
||||
pub input: input::Component<16>,
|
||||
pub job: job::Component,
|
||||
pub prefix: prefix::Component,
|
||||
pub registers_i32: registers::Component<i32, 32768>,
|
||||
pub registers_scaled: registers::Component<common::Scaled, 32768>,
|
||||
pub registers_glue: registers::Component<common::Glue, 32768>,
|
||||
pub registers_token_list: registers::Component<Vec<token::Token>, 256>,
|
||||
pub repl: repl::Component,
|
||||
pub script: script::Component,
|
||||
#[cfg(test)]
|
||||
pub testing: texlang_testing::TestingComponent,
|
||||
pub time: time::Component,
|
||||
pub tracing_macros: tracingmacros::Component,
|
||||
}
|
||||
|
||||
impl TexlangState for StdLibState {
|
||||
#[inline]
|
||||
fn cat_code(&self, c: char) -> texlang::types::CatCode {
|
||||
codes::cat_code(self, c)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn end_line_char(&self) -> Option<char> {
|
||||
endlinechar::end_line_char(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn post_macro_expansion_hook(
|
||||
token: texlang::token::Token,
|
||||
input: &vm::ExpansionInput<Self>,
|
||||
tex_macro: &texlang::texmacro::Macro,
|
||||
arguments: &[&[texlang::token::Token]],
|
||||
reversed_expansion: &[texlang::token::Token],
|
||||
) {
|
||||
tracingmacros::hook(token, input, tex_macro, arguments, reversed_expansion)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn expansion_override_hook(
|
||||
token: texlang::token::Token,
|
||||
input: &mut vm::ExpansionInput<Self>,
|
||||
tag: Option<texlang::command::Tag>,
|
||||
) -> txl::Result<Option<texlang::token::Token>> {
|
||||
expansion::noexpand_hook(token, input, tag)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn variable_assignment_scope_hook(
|
||||
state: &mut Self,
|
||||
) -> texcraft_stdext::collections::groupingmap::Scope {
|
||||
prefix::variable_assignment_scope_hook(state)
|
||||
}
|
||||
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: texlang::error::TracedTexError,
|
||||
) -> Result<(), Box<dyn texlang::error::TexError>> {
|
||||
errormode::recoverable_error_hook(self, recoverable_error)
|
||||
}
|
||||
}
|
||||
|
||||
impl the::TheCompatible for StdLibState {}
|
||||
|
||||
implement_has_component![StdLibState{
|
||||
alloc: alloc::Component,
|
||||
codes_cat_code: codes::Component<CatCode>,
|
||||
codes_math_code: codes::Component<types::MathCode>,
|
||||
conditional: conditional::Component,
|
||||
end_line_char: endlinechar::Component,
|
||||
error_mode: errormode::Component,
|
||||
input: input::Component<16>,
|
||||
job: job::Component,
|
||||
prefix: prefix::Component,
|
||||
registers_i32: registers::Component<i32, 32768>,
|
||||
registers_scaled: registers::Component<common::Scaled, 32768>,
|
||||
registers_glue: registers::Component<common::Glue, 32768>,
|
||||
registers_token_list: registers::Component<Vec<token::Token>, 256>,
|
||||
repl: repl::Component,
|
||||
script: script::Component,
|
||||
time: time::Component,
|
||||
tracing_macros: tracingmacros::Component,
|
||||
}];
|
||||
|
||||
impl texlang_common::HasLogging for StdLibState {}
|
||||
impl texlang_common::HasFileSystem for StdLibState {}
|
||||
impl texlang_common::HasTerminalIn for StdLibState {
|
||||
fn terminal_in(&self) -> std::rc::Rc<std::cell::RefCell<dyn texlang_common::TerminalIn>> {
|
||||
self.error_mode.terminal_in()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn built_in_commands<S>() -> HashMap<&'static str, command::BuiltIn<S>>
|
||||
where
|
||||
S: TexlangState
|
||||
+ HasFileSystem
|
||||
+ HasTerminalIn
|
||||
+ HasLogging
|
||||
+ HasComponent<alloc::Component>
|
||||
+ HasComponent<codes::Component<CatCode>>
|
||||
+ HasComponent<codes::Component<types::MathCode>>
|
||||
+ HasComponent<conditional::Component>
|
||||
+ the::TheCompatible
|
||||
+ HasComponent<endlinechar::Component>
|
||||
+ HasComponent<errormode::Component>
|
||||
+ HasComponent<input::Component<16>>
|
||||
+ HasComponent<job::Component>
|
||||
+ HasComponent<prefix::Component>
|
||||
+ HasComponent<registers::Component<i32, 32768>>
|
||||
+ HasComponent<registers::Component<common::Scaled, 32768>>
|
||||
+ HasComponent<registers::Component<common::Glue, 32768>>
|
||||
+ HasComponent<registers::Component<Vec<token::Token>, 256>>
|
||||
+ HasComponent<repl::Component>
|
||||
+ HasComponent<script::Component>
|
||||
+ HasComponent<time::Component>
|
||||
+ HasComponent<tracingmacros::Component>,
|
||||
{
|
||||
let mut built_ins = built_in_commands_without_catcode::<S>();
|
||||
built_ins.insert("catcode", codes::get_catcode());
|
||||
built_ins
|
||||
}
|
||||
|
||||
/// Build standard primitives without category-code, math-code, end-line, or
|
||||
/// register commands.
|
||||
///
|
||||
/// Engines that own these variables can register them against their own state.
|
||||
pub fn built_in_commands_without_catcode_mathcode_and_endlinechar_and_registers<S>() ->
|
||||
HashMap<&'static str, command::BuiltIn<S>>
|
||||
where
|
||||
S: TexlangState
|
||||
+ HasFileSystem
|
||||
+ HasTerminalIn
|
||||
+ HasLogging
|
||||
+ HasComponent<alloc::Component>
|
||||
+ HasComponent<conditional::Component>
|
||||
+ the::TheCompatible
|
||||
+ HasComponent<errormode::Component>
|
||||
+ HasComponent<input::Component<16>>
|
||||
+ HasComponent<job::Component>
|
||||
+ HasComponent<prefix::Component>
|
||||
+ HasComponent<repl::Component>
|
||||
+ HasComponent<script::Component>
|
||||
+ HasComponent<time::Component>
|
||||
+ HasComponent<tracingmacros::Component>,
|
||||
{
|
||||
HashMap::from([
|
||||
("advance", math::get_advance()),
|
||||
//
|
||||
("batchmode", errormode::get_batchmode()),
|
||||
//
|
||||
("closein", input::get_closein()),
|
||||
("chardef", chardef::get_chardef()),
|
||||
//
|
||||
("day", time::get_day()),
|
||||
("def", def::get_def()),
|
||||
("divide", math::get_divide()),
|
||||
("dumpFormat", job::get_dumpformat()),
|
||||
("dumpValidate", job::get_dumpvalidate()),
|
||||
//
|
||||
("else", conditional::get_else()),
|
||||
("endinput", input::get_endinput()),
|
||||
("errorstopmode", errormode::get_errorstopmode()),
|
||||
("expandafter", expansion::get_expandafter_optimized()),
|
||||
//
|
||||
("fi", conditional::get_fi()),
|
||||
//
|
||||
("gdef", def::get_gdef()),
|
||||
("global", prefix::get_global()),
|
||||
("globaldefs", prefix::get_globaldefs()),
|
||||
//
|
||||
("ifcase", conditional::get_ifcase()),
|
||||
("ifeof", input::get_ifeof()),
|
||||
("iffalse", conditional::get_iffalse()),
|
||||
("ifnum", conditional::get_ifnum()),
|
||||
("ifodd", conditional::get_ifodd()),
|
||||
("iftrue", conditional::get_iftrue()),
|
||||
("input", input::get_input()),
|
||||
//
|
||||
("jobname", job::get_jobname()),
|
||||
//
|
||||
("let", alias::get_let()),
|
||||
("long", prefix::get_long()),
|
||||
//
|
||||
("mathchardef", mathchardef::get_mathchardef()),
|
||||
("month", time::get_month()),
|
||||
("multiply", math::get_multiply()),
|
||||
//
|
||||
("newInt", alloc::get_newint()),
|
||||
(
|
||||
"newInt_getter_provider_\u{0}",
|
||||
alloc::get_newint_getter_provider(),
|
||||
),
|
||||
("newIntArray", alloc::get_newintarray()),
|
||||
(
|
||||
"newIntArray_getter_provider_\u{0}",
|
||||
alloc::get_newintarray_getter_provider(),
|
||||
),
|
||||
("noexpand", expansion::get_noexpand()),
|
||||
("nonstopmode", errormode::get_nonstopmode()),
|
||||
//
|
||||
("or", conditional::get_or()),
|
||||
("openin", input::get_openin()),
|
||||
("outer", prefix::get_outer()),
|
||||
//
|
||||
("read", input::get_read()),
|
||||
("relax", expansion::get_relax()),
|
||||
//
|
||||
("scrollmode", errormode::get_scrollmode()),
|
||||
("sleep", sleep::get_sleep()),
|
||||
//
|
||||
("the", the::get_the()),
|
||||
("time", time::get_time()),
|
||||
("tracingmacros", tracingmacros::get_tracingmacros()),
|
||||
//
|
||||
("year", time::get_year()),
|
||||
])
|
||||
}
|
||||
|
||||
/// Build the standard primitive map without `\catcode`, `\mathcode`, or
|
||||
/// `\endlinechar`, while retaining Texlang's standard register commands.
|
||||
///
|
||||
/// This variant is for engines that use Texlang's register state but provide
|
||||
/// their own category-code, math-code, and end-line-character state.
|
||||
pub fn built_in_commands_without_catcode_mathcode_and_endlinechar<S>() ->
|
||||
HashMap<&'static str, command::BuiltIn<S>>
|
||||
where
|
||||
S: TexlangState
|
||||
+ HasFileSystem
|
||||
+ HasTerminalIn
|
||||
+ HasLogging
|
||||
+ HasComponent<alloc::Component>
|
||||
+ HasComponent<conditional::Component>
|
||||
+ the::TheCompatible
|
||||
+ HasComponent<errormode::Component>
|
||||
+ HasComponent<input::Component<16>>
|
||||
+ HasComponent<job::Component>
|
||||
+ HasComponent<prefix::Component>
|
||||
+ HasComponent<registers::Component<i32, 32768>>
|
||||
+ HasComponent<registers::Component<common::Scaled, 32768>>
|
||||
+ HasComponent<registers::Component<common::Glue, 32768>>
|
||||
+ HasComponent<registers::Component<Vec<token::Token>, 256>>
|
||||
+ HasComponent<repl::Component>
|
||||
+ HasComponent<script::Component>
|
||||
+ HasComponent<time::Component>
|
||||
+ HasComponent<tracingmacros::Component>,
|
||||
{
|
||||
let mut built_ins =
|
||||
built_in_commands_without_catcode_mathcode_and_endlinechar_and_registers::<S>();
|
||||
built_ins.extend([
|
||||
("count", registers::get_count()),
|
||||
("countdef", registers::get_countdef()),
|
||||
("dimen", registers::get_dimen()),
|
||||
("skip", registers::get_skip()),
|
||||
("toks", registers::get_toks()),
|
||||
("toksdef", registers::get_toksdef()),
|
||||
]);
|
||||
built_ins
|
||||
}
|
||||
|
||||
/// Build the standard primitive map without `\catcode` or `\mathcode`.
|
||||
///
|
||||
/// This variant retains the standard `\endlinechar` implementation for
|
||||
/// engines that use Texlang's end-line-character component.
|
||||
pub fn built_in_commands_without_catcode_and_mathcode<S>() ->
|
||||
HashMap<&'static str, command::BuiltIn<S>>
|
||||
where
|
||||
S: TexlangState
|
||||
+ HasFileSystem
|
||||
+ HasTerminalIn
|
||||
+ HasLogging
|
||||
+ HasComponent<alloc::Component>
|
||||
+ HasComponent<conditional::Component>
|
||||
+ the::TheCompatible
|
||||
+ HasComponent<endlinechar::Component>
|
||||
+ HasComponent<errormode::Component>
|
||||
+ HasComponent<input::Component<16>>
|
||||
+ HasComponent<job::Component>
|
||||
+ HasComponent<prefix::Component>
|
||||
+ HasComponent<registers::Component<i32, 32768>>
|
||||
+ HasComponent<registers::Component<common::Scaled, 32768>>
|
||||
+ HasComponent<registers::Component<common::Glue, 32768>>
|
||||
+ HasComponent<registers::Component<Vec<token::Token>, 256>>
|
||||
+ HasComponent<repl::Component>
|
||||
+ HasComponent<script::Component>
|
||||
+ HasComponent<time::Component>
|
||||
+ HasComponent<tracingmacros::Component>,
|
||||
{
|
||||
let mut built_ins = built_in_commands_without_catcode_mathcode_and_endlinechar::<S>();
|
||||
built_ins.insert("endlinechar", endlinechar::get_endlinechar());
|
||||
built_ins
|
||||
}
|
||||
|
||||
/// Build the standard primitive map without `\catcode`.
|
||||
///
|
||||
/// This retains the standard `\mathcode` implementation for engines that use
|
||||
/// Texlang's math-code component.
|
||||
pub fn built_in_commands_without_catcode<S>() -> HashMap<&'static str, command::BuiltIn<S>>
|
||||
where
|
||||
S: TexlangState
|
||||
+ HasFileSystem
|
||||
+ HasTerminalIn
|
||||
+ HasLogging
|
||||
+ HasComponent<alloc::Component>
|
||||
+ HasComponent<codes::Component<types::MathCode>>
|
||||
+ HasComponent<conditional::Component>
|
||||
+ the::TheCompatible
|
||||
+ HasComponent<endlinechar::Component>
|
||||
+ HasComponent<errormode::Component>
|
||||
+ HasComponent<input::Component<16>>
|
||||
+ HasComponent<job::Component>
|
||||
+ HasComponent<prefix::Component>
|
||||
+ HasComponent<registers::Component<i32, 32768>>
|
||||
+ HasComponent<registers::Component<common::Scaled, 32768>>
|
||||
+ HasComponent<registers::Component<common::Glue, 32768>>
|
||||
+ HasComponent<registers::Component<Vec<token::Token>, 256>>
|
||||
+ HasComponent<repl::Component>
|
||||
+ HasComponent<script::Component>
|
||||
+ HasComponent<time::Component>
|
||||
+ HasComponent<tracingmacros::Component>,
|
||||
{
|
||||
let mut built_ins = built_in_commands_without_catcode_and_mathcode::<S>();
|
||||
built_ins.insert("mathcode", codes::get_mathcode());
|
||||
built_ins
|
||||
}
|
||||
|
||||
impl HasDefaultBuiltInCommands for StdLibState {
|
||||
fn default_built_in_commands() -> HashMap<&'static str, command::BuiltIn<Self>> {
|
||||
built_in_commands()
|
||||
}
|
||||
}
|
||||
|
||||
/// A TeX snippet that exercises some error case in the standard library.
|
||||
pub struct ErrorCase {
|
||||
pub description: &'static str,
|
||||
pub source_code: &'static str,
|
||||
}
|
||||
|
||||
impl ErrorCase {
|
||||
/// Returns a vector of TeX snippets that exercise all error paths in Texlang.
|
||||
///
|
||||
/// TODO: instead of duplicating these here, we should have a way of dumping all
|
||||
/// error cases in the regular unit tests into a file.
|
||||
pub fn all_error_cases() -> Vec<ErrorCase> {
|
||||
let mut cases = vec![];
|
||||
for (description, source_code) in vec![
|
||||
(r"\toks starts with a letter token", r"\toks 0 = a"),
|
||||
(
|
||||
r"\toks starts with a non-variable command",
|
||||
r"\toks 0 = \def",
|
||||
),
|
||||
(
|
||||
r"\toks starts is a variable command of the wrong type",
|
||||
r"\toks 0 = \count 0",
|
||||
),
|
||||
(
|
||||
r"end of input while scanning token list",
|
||||
r"\toks 0 = { no closing brace",
|
||||
),
|
||||
(r"assign number from \toks", r"\count 0 = \toks 0"),
|
||||
(r"end of input right after \toks", r"\toks 0"),
|
||||
(r"\count is out of bounds (negative)", r"\count -200"),
|
||||
(r"\count is out of bounds (positive)", r"\count 2000000"),
|
||||
("file does not exist", r"\input doesNotExist"),
|
||||
("end of input after \\global", r"\global"),
|
||||
("can't be prefixed by \\global", r"\global \sleep"),
|
||||
("can't be prefixed by \\global (character)", r"\global a"),
|
||||
("can't be prefixed by \\long", r"\long \let \a = \def"),
|
||||
("can't be prefixed by \\outer", r"\outer \let \a = \def"),
|
||||
("bad rhs in assignment", r"\year = X"),
|
||||
("invalid variable (undefined)", r"\advance \undefined by 4"),
|
||||
(
|
||||
"invalid variable (not a variable command)",
|
||||
r"\advance \def by 4",
|
||||
),
|
||||
("invalid variable (character token)", r"\advance a by 4"),
|
||||
("invalid variable (eof)", r"\advance"),
|
||||
("invalid relation", r"\ifnum 3 z 4"),
|
||||
("malformed by keyword", r"\advance \year bg"),
|
||||
("undefined control sequence", r"\elephant"),
|
||||
("invalid character", "\u{7F}"),
|
||||
("empty control sequence", r"\"),
|
||||
("invalid end of group", r"}"),
|
||||
("invalid start of number", r"\count X"),
|
||||
("invalid start of number (eof)", r"\count"),
|
||||
("invalid start of number (not a variable)", r"\count \def"),
|
||||
(
|
||||
"case negative number to positive (from constant)",
|
||||
r"\count -1",
|
||||
),
|
||||
(
|
||||
"cast negative number to positive (from variable)",
|
||||
r"\count 0 = 1 \count - \count 0",
|
||||
),
|
||||
(
|
||||
"read positive number from negative variable value",
|
||||
r"\count 0 = -1 \count \count 0",
|
||||
),
|
||||
("invalid character", r"\count `\def"),
|
||||
("invalid character (eof)", r"\count `"),
|
||||
("invalid octal digit", r"\count '9"),
|
||||
("invalid octal digit (eof)", r"\count '"),
|
||||
("invalid hexadecimal digit", "\\count \"Z"),
|
||||
("invalid hexadecimal digit (eof)", "\\count \""),
|
||||
(
|
||||
"decimal number too big (radix)",
|
||||
r"\count 1000000000000000000000",
|
||||
),
|
||||
(
|
||||
"decimal number too big (sum)",
|
||||
r"\count 18446744073709551617",
|
||||
),
|
||||
("octal number too big", r"\count '7777777777777777777777"),
|
||||
(
|
||||
"hexadecimal number too big",
|
||||
"\\count \"AAAAAAAAAAAAAAAAAAAAAA",
|
||||
),
|
||||
("number with letter catcode", r"\catcode `1 = 11 \count 1"),
|
||||
(
|
||||
"non-arithmetic argument to math command",
|
||||
r"\advance \catcode 1 by 3",
|
||||
),
|
||||
/*
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""),
|
||||
("", r""), */
|
||||
("category code out of bounds", r"\catcode 0 = 17"),
|
||||
("invalid command target", r"\let a = \year"),
|
||||
("invalid command target (eof)", r"\let"),
|
||||
] {
|
||||
cases.push(ErrorCase {
|
||||
description,
|
||||
source_code,
|
||||
})
|
||||
}
|
||||
cases
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl HasComponent<texlang_testing::TestingComponent> for StdLibState {
|
||||
fn component(&self) -> &texlang_testing::TestingComponent {
|
||||
&self.testing
|
||||
}
|
||||
|
||||
fn component_mut(&mut self) -> &mut texlang_testing::TestingComponent {
|
||||
&mut self.testing
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texlang_testing::*;
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<StdLibState>> {
|
||||
StdLibState::default_built_in_commands()
|
||||
}
|
||||
|
||||
type State = StdLibState;
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(
|
||||
relation_before_spaces,
|
||||
r"\countdef\A1 \A=2 \def\cmp#1{\ifnum#1 <3}\cmp{\A}Pass\else Fail \fi",
|
||||
r"Pass"
|
||||
),
|
||||
(
|
||||
overwrite_else,
|
||||
r"\def\else{}\ifodd 2 \else should be skipped \fi",
|
||||
r""
|
||||
),
|
||||
(
|
||||
math_and_active_char,
|
||||
r"-\catcode`\A=13 \countdef A5 \countdef ~6 ~=7 A=8 \advance~byA \the~",
|
||||
r"- 15",
|
||||
),
|
||||
/*
|
||||
s.cat_code_map_mut().insert(
|
||||
'[' as u32,
|
||||
catcode::RawCatCode::Regular(catcode::CatCode::BeginGroup),
|
||||
);
|
||||
s.cat_code_map_mut().insert(
|
||||
']' as u32,
|
||||
catcode::RawCatCode::Regular(catcode::CatCode::EndGroup),
|
||||
);
|
||||
s.cat_code_map_mut().insert(
|
||||
'!' as u32,
|
||||
catcode::RawCatCode::Regular(catcode::CatCode::texmacro::Parameter),
|
||||
*/
|
||||
(
|
||||
texbook_exercise_20_7,
|
||||
r"\catcode`\[=1 \catcode`\]=2 \catcode`\!=6 \def\!!1#2![{!#]#!!2}\! x{[y]][z}",
|
||||
r"\catcode`\[=1 \catcode`\]=2 \catcode`\!=6 {#]![y][z}",
|
||||
),
|
||||
(
|
||||
variable_assignment_space_before_equal,
|
||||
r"\def\assign#1{#1 = 20\relax}\assign\year\the\year",
|
||||
"20",
|
||||
),
|
||||
),
|
||||
serde_tests((serde_sanity, r"\def\HW{Hello World} ", r"\HW"),),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn all_error_cases() {
|
||||
let options = vec![TestOption::BuiltInCommands(
|
||||
StdLibState::default_built_in_commands,
|
||||
)];
|
||||
for case in ErrorCase::all_error_cases() {
|
||||
println!("CASE {}", case.description);
|
||||
run_fatal_error_test::<StdLibState>(case.source_code, &options, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+577
@@ -0,0 +1,577 @@
|
||||
//! Operations on variables (add, multiply, divide)
|
||||
|
||||
use texcraft_stdext::collections::groupingmap;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::variable::SupportedType;
|
||||
use texlang::variable::TypedVariable;
|
||||
use texlang::*;
|
||||
|
||||
/// Get the `\advance` command.
|
||||
pub fn get_advance<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
get_command::<S, AdvanceOp>()
|
||||
}
|
||||
|
||||
/// Get the `\advanceChecked` command.
|
||||
pub fn get_advance_checked<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
get_command::<S, AdvanceCheckedOp>()
|
||||
}
|
||||
|
||||
/// Get the `\multiply` command.
|
||||
pub fn get_multiply<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
get_command::<S, MultiplyOp>()
|
||||
}
|
||||
|
||||
/// Get the `\multiplyWrapped` command.
|
||||
pub fn get_multiply_wrapped<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
get_command::<S, MultiplyWrappedOp>()
|
||||
}
|
||||
|
||||
/// Get the `\divide` command.
|
||||
pub fn get_divide<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
get_command::<S, DivideOp>()
|
||||
}
|
||||
|
||||
fn get_command<S: TexlangState, O: Op>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(math_primitive_fn::<S, O>)
|
||||
.with_tag(variable_op_tag())
|
||||
.with_doc(O::DOC)
|
||||
}
|
||||
|
||||
static VARIABLE_OP_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
pub fn variable_op_tag() -> command::Tag {
|
||||
VARIABLE_OP_TAG.get()
|
||||
}
|
||||
|
||||
trait Number: Sized + Default + SupportedType + Copy + std::fmt::Display {
|
||||
fn wrapping_add(lhs: Self, rhs: Self) -> Self;
|
||||
fn checked_add(lhs: Self, rhs: Self) -> Option<Self>;
|
||||
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self>;
|
||||
fn wrapping_mul(lhs: Self, rhs: i32) -> Self;
|
||||
fn checked_div(lhs: Self, rhs: i32) -> Option<Self>;
|
||||
}
|
||||
|
||||
impl Number for i32 {
|
||||
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
|
||||
lhs.wrapping_add(rhs)
|
||||
}
|
||||
fn checked_add(lhs: Self, rhs: Self) -> Option<Self> {
|
||||
lhs.checked_add(rhs)
|
||||
}
|
||||
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_mul(rhs)
|
||||
}
|
||||
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
|
||||
lhs.wrapping_mul(rhs)
|
||||
}
|
||||
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_div(rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Number for common::Scaled {
|
||||
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
|
||||
lhs.wrapping_add(rhs)
|
||||
}
|
||||
fn checked_add(lhs: Self, rhs: Self) -> Option<Self> {
|
||||
lhs.checked_add(rhs)
|
||||
}
|
||||
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_mul(rhs)
|
||||
}
|
||||
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
|
||||
lhs.wrapping_mul(rhs)
|
||||
}
|
||||
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_div(rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Number for common::Glue {
|
||||
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
|
||||
lhs.wrapping_add(rhs)
|
||||
}
|
||||
fn checked_add(lhs: Self, rhs: Self) -> Option<Self> {
|
||||
lhs.checked_add(rhs)
|
||||
}
|
||||
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_mul(rhs)
|
||||
}
|
||||
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
|
||||
lhs.wrapping_mul(rhs)
|
||||
}
|
||||
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_div(rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Number for types::MuGlue {
|
||||
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
|
||||
lhs.wrapping_add(rhs)
|
||||
}
|
||||
fn checked_add(lhs: Self, rhs: Self) -> Option<Self> {
|
||||
lhs.checked_add(rhs)
|
||||
}
|
||||
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_mul(rhs)
|
||||
}
|
||||
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
|
||||
lhs.wrapping_mul(rhs)
|
||||
}
|
||||
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
|
||||
lhs.checked_div(rhs)
|
||||
}
|
||||
}
|
||||
|
||||
trait Op {
|
||||
const DOC: &'static str;
|
||||
const RHS_SAME: bool;
|
||||
type Error: error::TexError;
|
||||
fn apply<N: Number>(lhs: N, rhs_i: i32, rhs_n: N) -> Result<N, Self::Error>;
|
||||
|
||||
fn apply_to_variable<S: TexlangState, N: Number>(
|
||||
variable: TypedVariable<S, N>,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
scope: groupingmap::Scope,
|
||||
) -> txl::Result<()> {
|
||||
let lhs = *variable.get(input.state());
|
||||
let (rhs_i, rhs_n) = if Self::RHS_SAME {
|
||||
(0_i32, N::parse(input)?)
|
||||
} else {
|
||||
(i32::parse(input)?, Default::default())
|
||||
};
|
||||
let result = match Self::apply(lhs, rhs_i, rhs_n) {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
return input.error(err);
|
||||
}
|
||||
};
|
||||
variable.set(input, scope, result);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct AdvanceOp;
|
||||
|
||||
impl Op for AdvanceOp {
|
||||
const DOC: &'static str = "Add a quantity to a variable";
|
||||
const RHS_SAME: bool = true;
|
||||
type Error = OverflowError;
|
||||
fn apply<N: Number>(lhs: N, _: i32, rhs_n: N) -> Result<N, Self::Error> {
|
||||
// TeX silently overflows in \advance
|
||||
Ok(N::wrapping_add(lhs, rhs_n))
|
||||
}
|
||||
}
|
||||
|
||||
struct AdvanceCheckedOp;
|
||||
|
||||
impl Op for AdvanceCheckedOp {
|
||||
const DOC: &'static str = "Add a number to a variable (error on overflow)";
|
||||
const RHS_SAME: bool = true;
|
||||
type Error = OverflowError;
|
||||
fn apply<N: Number>(lhs: N, _: i32, rhs_n: N) -> Result<N, Self::Error> {
|
||||
match N::checked_add(lhs, rhs_n) {
|
||||
Some(result) => Ok(result),
|
||||
None => Err(OverflowError {
|
||||
op_name: "addition",
|
||||
lhs: format!["{lhs}"],
|
||||
rhs: format!["{rhs_n}"],
|
||||
wrapped_result: format!["{}", N::wrapping_add(lhs, rhs_n)],
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MultiplyOp;
|
||||
|
||||
impl Op for MultiplyOp {
|
||||
const DOC: &'static str = "Multiply a variable by an integer";
|
||||
const RHS_SAME: bool = false;
|
||||
type Error = OverflowError;
|
||||
fn apply<N: Number>(lhs: N, rhs_i: i32, _: N) -> Result<N, Self::Error> {
|
||||
match N::checked_mul(lhs, rhs_i) {
|
||||
Some(result) => Ok(result),
|
||||
None => Err(OverflowError {
|
||||
op_name: "multiplication",
|
||||
lhs: format!["{lhs}"],
|
||||
rhs: format!["{rhs_i}"],
|
||||
wrapped_result: format!["{}", N::wrapping_mul(lhs, rhs_i)],
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MultiplyWrappedOp;
|
||||
|
||||
impl Op for MultiplyWrappedOp {
|
||||
const DOC: &'static str = "Multiply a variable by an integer (wrap on overflow)";
|
||||
const RHS_SAME: bool = false;
|
||||
type Error = OverflowError;
|
||||
fn apply<N: Number>(lhs: N, rhs_i: i32, _: N) -> Result<N, Self::Error> {
|
||||
Ok(N::wrapping_mul(lhs, rhs_i))
|
||||
}
|
||||
}
|
||||
|
||||
struct DivideOp;
|
||||
|
||||
impl Op for DivideOp {
|
||||
const DOC: &'static str = "Divide a variable by an integer";
|
||||
const RHS_SAME: bool = false;
|
||||
type Error = DivisionByZeroError;
|
||||
fn apply<N: Number>(lhs: N, rhs_i: i32, _: N) -> Result<N, Self::Error> {
|
||||
match N::checked_div(lhs, rhs_i) {
|
||||
Some(result) => Ok(result),
|
||||
None => Err(DivisionByZeroError {
|
||||
numerator: format!["{lhs}"],
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OverflowError {
|
||||
op_name: &'static str,
|
||||
lhs: String,
|
||||
rhs: String,
|
||||
wrapped_result: String,
|
||||
}
|
||||
|
||||
impl error::TexError for OverflowError {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::FailedPrecondition
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
format!["overflow in checked {}", self.op_name]
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
format!["left hand side evaluated to {}", self.lhs].into(),
|
||||
format!["right hand side evaluated to {}", self.rhs].into(),
|
||||
format!["wrapped result would be {}", self.wrapped_result].into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DivisionByZeroError {
|
||||
numerator: String,
|
||||
}
|
||||
|
||||
impl error::TexError for DivisionByZeroError {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::FailedPrecondition
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"division by zero".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![format!["numerator evaluated to {}", self.numerator].into()]
|
||||
}
|
||||
}
|
||||
|
||||
/// TeX.2021.446-1240
|
||||
fn math_primitive_fn<S: TexlangState, O: Op>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
let token = input.next_or_err(ArithmeticVariableEndOfInput {})?;
|
||||
match token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match input.commands_map().get_command(&command_ref) {
|
||||
None => input.error(
|
||||
parse::Error::new("a variable", Some(token), "")
|
||||
.with_got_override("got an undefined control sequence")
|
||||
.with_annotation_override("undefined control sequence"),
|
||||
),
|
||||
Some(command::Command::Variable(cmd)) => {
|
||||
if !cmd.is_arithmetic() {
|
||||
input.error(
|
||||
parse::Error::new("an arithmetic variable", Some(token), "")
|
||||
.with_got_override("got a non-arithmetic variable"),
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
let variable = cmd.clone().resolve(token, input.as_mut())?;
|
||||
OptionalBy::parse(input)?;
|
||||
match variable {
|
||||
variable::Variable::Int(variable) => {
|
||||
O::apply_to_variable(variable, input, scope)
|
||||
}
|
||||
variable::Variable::Dimen(variable) => {
|
||||
O::apply_to_variable(variable, input, scope)
|
||||
}
|
||||
variable::Variable::Glue(variable) => {
|
||||
O::apply_to_variable(variable, input, scope)
|
||||
}
|
||||
variable::Variable::MuGlue(variable) => {
|
||||
O::apply_to_variable(variable, input, scope)
|
||||
}
|
||||
variable::Variable::SmallInt(_)
|
||||
| variable::Variable::CatCode(_)
|
||||
| variable::Variable::TokenList(_)
|
||||
| variable::Variable::MathCode(_)
|
||||
| variable::Variable::Font(_) => {
|
||||
unreachable!("only arithmetic commands are considered");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(cmd) => input.error(
|
||||
parse::Error::new("a variable", Some(token), "")
|
||||
.with_got_override("got a non-variable command")
|
||||
.with_annotation_override(format!["control sequence referencing {cmd}"]),
|
||||
),
|
||||
}
|
||||
}
|
||||
_ => input.error(
|
||||
parse::Error::new("a variable", Some(token), "")
|
||||
.with_got_override("got a character token"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ArithmeticVariableEndOfInput;
|
||||
|
||||
impl error::EndOfInputError for ArithmeticVariableEndOfInput {
|
||||
fn doing(&self) -> String {
|
||||
"parsing an arithmetic variable".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an optional `by` keyword from the input stream.
|
||||
struct OptionalBy;
|
||||
|
||||
impl Parsable for OptionalBy {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
texlang::parse::parse_keyword(input, "by")?;
|
||||
Ok(OptionalBy)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use crate::codes;
|
||||
use crate::prefix;
|
||||
use crate::registers;
|
||||
use crate::the;
|
||||
use texlang::types::CatCode;
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
catcode: codes::Component<CatCode>,
|
||||
prefix: prefix::Component,
|
||||
registers: registers::Component<i32, 256>,
|
||||
registers_dimen: registers::Component<common::Scaled, 256>,
|
||||
registers_skip: registers::Component<common::Glue, 256>,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn variable_assignment_scope_hook(
|
||||
state: &mut Self,
|
||||
) -> texcraft_stdext::collections::groupingmap::Scope {
|
||||
prefix::variable_assignment_scope_hook(state)
|
||||
}
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
texlang_testing::TestingComponent::recoverable_error_hook(self, recoverable_error)
|
||||
}
|
||||
}
|
||||
impl the::TheCompatible for State {}
|
||||
|
||||
implement_has_component![State{
|
||||
catcode: codes::Component<CatCode>,
|
||||
prefix: prefix::Component,
|
||||
registers: registers::Component<i32, 256>,
|
||||
registers_dimen: registers::Component<common::Scaled, 256>,
|
||||
registers_skip: registers::Component<common::Glue, 256>,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("advance", get_advance()),
|
||||
("advanceChecked", get_advance_checked()),
|
||||
("multiply", get_multiply()),
|
||||
("multiplyWrapped", get_multiply_wrapped()),
|
||||
("divide", get_divide()),
|
||||
//
|
||||
("catcode", codes::get_catcode()),
|
||||
("count", registers::get_count()),
|
||||
("dimen", registers::get_dimen()),
|
||||
("skip", registers::get_skip()),
|
||||
("global", prefix::get_global()),
|
||||
("the", the::get_the()),
|
||||
])
|
||||
}
|
||||
|
||||
macro_rules! arithmetic_tests {
|
||||
( $register: expr, $( ($name: ident, $op: expr, $lhs: expr, $rhs: expr, $expected: expr) ),* $(,)? ) => {
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
$(
|
||||
(
|
||||
$name,
|
||||
format![r"{} 1 {} {} {} 1 {} \the{} 1", $register, $lhs, $op, $register, $rhs, $register],
|
||||
$expected
|
||||
),
|
||||
)*
|
||||
),
|
||||
];
|
||||
};
|
||||
}
|
||||
|
||||
arithmetic_tests![
|
||||
r"\count",
|
||||
(advance_base_case, r"\advance", "1", "2", "3"),
|
||||
(advance_base_case_with_by, r"\advance", "1", "by 2", "3"),
|
||||
(advance_negative_summand, r"\advance", "10", "-2", "8"),
|
||||
(
|
||||
advance_overflow_case,
|
||||
r"\advance",
|
||||
"2147483647",
|
||||
"1",
|
||||
"-2147483648"
|
||||
),
|
||||
(multiply_base_case, r"\multiply", "5", "4", "20"),
|
||||
(multiply_base_case_with_by, r"\multiply", "5", "by 4", "20"),
|
||||
(multiply_pos_neg, r"\multiply", "-5", "4", "-20"),
|
||||
(multiply_neg_pos, r"\multiply", "5", "-4", "-20"),
|
||||
(multiply_neg_neg, r"\multiply", "-5", "-4", "20"),
|
||||
(
|
||||
multiply_wrapping_overflow,
|
||||
r"\multiplyWrapped",
|
||||
"100000",
|
||||
"100000",
|
||||
"1410065408"
|
||||
),
|
||||
(
|
||||
multiply_wrapping_base_case,
|
||||
r"\multiplyWrapped",
|
||||
"5",
|
||||
"4",
|
||||
"20"
|
||||
),
|
||||
(divide_base_case, r"\divide", "9", "4", "2"),
|
||||
(divide_with_by, r"\divide", "9", "by 4", "2"),
|
||||
(divide_pos_neg, r"\divide", "-9", "4", "-2"),
|
||||
(divide_neg_pos, r"\divide", "9", "-4", "-2"),
|
||||
(divide_neg_neg, r"\divide", "-9", "-4", "2"),
|
||||
(divide_exact, r"\divide", "100", "10", "10"),
|
||||
(advance_checked_base_case, r"\advanceChecked", "1", "2", "3"),
|
||||
(
|
||||
advance_checked_negative_summand,
|
||||
r"\advanceChecked",
|
||||
"10",
|
||||
"-2",
|
||||
"8"
|
||||
)
|
||||
];
|
||||
|
||||
arithmetic_tests![
|
||||
r"\dimen",
|
||||
(advance_dimen_1, r"\advance", "1pt", "2pt", "3.0pt"),
|
||||
(advance_dimen_2, r"\advance", "0.025pt", "0.5pt", "0.525pt"),
|
||||
(mul_dimen_1, r"\multiply", "10pt", "2", "20.0pt"),
|
||||
(div_dimen_1, r"\divide", "10pt", "2", "5.0pt"),
|
||||
];
|
||||
|
||||
arithmetic_tests![
|
||||
r"\skip",
|
||||
(
|
||||
advance_glue_1,
|
||||
r"\advance",
|
||||
"1pt plus 2pt minus 3pt",
|
||||
"60pt plus 50pt minus 40pt",
|
||||
"61.0pt plus 52.0pt minus 43.0pt"
|
||||
),
|
||||
// This next test IS correct. The skip is expanded before the addition
|
||||
// as part of scanning the optional plus/minus keywords...
|
||||
(advance_glue_2, r"\advance", "0.025pt", "0.5pt", "0.025pt"),
|
||||
(
|
||||
advance_glue_3,
|
||||
r"\advance",
|
||||
"1pt plus 2fill minus 3fil",
|
||||
"60pt plus 50pt minus 40filll",
|
||||
"61.0pt plus 2.0fill minus 40.0filll"
|
||||
),
|
||||
(
|
||||
mul_glue_1,
|
||||
r"\multiply",
|
||||
"1pt plus 2pt minus 1.25pt",
|
||||
"2",
|
||||
"2.0pt plus 4.0pt minus 2.5pt"
|
||||
),
|
||||
(
|
||||
div_glue_1,
|
||||
r"\divide",
|
||||
"10pt plus 20pt minus 3pt",
|
||||
"2",
|
||||
"5.0pt plus 10.0pt minus 1.5pt"
|
||||
),
|
||||
];
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(
|
||||
advance_x_by_x,
|
||||
r"\count 1 200 \advance \count 1 by \count 1 a\the\count 1",
|
||||
r"a400"
|
||||
),
|
||||
(
|
||||
global_advance,
|
||||
r"\count 1 5{\global\advance\count 1 8}\the\count 1",
|
||||
"13"
|
||||
),
|
||||
(
|
||||
local_advance,
|
||||
r"\count 1 5{\advance\count 1 8}\the\count 1",
|
||||
"5"
|
||||
),
|
||||
),
|
||||
recoverable_failure_tests(
|
||||
(
|
||||
advance_incorrect_keyword_1,
|
||||
r"\count 1 1\advance\count 1 fy 2 \the \count 1",
|
||||
"fy 2 1",
|
||||
),
|
||||
(
|
||||
advance_incorrect_keyword_2,
|
||||
r"\count 1 1\advance\count 1 be 2 \the \count 1",
|
||||
"be 2 1",
|
||||
),
|
||||
(
|
||||
advance_catcode_not_supported,
|
||||
r"\advance\catcode 100 by 2",
|
||||
"100 by 2",
|
||||
),
|
||||
(
|
||||
advance_checked_overflow,
|
||||
r"\count 1 2147483647 \advanceChecked\count 1 by 1",
|
||||
"",
|
||||
),
|
||||
(
|
||||
multiply_overflow,
|
||||
r"\count 1 100000 \multiply\count 1 by 100000 \the \count 1",
|
||||
"100000"
|
||||
),
|
||||
(
|
||||
divide_by_zero,
|
||||
r"\count 1 20 \divide\count 1 by 0 \the\count 1",
|
||||
"20"
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
//! The `\mathchardef` primitive.
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
/// Get the `\mathchardef` command.
|
||||
pub fn get_mathchardef<S: TexlangState>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(mathchardef_primitive_fn)
|
||||
}
|
||||
|
||||
fn mathchardef_primitive_fn<S: TexlangState>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
// TeX.2021.1224: unlike `\mathcode`, the value is a 15-bit integer so `"8000` is not valid.
|
||||
let (cmd_ref_or, _, c) = <(
|
||||
Option<token::CommandRef>,
|
||||
parse::OptionalEquals,
|
||||
parse::Uint<32768>,
|
||||
)>::parse(input)?;
|
||||
let c = types::MathCode(c.0.try_into().unwrap());
|
||||
if let Some(cmd_ref) = cmd_ref_or {
|
||||
input
|
||||
.commands_map_mut()
|
||||
.insert(cmd_ref, command::Command::MathCharacter(c), scope);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::the;
|
||||
use std::collections::HashMap;
|
||||
use texlang_testing::*;
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("mathchardef", get_mathchardef()),
|
||||
("the", the::get_the()),
|
||||
("i", TestingComponent::get_integer()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(
|
||||
basic_case,
|
||||
r"\mathchardef\Hello = `\+ \Hello",
|
||||
"MathCode(43)"
|
||||
),
|
||||
(
|
||||
basic_case_with_the,
|
||||
r"\mathchardef\Hello = 123 \the\Hello",
|
||||
"123"
|
||||
),
|
||||
(
|
||||
parsable_as_number,
|
||||
r"\mathchardef\Hello = 13 \i=\Hello x\the\i",
|
||||
"x13"
|
||||
),
|
||||
(
|
||||
parsable_as_number_negative,
|
||||
r"\mathchardef\Hello = 13 \i=-\Hello x\the\i",
|
||||
"x-13"
|
||||
),
|
||||
),
|
||||
serde_tests((basic_case, r"\mathchardef\Hello = `\+ ", r"\Hello"),),
|
||||
recoverable_failure_tests((
|
||||
value_too_large,
|
||||
r#"\mathchardef\Hello = "8000 \the\Hello"#,
|
||||
"0"
|
||||
),),
|
||||
];
|
||||
}
|
||||
Vendored
+539
@@ -0,0 +1,539 @@
|
||||
//! The `\global`, `\long` and `\outer` prefix commands
|
||||
//!
|
||||
//! ## Global
|
||||
//!
|
||||
//! The `\global` command makes the subsequent assignment global;
|
||||
//! i.e., not scoped to the current group.
|
||||
//! This command checks that the subsequent command is allowed to be prefixed
|
||||
//! by global and then sets a `\global` bit.
|
||||
//! All commands that can be prefixed then consume this bit by calling
|
||||
//! the hook [`TexlangState::variable_assignment_scope_hook`].
|
||||
//!
|
||||
//! In order for this to work correctly it is essential that *all* code
|
||||
//! paths within the command call the hook -
|
||||
//! even if the result is not used!
|
||||
//! For example `\gdef` always creates a macro in the global scope, but it still needs to
|
||||
//! call the hook.
|
||||
//! Otherwise the global bit will still be set, and the next assignment may be
|
||||
//! incorrectly performed in the global scope.
|
||||
//!
|
||||
//! This behavior should be verified with unit tests.
|
||||
//! This module provides
|
||||
//! an [`assert_global_is_false`](get_assert_global_is_false) execution command
|
||||
//! to make this easy - the command just raises an error if the global bit is still true.
|
||||
//!
|
||||
//! ## Outer and long
|
||||
//!
|
||||
//! The `\long` and `\outer` commands are designed to place restrictions on macros
|
||||
//! to avoid performance problems.
|
||||
//! These restrictions are described in the TeXBook.
|
||||
//! Texlang does not currently impose these restrictions.
|
||||
//! However, Texlang does enforce the rule that these prefix commands can only come before
|
||||
//! `\def`, `\gdef`, `\edef` and `\xdef`.
|
||||
//!
|
||||
|
||||
use crate::alias;
|
||||
use crate::def;
|
||||
use crate::math;
|
||||
use crate::registers;
|
||||
use std::collections::HashSet;
|
||||
use texcraft_stdext::collections::groupingmap;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
/// Component for the prefix commands.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
scope: groupingmap::Scope,
|
||||
global_defs_value: i32,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
tags: Tags,
|
||||
}
|
||||
|
||||
impl Default for Component {
|
||||
fn default() -> Self {
|
||||
Component {
|
||||
scope: groupingmap::Scope::Local,
|
||||
global_defs_value: 0,
|
||||
tags: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Tags {
|
||||
can_be_prefixed_with_any: HashSet<command::Tag>,
|
||||
can_be_prefixed_with_global: HashSet<command::Tag>,
|
||||
global_tag: command::Tag,
|
||||
long_tag: command::Tag,
|
||||
outer_tag: command::Tag,
|
||||
}
|
||||
|
||||
impl Default for Tags {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
can_be_prefixed_with_any: vec![def::def_tag()].into_iter().collect(),
|
||||
can_be_prefixed_with_global: vec![
|
||||
alias::let_tag(),
|
||||
math::variable_op_tag(),
|
||||
registers::countdef_tag(),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
global_tag: GLOBAL_TAG.get(),
|
||||
long_tag: LONG_TAG.get(),
|
||||
outer_tag: OUTER_TAG.get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Component {
|
||||
/// Register a command that can be prefixed with `\global`.
|
||||
pub fn register_globally_prefixable_command(&mut self, tag: command::Tag) {
|
||||
self.tags.can_be_prefixed_with_global.insert(tag);
|
||||
}
|
||||
|
||||
/// Read the value of the global flag and reset the flag to false.
|
||||
#[inline]
|
||||
fn read_and_reset_global(&mut self) -> groupingmap::Scope {
|
||||
match self.global_defs_value.cmp(&0) {
|
||||
std::cmp::Ordering::Less => groupingmap::Scope::Local,
|
||||
std::cmp::Ordering::Equal => {
|
||||
std::mem::replace(&mut self.scope, groupingmap::Scope::Local)
|
||||
}
|
||||
std::cmp::Ordering::Greater => groupingmap::Scope::Global,
|
||||
}
|
||||
}
|
||||
|
||||
fn set_scope(&mut self, scope: groupingmap::Scope) {
|
||||
self.scope = if self.global_defs_value == 0 {
|
||||
scope
|
||||
} else {
|
||||
// If either globaldefs override is enabled we skip setting the scope here so that
|
||||
// we can avoid setting it in the (hotter) variable assignment path.
|
||||
groupingmap::Scope::Local
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct Prefix {
|
||||
global: Option<token::Token>,
|
||||
long: Option<token::Token>,
|
||||
outer: Option<token::Token>,
|
||||
}
|
||||
|
||||
impl Prefix {
|
||||
fn get_one(&self) -> (token::Token, Kind) {
|
||||
if let Some(global_token) = self.global {
|
||||
(global_token, Kind::Global)
|
||||
} else if let Some(long_token) = self.long {
|
||||
(long_token, Kind::Long)
|
||||
} else if let Some(outer_token) = self.outer {
|
||||
(outer_token, Kind::Outer)
|
||||
} else {
|
||||
panic!("")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\globaldefs` command.
|
||||
pub fn get_globaldefs<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_variable(variable::Command::new_singleton(
|
||||
|s, _| &s.component().global_defs_value,
|
||||
|s, _| &mut s.component_mut().global_defs_value,
|
||||
))
|
||||
}
|
||||
|
||||
/// Get the `\global` command.
|
||||
pub fn get_global<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(global_primitive_fn).with_tag(GLOBAL_TAG.get())
|
||||
}
|
||||
|
||||
static GLOBAL_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
/// Implementation of the variable assignment scope hook.
|
||||
#[inline]
|
||||
pub fn variable_assignment_scope_hook<S: HasComponent<Component>>(
|
||||
state: &mut S,
|
||||
) -> groupingmap::Scope {
|
||||
state.component_mut().read_and_reset_global()
|
||||
}
|
||||
|
||||
/// Get the `\long` command.
|
||||
pub fn get_long<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(long_primitive_fn).with_tag(LONG_TAG.get())
|
||||
}
|
||||
|
||||
static LONG_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
/// Get the `\outer` command.
|
||||
pub fn get_outer<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(outer_primitive_fn).with_tag(OUTER_TAG.get())
|
||||
}
|
||||
|
||||
static OUTER_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
fn global_primitive_fn<S: HasComponent<Component>>(
|
||||
global_token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
process_prefixes(
|
||||
Prefix {
|
||||
global: Some(global_token),
|
||||
long: None,
|
||||
outer: None,
|
||||
},
|
||||
input,
|
||||
)
|
||||
}
|
||||
|
||||
fn long_primitive_fn<S: HasComponent<Component>>(
|
||||
long_token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
process_prefixes(
|
||||
Prefix {
|
||||
global: None,
|
||||
long: Some(long_token),
|
||||
outer: None,
|
||||
},
|
||||
input,
|
||||
)
|
||||
}
|
||||
|
||||
fn outer_primitive_fn<S: HasComponent<Component>>(
|
||||
outer_token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
process_prefixes(
|
||||
Prefix {
|
||||
global: None,
|
||||
long: None,
|
||||
outer: Some(outer_token),
|
||||
},
|
||||
input,
|
||||
)
|
||||
}
|
||||
|
||||
fn process_prefixes<S: HasComponent<Component>>(
|
||||
mut prefix: Prefix,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
complete_prefix(&mut prefix, input)?;
|
||||
let t = input.next_or_err(PrefixEndOfInputError {})?;
|
||||
input.back(t);
|
||||
match t.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
// First check it it's a command that can be prefixed by global only.
|
||||
if let Some(command::Command::Variable(_) | command::Command::Font(_)) =
|
||||
input.commands_map_mut().get_command(&command_ref)
|
||||
{
|
||||
assert_only_global_prefix(input, t, prefix)?;
|
||||
if prefix.global.is_some() {
|
||||
input
|
||||
.state_mut()
|
||||
.component_mut()
|
||||
.set_scope(groupingmap::Scope::Global);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// Next check if it's a command that can be prefixed by any of the prefix command.
|
||||
let component = input.state().component();
|
||||
let tag = input.commands_map().get_tag(&command_ref);
|
||||
if let Some(tag) = tag {
|
||||
if component.tags.can_be_prefixed_with_any.contains(&tag) {
|
||||
if prefix.global.is_some() {
|
||||
input
|
||||
.state_mut()
|
||||
.component_mut()
|
||||
.set_scope(groupingmap::Scope::Global);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// Next check if it's a command that can be prefixed by global only. In this case we check
|
||||
// that no other prefixes are present.
|
||||
if component.tags.can_be_prefixed_with_global.contains(&tag) {
|
||||
assert_only_global_prefix(input, t, prefix)?;
|
||||
if prefix.global.is_some() {
|
||||
input
|
||||
.state_mut()
|
||||
.component_mut()
|
||||
.set_scope(groupingmap::Scope::Global);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// If we make it to here, this is not a valid target for the prefix command.
|
||||
let (prefix_token, kind) = prefix.get_one();
|
||||
Err(input.fatal_error(Error {
|
||||
kind,
|
||||
got: t,
|
||||
prefix: prefix_token,
|
||||
prefix_kind: kind,
|
||||
}))
|
||||
}
|
||||
_ => {
|
||||
let (prefix_token, kind) = prefix.get_one();
|
||||
Err(input.fatal_error(Error {
|
||||
kind,
|
||||
got: t,
|
||||
prefix: prefix_token,
|
||||
prefix_kind: kind,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PrefixEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for PrefixEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"scanning a command to prefix".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
r"prefix commands (\global, \long, \outer) must be followed by a command to prefix"
|
||||
.into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn complete_prefix<S: HasComponent<Component>>(
|
||||
prefix: &mut Prefix,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
// BUG: spaces and \relax are allowed after prefixes per TeX source sections 1211 and 404.
|
||||
let found_prefix = match input.next()? {
|
||||
None => false,
|
||||
Some(t) => match t.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
let tag = input.commands_map().get_tag(&command_ref);
|
||||
if tag == Some(input.state().component().tags.global_tag) {
|
||||
prefix.global = Some(t);
|
||||
true
|
||||
} else if tag == Some(input.state().component().tags.outer_tag) {
|
||||
prefix.outer = Some(t);
|
||||
true
|
||||
} else if tag == Some(input.state().component().tags.long_tag) {
|
||||
prefix.long = Some(t);
|
||||
true
|
||||
} else {
|
||||
input.back(t);
|
||||
false
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
input.back(t);
|
||||
false
|
||||
}
|
||||
},
|
||||
};
|
||||
if !found_prefix {
|
||||
return Ok(());
|
||||
}
|
||||
complete_prefix(prefix, input)
|
||||
}
|
||||
|
||||
fn assert_only_global_prefix<S: TexlangState>(
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
token: token::Token,
|
||||
prefix: Prefix,
|
||||
) -> txl::Result<()> {
|
||||
if let Some(outer_token) = prefix.outer {
|
||||
Err(input.fatal_error(Error {
|
||||
kind: Kind::Outer,
|
||||
got: token,
|
||||
prefix: outer_token,
|
||||
prefix_kind: Kind::Outer,
|
||||
}))
|
||||
} else if let Some(long_token) = prefix.long {
|
||||
Err(input.fatal_error(Error {
|
||||
kind: Kind::Long,
|
||||
got: token,
|
||||
prefix: long_token,
|
||||
prefix_kind: Kind::Long,
|
||||
}))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Kind {
|
||||
Global,
|
||||
Long,
|
||||
Outer,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
fn control_sequence(&self) -> &'static str {
|
||||
match self {
|
||||
Kind::Global => r"\global",
|
||||
Kind::Long => r"\long",
|
||||
Kind::Outer => r"\outer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Error {
|
||||
kind: Kind,
|
||||
got: token::Token,
|
||||
prefix: token::Token,
|
||||
prefix_kind: Kind,
|
||||
}
|
||||
|
||||
impl error::TexError for Error {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::Token(self.got)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
match self.got.value() {
|
||||
token::Value::CommandRef(_) => {
|
||||
format![
|
||||
"this command cannot be prefixed by {}",
|
||||
self.prefix_kind.control_sequence()
|
||||
]
|
||||
}
|
||||
_ => format![
|
||||
"character tokens cannot be prefixed by {}",
|
||||
self.prefix_kind.control_sequence()
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn source_annotation(&self) -> String {
|
||||
format![
|
||||
"cannot by prefixed by {}",
|
||||
self.prefix_kind.control_sequence()
|
||||
]
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
let guidance = match self.kind {
|
||||
Kind::Global => {
|
||||
r"see the documentation for \global for the list of commands it can be used with"
|
||||
}
|
||||
Kind::Long => {
|
||||
r"the \long prefix can only be used with \def, \gdef, \edef and \xdef (or their aliases)"
|
||||
}
|
||||
Kind::Outer => {
|
||||
r"the \outer prefix can only be used with \def, \gdef, \edef and \xdef (or their aliases)"
|
||||
}
|
||||
};
|
||||
vec![
|
||||
guidance.into(),
|
||||
error::display::Note::SourceCodeTrace("the prefix appeared here:".into(), self.prefix),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Get an execution command that checks that the global flag is off.
|
||||
///
|
||||
/// This command is used for unit testing Texlang.
|
||||
/// It tests that functions that can be prefixed with `\global`
|
||||
/// are following the convention described in the module docs.
|
||||
/// To use it, create a test for the following TeX snippet:
|
||||
/// ```tex
|
||||
/// \global \command <input to command> \assertGlobalIsFalse
|
||||
/// ```
|
||||
pub fn get_assert_global_is_false<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
fn noop_execution_cmd_fn<S: HasComponent<Component>>(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
match input.state_mut().component_mut().read_and_reset_global() {
|
||||
groupingmap::Scope::Global => Err(input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"assertion failed: global is true",
|
||||
))),
|
||||
groupingmap::Scope::Local => Ok(()),
|
||||
}
|
||||
}
|
||||
command::BuiltIn::new_execution(noop_execution_cmd_fn)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::the;
|
||||
use std::collections::HashMap;
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
prefix: Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn variable_assignment_scope_hook(state: &mut Self) -> groupingmap::Scope {
|
||||
variable_assignment_scope_hook(state)
|
||||
}
|
||||
}
|
||||
impl the::TheCompatible for State {}
|
||||
|
||||
implement_has_component![State {
|
||||
prefix: Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("global", get_global()),
|
||||
("globaldefs", get_globaldefs()),
|
||||
("long", get_long()),
|
||||
("outer", get_outer()),
|
||||
("i", TestingComponent::get_integer()),
|
||||
("the", the::get_the()),
|
||||
("def", def::get_def()),
|
||||
("advance", math::get_advance()),
|
||||
(
|
||||
"noOpExpansion",
|
||||
command::BuiltIn::new_expansion(|_, _| Ok(())),
|
||||
),
|
||||
(
|
||||
"noOpExecution",
|
||||
command::BuiltIn::new_execution(|_, _| Ok(())),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(non_global, r"\i=5{\i=8}\the\i", "5"),
|
||||
(non_global_2, r"\i=5\i=6{\i=8}\the\i", "6"),
|
||||
(non_global_3, r"\i=5{\i=6{\i=8 \the\i}\the\i}\the\i", "865"),
|
||||
(global, r"\i=5{\global\i=8}\the\i", "8"),
|
||||
(global_squared, r"\i=5{\global\global\i=8}\the\i", "8"),
|
||||
(long, r"\long\def\A{Hello}\A", "Hello"),
|
||||
(outer, r"\outer\def\A{Hello}\A", "Hello"),
|
||||
(
|
||||
many_prefixes,
|
||||
r"\long\outer\global\long\global\outer\def\A{Hello}\A",
|
||||
"Hello"
|
||||
),
|
||||
(global_defs_1, r"\i=5{\globaldefs=1 \i=8}\the\i", "8"),
|
||||
(global_defs_2, r"\i=5{\globaldefs=-1\global\i=8}\the\i", "5"),
|
||||
),
|
||||
fatal_error_tests(
|
||||
(global_end_of_input, r"\global"),
|
||||
(global_with_character, r"\global a"),
|
||||
(global_with_undefined_command, r"\global \undefinedCommand"),
|
||||
(
|
||||
global_with_no_op_expansion_command,
|
||||
r"\global \noOpExpansion"
|
||||
),
|
||||
(
|
||||
global_with_no_op_execution_command,
|
||||
r"\global \noOpExecution"
|
||||
),
|
||||
(long_prefix_when_global_allowed, r"\long\advance\i 0"),
|
||||
(outer_prefix_when_global_allowed, r"\outer\advance\i 0"),
|
||||
),
|
||||
];
|
||||
}
|
||||
+475
@@ -0,0 +1,475 @@
|
||||
//! Register variables (`\count`, `\countdef`)
|
||||
|
||||
use texlang::parse::OptionalEquals;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::variable::SupportedType;
|
||||
use texlang::*;
|
||||
|
||||
pub const COUNT_DOC: &str = "Get or set an integer register";
|
||||
pub const COUNTDEF_DOC: &str = "Bind an integer register to a control sequence";
|
||||
|
||||
/// See [Component].
|
||||
pub struct DefaultMarker;
|
||||
|
||||
/// Component required to have registers of type `T`.
|
||||
///
|
||||
/// The `Marker` generic parameter exists so that a single state type
|
||||
/// can contain multiple copies of this component (`Component<MarkerOne>`,
|
||||
/// `Component<MarkerTwo>`, etc.) and implement that HasComponent pattern
|
||||
/// multiple times. This allows for multiple register commands of the same
|
||||
/// type to be included in the same VM.
|
||||
pub struct Component<T, const N: usize, Marker = DefaultMarker>(
|
||||
// We currently box the values because putting them directly on the stack causes the
|
||||
// message pack decoder to stack overflow. It's a pity that we have to pay a runtime
|
||||
// cost due to this, and it would be nice to fix the issue another way.
|
||||
Box<[T; N]>,
|
||||
std::marker::PhantomData<Marker>,
|
||||
);
|
||||
|
||||
impl<T, const N: usize, Marker> Component<T, N, Marker> {
|
||||
pub fn values(&self) -> &[T; N] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
static COUNTDEF_TAG: command::StaticTag = command::StaticTag::new();
|
||||
|
||||
pub fn countdef_tag() -> command::Tag {
|
||||
COUNTDEF_TAG.get()
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<T: serde::Serialize, const N: usize> serde::Serialize for Component<T, N> {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let v: Vec<&T> = self.0.iter().collect();
|
||||
v.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de, T: std::fmt::Debug + serde::Deserialize<'de>, const N: usize> serde::Deserialize<'de>
|
||||
for Component<T, N>
|
||||
{
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let v = Vec::<T>::deserialize(deserializer)?;
|
||||
let a: Box<[T; N]> = v.try_into().unwrap();
|
||||
Ok(Component(a, Default::default()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: std::fmt::Debug + Default, const N: usize, Marker> Default for Component<T, N, Marker> {
|
||||
fn default() -> Self {
|
||||
let mut v = vec![];
|
||||
for _ in 0..N {
|
||||
v.push(T::default())
|
||||
}
|
||||
Self(Box::new(v.try_into().unwrap()), Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\count` command.
|
||||
pub fn get_count<S: HasComponent<Component<i32, N>>, const N: usize>() -> command::BuiltIn<S> {
|
||||
new_registers_command()
|
||||
}
|
||||
|
||||
/// Get the `\dimen` command.
|
||||
pub fn get_dimen<S: HasComponent<Component<common::Scaled, N>>, const N: usize>(
|
||||
) -> command::BuiltIn<S> {
|
||||
new_registers_command()
|
||||
}
|
||||
|
||||
/// Get the `\skip` command.
|
||||
pub fn get_skip<S: HasComponent<Component<common::Glue, N>>, const N: usize>() -> command::BuiltIn<S>
|
||||
{
|
||||
new_registers_command()
|
||||
}
|
||||
|
||||
/// Get the `\toks` command.
|
||||
pub fn get_toks<S: HasComponent<Component<Vec<token::Token>, N>>, const N: usize>(
|
||||
) -> command::BuiltIn<S> {
|
||||
new_registers_command()
|
||||
}
|
||||
|
||||
/// Creates a new registers command that stores values in the component.
|
||||
pub fn new_registers_command<
|
||||
T: SupportedType,
|
||||
Marker: 'static,
|
||||
S: HasComponent<Component<T, N, Marker>>,
|
||||
const N: usize,
|
||||
>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_array(ref_fn, mut_fn, variable::IndexResolver::Dynamic(count_fn)).into()
|
||||
}
|
||||
|
||||
fn count_fn<T, Marker: 'static, S: HasComponent<Component<T, N, Marker>>, const N: usize>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<variable::Index> {
|
||||
let index = parse::Uint::<N>::parse(input)?;
|
||||
Ok(index.0.into())
|
||||
}
|
||||
|
||||
/// Get the `\countdef` command.
|
||||
pub fn get_countdef<S: HasComponent<Component<i32, N>>, const N: usize>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(countdef_fn).with_tag(countdef_tag())
|
||||
}
|
||||
|
||||
/// Get the `\toksdef` command.
|
||||
pub fn get_toksdef<S: HasComponent<Component<Vec<token::Token>, N>>, const N: usize>(
|
||||
) -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(countdef_fn).with_tag(countdef_tag())
|
||||
}
|
||||
|
||||
/// Get the `\muskipdef` command.
|
||||
pub fn get_muskipdef<S: HasComponent<Component<texlang::types::MuGlue, N>>, const N: usize>(
|
||||
) -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(countdef_fn).with_tag(countdef_tag())
|
||||
}
|
||||
|
||||
fn countdef_fn<T: variable::SupportedType, S: HasComponent<Component<T, N>>, const N: usize>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
|
||||
let (cmd_ref_or, _, index) =
|
||||
<(Option<token::CommandRef>, OptionalEquals, parse::Uint<N>)>::parse(input)?;
|
||||
if let Some(cmd_ref) = cmd_ref_or {
|
||||
input.commands_map_mut().insert_variable_command(
|
||||
cmd_ref,
|
||||
variable::Command::new_array(
|
||||
ref_fn,
|
||||
mut_fn,
|
||||
variable::IndexResolver::Static(index.0.into()),
|
||||
),
|
||||
scope,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ref_fn<T, Marker: 'static, S: HasComponent<Component<T, N, Marker>>, const N: usize>(
|
||||
state: &S,
|
||||
index: variable::Index,
|
||||
) -> &T {
|
||||
state.component().0.get(index.0).unwrap()
|
||||
}
|
||||
|
||||
fn mut_fn<T, Marker: 'static, S: HasComponent<Component<T, N, Marker>>, const N: usize>(
|
||||
state: &mut S,
|
||||
index: variable::Index,
|
||||
) -> &mut T {
|
||||
state.component_mut().0.get_mut(index.0).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use crate::{prefix, the};
|
||||
use texlang::vm::implement_has_component;
|
||||
use texlang_testing::*;
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
registers_i32: Component<i32, 256>,
|
||||
registers_dimen: Component<common::Scaled, 256>,
|
||||
registers_token_list: Component<Vec<token::Token>, 256>,
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}
|
||||
|
||||
impl TexlangState for State {
|
||||
fn em_width(&self) -> common::Scaled {
|
||||
self.registers_dimen.0[254]
|
||||
}
|
||||
fn ex_height(&self) -> common::Scaled {
|
||||
self.registers_dimen.0[255]
|
||||
}
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: error::TracedTexError,
|
||||
) -> Result<(), Box<dyn error::TexError>> {
|
||||
TestingComponent::recoverable_error_hook(self, recoverable_error)
|
||||
}
|
||||
fn variable_assignment_scope_hook(
|
||||
state: &mut Self,
|
||||
) -> texcraft_stdext::collections::groupingmap::Scope {
|
||||
prefix::variable_assignment_scope_hook(state)
|
||||
}
|
||||
}
|
||||
impl the::TheCompatible for State {}
|
||||
|
||||
implement_has_component![State{
|
||||
registers_i32: Component<i32, 256>,
|
||||
registers_dimen: Component<common::Scaled, 256>,
|
||||
registers_token_list: Component<Vec<token::Token>, 256>,
|
||||
prefix: prefix::Component,
|
||||
testing: TestingComponent,
|
||||
}];
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([
|
||||
("the", the::get_the()),
|
||||
("count", get_count()),
|
||||
("countdef", get_countdef()),
|
||||
("dimen", get_dimen()),
|
||||
("global", prefix::get_global()),
|
||||
("toks", get_toks()),
|
||||
("toksdef", get_toksdef()),
|
||||
])
|
||||
}
|
||||
|
||||
test_suite![
|
||||
expansion_equality_tests(
|
||||
(write_and_read_register, r"\count 23 4 \the\count 23", r"4"),
|
||||
(
|
||||
write_and_read_register_eq,
|
||||
r"\count 23 = 4 \the\count 23",
|
||||
r"4"
|
||||
),
|
||||
(
|
||||
negative_negative,
|
||||
r"\count 1=5000 \count 0=-1 \the \count -\count 0",
|
||||
r"5000"
|
||||
),
|
||||
(countdef_base_case, r"\countdef\A 23\A 4 \the\A", r"4"),
|
||||
(countdef_base_case_eq, r"\countdef\A = 23\A 4 \the\A", r"4"),
|
||||
(
|
||||
countdef_with_count,
|
||||
r"\countdef\A 23\A 4\count 1 0 \the\A",
|
||||
r"4"
|
||||
),
|
||||
(
|
||||
countdef_local,
|
||||
r"\count 1=1 \count 2=2 \countdef\A 1{\countdef\A 2}\the\A",
|
||||
r"1"
|
||||
),
|
||||
(
|
||||
countdef_global,
|
||||
r"\count 1=1 \count 2=2 \countdef\A 1{\global\countdef\A 2}\the\A",
|
||||
r"2"
|
||||
),
|
||||
(
|
||||
countdef_with_same_count,
|
||||
r"\countdef\A 23\A 4\count 23 5 \the\A",
|
||||
r"5"
|
||||
),
|
||||
(
|
||||
toks_basic,
|
||||
r"\toks 1 = {Hola, Mundo}\the \toks 1",
|
||||
r"Hola, Mundo"
|
||||
),
|
||||
(
|
||||
toksdef_basic,
|
||||
r"\toksdef\content 1 \toks 1 = {Hola, Mundo}\the \content",
|
||||
r"Hola, Mundo"
|
||||
),
|
||||
(
|
||||
toks_copy,
|
||||
r"\toks 1 = {Hola, Mundo}\toks 2 = \toks 1 \the \toks 2",
|
||||
r"Hola, Mundo"
|
||||
),
|
||||
(
|
||||
dimen_to_int_1,
|
||||
r"\dimen 1 = 40sp \count 1 = \dimen 1 \the \count 1",
|
||||
r"40",
|
||||
),
|
||||
(
|
||||
dimen_to_int_2,
|
||||
r"\dimen 1 = 40in \count 1 = \dimen 1 \the \count 1",
|
||||
r"189451468",
|
||||
),
|
||||
(
|
||||
int_to_dimen_1,
|
||||
r"\count 1 = 40 \dimen 1 = \count 1 pt \the \dimen 1",
|
||||
r"40.0pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_2,
|
||||
r"\count 1 = -40 \dimen 1 = \count 1 pt \the \dimen 1",
|
||||
r"-40.0pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_3,
|
||||
// <int><int> is interpreted as <int>*<int>sp, so the result here is 40*2sp
|
||||
r"\count 3 = 40 \count 5 = 2 \dimen 7 = \count 3 \count 5 \the \dimen 7",
|
||||
r"0.00122pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_4,
|
||||
r"\count 1 = 40 \dimen 2 = 5sp \dimen 1 = \count 1 \dimen 2 \the \dimen 1",
|
||||
r"0.00305pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_5,
|
||||
r"\count 1 = 0 \dimen 2 = 5sp \dimen 1 = \count 1 \dimen 2 \the \dimen 1",
|
||||
r"0.0pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_1,
|
||||
r"\dimen 1 = 10pt \dimen 2 = 5 \dimen 1 \the \dimen 2",
|
||||
r"50.0pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_2,
|
||||
r"\dimen 2 = 10pt \dimen 1 = - 1.5 \dimen 2 \the \dimen 1",
|
||||
r"-15.0pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_3,
|
||||
r"\dimen 2 = 5pt \dimen 1 = - 1.5 \dimen 2 \the \dimen 1",
|
||||
r"-7.5pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_4,
|
||||
r"\dimen 2 = -10pt \dimen 1 = 1.5 \dimen 2 \the \dimen 1",
|
||||
r"-15.0pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_5,
|
||||
r"\dimen 2 = -5pt \dimen 1 = 1.5 \dimen 2 \the \dimen 1",
|
||||
r"-7.5pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_6,
|
||||
r"\dimen 2 = -10pt \dimen 1 = - 1.5 \dimen 2 \the \dimen 1",
|
||||
r"15.0pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_7,
|
||||
r"\dimen 2 = -5pt \dimen 1 = - 1.5 \dimen 2 \the \dimen 1",
|
||||
r"7.5pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_1,
|
||||
r"\count 1 = 2 \dimen 1 = 3pt \dimen 2 = \count 1 \dimen 1 \the \dimen 2",
|
||||
r"6.0pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_2,
|
||||
r"\count 1 = -2 \dimen 1 = 3pt \dimen 2 = \count 1 \dimen 1 \the \dimen 2",
|
||||
r"-6.0pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_3,
|
||||
r"\count 1 = 2 \dimen 1 = -3pt \dimen 2 = \count 1 \dimen 1 \the \dimen 2",
|
||||
r"-6.0pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_4,
|
||||
r"\count 1 = 2 \dimen 1 = 3pt \dimen 2 = -\count 1 \dimen 1 \the \dimen 2",
|
||||
r"-6.0pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_5,
|
||||
r"\count 1 = 2 \dimen 1 = 0pt \dimen 2 = -\count 1 \dimen 1 \the \dimen 2",
|
||||
r"0.0pt",
|
||||
),
|
||||
(
|
||||
em_dimen,
|
||||
r"\dimen 254 = 2.25pt \dimen 0 = 4.5em \the \dimen 0",
|
||||
r"10.125pt",
|
||||
),
|
||||
(
|
||||
ex_dimen,
|
||||
r"\dimen 255 = 2.25pt \dimen 0 = 4.5ex \the \dimen 0",
|
||||
r"10.125pt",
|
||||
),
|
||||
),
|
||||
serde_tests(
|
||||
(serde_basic, r"\count 100 200 ", r"\the \count 100"),
|
||||
(serde_countdef, r"\countdef \A 100 \A = 200 ", r"\the \A"),
|
||||
(
|
||||
serde_group,
|
||||
r"\count 1 2 {\count 1 3 ",
|
||||
r"\the \count 1 } \the \count 1"
|
||||
),
|
||||
),
|
||||
recoverable_failure_tests(
|
||||
(
|
||||
write_register_index_too_big,
|
||||
r"\count 260 = 4 \the\count 0",
|
||||
"4"
|
||||
),
|
||||
(
|
||||
write_register_negative_index,
|
||||
r"\count -1 = 4 \the\count 0",
|
||||
"4"
|
||||
),
|
||||
(
|
||||
countdef_register_index_too_big,
|
||||
r"\countdef\A 260 \A= 4 \the\count 0",
|
||||
"4"
|
||||
),
|
||||
(countdef_missing_cs, r"\countdef 260 End", "End"),
|
||||
(
|
||||
dimen_to_dimen_too_big_1,
|
||||
r"\dimen 1 = 10000pt \dimen 2 = 2 \dimen 1 \the \dimen 2",
|
||||
r"16383.99998pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_too_big_2,
|
||||
r"\dimen 1 = -10000pt \dimen 2 = 2 \dimen 1 \the \dimen 2",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_too_big_3,
|
||||
r"\dimen 1 = 10000pt \dimen 2 = -2 \dimen 1 \the \dimen 2",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
(
|
||||
dimen_to_dimen_too_big_4,
|
||||
r"\dimen 1 = -10000pt \dimen 2 = -2 \dimen 1 \the \dimen 2",
|
||||
r"16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_too_big_1,
|
||||
r"\count 1 = 400 \dimen 1 = \count 1 in \the \dimen 1",
|
||||
r"16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_too_big_2,
|
||||
r"\count 1 = -400 \dimen 1 = \count 1 in \the \dimen 1",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_too_big_3,
|
||||
r"\count 1 = 400 \dimen 1 = - \count 1 in \the \dimen 1",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_to_dimen_too_big_4,
|
||||
r"\count 1 = -400 \dimen 1 = - \count 1 in \the \dimen 1",
|
||||
r"16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_too_big_1,
|
||||
r"\count 1 = 2 \dimen 1 = 10000pt \dimen 2 = \count 1 \dimen 1 \the \dimen 2",
|
||||
r"16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_too_big_2,
|
||||
r"\count 1 = 2 \dimen 1 = 10000pt \dimen 2 = -\count 1 \dimen 1 \the \dimen 2",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_too_big_3,
|
||||
r"\count 1 = -2 \dimen 1 = 10000pt \dimen 2 = \count 1 \dimen 1 \the \dimen 2",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
(
|
||||
int_dimen_to_dimen_too_big_4,
|
||||
r"\count 1 = 2 \dimen 1 = -10000pt \dimen 2 = \count 1 \dimen 1 \the \dimen 2",
|
||||
r"-16383.99998pt",
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+175
@@ -0,0 +1,175 @@
|
||||
//! Support for running TeX REPLs
|
||||
|
||||
#[cfg(feature = "repl")]
|
||||
use super::script;
|
||||
#[cfg(feature = "repl")]
|
||||
use std::sync::Arc;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
use texlang_common as common;
|
||||
|
||||
pub struct RunOptions<'a> {
|
||||
pub prompt: &'a str,
|
||||
pub help: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
help: String,
|
||||
quit_requested: bool,
|
||||
}
|
||||
|
||||
/// Start a REPL session using the provided VM.
|
||||
#[cfg(feature = "repl")]
|
||||
pub fn start<S: HasComponent<script::Component> + HasComponent<Component>>(
|
||||
vm: &mut vm::VM<S>,
|
||||
opts: RunOptions,
|
||||
) {
|
||||
use linefeed::{Interface, ReadResult};
|
||||
|
||||
let c = HasComponent::<Component>::component_mut(&mut vm.state);
|
||||
c.help = opts.help.into();
|
||||
c.quit_requested = false;
|
||||
|
||||
let reader = Interface::new("").unwrap();
|
||||
reader.set_prompt(opts.prompt).unwrap();
|
||||
script::set_io_writer(vm, std::io::stdout());
|
||||
|
||||
let mut num_commands: Option<usize> = None;
|
||||
loop {
|
||||
// We detect new commands (via \def say) by seeing if the number of commands
|
||||
// have changed. This is incorrect though; in the following case, the
|
||||
// commands will not be updated:
|
||||
//
|
||||
// TeX> {
|
||||
// TeX> \def \Apple{A}
|
||||
// TeX> } \def \Orange{B}
|
||||
//
|
||||
// Instead we need to iterate over all commands in the map and
|
||||
// check the diff.
|
||||
if Some(vm.commands_map.len()) != num_commands {
|
||||
let mut names: Vec<String> = vm
|
||||
.get_commands_as_map_slow()
|
||||
.into_keys()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
num_commands = Some(names.len());
|
||||
let a = Arc::new(ControlSequenceCompleter { names });
|
||||
reader.set_completer(a);
|
||||
}
|
||||
|
||||
let ReadResult::Input(input) = reader.read_line().unwrap() else {
|
||||
break;
|
||||
};
|
||||
reader.add_history(input.clone());
|
||||
|
||||
vm.clear_sources();
|
||||
vm.push_source("".to_string(), input).unwrap();
|
||||
match script::run(vm) {
|
||||
Ok(()) => (),
|
||||
Err(err) => {
|
||||
println!("{err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if HasComponent::<Component>::component(&vm.state).quit_requested {
|
||||
return;
|
||||
}
|
||||
// TODO: better new line handling in the REPL
|
||||
println!();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "repl")]
|
||||
struct ControlSequenceCompleter {
|
||||
names: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "repl")]
|
||||
impl<Term: linefeed::Terminal> linefeed::Completer<Term> for ControlSequenceCompleter {
|
||||
fn complete(
|
||||
&self,
|
||||
word: &str,
|
||||
prompter: &linefeed::Prompter<Term>,
|
||||
start: usize,
|
||||
_end: usize,
|
||||
) -> Option<Vec<linefeed::Completion>> {
|
||||
if !prompter.buffer()[..start].ends_with('\\') {
|
||||
return None;
|
||||
}
|
||||
let mut completions = Vec::new();
|
||||
for name in &self.names {
|
||||
if name.starts_with(word) {
|
||||
completions.push(linefeed::Completion {
|
||||
completion: name.to_string(),
|
||||
display: Some(format!["\\{name}"]),
|
||||
suffix: linefeed::Suffix::Default,
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(completions)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\exit` command.
|
||||
///
|
||||
/// This exits the REPL.
|
||||
pub fn get_exit<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(
|
||||
|_: token::Token, input: &mut vm::ExecutionInput<S>| -> txl::Result<()> {
|
||||
HasComponent::<Component>::component_mut(input.state_mut()).quit_requested = true;
|
||||
Err(input.shutdown())
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the `\help` command.
|
||||
///
|
||||
/// This prints help text for the REPL.
|
||||
pub fn get_help<S: HasComponent<Component> + common::HasLogging>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(
|
||||
|token: token::Token, input: &mut vm::ExecutionInput<S>| -> txl::Result<()> {
|
||||
let help = HasComponent::<Component>::component(input.state())
|
||||
.help
|
||||
.clone();
|
||||
match writeln![input.state().terminal_out().borrow_mut(), "{help}"] {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
format!["failed to write help text: {err}"],
|
||||
))),
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the `\doc` command.
|
||||
///
|
||||
/// This prints the documentation for a TeX command.
|
||||
pub fn get_doc<S: TexlangState + common::HasLogging>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(
|
||||
|token: token::Token, input: &mut vm::ExecutionInput<S>| -> txl::Result<()> {
|
||||
let Some(cmd_ref) = Option::<token::CommandRef>::parse(input)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let name = cmd_ref.to_string(input.vm().cs_name_interner());
|
||||
let doc = match input.commands_map().get_command_slow(&cmd_ref) {
|
||||
None => format!["Unknown command {name}"],
|
||||
Some(cmd) => match cmd.doc() {
|
||||
None => format!["No documentation available for the {name} command"],
|
||||
Some(doc) => format!["{name} {doc}"],
|
||||
},
|
||||
};
|
||||
match writeln![input.state().terminal_out().borrow_mut(), "{doc}"] {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(input.fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
format!["failed to write doc text: {err}"],
|
||||
))),
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
Vendored
+197
@@ -0,0 +1,197 @@
|
||||
//! Support for running TeX scripts.
|
||||
//!
|
||||
//! This module enables using TeX as a scripting language.
|
||||
//! TeX files are processed using the usual TeX semantics, but instead
|
||||
//! of typesetting the result and outputting it to PDF (say), the output is written to an IO writer.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::rc::Rc;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
pub struct Component {
|
||||
io_writer: Rc<RefCell<dyn std::io::Write>>,
|
||||
writer: token::Writer,
|
||||
}
|
||||
|
||||
impl Default for Component {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
io_writer: Rc::new(RefCell::new(std::io::sink())),
|
||||
writer: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl serde::Serialize for Component {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
().serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de> serde::Deserialize<'de> for Component {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
<()>::deserialize(deserializer)?;
|
||||
Ok(Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Component {
|
||||
fn write_token<S: HasComponent<Self>>(input: &mut vm::ExecutionInput<S>, token: token::Token) {
|
||||
let vm::Parts {
|
||||
state,
|
||||
cs_name_interner,
|
||||
..
|
||||
} = input.vm_parts();
|
||||
let c = state.component_mut();
|
||||
c.writer
|
||||
.write(
|
||||
c.io_writer.borrow_mut().deref_mut(),
|
||||
cs_name_interner,
|
||||
token.value(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\newline` command.
|
||||
///
|
||||
/// This adds a newline to the output.
|
||||
pub fn get_newline<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(newline_primitive_fn)
|
||||
}
|
||||
|
||||
fn newline_primitive_fn<S: HasComponent<Component>>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
input.state_mut().component_mut().writer.add_newline();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the `\par` command.
|
||||
///
|
||||
/// The `\par` command adds two newlines to the output.
|
||||
/// Consecutive `\par` commands are treated as one.
|
||||
pub fn get_par<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(par_primitive_fn)
|
||||
}
|
||||
|
||||
fn par_primitive_fn<S: HasComponent<Component>>(
|
||||
_: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
input.state_mut().component_mut().writer.start_paragraph();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the Texlang interpreter for the provided VM and return the result as a string.
|
||||
pub fn run_to_string<S: HasComponent<Component>>(
|
||||
vm: &mut vm::VM<S>,
|
||||
) -> Result<String, Box<error::TracedTexError>> {
|
||||
let buffer = Rc::new(RefCell::new(Vec::<u8>::new()));
|
||||
vm.state.component_mut().io_writer = buffer.clone();
|
||||
run(vm)?;
|
||||
let result: String = std::str::from_utf8(buffer.borrow().deref()).unwrap().into();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Run the Texlang interpreter for the provided VM and return the result as list of tokens.
|
||||
pub fn run<S: HasComponent<Component>>(
|
||||
vm: &mut vm::VM<S>,
|
||||
) -> Result<(), Box<error::TracedTexError>> {
|
||||
vm.run::<Handlers>()
|
||||
}
|
||||
|
||||
// Set the IO writer that the script component writes to.
|
||||
pub fn set_io_writer<S: HasComponent<Component>, I: std::io::Write + 'static>(
|
||||
vm: &mut vm::VM<S>,
|
||||
writer: I,
|
||||
) {
|
||||
vm.state.component_mut().io_writer = Rc::new(RefCell::new(writer))
|
||||
}
|
||||
|
||||
struct Handlers;
|
||||
|
||||
impl<S: HasComponent<Component>> vm::Handlers<S> for Handlers {
|
||||
fn character_handler(
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
token: token::Token,
|
||||
_: char,
|
||||
) -> txl::Result<()> {
|
||||
// TODO: it's really not great that the character is ignored.
|
||||
Component::write_token(input, token);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unexpanded_expansion_command(
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
token: token::Token,
|
||||
) -> txl::Result<()> {
|
||||
Component::write_token(input, token);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
script: Component,
|
||||
}
|
||||
|
||||
impl vm::TexlangState for State {}
|
||||
|
||||
implement_has_component![State { script: Component }];
|
||||
|
||||
fn run_script_test(input: &str, want: &str) {
|
||||
let built_ins = HashMap::from([("par", get_par()), ("newline", get_newline())]);
|
||||
let mut vm = vm::VM::<State>::new_with_built_in_commands(built_ins);
|
||||
vm.push_source("testing.tex", input).unwrap();
|
||||
let got = run_to_string(&mut vm).unwrap();
|
||||
let want = want.to_string();
|
||||
|
||||
if got != want {
|
||||
println!("Output is different:");
|
||||
println!("------[got]-------");
|
||||
println!("{}", got);
|
||||
println!("------[want]------");
|
||||
println!("{}", want);
|
||||
println!("-----------------");
|
||||
panic!("run_script test failed");
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! script_tests {
|
||||
( $( ($name: ident, $input: expr, $want: expr) ),* $(,)? ) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
run_script_test($input, $want);
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
script_tests![
|
||||
(char_newline_1, "H\nW", "H W"),
|
||||
(newline_1, "H\\newline W", "H\nW"),
|
||||
(newline_2, "H\\newline \\newline W", "H\n\nW"),
|
||||
(newline_3, "H\\newline \\newline \\newline W", "H\n\n\nW"),
|
||||
(par_1, "H\n\n\nW", "H\n\nW"),
|
||||
(par_2, "H\n\n\n\n\nW", "H\n\nW"),
|
||||
];
|
||||
}
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
//! Primitive that pauses execution for a duration of time
|
||||
|
||||
use std::thread;
|
||||
use std::time;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
use texlang_common as common;
|
||||
|
||||
pub const SLEEP_DOC: &str = "Sleep for a number of milliseconds";
|
||||
|
||||
/// Get the `\sleep` expansion primitive.
|
||||
pub fn get_sleep<S: TexlangState + common::HasLogging>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_execution(
|
||||
|_: token::Token, input: &mut vm::ExecutionInput<S>| -> txl::Result<()> {
|
||||
let milliseconds = parse::Uint::<{ parse::Uint::MAX }>::parse(input)?.0;
|
||||
writeln![
|
||||
input.state().terminal_out().borrow_mut(),
|
||||
"\\sleep: sleeping for {milliseconds}ms",
|
||||
]
|
||||
.unwrap();
|
||||
thread::sleep(time::Duration::from_millis(milliseconds as u64));
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
//! The Texcraft primitive, which returns the word Texcraft as eight separate letter tokens
|
||||
//!
|
||||
//! This primitive is essentially equivalent to `\def\Texcraft{Texcraft}`.
|
||||
//! It was implemented to serve as a simple example of a custom expansion primitive.
|
||||
|
||||
use texlang::prelude as txl;
|
||||
use texlang::*;
|
||||
|
||||
/// Get the `\texcraft` expansion primitive.
|
||||
pub fn get_texcraft<S>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(texcraft_primitive_fn)
|
||||
}
|
||||
|
||||
pub fn texcraft_primitive_fn<S>(
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let expansions = input.expansions_mut();
|
||||
for c in "Texcraft".chars().rev() {
|
||||
expansions.push(token::Token::new_letter(c, token.trace_key()))
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use texlang_testing::State;
|
||||
|
||||
fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
|
||||
HashMap::from([("texcraft", get_texcraft())])
|
||||
}
|
||||
|
||||
texlang_testing::test_suite![expansion_equality_tests((
|
||||
texcraft,
|
||||
r"\texcraft",
|
||||
r"Texcraft"
|
||||
),),];
|
||||
}
|
||||
Vendored
+173
@@ -0,0 +1,173 @@
|
||||
//! The `\the` primitive
|
||||
|
||||
use common::font;
|
||||
use std::char;
|
||||
use texlang::prelude as txl;
|
||||
use texlang::traits::*;
|
||||
use texlang::*;
|
||||
|
||||
pub const THE_DOC: &str = "Output text describing some inputted tokens";
|
||||
|
||||
/// Trait satisfied by states that can be used with the control sequence `\the`
|
||||
pub trait TheCompatible: TexlangState {
|
||||
fn get_command_ref_for_font(&self, font: font::Id) -> Option<token::CommandRef> {
|
||||
_ = font;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\the` expansion primitive.
|
||||
pub fn get_the<S: TheCompatible>() -> command::BuiltIn<S> {
|
||||
command::BuiltIn::new_expansion(the_primitive_fn)
|
||||
}
|
||||
|
||||
fn the_primitive_fn<S: TheCompatible>(
|
||||
the_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let token = input.next_or_err(EndOfInputError {})?;
|
||||
// TeX.2021.465
|
||||
match &token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match input.commands_map().get_command(command_ref) {
|
||||
Some(command::Command::Variable(cmd)) => {
|
||||
let variable = cmd.clone().resolve(token, input.as_mut())?;
|
||||
let (state, expansions) = input.state_and_expansions_mut();
|
||||
match variable.value(state) {
|
||||
variable::ValueRef::Int(i) => {
|
||||
write(expansions, the_token, *i);
|
||||
}
|
||||
variable::ValueRef::SmallInt(i) => {
|
||||
write(expansions, the_token, *i);
|
||||
}
|
||||
variable::ValueRef::CatCode(i) => {
|
||||
write(expansions, the_token, (*i as u8) as i32);
|
||||
}
|
||||
variable::ValueRef::MathCode(i) => write(expansions, the_token, i.0 as i32),
|
||||
variable::ValueRef::Dimen(d) => {
|
||||
write(expansions, the_token, *d);
|
||||
}
|
||||
variable::ValueRef::Glue(g) => {
|
||||
write(expansions, the_token, *g);
|
||||
}
|
||||
variable::ValueRef::MuGlue(g) => {
|
||||
write(expansions, the_token, *g);
|
||||
}
|
||||
variable::ValueRef::Font(font) => {
|
||||
let font = *font;
|
||||
let command_ref = input.state().get_command_ref_for_font(font).unwrap();
|
||||
let font_token =
|
||||
token::Token::new_command_ref(command_ref, the_token.trace_key());
|
||||
input.back(font_token);
|
||||
}
|
||||
variable::ValueRef::TokenList(t) => {
|
||||
expansions.extend(t.iter().rev());
|
||||
}
|
||||
};
|
||||
}
|
||||
Some(command::Command::Character(c)) => {
|
||||
let i = *c as i32;
|
||||
write(input.expansions_mut(), the_token, i);
|
||||
}
|
||||
Some(command::Command::MathCharacter(c)) => {
|
||||
let i = c.0 as i32;
|
||||
write(input.expansions_mut(), the_token, i);
|
||||
}
|
||||
Some(command::Command::UnicodeMathCharacter {
|
||||
class,
|
||||
family,
|
||||
character,
|
||||
}) => {
|
||||
let packed = (u32::from(*family) << 24)
|
||||
| (u32::from(*class) << 21)
|
||||
| (*character as u32);
|
||||
write(input.expansions_mut(), the_token, packed as i32);
|
||||
}
|
||||
Some(command::Command::Font(font)) => {
|
||||
// \the is a no-op for font commands?
|
||||
// It may return the frozen control sequence and this would
|
||||
// be visible e.g. in macro matching and equality conditions
|
||||
// in general.
|
||||
font_to_tokens(the_token, input, *font);
|
||||
}
|
||||
Some(command::Command::Execution(_, Some(tag))) => {
|
||||
if input.state().is_current_font_command(*tag) {
|
||||
font_to_tokens(the_token, input, input.vm().current_font());
|
||||
} else {
|
||||
todo!("should return an error")
|
||||
}
|
||||
}
|
||||
None
|
||||
| Some(
|
||||
command::Command::Expansion(..)
|
||||
| command::Command::Macro(..)
|
||||
| command::Command::Execution(..)
|
||||
| command::Command::CharacterTokenAlias(..),
|
||||
) => {
|
||||
todo!("should return an error")
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => todo!("should return an error"),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn font_to_tokens<S: TexlangState + TheCompatible>(
|
||||
the_token: token::Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
font: font::Id,
|
||||
) {
|
||||
let command_ref = input.state().get_command_ref_for_font(font).unwrap();
|
||||
let font_token = token::Token::new_command_ref(command_ref, the_token.trace_key());
|
||||
input.back(font_token);
|
||||
}
|
||||
|
||||
/// Implementation of [`std::fmt::Write`] that writes to a token buffer.
|
||||
///
|
||||
/// As well as being sort of elegant (?), converting values to tokens this way
|
||||
/// avoids all allocations outside of the buffer.
|
||||
struct TokenWrite<'a>(&'a mut Vec<token::Token>, token::trace::Key);
|
||||
|
||||
impl<'a> std::fmt::Write for TokenWrite<'a> {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
for c in s.chars() {
|
||||
self.write_char(c)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn write_char(&mut self, c: char) -> std::fmt::Result {
|
||||
let token = if c == ' ' {
|
||||
token::Token::new_space(c, self.1)
|
||||
} else if c.is_ascii_alphabetic() {
|
||||
token::Token::new_letter(c, self.1)
|
||||
} else {
|
||||
token::Token::new_other(c, self.1)
|
||||
};
|
||||
self.0.push(token);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn write<D: std::fmt::Display>(buffer: &mut Vec<token::Token>, the_token: token::Token, value: D) {
|
||||
let start = buffer.len();
|
||||
use std::fmt::Write;
|
||||
let mut t = TokenWrite(buffer, the_token.trace_key());
|
||||
write!(t, "{value}").expect("the token writer cannot error");
|
||||
buffer[start..].reverse();
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct EndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for EndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
r"determining the argument to \the".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
impl TheCompatible for texlang_testing::State {}
|
||||
}
|
||||
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
//! Time commands (`\year`, `\month`, etc.)
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
use chrono::prelude::*;
|
||||
use texlang::{command, variable, vm::HasComponent};
|
||||
|
||||
/// Component for storing state related to the time commands.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
minutes_since_midnight: i32,
|
||||
day: i32,
|
||||
month: i32,
|
||||
year: i32,
|
||||
}
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
impl Default for Component {
|
||||
fn default() -> Self {
|
||||
let dt: DateTime<Local> = Local::now();
|
||||
Self {
|
||||
minutes_since_midnight: 60 * (dt.time().hour() as i32) + (dt.time().minute() as i32),
|
||||
day: dt.day() as i32,
|
||||
month: dt.month() as i32,
|
||||
year: dt.year(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "time"))]
|
||||
impl Default for Component {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
minutes_since_midnight: 0,
|
||||
day: 0,
|
||||
month: 0,
|
||||
year: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Component {
|
||||
/// Create a new component with the variable initialized with the provided values.
|
||||
///
|
||||
/// This is useful in situations where the DateTime library can't be used; e.g., when
|
||||
/// Texcraft is compiled to WebAssembly and running in the browser.
|
||||
pub fn new_with_values(
|
||||
minutes_since_midnight: i32,
|
||||
day: i32,
|
||||
month: i32,
|
||||
year: i32,
|
||||
) -> Component {
|
||||
Component {
|
||||
minutes_since_midnight,
|
||||
day,
|
||||
month,
|
||||
year,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the `\time` command.
|
||||
pub fn get_time<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _: variable::Index| -> &i32 { &state.component().minutes_since_midnight },
|
||||
|state: &mut S, _: variable::Index| -> &mut i32 {
|
||||
&mut state.component_mut().minutes_since_midnight
|
||||
},
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Get the `\day` command.
|
||||
pub fn get_day<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _: variable::Index| -> &i32 { &state.component().day },
|
||||
|state: &mut S, _: variable::Index| -> &mut i32 { &mut state.component_mut().day },
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Get the `\month` command.
|
||||
pub fn get_month<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _: variable::Index| -> &i32 { &state.component().month },
|
||||
|state: &mut S, _: variable::Index| -> &mut i32 { &mut state.component_mut().month },
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Get the `\year` command.
|
||||
pub fn get_year<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _: variable::Index| -> &i32 { &state.component().year },
|
||||
|state: &mut S, _: variable::Index| -> &mut i32 { &mut state.component_mut().year },
|
||||
)
|
||||
.into()
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
//! TeX macro debugging
|
||||
|
||||
use texcraft_stdext::color::Colorize;
|
||||
use texlang::{command, texmacro, token::write_tokens, traits::*, variable, vm};
|
||||
|
||||
/// Component for storing state related to macro tracing.
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Component {
|
||||
tracing_macros: i32,
|
||||
}
|
||||
|
||||
/// Get the `\tracingmacros` command.
|
||||
pub fn get_tracingmacros<S: HasComponent<Component>>() -> command::BuiltIn<S> {
|
||||
variable::Command::new_singleton(
|
||||
|state: &S, _: variable::Index| -> &i32 { &state.component().tracing_macros },
|
||||
|state: &mut S, _: variable::Index| -> &mut i32 {
|
||||
&mut state.component_mut().tracing_macros
|
||||
},
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn hook<S: HasComponent<Component>>(
|
||||
token: texlang::token::Token,
|
||||
input: &vm::ExpansionInput<S>,
|
||||
tex_macro: &texlang::texmacro::Macro,
|
||||
arguments: &[&[texlang::token::Token]],
|
||||
reversed_expansion: &[texlang::token::Token],
|
||||
) {
|
||||
if input.state().component().tracing_macros <= 0 {
|
||||
return;
|
||||
}
|
||||
let trace = input.vm().trace(token);
|
||||
println!(
|
||||
"{}{}",
|
||||
"Macro expansion trace of ".bold(),
|
||||
trace.value.bold()
|
||||
);
|
||||
// TODO
|
||||
// println!("{trace}");
|
||||
let interner = input.vm().cs_name_interner();
|
||||
println![" ┌──",];
|
||||
print![" arguments "];
|
||||
if arguments.is_empty() {
|
||||
print!["│ (none)\n "];
|
||||
}
|
||||
for (i, argument) in arguments.iter().enumerate() {
|
||||
print![
|
||||
"│ {}{}={} \n ",
|
||||
"#".bright_yellow(),
|
||||
(i + 1).to_string().bright_yellow(),
|
||||
write_tokens(*argument, interner).bright_yellow()
|
||||
]
|
||||
}
|
||||
|
||||
print!["├──\n replacement definition │ ",];
|
||||
for replacement in tex_macro.replacements() {
|
||||
match replacement {
|
||||
texmacro::Replacement::Tokens(tokens) => {
|
||||
print!("{}", write_tokens(tokens.iter().rev(), interner))
|
||||
}
|
||||
texmacro::Replacement::Parameter(i) => {
|
||||
print!(
|
||||
"{}{}",
|
||||
"#".bright_yellow(),
|
||||
(i + 1).to_string().bright_yellow(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println![
|
||||
"\n ├──\n expansion │ {}",
|
||||
write_tokens(reversed_expansion.iter().rev(), interner)
|
||||
];
|
||||
println![" └──"];
|
||||
}
|
||||
Reference in new issue
Block a user