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
+590
@@ -0,0 +1,590 @@
|
||||
//! Map type
|
||||
use super::*;
|
||||
use std::borrow::Cow;
|
||||
use std::cell::{Ref, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::rc::Rc;
|
||||
use texcraft_stdext::collections::groupingmap;
|
||||
|
||||
/// Sparse command storage with TeX local and global assignment semantics.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct ScopedVec<V> {
|
||||
values: Vec<Option<V>>,
|
||||
groups: Vec<HashMap<usize, Option<V>>>,
|
||||
}
|
||||
|
||||
impl<V> Default for ScopedVec<V> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
values: Vec::new(),
|
||||
groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> ScopedVec<V> {
|
||||
fn get(&self, key: &usize) -> Option<&V> {
|
||||
self.values.get(*key).and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
fn iter(&self) -> impl Iterator<Item = (usize, &V)> {
|
||||
self.values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(key, value)| value.as_ref().map(|value| (key, value)))
|
||||
}
|
||||
|
||||
fn backing_container(&self) -> &[Option<V>] {
|
||||
&self.values
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.iter().count()
|
||||
}
|
||||
|
||||
fn insert(&mut self, key: usize, value: V, scope: groupingmap::Scope)
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
match scope {
|
||||
groupingmap::Scope::Global => {
|
||||
for group in &mut self.groups {
|
||||
group.remove(&key);
|
||||
}
|
||||
}
|
||||
groupingmap::Scope::Local => {
|
||||
if let Some(group) = self.groups.last_mut() {
|
||||
group
|
||||
.entry(key)
|
||||
.or_insert_with(|| self.values.get(key).and_then(Option::as_ref).cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.set_current(key, Some(value));
|
||||
}
|
||||
|
||||
fn begin_group(&mut self) {
|
||||
self.groups.push(HashMap::new());
|
||||
}
|
||||
|
||||
fn end_group(&mut self) -> Result<(), groupingmap::NoGroupToEndError> {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return Err(groupingmap::NoGroupToEndError);
|
||||
};
|
||||
for (key, value) in group {
|
||||
self.set_current(key, value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_values<'a, U>(&'a self, mut f: impl FnMut(&'a V) -> U) -> ScopedVec<U> {
|
||||
ScopedVec {
|
||||
values: self
|
||||
.values
|
||||
.iter()
|
||||
.map(|value| value.as_ref().map(&mut f))
|
||||
.collect(),
|
||||
groups: self
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
group
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, value.as_ref().map(&mut f)))
|
||||
.collect()
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_current(&mut self, key: usize, value: Option<V>) {
|
||||
if key >= self.values.len() {
|
||||
self.values.resize_with(key + 1, || None);
|
||||
}
|
||||
self.values[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> FromIterator<(usize, V)> for ScopedVec<V> {
|
||||
fn from_iter<T: IntoIterator<Item = (usize, V)>>(iter: T) -> Self {
|
||||
let mut result = Self::default();
|
||||
for (key, value) in iter {
|
||||
result.set_current(key, Some(value));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Sparse hash storage with the same TeX assignment semantics as `ScopedVec`.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct ScopedHashMap<V> {
|
||||
values: HashMap<char, V>,
|
||||
groups: Vec<HashMap<char, Option<V>>>,
|
||||
}
|
||||
|
||||
impl<V> Default for ScopedHashMap<V> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
values: HashMap::new(),
|
||||
groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> ScopedHashMap<V> {
|
||||
fn get(&self, key: &char) -> Option<&V> {
|
||||
self.values.get(key)
|
||||
}
|
||||
|
||||
fn insert(&mut self, key: char, value: V, scope: groupingmap::Scope)
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
match scope {
|
||||
groupingmap::Scope::Global => {
|
||||
for group in &mut self.groups {
|
||||
group.remove(&key);
|
||||
}
|
||||
}
|
||||
groupingmap::Scope::Local => {
|
||||
if let Some(group) = self.groups.last_mut() {
|
||||
group
|
||||
.entry(key)
|
||||
.or_insert_with(|| self.values.get(&key).cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.values.insert(key, value);
|
||||
}
|
||||
|
||||
fn begin_group(&mut self) {
|
||||
self.groups.push(HashMap::new());
|
||||
}
|
||||
|
||||
fn end_group(&mut self) -> Result<(), groupingmap::NoGroupToEndError> {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return Err(groupingmap::NoGroupToEndError);
|
||||
};
|
||||
for (key, value) in group {
|
||||
match value {
|
||||
Some(value) => {
|
||||
self.values.insert(key, value);
|
||||
}
|
||||
None => {
|
||||
self.values.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_values<'a, U>(&'a self, mut f: impl FnMut(&'a V) -> U) -> ScopedHashMap<U> {
|
||||
ScopedHashMap {
|
||||
values: self
|
||||
.values
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, f(value)))
|
||||
.collect(),
|
||||
groups: self
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
group
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, value.as_ref().map(&mut f)))
|
||||
.collect()
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Map is a map type where the keys are control sequence names and the values are TeX commands.
|
||||
///
|
||||
/// There are a number of design goals for the map:
|
||||
///
|
||||
/// - Make retrieving the function for a command very fast. This is achieved primarily by storing
|
||||
/// command functions by themselves in an array. The index in the array is the control sequence
|
||||
/// name, which is an integer when interned. This implementation choice means fast-as-possible lookups.
|
||||
/// Storing the function by itself means there is good cache locality.
|
||||
///
|
||||
///
|
||||
/// - Insert built in commands at the start
|
||||
/// insert_built_in(cs_name, cmd),
|
||||
/// - Insert variable commands that aren't there at the start, but will be in the future. E.g., \countdef
|
||||
/// register_built_in(cmd) <- must have a unique ID. Is type ID stable across binary builds? Maybe need to
|
||||
/// use a string ID instead? But then need to feed that the library using this registered
|
||||
/// - Should we enforce that the previous two steps can only be done at creation time? Probably
|
||||
/// Maybe initialize the map using Map<cs_name, cmd> and `Vec<cmd>`. Can provide cs_name<->str wrapper at
|
||||
/// the VM level
|
||||
///
|
||||
/// - While running, insert macros
|
||||
/// insert_macro(&str, macro)
|
||||
/// - While running, alias commands by current name or using the special ID inserts
|
||||
/// alias_control_sequence(cs_name, cs_name) -> undefined control sequence error
|
||||
/// alias_registered_built_in(cs_name, cmd_id, variable_addr)
|
||||
/// alias_character(cs_name, token::Token)
|
||||
pub struct Map<S> {
|
||||
commands: ScopedVec<Command<S>>,
|
||||
active_char: ScopedHashMap<Command<S>>,
|
||||
|
||||
built_in_commands: HashMap<token::CsName, BuiltIn<S>>,
|
||||
primitive_key_to_built_in_lazy: RefCell<Option<HashMap<PrimitiveKey, token::CsName>>>,
|
||||
getters_key_to_built_in_lazy: RefCell<Option<HashMap<variable::GettersKey, token::CsName>>>,
|
||||
}
|
||||
|
||||
impl<S> Map<S> {
|
||||
pub(crate) fn new(built_in_commands: HashMap<token::CsName, BuiltIn<S>>) -> Map<S> {
|
||||
Self {
|
||||
commands: built_in_commands
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_usize(), v.cmd.clone()))
|
||||
.collect(),
|
||||
active_char: Default::default(),
|
||||
built_in_commands,
|
||||
primitive_key_to_built_in_lazy: Default::default(),
|
||||
getters_key_to_built_in_lazy: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_command(&self, command_ref: &token::CommandRef) -> Option<&Command<S>> {
|
||||
match command_ref {
|
||||
token::CommandRef::ControlSequence(name) => self.commands.get(&name.to_usize()),
|
||||
token::CommandRef::ActiveCharacter(c) => self.active_char.get(c),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_tag(&self, command_ref: &token::CommandRef) -> Option<Tag> {
|
||||
let command = match command_ref {
|
||||
token::CommandRef::ControlSequence(name) => self.commands.get(&name.to_usize()),
|
||||
token::CommandRef::ActiveCharacter(c) => self.active_char.get(c),
|
||||
};
|
||||
command.map(Command::tag).unwrap_or(None)
|
||||
}
|
||||
|
||||
pub fn built_in_commands(&self) -> &HashMap<token::CsName, BuiltIn<S>> {
|
||||
&self.built_in_commands
|
||||
}
|
||||
|
||||
pub fn get_command_slow(&self, command_ref: &token::CommandRef) -> Option<BuiltIn<S>> {
|
||||
let command = self.get_command(command_ref)?;
|
||||
if let Some(ref key) = PrimitiveKey::new(command) {
|
||||
if let Some(built_in) = self.primitive_key_to_built_in().get(key) {
|
||||
return self.built_in_commands.get(built_in).cloned();
|
||||
}
|
||||
}
|
||||
Some(BuiltIn {
|
||||
cmd: command.clone(),
|
||||
doc: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn insert_variable_command(
|
||||
&mut self,
|
||||
command_ref: token::CommandRef,
|
||||
variable_command: variable::Command<S>,
|
||||
scope: groupingmap::Scope,
|
||||
) {
|
||||
self.insert(
|
||||
command_ref,
|
||||
Command::Variable(rc::Rc::new(variable_command)),
|
||||
scope,
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: reconsider this API of 4 setters ... it seems to be unnecessary complexity?
|
||||
pub fn insert_macro(
|
||||
&mut self,
|
||||
name: token::CommandRef,
|
||||
texmacro: texmacro::Macro,
|
||||
scope: groupingmap::Scope,
|
||||
) {
|
||||
self.insert(name, Command::Macro(rc::Rc::new(texmacro)), scope);
|
||||
}
|
||||
|
||||
pub fn alias_control_sequence(
|
||||
&mut self,
|
||||
alias: token::CommandRef,
|
||||
command: &token::CommandRef,
|
||||
scope: groupingmap::Scope,
|
||||
) {
|
||||
if let Some(command) = self.get_command(command) {
|
||||
self.insert(alias, command.clone(), scope);
|
||||
};
|
||||
}
|
||||
|
||||
pub fn alias_token(
|
||||
&mut self,
|
||||
alias: token::CommandRef,
|
||||
token: token::Token,
|
||||
scope: groupingmap::Scope,
|
||||
) {
|
||||
self.insert(alias, Command::CharacterTokenAlias(token.value()), scope);
|
||||
}
|
||||
|
||||
pub fn insert(
|
||||
&mut self,
|
||||
command_ref: token::CommandRef,
|
||||
func: Command<S>,
|
||||
scope: groupingmap::Scope,
|
||||
) {
|
||||
match command_ref {
|
||||
token::CommandRef::ControlSequence(name) => {
|
||||
let key = name.to_usize();
|
||||
self.commands.insert(key, func, scope);
|
||||
}
|
||||
token::CommandRef::ActiveCharacter(c) => {
|
||||
self.active_char.insert(c, func, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: support active characters
|
||||
pub fn to_hash_map_slow(&self) -> HashMap<token::CsName, BuiltIn<S>> {
|
||||
let mut result = HashMap::new();
|
||||
for (key, _value) in self.commands.backing_container().iter().enumerate() {
|
||||
let cs_name = match token::CsName::try_from_usize(key) {
|
||||
None => continue,
|
||||
Some(cs_name) => cs_name,
|
||||
};
|
||||
let command_ref = token::CommandRef::ControlSequence(cs_name);
|
||||
let cmd = match self.get_command_slow(&command_ref) {
|
||||
None => continue,
|
||||
Some(cmd) => cmd,
|
||||
};
|
||||
result.insert(cs_name, cmd);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn begin_group(&mut self) {
|
||||
self.commands.begin_group();
|
||||
self.active_char.begin_group();
|
||||
}
|
||||
|
||||
pub(crate) fn end_group(&mut self) -> std::result::Result<(), groupingmap::NoGroupToEndError> {
|
||||
self.commands.end_group()?;
|
||||
self.active_char.end_group()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.commands.len()
|
||||
}
|
||||
|
||||
fn primitive_key_to_built_in(&self) -> Ref<'_, HashMap<PrimitiveKey, token::CsName>> {
|
||||
if let Ok(r) = Ref::filter_map(self.primitive_key_to_built_in_lazy.borrow(), Option::as_ref)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
*self.primitive_key_to_built_in_lazy.borrow_mut() = Some(
|
||||
self.built_in_commands
|
||||
.iter()
|
||||
.filter_map(|(cs_name, built_in)| {
|
||||
PrimitiveKey::new(built_in.cmd()).map(|key| (key, *cs_name))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
self.primitive_key_to_built_in()
|
||||
}
|
||||
|
||||
pub(crate) fn getters_key_to_built_in(
|
||||
&self,
|
||||
) -> Ref<'_, HashMap<variable::GettersKey, token::CsName>> {
|
||||
if let Ok(r) = Ref::filter_map(self.getters_key_to_built_in_lazy.borrow(), Option::as_ref) {
|
||||
return r;
|
||||
}
|
||||
*self.getters_key_to_built_in_lazy.borrow_mut() = Some(
|
||||
self.primitive_key_to_built_in()
|
||||
.iter()
|
||||
.filter_map(|(key, cs_name)| match key {
|
||||
PrimitiveKey::Variable(variable_command_key) => {
|
||||
Some((variable_command_key.getter_key(), *cs_name))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
self.getters_key_to_built_in()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct InvalidAlias;
|
||||
|
||||
impl fmt::Display for InvalidAlias {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"invalid alias: the control sequence to alias is undefined"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidAlias {}
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
enum SerializableCommand {
|
||||
BuiltIn(token::CsName),
|
||||
VariableArrayStatic(token::CsName, usize),
|
||||
Macro(usize),
|
||||
CharacterTokenAlias(token::Value),
|
||||
Character(char),
|
||||
MathCharacter(types::MathCode),
|
||||
UnicodeMathCharacter {
|
||||
class: u8,
|
||||
family: u8,
|
||||
character: char,
|
||||
},
|
||||
Font(font::Id),
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub(crate) struct SerializableMap<'a> {
|
||||
commands: ScopedVec<SerializableCommand>,
|
||||
active_char: ScopedHashMap<SerializableCommand>,
|
||||
macros: Vec<Cow<'a, texmacro::Macro>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<State> serde::Serialize for Map<State> {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let serializable_map = SerializableMap::new(self);
|
||||
serializable_map.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SerializableMap<'a> {
|
||||
fn new<S>(map: &'a Map<S>) -> Self {
|
||||
let mut macros_de_dup = HashMap::<usize, usize>::new();
|
||||
let mut macros: Vec<Cow<'a, texmacro::Macro>> = Default::default();
|
||||
let primitive_key_to_built_in = map.primitive_key_to_built_in();
|
||||
let getters_key_to_built_in = map.getters_key_to_built_in();
|
||||
let mut encode_command = |command: &'a Command<S>| match command {
|
||||
Command::Expansion(_, _) | Command::Execution(_, _) => {
|
||||
let key = PrimitiveKey::new(command).unwrap();
|
||||
match primitive_key_to_built_in.get(&key) {
|
||||
None => todo!("return an error"),
|
||||
Some(built_in) => SerializableCommand::BuiltIn(*built_in),
|
||||
}
|
||||
}
|
||||
Command::Variable(variable_command) => {
|
||||
let key = PrimitiveKey::new(command).unwrap();
|
||||
if let Some(built_in) = primitive_key_to_built_in.get(&key) {
|
||||
SerializableCommand::BuiltIn(*built_in)
|
||||
} else {
|
||||
match variable_command.key() {
|
||||
variable::CommandKey::ArrayStatic(getters_key, index, _) => {
|
||||
let built_in = getters_key_to_built_in.get(&getters_key).unwrap();
|
||||
SerializableCommand::VariableArrayStatic(*built_in, index.0)
|
||||
}
|
||||
_ => todo!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Macro(tex_macro) => {
|
||||
let rc_addr = Rc::as_ptr(tex_macro) as usize;
|
||||
let index = *macros_de_dup.entry(rc_addr).or_insert_with(|| {
|
||||
let index = macros.len();
|
||||
macros.push(Cow::Borrowed(tex_macro));
|
||||
index
|
||||
});
|
||||
SerializableCommand::Macro(index)
|
||||
}
|
||||
Command::CharacterTokenAlias(value) => {
|
||||
SerializableCommand::CharacterTokenAlias(*value)
|
||||
}
|
||||
Command::Character(character) => SerializableCommand::Character(*character),
|
||||
Command::MathCharacter(character) => {
|
||||
SerializableCommand::MathCharacter(*character)
|
||||
}
|
||||
Command::UnicodeMathCharacter {
|
||||
class,
|
||||
family,
|
||||
character,
|
||||
} => SerializableCommand::UnicodeMathCharacter {
|
||||
class: *class,
|
||||
family: *family,
|
||||
character: *character,
|
||||
},
|
||||
Command::Font(font) => SerializableCommand::Font(*font),
|
||||
};
|
||||
let commands = map.commands.map_values(&mut encode_command);
|
||||
let active_char = map.active_char.map_values(&mut encode_command);
|
||||
Self {
|
||||
commands,
|
||||
active_char,
|
||||
macros,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_deserialization<S>(
|
||||
self,
|
||||
built_in_commands: HashMap<token::CsName, BuiltIn<S>>,
|
||||
interner: &token::CsNameInterner,
|
||||
) -> Map<S> {
|
||||
let macros: Vec<Rc<texmacro::Macro>> = self
|
||||
.macros
|
||||
.into_iter()
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.map(Rc::new)
|
||||
.collect();
|
||||
let mut decode_command = |serialized_command: &SerializableCommand| match serialized_command {
|
||||
SerializableCommand::BuiltIn(cs_name) => match built_in_commands.get(cs_name) {
|
||||
None => panic!("unknown control sequence {:?}", interner.resolve(*cs_name)),
|
||||
Some(command) => command.cmd.clone(),
|
||||
},
|
||||
SerializableCommand::VariableArrayStatic(cs_name, index) => {
|
||||
match &built_in_commands.get(cs_name).unwrap().cmd {
|
||||
Command::Variable(variable_command) => Command::Variable(std::rc::Rc::new(
|
||||
variable_command.new_array_element(variable::Index(*index)),
|
||||
)),
|
||||
_ => todo!(),
|
||||
}
|
||||
}
|
||||
SerializableCommand::Macro(index) => {
|
||||
// TODO: error handling if the macro is missing
|
||||
Command::Macro(macros.get(*index).unwrap().clone())
|
||||
}
|
||||
SerializableCommand::CharacterTokenAlias(value) => {
|
||||
Command::CharacterTokenAlias(*value)
|
||||
}
|
||||
SerializableCommand::Character(character) => Command::Character(*character),
|
||||
SerializableCommand::MathCharacter(character) => {
|
||||
Command::MathCharacter(*character)
|
||||
}
|
||||
SerializableCommand::UnicodeMathCharacter {
|
||||
class,
|
||||
family,
|
||||
character,
|
||||
} => Command::UnicodeMathCharacter {
|
||||
class: *class,
|
||||
family: *family,
|
||||
character: *character,
|
||||
},
|
||||
SerializableCommand::Font(font) => Command::Font(*font),
|
||||
};
|
||||
let commands = self.commands.map_values(&mut decode_command);
|
||||
let active_char = self.active_char.map_values(&mut decode_command);
|
||||
Map {
|
||||
commands,
|
||||
active_char,
|
||||
built_in_commands,
|
||||
primitive_key_to_built_in_lazy: Default::default(),
|
||||
getters_key_to_built_in_lazy: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+428
@@ -0,0 +1,428 @@
|
||||
//! Texlang commands API
|
||||
//!
|
||||
//! # Texcraft commands API
|
||||
//!
|
||||
//! One of the most important parts of any TeX engine is the primitives that it provides.
|
||||
//! This documentation describes the *Texcraft commands API*,
|
||||
//! which is the mechanism by which TeX engines add new primitives.
|
||||
//!
|
||||
//! A note on terminology: *commands* can be categorized into primitives,
|
||||
//! which are implemented in the TeX engine, and user defined macros,
|
||||
//! which are created in specific TeX documents using primitives like `\def`.
|
||||
//! We often use the word command and primitive interchangeably here because in the context
|
||||
//! of implementing TeX engines they’re basically synonymous.
|
||||
//! A TeX engine could theoretically provide a native user defined macro...but it’s unlikely.
|
||||
//!
|
||||
//! ## Expansion vs execution
|
||||
//!
|
||||
//! Expansion and execution commands seem similar because they both optionally
|
||||
//! read input tokens and then make changes to the VM.
|
||||
//! However the differences are pretty significant in practice:
|
||||
//!
|
||||
//! | | Expansion | Execution
|
||||
//! |------------------------------------------|-----------|-----------
|
||||
//! Can read tokens from the input stream? | Yes | Yes
|
||||
//! Can add tokens to the input stream> | Yes | It’s possible, but the API discourages it.[^futurelet]
|
||||
//! Can make changes to the state? | No | Yes
|
||||
//! Is evaluated when tokens are only being expanded, like in `\edef` | Yes | No
|
||||
//!
|
||||
//!
|
||||
//! [^futurelet]: `\futurelet` is an example of an execution command that does this.
|
||||
//!
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::texmacro;
|
||||
use crate::token;
|
||||
use crate::types;
|
||||
use crate::variable;
|
||||
use crate::vm;
|
||||
use common::font;
|
||||
use std::num;
|
||||
use std::rc;
|
||||
use std::sync;
|
||||
|
||||
pub(crate) mod map;
|
||||
|
||||
pub use map::Map;
|
||||
|
||||
/// The Rust type of expansion primitive functions.
|
||||
pub type ExpansionFn<S> =
|
||||
fn(token: token::Token, input: &mut vm::ExpansionInput<S>) -> txl::Result<()>;
|
||||
|
||||
/// The Rust type of execution primitive functions.
|
||||
pub type ExecutionFn<S> =
|
||||
fn(token: token::Token, input: &mut vm::ExecutionInput<S>) -> txl::Result<()>;
|
||||
|
||||
/// A TeX command.
|
||||
pub enum Command<S> {
|
||||
/// An expansion primitive that is implemented in the engine.
|
||||
///
|
||||
/// Examples: `\the`, `\ifnum`.
|
||||
Expansion(ExpansionFn<S>, Option<Tag>),
|
||||
|
||||
/// A user defined macro.
|
||||
///
|
||||
/// Examples: `\newcommand` and `\include` in LaTeX.
|
||||
Macro(rc::Rc<texmacro::Macro>),
|
||||
|
||||
/// A non-expansion primitive that performs operations on the state.
|
||||
///
|
||||
/// Examples: `\def`, `\par`.
|
||||
Execution(ExecutionFn<S>, Option<Tag>),
|
||||
|
||||
/// A command that is used to reference a variable, like a parameter or a register.
|
||||
///
|
||||
/// Such a command is *resolved* to get the variable using the function pointer it holds.
|
||||
///
|
||||
/// Examples: `\count`, `\year`.
|
||||
Variable(rc::Rc<variable::Command<S>>),
|
||||
|
||||
/// A command that aliases a character token.
|
||||
///
|
||||
/// Depending on the context in which this command appears it may behave like a
|
||||
/// character (when typesetting) or like an unexpandable command (when parsing integers).
|
||||
/// Created using `\let\cmd=<character>`.
|
||||
CharacterTokenAlias(token::Value),
|
||||
|
||||
/// A command that references a character.
|
||||
///
|
||||
/// These commands are generally created using `\countdef`.
|
||||
/// In the main inner loop they result in a character being typeset.
|
||||
/// In other contexts they are interpreted as numbers.
|
||||
/// In Plain TeX, `\countdef 255` is used as a more efficient version of `\def{255 }`.
|
||||
Character(char),
|
||||
|
||||
/// A command that references a math character.
|
||||
///
|
||||
/// These commands are generally created using `\mathchardef`.
|
||||
MathCharacter(types::MathCode),
|
||||
UnicodeMathCharacter {
|
||||
class: u8,
|
||||
family: u8,
|
||||
character: char,
|
||||
},
|
||||
|
||||
/// A command that enables a font.
|
||||
Font(font::Id),
|
||||
}
|
||||
|
||||
impl<S> std::fmt::Display for Command<S> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Command::Expansion(_, _) => write![f, "an expansion command"],
|
||||
Command::Macro(_) => write![f, "a user-defined macro"],
|
||||
Command::Execution(_, _) => write![f, "an execution command"],
|
||||
Command::Variable(_) => write![f, "a variable command"],
|
||||
Command::CharacterTokenAlias(_) => write![f, "a character token alias"],
|
||||
Command::Character(_) => write![f, "a character command"],
|
||||
Command::MathCharacter(_) => write![f, "a math character command"],
|
||||
Command::UnicodeMathCharacter { .. } => {
|
||||
write![f, "a Unicode math character command"]
|
||||
}
|
||||
Command::Font(_) => write![f, "a font command"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Command<S> {
|
||||
/// Gets the tag associated to this command, or [None] if the command has no tag.
|
||||
pub fn tag(&self) -> Option<Tag> {
|
||||
match self {
|
||||
Command::Expansion(_, tag) => *tag,
|
||||
Command::Execution(_, tag) => *tag,
|
||||
Command::Macro(_)
|
||||
| Command::Variable(_)
|
||||
| Command::CharacterTokenAlias(_)
|
||||
| Command::Character(_)
|
||||
| Command::MathCharacter(_)
|
||||
| Command::UnicodeMathCharacter { .. }
|
||||
| Command::Font(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A built-in command. This is a command provided at VM initialization.
|
||||
///
|
||||
/// This struct is simply a combination of a [Command] and a documentation string for the command.
|
||||
/// It is used when providing the built-in commands for a VM.
|
||||
pub struct BuiltIn<S> {
|
||||
cmd: Command<S>,
|
||||
doc: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl<S> BuiltIn<S> {
|
||||
/// Create a new expansion built-in command.
|
||||
pub fn new_expansion(t: ExpansionFn<S>) -> BuiltIn<S> {
|
||||
t.into()
|
||||
}
|
||||
|
||||
/// Create a new expansion built-in command.
|
||||
pub fn new_execution(t: ExecutionFn<S>) -> BuiltIn<S> {
|
||||
t.into()
|
||||
}
|
||||
|
||||
/// Create a new variable built-in command.
|
||||
pub fn new_variable(cmd: variable::Command<S>) -> BuiltIn<S> {
|
||||
Command::Variable(rc::Rc::new(cmd)).into()
|
||||
}
|
||||
|
||||
/// Create a new font built-in command.
|
||||
pub fn new_font(font: font::Id) -> BuiltIn<S> {
|
||||
Command::Font(font).into()
|
||||
}
|
||||
|
||||
/// Set the tag for this built-in command.
|
||||
pub fn with_tag(mut self, tag: Tag) -> BuiltIn<S> {
|
||||
match &mut self.cmd {
|
||||
Command::Expansion(_, t) => *t = Some(tag),
|
||||
Command::Execution(_, t) => *t = Some(tag),
|
||||
Command::Macro(_)
|
||||
| Command::Variable(_)
|
||||
| Command::CharacterTokenAlias(_)
|
||||
| Command::Character(_)
|
||||
| Command::MathCharacter(_)
|
||||
| Command::UnicodeMathCharacter { .. }
|
||||
| Command::Font(_) => {
|
||||
panic!("cannot add a tag to this type of command")
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
// Set the doc for this built-in command.
|
||||
pub fn with_doc(mut self, doc: &'static str) -> BuiltIn<S> {
|
||||
self.doc = Some(doc);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn cmd(&self) -> &Command<S> {
|
||||
&self.cmd
|
||||
}
|
||||
|
||||
pub fn doc(&self) -> Option<&'static str> {
|
||||
self.doc
|
||||
}
|
||||
}
|
||||
|
||||
// We need to implement Clone manually as the derived implementation requires S to be Clone.
|
||||
impl<S> Clone for Command<S> {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
Command::Expansion(e, t) => Command::Expansion::<S>(*e, *t),
|
||||
Command::Macro(m) => Command::Macro(m.clone()),
|
||||
Command::Execution(e, t) => Command::Execution(*e, *t),
|
||||
Command::Variable(v) => Command::Variable(v.clone()),
|
||||
Command::CharacterTokenAlias(tv) => Command::CharacterTokenAlias(*tv),
|
||||
Command::Character(c) => Command::Character(*c),
|
||||
Command::MathCharacter(c) => Command::MathCharacter(*c),
|
||||
Command::UnicodeMathCharacter {
|
||||
class,
|
||||
family,
|
||||
character,
|
||||
} => Command::UnicodeMathCharacter {
|
||||
class: *class,
|
||||
family: *family,
|
||||
character: *character,
|
||||
},
|
||||
Command::Font(font) => Command::Font(*font),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We need to implement Clone manually as the derived implementation requires S to be Clone.
|
||||
impl<S> Clone for BuiltIn<S> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
cmd: self.cmd.clone(),
|
||||
doc: self.doc,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<ExpansionFn<S>> for BuiltIn<S> {
|
||||
fn from(cmd: ExpansionFn<S>) -> Self {
|
||||
Command::Expansion(cmd, None).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<rc::Rc<texmacro::Macro>> for BuiltIn<S> {
|
||||
fn from(cmd: rc::Rc<texmacro::Macro>) -> Self {
|
||||
Command::Macro(cmd).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<ExecutionFn<S>> for BuiltIn<S> {
|
||||
fn from(cmd: ExecutionFn<S>) -> Self {
|
||||
Command::Execution(cmd, None).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<variable::Command<S>> for BuiltIn<S> {
|
||||
fn from(cmd: variable::Command<S>) -> Self {
|
||||
Command::Variable(rc::Rc::new(cmd)).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<Command<S>> for BuiltIn<S> {
|
||||
fn from(cmd: Command<S>) -> Self {
|
||||
BuiltIn { cmd, doc: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// A tag is a piece of metadata that is optionally attached to a command.
|
||||
///
|
||||
/// Tags are used to implement certain TeX language semantics.
|
||||
/// An example is TeX conditionals.
|
||||
/// When a TeX conditional statement evaluates to false, the `\if` command must scan
|
||||
/// the input stream until it finds either an `\else` or `\fi` command.
|
||||
/// (The tokens scanned in this process are in the true branch of the conditional,
|
||||
/// and must thus be discarded.)
|
||||
/// Tags are the mechanism by which the scanning algorithm can
|
||||
/// determine if a token corresponds to an `\else` of `\fi` command.
|
||||
/// Concretely, both `\else` of `\fi` command have unique tags associated to them.
|
||||
/// When scanning the stream,
|
||||
/// if a token is a command token then the tag for the associated command is
|
||||
/// compared to the known tags for `\else` and `\fi`.
|
||||
/// If the tags match, the true branch is finished.
|
||||
///
|
||||
/// In general, TeX commands interface with the VM in two ways.
|
||||
/// The first most common way is when the main VM loop or expansion loop encounters a command.
|
||||
/// The loop invokes the command's associated Rust function.
|
||||
/// One can think of the Rust function as providing the behavior of the command in this context.
|
||||
///
|
||||
/// The second way is when a different command, like a conditional command, performs some operation
|
||||
/// that is dependent on the commands it reads out of the input stream.
|
||||
/// In this context the commands in the input stream provide behavior using tags.
|
||||
/// The `\else` command having the specific else tag results in the conditional branch processing completing.
|
||||
///
|
||||
/// Note that the same tag can be used for multiple commands,
|
||||
/// but each command can only have one tag.
|
||||
///
|
||||
/// ## Implementation details
|
||||
///
|
||||
/// Tags are non-zero 32 bit integers.
|
||||
/// The first tag created has value 1, the second tag has value 2, and so on.
|
||||
/// A global mutex is used to store the next tag value.
|
||||
/// Tags have the property that `Option<Tag>` takes up 4 bytes in memory.
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Debug, PartialOrd, Ord, Hash)]
|
||||
pub struct Tag(num::NonZeroU32);
|
||||
|
||||
static NEXT_TAG_VALUE: sync::Mutex<u32> = sync::Mutex::new(1);
|
||||
|
||||
impl Tag {
|
||||
/// Creates a new unique tag.
|
||||
///
|
||||
/// ```
|
||||
/// # use texlang::command::Tag;
|
||||
/// let tag_1 = Tag::new();
|
||||
/// let tag_2 = Tag::new();
|
||||
/// assert_ne!(tag_1, tag_2);
|
||||
/// ```
|
||||
// We suppress the clippy warning because creating a new tag is a global operation and
|
||||
// shouldn't be done without explicit intention.
|
||||
#[allow(clippy::new_without_default)]
|
||||
pub fn new() -> Tag {
|
||||
let mut n = NEXT_TAG_VALUE.lock().unwrap();
|
||||
let tag = Tag(num::NonZeroU32::new(*n).unwrap());
|
||||
*n = n.checked_add(1).unwrap();
|
||||
tag
|
||||
}
|
||||
}
|
||||
|
||||
/// A static tag enables creating a tag in a static variable.
|
||||
///
|
||||
/// ```
|
||||
/// # use texlang::command::StaticTag;
|
||||
/// static TAG: StaticTag = StaticTag::new();
|
||||
///
|
||||
/// let first_get = TAG.get();
|
||||
/// let second_get = TAG.get();
|
||||
/// assert_eq!(first_get, second_get);
|
||||
/// ```
|
||||
pub struct StaticTag(std::sync::OnceLock<Tag>);
|
||||
|
||||
impl Default for StaticTag {
|
||||
fn default() -> Self {
|
||||
StaticTag::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl StaticTag {
|
||||
/// Create a new static tag.
|
||||
pub const fn new() -> StaticTag {
|
||||
StaticTag(std::sync::OnceLock::new())
|
||||
}
|
||||
|
||||
/// Get the actual [Tag] out of this [StaticTag].
|
||||
/// Repeated calls to this function return the same tag.
|
||||
///
|
||||
/// This is not a trivial getter.
|
||||
/// The [Tag] is lazily constructed so even subsequent calls to this getter must do some work to check if the [Tag]
|
||||
/// exists or not.
|
||||
/// For very hot code paths it is advised to cache the return value somewhere, for example in a relevant command's state.
|
||||
pub fn get(&self) -> Tag {
|
||||
*self.0.get_or_init(Tag::new)
|
||||
}
|
||||
}
|
||||
|
||||
/// A primitive key uniquely identifies a primitive.
|
||||
///
|
||||
/// If two commands have the same key, they are the same primitive (expansion, execution, or variable primitive)
|
||||
/// The function returns [None] if the command is not a primitive (a macro or a token alias).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum PrimitiveKey {
|
||||
Execution(usize, Option<Tag>),
|
||||
Expansion(usize, Option<Tag>),
|
||||
Variable(variable::CommandKey),
|
||||
}
|
||||
|
||||
impl PrimitiveKey {
|
||||
pub(crate) fn new<S>(command: &Command<S>) -> Option<Self> {
|
||||
match command {
|
||||
Command::Expansion(f, tag) => Some(PrimitiveKey::Expansion(*f as usize, *tag)),
|
||||
Command::Execution(f, tag) => Some(PrimitiveKey::Execution(*f as usize, *tag)),
|
||||
Command::Variable(v) => Some(PrimitiveKey::Variable(v.key())),
|
||||
Command::Macro(_)
|
||||
| Command::CharacterTokenAlias(_)
|
||||
| Command::Character(_)
|
||||
| Command::MathCharacter(_)
|
||||
| Command::UnicodeMathCharacter { .. }
|
||||
| Command::Font(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn func_size() {
|
||||
assert_eq!(std::mem::size_of::<Command<()>>(), 16);
|
||||
}
|
||||
|
||||
static STATIC_TAG_1: StaticTag = StaticTag::new();
|
||||
static STATIC_TAG_2: StaticTag = StaticTag::new();
|
||||
|
||||
#[test]
|
||||
fn tag() {
|
||||
let tag_1_val_1 = STATIC_TAG_1.get();
|
||||
let tag_2_val_1 = STATIC_TAG_2.get();
|
||||
let other_tag_1 = Tag::new();
|
||||
let tag_1_val_2 = STATIC_TAG_1.get();
|
||||
let tag_2_val_2 = STATIC_TAG_2.get();
|
||||
let other_tag_2 = Tag::new();
|
||||
|
||||
assert_eq!(tag_1_val_1, tag_1_val_2);
|
||||
assert_eq!(tag_2_val_1, tag_2_val_2);
|
||||
|
||||
assert_ne!(tag_1_val_1, tag_2_val_2);
|
||||
assert_ne!(tag_1_val_1, other_tag_1);
|
||||
assert_ne!(tag_1_val_1, other_tag_2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_size() {
|
||||
assert_eq!(std::mem::size_of::<Option<Tag>>(), 4);
|
||||
}
|
||||
}
|
||||
Vendored
+337
@@ -0,0 +1,337 @@
|
||||
use crate::token::trace::{self, SourceCodeTrace};
|
||||
use crate::{error, token};
|
||||
use std::collections::HashMap;
|
||||
use texcraft_stdext::color::{self, Colorize};
|
||||
|
||||
pub fn format_error(
|
||||
f: &mut std::fmt::Formatter<'_>,
|
||||
err: &error::TracedTexError,
|
||||
) -> std::fmt::Result {
|
||||
let root = err.error.as_ref();
|
||||
let stack = &err.stack_trace;
|
||||
|
||||
let (error_line, immediate_command) = match root.kind() {
|
||||
error::Kind::Token(s) => (err.token_traces.get(&s).unwrap(), stack.last()),
|
||||
error::Kind::EndOfInput => (err.end_of_input_trace.as_ref().unwrap(), stack.last()),
|
||||
error::Kind::FailedPrecondition => (
|
||||
match err.error.source_code_trace_override() {
|
||||
None => &stack.last().unwrap().trace,
|
||||
Some(trace) => trace,
|
||||
},
|
||||
None,
|
||||
),
|
||||
};
|
||||
|
||||
let line = PrimaryLine {
|
||||
kind: PrimaryLineKind::Error,
|
||||
source: error_line,
|
||||
title: root.title(),
|
||||
token_annotation: root.source_annotation(),
|
||||
notes: root
|
||||
.notes()
|
||||
.iter()
|
||||
.map(|n| n.trace(&err.token_traces))
|
||||
.map(|n| format!("{n}"))
|
||||
.collect(),
|
||||
};
|
||||
write!(f, "{line}")?;
|
||||
|
||||
if let Some(err) = immediate_command {
|
||||
let line = PrimaryLine {
|
||||
kind: PrimaryLineKind::Context,
|
||||
source: &err.trace,
|
||||
title: format!["this error occurred while {}:", err.context.action()],
|
||||
token_annotation: "".into(),
|
||||
notes: vec![format![
|
||||
"this is the full stack trace of the error:\n\n{}",
|
||||
ErrorStack(stack)
|
||||
]],
|
||||
};
|
||||
write!(f, "\n{line}")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PrimaryLine<'a> {
|
||||
kind: PrimaryLineKind,
|
||||
source: &'a trace::SourceCodeTrace,
|
||||
title: String,
|
||||
token_annotation: String,
|
||||
notes: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum PrimaryLineKind {
|
||||
Error,
|
||||
Context,
|
||||
}
|
||||
|
||||
impl PrimaryLineKind {
|
||||
fn color(&self, s: &str) -> color::ColoredString {
|
||||
match self {
|
||||
PrimaryLineKind::Error => s.bright_red(),
|
||||
PrimaryLineKind::Context => s.bright_yellow(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PrimaryLineKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
match self {
|
||||
PrimaryLineKind::Error => "Error".bright_red(),
|
||||
PrimaryLineKind::Context => "Context".bright_yellow(),
|
||||
}
|
||||
.bold()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> std::fmt::Display for PrimaryLine<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let margin_width = self.source.line_number.to_string().len() + 1;
|
||||
let printer = Printer {
|
||||
indent: margin_width,
|
||||
};
|
||||
writeln!(f, "{}: {}", self.kind, self.title.bold())?;
|
||||
fmt_source_code_trace(&printer, f, self.source, &self.token_annotation, self.kind)?;
|
||||
|
||||
for (i, note) in self.notes.iter().enumerate() {
|
||||
let mut note_lines = note.trim_end().lines();
|
||||
let first_note_line = match note_lines.next() {
|
||||
None => continue,
|
||||
Some(s) => s,
|
||||
};
|
||||
printer.new_line().print(f)?;
|
||||
printer
|
||||
.new_line()
|
||||
.with_separator('=')
|
||||
.with_content(format!["{} {}", "note:".bold(), first_note_line])
|
||||
.print(f)?;
|
||||
for line in note_lines {
|
||||
let mut l = printer.new_line().with_content(format![" {line}"]);
|
||||
if i == self.notes.len() - 1 {
|
||||
l = l.with_separator(' ');
|
||||
}
|
||||
l.print(f)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct ErrorStack<'a>(&'a Vec<error::StackTraceElement>);
|
||||
|
||||
impl<'a> std::fmt::Display for ErrorStack<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for (u, propagated) in self.0.iter().rev().enumerate() {
|
||||
if u > 0 {
|
||||
writeln!(f)?;
|
||||
}
|
||||
let (s, p) = (&propagated.trace, &propagated.context);
|
||||
fmt_source_code_trace_light(f, s, 2, PrimaryLineKind::Context, p.action())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Printer {
|
||||
indent: usize,
|
||||
}
|
||||
|
||||
struct PrintLineBuilder<'a> {
|
||||
printer: &'a Printer,
|
||||
margin_content: String,
|
||||
separator: Option<char>,
|
||||
content: String,
|
||||
indent_adjustment: usize,
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
fn new_line(&self) -> PrintLineBuilder<'_> {
|
||||
PrintLineBuilder {
|
||||
printer: self,
|
||||
margin_content: "".into(),
|
||||
separator: Some('|'),
|
||||
content: "".into(),
|
||||
indent_adjustment: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> PrintLineBuilder<'a> {
|
||||
fn with_content<T: Into<String>>(mut self, content: T) -> Self {
|
||||
self.content = content.into();
|
||||
self
|
||||
}
|
||||
fn with_margin_content<T: Into<String>>(mut self, content: T) -> Self {
|
||||
self.margin_content = content.into();
|
||||
self
|
||||
}
|
||||
fn with_indent_adjustment(mut self, u: usize) -> Self {
|
||||
self.indent_adjustment = u;
|
||||
self
|
||||
}
|
||||
fn with_separator(mut self, c: char) -> Self {
|
||||
self.separator = Some(c);
|
||||
self
|
||||
}
|
||||
fn without_separator(mut self) -> Self {
|
||||
self.separator = None;
|
||||
self
|
||||
}
|
||||
|
||||
fn print(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let indent: usize = self
|
||||
.printer
|
||||
.indent
|
||||
.saturating_sub(self.indent_adjustment)
|
||||
.saturating_sub(self.margin_content.len() + 1);
|
||||
let margin_content = format!["{}{} ", " ".repeat(indent), self.margin_content];
|
||||
let separator = match self.separator {
|
||||
None => "".to_string(),
|
||||
Some(c) => format!["{c} "],
|
||||
};
|
||||
writeln!(
|
||||
f,
|
||||
"{}{}{}",
|
||||
margin_content.bright_cyan(),
|
||||
separator.bright_cyan(),
|
||||
self.content
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_source_code_trace(
|
||||
printer: &Printer,
|
||||
f: &mut std::fmt::Formatter<'_>,
|
||||
s: &trace::SourceCodeTrace,
|
||||
annotation: &str,
|
||||
line_kind: PrimaryLineKind,
|
||||
) -> std::fmt::Result {
|
||||
printer
|
||||
.new_line()
|
||||
.without_separator()
|
||||
.with_indent_adjustment(1)
|
||||
.with_content(format!(
|
||||
"{} {}:{}:{}",
|
||||
">>>".bright_cyan().bold(),
|
||||
match &s.origin {
|
||||
trace::Origin::File(file_name) => format!["{}", file_name.display()],
|
||||
trace::Origin::Terminal => "<input from terminal>".to_string(),
|
||||
},
|
||||
s.line_number,
|
||||
s.index + 1
|
||||
))
|
||||
.print(f)?;
|
||||
printer.new_line().print(f)?;
|
||||
printer
|
||||
.new_line()
|
||||
.with_margin_content(format!["{}", s.line_number])
|
||||
.with_content(highlight_substring(&s.line_content, s.index, s.value.len()))
|
||||
.print(f)?;
|
||||
printer
|
||||
.new_line()
|
||||
.with_content(format![
|
||||
"{}{} {}",
|
||||
" ".repeat(s.index),
|
||||
line_kind.color(&"^".repeat(s.value.len())).bold(),
|
||||
line_kind.color(annotation).bold(),
|
||||
])
|
||||
.print(f)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn highlight_substring(line: &str, start: usize, length: usize) -> String {
|
||||
if line.len() < start + length {
|
||||
return line.into();
|
||||
}
|
||||
format![
|
||||
"{}{}{}",
|
||||
&line[..start],
|
||||
(&line[start..start + length]).bold(),
|
||||
line[start + length..].trim_end(),
|
||||
]
|
||||
}
|
||||
|
||||
fn fmt_source_code_trace_light(
|
||||
f: &mut std::fmt::Formatter<'_>,
|
||||
s: &SourceCodeTrace,
|
||||
indent: usize,
|
||||
line_kind: PrimaryLineKind,
|
||||
annotation: &str,
|
||||
) -> std::fmt::Result {
|
||||
let prefix = format!(
|
||||
"{}{}:{}:{}",
|
||||
" ".repeat(indent),
|
||||
match &s.origin {
|
||||
trace::Origin::File(file_name) => format!["{}", file_name.display()],
|
||||
trace::Origin::Terminal => "<input from terminal>".to_string(),
|
||||
},
|
||||
s.line_number,
|
||||
s.index + 1
|
||||
);
|
||||
writeln!(
|
||||
f,
|
||||
"{} {}",
|
||||
prefix,
|
||||
highlight_substring(&s.line_content, s.index, s.value.len())
|
||||
)?;
|
||||
writeln!(
|
||||
f,
|
||||
"{} {} {}",
|
||||
" ".repeat(prefix.len() + s.index),
|
||||
line_kind.color(&"^".repeat(s.value.len())).bold(),
|
||||
annotation,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Note {
|
||||
Text(String),
|
||||
SourceCodeTrace(String, token::Token),
|
||||
}
|
||||
|
||||
impl Note {
|
||||
fn trace<'a>(&'a self, m: &'a HashMap<token::Token, trace::SourceCodeTrace>) -> TracedNote<'a> {
|
||||
match self {
|
||||
Note::Text(t) => TracedNote::Text(t),
|
||||
Note::SourceCodeTrace(s, token) => TracedNote::SourceCodeTrace(
|
||||
s,
|
||||
m.get(token)
|
||||
.expect("all tokens in the error have been traced"),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Into<String>> From<T> for Note {
|
||||
fn from(value: T) -> Self {
|
||||
Note::Text(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TracedNote<'a> {
|
||||
Text(&'a str),
|
||||
SourceCodeTrace(&'a str, &'a trace::SourceCodeTrace),
|
||||
}
|
||||
|
||||
impl<'a> std::fmt::Display for TracedNote<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
TracedNote::Text(s) => write!(f, "{s}"),
|
||||
TracedNote::SourceCodeTrace(s, trace) => {
|
||||
write!(f, "{s}\n\n")?;
|
||||
fmt_source_code_trace_light(f, trace, 2, PrimaryLineKind::Error, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+397
@@ -0,0 +1,397 @@
|
||||
//! Error handling
|
||||
//!
|
||||
//! This is reference documentation.
|
||||
//! The Texlang documentation has a [dedicated page about error handling
|
||||
//! ](<https://texcraft.dev/texlang/09-errors.html>).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::token;
|
||||
use crate::token::trace;
|
||||
use crate::vm;
|
||||
use texcraft_stdext::algorithms::spellcheck::{self, WordDiff};
|
||||
|
||||
pub mod display;
|
||||
|
||||
/// A fully traced error
|
||||
///
|
||||
/// Note that serializing and deserializing this type results in type erasure.
|
||||
/// Also the serialization format is private.
|
||||
/// This is not by design: the minimal amount of work was done to make the type
|
||||
/// serializable, and future work to make this better is welcome!
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TracedTexError {
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
serde(
|
||||
serialize_with = "serialize_error",
|
||||
deserialize_with = "deserialize_error"
|
||||
)
|
||||
)]
|
||||
pub error: Box<dyn TexError>,
|
||||
pub stack_trace: Vec<StackTraceElement>,
|
||||
pub token_traces: HashMap<token::Token, trace::SourceCodeTrace>,
|
||||
pub end_of_input_trace: Option<trace::SourceCodeTrace>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[allow(clippy::borrowed_box)] // we need this exact function signature for serde.
|
||||
fn serialize_error<S>(value: &Box<dyn TexError>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
use serde::Serialize;
|
||||
let serializable_error = SerializableError {
|
||||
kind: value.kind().clone(),
|
||||
title: value.title(),
|
||||
notes: value.notes(),
|
||||
source_annotation: value.source_annotation(),
|
||||
};
|
||||
serializable_error.serialize(serializer)
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
fn deserialize_error<'de, D>(deserializer: D) -> Result<Box<dyn TexError>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
use serde::Deserialize;
|
||||
let serializable_error = SerializableError::deserialize(deserializer)?;
|
||||
Ok(Box::new(serializable_error))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
struct SerializableError {
|
||||
kind: Kind,
|
||||
title: String,
|
||||
notes: Vec<display::Note>,
|
||||
source_annotation: String,
|
||||
}
|
||||
|
||||
impl TexError for SerializableError {
|
||||
fn kind(&self) -> Kind {
|
||||
self.kind.clone()
|
||||
}
|
||||
fn title(&self) -> String {
|
||||
self.title.clone()
|
||||
}
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
self.notes.clone()
|
||||
}
|
||||
fn source_annotation(&self) -> String {
|
||||
self.source_annotation.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl TracedTexError {
|
||||
pub(crate) fn new(
|
||||
error: Box<dyn TexError>,
|
||||
tracer: &trace::Tracer,
|
||||
cs_name_interner: &token::CsNameInterner,
|
||||
stack_trace: Vec<StackTraceElement>,
|
||||
) -> Self {
|
||||
let (end_of_input_trace, mut tokens) = match error.kind() {
|
||||
Kind::Token(token) => (None, vec![token]),
|
||||
Kind::EndOfInput => (Some(tracer.trace_end_of_input()), vec![]),
|
||||
Kind::FailedPrecondition => (None, vec![]),
|
||||
};
|
||||
for note in error.notes() {
|
||||
if let display::Note::SourceCodeTrace(_, token) = note {
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
let token_traces: HashMap<token::Token, trace::SourceCodeTrace> = tokens
|
||||
.into_iter()
|
||||
.map(|token| (token, tracer.trace(token, cs_name_interner)))
|
||||
.collect();
|
||||
TracedTexError {
|
||||
error,
|
||||
stack_trace,
|
||||
token_traces,
|
||||
end_of_input_trace,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementations of this trait describe an error in which in the input ended prematurely.
|
||||
pub trait EndOfInputError: std::fmt::Debug + 'static {
|
||||
fn doing(&self) -> String;
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
/// An error for work-in-progress Texlang code.
|
||||
///
|
||||
/// When working on Texlang code it's often nice to figure out the logic first,
|
||||
/// and then go through later to polish the error cases.
|
||||
/// This function returns a "TODO" error that helps with this process.
|
||||
///
|
||||
/// Use the return value of this function in any place you plan to generate an error.
|
||||
/// Later on, follow Texlang best practices and create a specific error
|
||||
/// type for the case with a good error message.
|
||||
#[allow(non_snake_case)]
|
||||
pub fn TODO() -> impl TexError + EndOfInputError {
|
||||
TodoError {}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TodoError {}
|
||||
|
||||
impl EndOfInputError for TodoError {
|
||||
fn doing(&self) -> String {
|
||||
"? (TODO: add a specific end of input error for this case.)".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
vec![
|
||||
"the Rust source code uses `texlang::error::TODO()` for this error case".into(),
|
||||
"a more specific end of input error needs to be added".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
impl TexError for TodoError {
|
||||
fn kind(&self) -> Kind {
|
||||
Kind::FailedPrecondition
|
||||
}
|
||||
fn title(&self) -> String {
|
||||
"? (TODO: add a specific error for this case.)".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
vec![
|
||||
"the Rust source code uses `texlang::error::TODO()` for this error case".into(),
|
||||
"a more specific error needs to be added".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct EofError {
|
||||
doing: String,
|
||||
notes: Vec<display::Note>,
|
||||
}
|
||||
|
||||
impl EofError {
|
||||
pub(crate) fn new<E: EndOfInputError>(err: E) -> Self {
|
||||
Self {
|
||||
doing: err.doing(),
|
||||
notes: err.notes(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TexError for EofError {
|
||||
fn kind(&self) -> Kind {
|
||||
Kind::EndOfInput
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
format!("Unexpected end of input while {}", self.doing)
|
||||
}
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
self.notes.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Element of a stack trace.
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct StackTraceElement {
|
||||
pub context: OperationKind,
|
||||
pub token: token::Token,
|
||||
pub trace: trace::SourceCodeTrace,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for TracedTexError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
display::format_error(f, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of an error.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Kind {
|
||||
/// An error at a particular TeX token.
|
||||
///
|
||||
/// For example, a TeX command expects a number but the next token is a letter.
|
||||
Token(token::Token),
|
||||
/// An end-of-input error.
|
||||
///
|
||||
/// For example, a TeX command expects a number but there is no more input.
|
||||
EndOfInput,
|
||||
/// Some external condition does not hold and so the TeX code is incorrect.
|
||||
///
|
||||
/// For example, a TeX command tries to open a file a particular path,
|
||||
/// but the file does not exist.
|
||||
FailedPrecondition,
|
||||
}
|
||||
|
||||
/// Implementations of this trait describe an error in TeX source code.
|
||||
pub trait TexError: std::fmt::Debug + 'static {
|
||||
fn kind(&self) -> Kind;
|
||||
|
||||
fn title(&self) -> String;
|
||||
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn source_annotation(&self) -> String {
|
||||
TexError::default_source_annotation(self)
|
||||
}
|
||||
|
||||
fn default_source_annotation(&self) -> String {
|
||||
match TexError::kind(self) {
|
||||
Kind::Token(t) => match (t.char(), t.cat_code()) {
|
||||
(Some(c), Some(code)) => {
|
||||
format!["character token with value {c} and category code {code}",]
|
||||
}
|
||||
_ => "control sequence".to_string(),
|
||||
},
|
||||
Kind::EndOfInput => "input ended here".into(),
|
||||
Kind::FailedPrecondition => "error occurred while running this command".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn source_code_trace_override(&self) -> Option<&trace::SourceCodeTrace> {
|
||||
None
|
||||
}
|
||||
// TODO: have a method that returns the exact error messages as Knuth's TeX
|
||||
// The method will return a vector of static strings
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
|
||||
pub enum OperationKind {
|
||||
Expansion,
|
||||
Execution,
|
||||
VariableIndex,
|
||||
VariableAssignment,
|
||||
}
|
||||
|
||||
impl OperationKind {
|
||||
fn action(&self) -> &'static str {
|
||||
match self {
|
||||
OperationKind::Expansion => "expanding this command",
|
||||
OperationKind::Execution => "executing this command",
|
||||
OperationKind::VariableIndex => "determining the index of this variable",
|
||||
OperationKind::VariableAssignment => "determining the value to assign to this variable",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SimpleTokenError {
|
||||
pub token: token::Token,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
impl SimpleTokenError {
|
||||
/// Create a new simple token error.
|
||||
pub fn new<T: AsRef<str>>(token: token::Token, title: T) -> SimpleTokenError {
|
||||
SimpleTokenError {
|
||||
token,
|
||||
title: title.as_ref().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TexError for SimpleTokenError {
|
||||
fn kind(&self) -> Kind {
|
||||
Kind::Token(self.token)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
self.title.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SimpleFailedPreconditionError {
|
||||
pub title: String,
|
||||
pub text_notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl SimpleFailedPreconditionError {
|
||||
/// Create a new simple failed precondition error.
|
||||
pub fn new<T: AsRef<str>>(title: T) -> Self {
|
||||
Self {
|
||||
title: title.as_ref().into(),
|
||||
text_notes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_note<T: Into<String>>(mut self, note: T) -> Self {
|
||||
self.text_notes.push(note.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl TexError for SimpleFailedPreconditionError {
|
||||
fn kind(&self) -> Kind {
|
||||
Kind::FailedPrecondition
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
self.title.clone()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
let mut notes = vec![];
|
||||
for text_note in &self.text_notes {
|
||||
notes.push(text_note.into())
|
||||
}
|
||||
notes
|
||||
}
|
||||
}
|
||||
|
||||
/// Concrete error for the case when a command is undefined.
|
||||
///
|
||||
/// This error is returned when a control sequence or active character
|
||||
/// is not defined.
|
||||
#[derive(Debug)]
|
||||
pub struct UndefinedCommandError {
|
||||
/// The token that was referred to an undefined command.
|
||||
pub token: token::Token,
|
||||
/// Control sequences that are spelled similarly to the token.
|
||||
pub close_names: Vec<WordDiff>,
|
||||
}
|
||||
|
||||
impl UndefinedCommandError {
|
||||
/// Create a new undefined command error.
|
||||
pub fn new<S>(vm: &vm::VM<S>, token: token::Token) -> UndefinedCommandError {
|
||||
let name = match &token.value() {
|
||||
token::Value::CommandRef(command_ref) => command_ref.to_string(vm.cs_name_interner()),
|
||||
_ => panic!("undefined command error does not work for non-command-ref tokens"),
|
||||
};
|
||||
let mut all_names = Vec::<&str>::new();
|
||||
for (cs_name, _) in vm.get_commands_as_map_slow().into_iter() {
|
||||
all_names.push(cs_name);
|
||||
}
|
||||
let close_names = spellcheck::find_close_words(&all_names, &name);
|
||||
|
||||
UndefinedCommandError { token, close_names }
|
||||
}
|
||||
}
|
||||
|
||||
impl TexError for UndefinedCommandError {
|
||||
fn kind(&self) -> Kind {
|
||||
Kind::Token(self.token)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
"undefined control sequence".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<display::Note> {
|
||||
let mut notes: Vec<display::Note> = Default::default();
|
||||
use texcraft_stdext::color::Colorize;
|
||||
if let Some(close_name) = self.close_names.first() {
|
||||
notes.push(format!["did you mean \\{}?\n", close_name.right().bold(),].into());
|
||||
}
|
||||
notes
|
||||
}
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
//! # Texlang: a TeX language interpreter.
|
||||
//!
|
||||
//! This crate implements a general purpose TeX language interpreter called Texlang.
|
||||
//!
|
||||
//! Most of the high level documentation is provided in the [Texcraft website](https://texcraft.dev),
|
||||
//! including guided introductions to using Texlang to build TeX interpreters.
|
||||
//! The documentation here is mostly for reference.
|
||||
|
||||
extern crate texcraft_stdext;
|
||||
|
||||
pub mod command;
|
||||
pub mod error;
|
||||
pub mod parse;
|
||||
pub mod prelude;
|
||||
pub mod texmacro;
|
||||
pub mod token;
|
||||
pub mod types;
|
||||
pub mod variable;
|
||||
pub mod vm;
|
||||
|
||||
/// Module that re-exports all of the crate's traits.
|
||||
///
|
||||
/// This is useful for getting all of the traits in scope in a Rust module:
|
||||
/// ```
|
||||
/// use texlang::traits::*;
|
||||
/// ```
|
||||
pub mod traits {
|
||||
pub use super::parse::Parsable;
|
||||
pub use super::vm::ExpandedStream;
|
||||
pub use super::vm::HasComponent;
|
||||
pub use super::vm::HasDefaultBuiltInCommands;
|
||||
pub use super::vm::TexlangState;
|
||||
pub use super::vm::TokenStream;
|
||||
}
|
||||
Vendored
+354
@@ -0,0 +1,354 @@
|
||||
use common::Scaled;
|
||||
|
||||
use super::keyword::parse_keyword;
|
||||
use crate::prelude as txl;
|
||||
use crate::token::Value;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
impl Parsable for Scaled {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(value) = S::scan_dimension(input)? {
|
||||
return Ok(value);
|
||||
}
|
||||
scan_dimen(input, None)
|
||||
}
|
||||
}
|
||||
|
||||
// TeX.2021.448 scan_dimen with:
|
||||
//
|
||||
// - shortcut=false
|
||||
// - the inf parameter is replaced by an optional pointer to a glue order
|
||||
pub(crate) fn scan_dimen<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
glue_order: Option<&mut common::GlueOrder>,
|
||||
) -> txl::Result<common::Scaled> {
|
||||
let negative = match super::integer::parse_optional_signs(input)? {
|
||||
None => 1,
|
||||
Some(_) => -1,
|
||||
};
|
||||
let first_token = input.next_or_err(DimenEndOfInputError {})?;
|
||||
let (negative, integer_part, fractional_part) = match first_token.value() {
|
||||
Value::CommandRef(command_ref) => {
|
||||
// TeX.2021.449
|
||||
use super::integer::InternalNumber;
|
||||
match super::integer::parse_internal_number(input, first_token, command_ref)? {
|
||||
InternalNumber::Integer(i) => (negative * i.signum(), i.abs(), Scaled::ZERO),
|
||||
InternalNumber::Dimen(d) => {
|
||||
return Ok(d * negative);
|
||||
}
|
||||
InternalNumber::Glue(g) => {
|
||||
return Ok(g.width * negative);
|
||||
}
|
||||
InternalNumber::MuGlue(_) => {
|
||||
input.error(parse::Error::new(
|
||||
"a dimension or ordinary glue value",
|
||||
Some(first_token),
|
||||
"a muskip value cannot be used as a dimension",
|
||||
))?;
|
||||
return Ok(Scaled::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let (i, f) = scan_constant_dimen(input, first_token)?;
|
||||
(negative, i, f)
|
||||
}
|
||||
};
|
||||
Ok(scan_and_apply_units(
|
||||
input,
|
||||
first_token,
|
||||
integer_part,
|
||||
fractional_part,
|
||||
glue_order,
|
||||
)? * negative)
|
||||
}
|
||||
|
||||
/// Part of TeX.2021.448
|
||||
pub(crate) fn scan_constant_dimen<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
) -> txl::Result<(i32, common::Scaled)> {
|
||||
Ok(match first_token.value() {
|
||||
Value::Other(',' | '.') => (0, scan_decimal_fraction(input)?),
|
||||
_ => {
|
||||
input.back(first_token);
|
||||
let (_, i, radix) = super::integer::parse_integer(input)?;
|
||||
// We scan for a fractional part if the integer was an decimal constant
|
||||
// and the next token is a period or comma.
|
||||
let fractional_part = if radix == Some(10) {
|
||||
match input.next()? {
|
||||
Some(next) => match next.value() {
|
||||
Value::Other(',' | '.') => scan_decimal_fraction(input)?,
|
||||
_ => {
|
||||
input.back(next);
|
||||
Scaled::ZERO
|
||||
}
|
||||
},
|
||||
None => Scaled::ZERO,
|
||||
}
|
||||
} else {
|
||||
Scaled::ZERO
|
||||
};
|
||||
(i, fractional_part)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// TeX.2021.453
|
||||
pub(crate) fn scan_and_apply_units<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
integer_part: i32,
|
||||
fractional_part: Scaled,
|
||||
glue_order: Option<&mut common::GlueOrder>,
|
||||
) -> txl::Result<common::Scaled> {
|
||||
// todo: scan spaces and non-call tokens
|
||||
|
||||
// First try to scan for infinite units, if this is the stretch
|
||||
// or shrink of a glue.
|
||||
if let Some(glue_order) = glue_order {
|
||||
if parse_keyword(input, "fil")? {
|
||||
*glue_order = common::GlueOrder::Fil;
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Letter('l' | 'L') => match glue_order.next() {
|
||||
None => {
|
||||
input.error(fillll_error(token))?;
|
||||
}
|
||||
Some(o) => *glue_order = o,
|
||||
},
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
super::OptionalSpace::parse(input)?;
|
||||
return match Scaled::from_integer(integer_part) {
|
||||
Ok(integer_part) => Ok(integer_part + fractional_part),
|
||||
Err(_) => handle_overflow(input, first_token, false),
|
||||
};
|
||||
}
|
||||
}
|
||||
// Then try to scan from an internal number.
|
||||
// TeX.2021.455
|
||||
if let Some(next) = input.next()? {
|
||||
let v_or = match next.value() {
|
||||
Value::CommandRef(command_ref) => {
|
||||
use super::integer::InternalNumber;
|
||||
Some(
|
||||
match super::integer::parse_internal_number(input, next, command_ref)? {
|
||||
// TeX silently interprets an integer as sp points in this position
|
||||
InternalNumber::Integer(i) => Scaled(i),
|
||||
InternalNumber::Dimen(scaled) => scaled,
|
||||
InternalNumber::Glue(glue) => glue.width,
|
||||
InternalNumber::MuGlue(_) => {
|
||||
input.error(parse::Error::new(
|
||||
"a dimension or ordinary glue value",
|
||||
Some(next),
|
||||
"a muskip value cannot be used as a dimension",
|
||||
))?;
|
||||
Scaled::ZERO
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
input.back(next);
|
||||
if parse_keyword(input, "em")? {
|
||||
super::OptionalSpace::parse(input)?;
|
||||
Some(input.state().em_width())
|
||||
} else if parse_keyword(input, "ex")? {
|
||||
super::OptionalSpace::parse(input)?;
|
||||
Some(input.state().ex_height())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(v) = v_or {
|
||||
let adjusted_fractional_part = v
|
||||
.xn_over_d(fractional_part.0, Scaled::ONE.0)
|
||||
.expect("n<d=Scaled::ONE, so overflow can't occur");
|
||||
return match v.nx_plus_y(integer_part, adjusted_fractional_part.0) {
|
||||
Ok(s) => Ok(s),
|
||||
Err(_) => handle_overflow(input, first_token, v < Scaled::ZERO),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Potentially adjust for the magnification ratio.
|
||||
if parse_keyword(input, "true")? {
|
||||
// TeX.2021.457
|
||||
// TODO
|
||||
}
|
||||
|
||||
// Finally try to scan unit constants.
|
||||
let scaled_unit = <common::ScaledUnit as Parsable>::parse(input)?;
|
||||
super::OptionalSpace::parse(input)?;
|
||||
match Scaled::new(integer_part, fractional_part, scaled_unit) {
|
||||
Ok(s) => Ok(s),
|
||||
Err(_) => handle_overflow(input, first_token, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_overflow<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
neg: bool,
|
||||
) -> txl::Result<common::Scaled> {
|
||||
input.error(
|
||||
parse::Error::new(
|
||||
"a dimension in the range (-2^14pt,2^14pt)",
|
||||
Some(first_token),
|
||||
"",
|
||||
)
|
||||
.with_got_override("a dimension that's too large"),
|
||||
)?;
|
||||
Ok(if neg {
|
||||
-common::Scaled::MAX_DIMEN
|
||||
} else {
|
||||
common::Scaled::MAX_DIMEN
|
||||
})
|
||||
}
|
||||
|
||||
fn fillll_error(token: token::Token) -> parse::Error {
|
||||
parse::Error::new("an infinite glue stretch or shrink order", Some(token), "")
|
||||
.with_got_override("too many l characters")
|
||||
}
|
||||
|
||||
impl Parsable for common::ScaledUnit {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
use common::ScaledUnit;
|
||||
for (keyword, unit) in [
|
||||
("pt", ScaledUnit::Point),
|
||||
("in", ScaledUnit::Inch),
|
||||
("pc", ScaledUnit::Pica),
|
||||
("cm", ScaledUnit::Centimeter),
|
||||
("mm", ScaledUnit::Millimeter),
|
||||
("bp", ScaledUnit::BigPoint),
|
||||
("dd", ScaledUnit::DidotPoint),
|
||||
("cc", ScaledUnit::Cicero),
|
||||
("sp", ScaledUnit::ScaledPoint),
|
||||
] {
|
||||
if parse_keyword(input, keyword)? {
|
||||
return Ok(unit);
|
||||
}
|
||||
}
|
||||
input.error(error::TODO())?;
|
||||
Ok(common::ScaledUnit::Point)
|
||||
}
|
||||
}
|
||||
|
||||
/// TeX.2021.452
|
||||
fn scan_decimal_fraction<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Scaled> {
|
||||
// We only get up to 17 digits, because further digits won't affect the result given
|
||||
// that the smallest scaled number is 2^(-16). This is very nice because it means
|
||||
// we don't need to allocate a vector to store the digits.
|
||||
let mut digits = [0_u8; 17];
|
||||
let mut i = 0_usize;
|
||||
while let Some(token) = input.next()? {
|
||||
let d: u8 = match token.value() {
|
||||
Value::Other('0') => 0,
|
||||
Value::Other('1') => 1,
|
||||
Value::Other('2') => 2,
|
||||
Value::Other('3') => 3,
|
||||
Value::Other('4') => 4,
|
||||
Value::Other('5') => 5,
|
||||
Value::Other('6') => 6,
|
||||
Value::Other('7') => 7,
|
||||
Value::Other('8') => 8,
|
||||
Value::Other('9') => 9,
|
||||
Value::Space(_) => {
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
};
|
||||
if let Some(digit) = digits.get_mut(i) {
|
||||
*digit = d;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok(Scaled::from_decimal_digits(&digits[0..i]))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DimenEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for DimenEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a dimension".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {}
|
||||
|
||||
parse_success_tests![
|
||||
(zero_pt, "0pt", Scaled::ZERO),
|
||||
(one_pt, "1pt", Scaled::ONE),
|
||||
(one_pt_negative, "-1pt", -Scaled::ONE),
|
||||
(two_pt, "2pt", Scaled::TWO),
|
||||
(empty_point, ".pt", Scaled::ZERO), // TeX.2021.452
|
||||
(fraction_1, "0.5pt", Scaled::from_decimal_digits(&[5])),
|
||||
(fraction_2, "-0.5pt", -Scaled::from_decimal_digits(&[5])),
|
||||
(
|
||||
fraction_3,
|
||||
"1.5pt",
|
||||
Scaled::ONE + Scaled::from_decimal_digits(&[5])
|
||||
),
|
||||
(
|
||||
fraction_4,
|
||||
"-1.5pt",
|
||||
-Scaled::ONE - Scaled::from_decimal_digits(&[5])
|
||||
),
|
||||
(units_in_1, "1in", (Scaled::ONE * 7227) / 100),
|
||||
(units_in_2, "1 in", (Scaled::ONE * 7227) / 100),
|
||||
(units_in_3, "0.075in", Scaled(355207)),
|
||||
(units_pc, "1pc", Scaled::ONE * 12),
|
||||
(units_cm, "1cm", (Scaled::ONE * 7227) / 254),
|
||||
(units_mm, "1mm", (Scaled::ONE * 7227) / 2540),
|
||||
(units_bp, "1bp", (Scaled::ONE * 7227) / 7200),
|
||||
(units_dd, "1dd", (Scaled::ONE * 1238) / 1157),
|
||||
(units_cc, "1cc", (Scaled::ONE * 14856) / 1157),
|
||||
(units_sp_1, "1sp", Scaled(1)),
|
||||
(units_sp_2, "1.999999sp", Scaled(1)),
|
||||
(nearly_overflow_pt, "16383.99998pt", Scaled::MAX_DIMEN,),
|
||||
// (2^30-1) * d / (n * 2^16)
|
||||
// (2^30-1) * d / (n * 2^16)
|
||||
// (nearly_overflow_in, "226.705406in", Scaled::MAX_DIMEN ),
|
||||
(nearly_overflow_sp_1, "1073741823sp", Scaled::MAX_DIMEN,),
|
||||
(
|
||||
nearly_overflow_sp_2,
|
||||
"1073741823.99999999sp",
|
||||
Scaled::MAX_DIMEN,
|
||||
)
|
||||
];
|
||||
|
||||
parse_failure_tests!(
|
||||
Scaled,
|
||||
State,
|
||||
(invalid_unit, "1xy", Scaled::ONE),
|
||||
(overflow_pt, "16384pt", Scaled::MAX_DIMEN),
|
||||
(overflow_pt_neg, "-16384pt", -Scaled::MAX_DIMEN),
|
||||
(overflow_in_1, "300in", Scaled::MAX_DIMEN),
|
||||
(overflow_in_2, "300000000in", Scaled::MAX_DIMEN),
|
||||
(overflow_in_3, "-300in", -Scaled::MAX_DIMEN),
|
||||
(overflow_in_4, "-300000000in", -Scaled::MAX_DIMEN),
|
||||
(overflow_sp, "1073741824sp", Scaled::MAX_DIMEN),
|
||||
(overflow_sp_neg, "-1073741824sp", -Scaled::MAX_DIMEN),
|
||||
);
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
//! File locations
|
||||
//!
|
||||
//! See section 511 of the TeXBook.
|
||||
|
||||
use std::path;
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
/// Representation of a file location in TeX
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
pub struct FileLocation {
|
||||
pub path: String,
|
||||
pub extension: Option<String>,
|
||||
pub area: Option<String>,
|
||||
}
|
||||
|
||||
impl Parsable for FileLocation {
|
||||
// scan_file_name
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let mut raw_string = String::new();
|
||||
let mut area_delimiter = None;
|
||||
let mut ext_delimiter = None;
|
||||
loop {
|
||||
let t = match input.next()? {
|
||||
None => break,
|
||||
Some(t) => t,
|
||||
};
|
||||
if let token::Value::Space(_) = t.value() {
|
||||
break;
|
||||
}
|
||||
let c = match t.char() {
|
||||
None => {
|
||||
input.back(t);
|
||||
break;
|
||||
}
|
||||
Some(c) => c,
|
||||
};
|
||||
match c {
|
||||
'>' | ':' => {
|
||||
area_delimiter = Some(raw_string.len() + 1);
|
||||
ext_delimiter = None;
|
||||
}
|
||||
'.' => {
|
||||
ext_delimiter = Some(raw_string.len());
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
raw_string.push(c);
|
||||
}
|
||||
|
||||
Ok(FileLocation {
|
||||
path: raw_string
|
||||
[area_delimiter.unwrap_or(0)..ext_delimiter.unwrap_or(raw_string.len())]
|
||||
.into(),
|
||||
extension: ext_delimiter.map(|j| raw_string[j + 1..].into()),
|
||||
area: area_delimiter.map(|i| raw_string[..i].into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl FileLocation {
|
||||
pub fn determine_full_path(
|
||||
&self,
|
||||
working_directory: Option<&path::Path>,
|
||||
default_extension: &str,
|
||||
) -> path::PathBuf {
|
||||
let mut path: path::PathBuf = match self.area {
|
||||
None => match working_directory {
|
||||
None => Default::default(),
|
||||
Some(working_directory) => working_directory.into(),
|
||||
},
|
||||
Some(_) => {
|
||||
// TODO: support file areas.
|
||||
// Probably we just need to extend the vm::FileSystem trait to accept areas.
|
||||
// Then in production TeX engines, we provide a map of areas to base path for
|
||||
// that area. There is still an error case when an undefined area is referenced.
|
||||
panic!("Texlang does not have support for file areas yet");
|
||||
}
|
||||
};
|
||||
path.push(std::ffi::OsString::from(&self.path));
|
||||
path.set_extension(std::ffi::OsString::from(
|
||||
self.extension.as_deref().unwrap_or(default_extension),
|
||||
));
|
||||
if !path.is_absolute() {
|
||||
panic!("TODO: handle this error (path is relative and no working directory set)");
|
||||
}
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
parse_success_tests![
|
||||
(
|
||||
path_only,
|
||||
"path/to/file",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_only_newline,
|
||||
"path/to/file\n",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_only_control_sequence,
|
||||
r"path/to/file\relax more",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_only_trailing_word,
|
||||
"path/to/file something",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
extension_only,
|
||||
".tex",
|
||||
FileLocation {
|
||||
path: "".to_string(),
|
||||
extension: Some("tex".to_string()),
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
empty,
|
||||
"",
|
||||
FileLocation {
|
||||
path: "".to_string(),
|
||||
extension: None,
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_extension,
|
||||
"path/to/file.tex",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: Some("tex".to_string()),
|
||||
area: None,
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_area_with_langle,
|
||||
"area>path/to/file",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: Some("area>".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_area_with_colon,
|
||||
"area:path/to/file",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: None,
|
||||
area: Some("area:".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
area_only,
|
||||
"area:",
|
||||
FileLocation {
|
||||
path: "".to_string(),
|
||||
extension: None,
|
||||
area: Some("area:".to_string()),
|
||||
},
|
||||
),
|
||||
(
|
||||
path_and_extension_and_area_with_colon,
|
||||
"area:path/to/file.tex",
|
||||
FileLocation {
|
||||
path: "path/to/file".to_string(),
|
||||
extension: Some("tex".to_string()),
|
||||
area: Some("area:".to_string()),
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
use common::{Glue, Scaled};
|
||||
|
||||
use super::keyword::parse_keyword;
|
||||
use crate::prelude as txl;
|
||||
use crate::token::Value;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
impl Parsable for Glue {
|
||||
// TeX.2021.461
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(value) = S::scan_glue(input)? {
|
||||
return Ok(value);
|
||||
}
|
||||
let negative = match super::integer::parse_optional_signs(input)? {
|
||||
None => 1,
|
||||
Some(_) => -1,
|
||||
};
|
||||
let first_token = input.next_or_err(GlueEndOfInputError {})?;
|
||||
let width = match first_token.value() {
|
||||
Value::CommandRef(command_ref) => {
|
||||
use super::integer::InternalNumber;
|
||||
match super::integer::parse_internal_number(input, first_token, command_ref)? {
|
||||
InternalNumber::Integer(i) => {
|
||||
super::dimen::scan_and_apply_units(
|
||||
input,
|
||||
first_token,
|
||||
i.abs(),
|
||||
Scaled::ZERO,
|
||||
None,
|
||||
)? * negative
|
||||
* i.signum()
|
||||
}
|
||||
InternalNumber::Dimen(d) => d * negative,
|
||||
InternalNumber::Glue(g) => {
|
||||
return Ok(g * negative);
|
||||
}
|
||||
InternalNumber::MuGlue(g) => {
|
||||
input.error(parse::Error::new(
|
||||
"ordinary glue",
|
||||
Some(first_token),
|
||||
"a muskip value cannot be used as an ordinary skip",
|
||||
))?;
|
||||
return Ok(g.0 * 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
input.back(first_token);
|
||||
common::Scaled::parse(input)? * negative
|
||||
}
|
||||
};
|
||||
|
||||
let mut g = Glue {
|
||||
width,
|
||||
..Default::default()
|
||||
};
|
||||
if parse_keyword(input, "plus")? {
|
||||
g.stretch = super::dimen::scan_dimen(input, Some(&mut g.stretch_order))?
|
||||
}
|
||||
if parse_keyword(input, "minus")? {
|
||||
g.shrink = super::dimen::scan_dimen(input, Some(&mut g.shrink_order))?
|
||||
};
|
||||
Ok(g)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GlueEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for GlueEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a glue".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
use common::GlueOrder;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {}
|
||||
|
||||
parse_success_tests![
|
||||
(
|
||||
width_1,
|
||||
"0pt",
|
||||
Glue {
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
width_2,
|
||||
"1pt",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
width_3,
|
||||
"-1pt",
|
||||
Glue {
|
||||
width: -Scaled::ONE,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_1,
|
||||
"1pt plus 1pt",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_fil,
|
||||
"1pt plus 1fil",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
stretch_order: GlueOrder::Fil,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_fill,
|
||||
"1pt plus 1fill",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
stretch_order: GlueOrder::Fill,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_filll,
|
||||
"1pt plus 1filll",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE,
|
||||
stretch_order: GlueOrder::Filll,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
];
|
||||
|
||||
parse_failure_tests!(
|
||||
Glue,
|
||||
State,
|
||||
(
|
||||
stretch_overflow_1,
|
||||
"1pt plus 30000000fil",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::MAX_DIMEN,
|
||||
stretch_order: GlueOrder::Fil,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_overflow_2,
|
||||
"1pt plus -30000000fil",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: -Scaled::MAX_DIMEN,
|
||||
stretch_order: GlueOrder::Fil,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
(
|
||||
stretch_fillll,
|
||||
"1pt plus 2fillll",
|
||||
Glue {
|
||||
width: Scaled::ONE,
|
||||
stretch: Scaled::ONE * 2,
|
||||
stretch_order: GlueOrder::Filll,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
);
|
||||
}
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
macro_rules! get_required_element {
|
||||
($stream :expr, $expected: expr, $guidance: expr, $($pat:pat => $result:expr,)+) => {
|
||||
// TODO: probably should call get_optional_element_with_token
|
||||
match ($stream).next()? {
|
||||
Some(token) => match token.value() {
|
||||
$(
|
||||
$pat => {
|
||||
Some($result)
|
||||
},
|
||||
)+
|
||||
_ => {
|
||||
$stream.error(crate::parse::Error::new($expected, Some(token), $guidance))?;
|
||||
$stream.back(token);
|
||||
None
|
||||
},
|
||||
}
|
||||
None => {
|
||||
$stream.error(crate::parse::Error::new($expected, None, $guidance))?;
|
||||
None
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! get_optional_element {
|
||||
($stream :expr, $($pat:pat => $result:expr,)+) => {
|
||||
match ($stream).next()? {
|
||||
None => None,
|
||||
Some(token) => match token.value() {
|
||||
$(
|
||||
$pat => Some($result),
|
||||
)+
|
||||
_ => {
|
||||
$stream.back(token);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! get_optional_element_with_token {
|
||||
($stream :expr, $($pat:pat => $result:expr,)+) => {
|
||||
match ($stream).next()? {
|
||||
None => None,
|
||||
Some(token) => match token.value() {
|
||||
$(
|
||||
$pat => {
|
||||
Some(($result, token))
|
||||
},
|
||||
)+
|
||||
_ => {
|
||||
$stream.back(token);
|
||||
None
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Vendored
+588
@@ -0,0 +1,588 @@
|
||||
//! Number parsing.
|
||||
//!
|
||||
//! The number may be octal, decimal, hexadecimal, cast from a character token, or read
|
||||
//! from an internal registers. The full definition of a number in the TeX grammar
|
||||
//! is given on page X of the TeXBook.
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::token::{CommandRef, Value};
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
impl Parsable for i32 {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(value) = S::scan_integer(input)? {
|
||||
return Ok(value);
|
||||
}
|
||||
let (_, i, _) = parse_integer(input)?;
|
||||
Ok(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for u8 {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let u = Uint::<256>::parse_impl(input)?;
|
||||
Ok(u.0.try_into().expect("smaller than 256 so in range"))
|
||||
}
|
||||
}
|
||||
/// When parsed, this type returns a nonnegative integer with the provided upper bound.
|
||||
///
|
||||
/// This type is used to implement the following parsing logic in TeX:
|
||||
///
|
||||
/// - TeX.2021.433 (scan_eight_bit_int) where N=256.
|
||||
/// - TeX.2021.434 (scan_char_num) where N=256.
|
||||
/// - TeX.2021.435 (scan_four_bit_int) where N=16.
|
||||
/// - TeX.2021.436 (scan_fifteen_bit_int) where N=2^15.
|
||||
/// - TeX.2021.437 (scan_twenty_seven_bit_int) where N=2^27.
|
||||
#[derive(Debug, PartialEq, Eq, Default)]
|
||||
pub struct Uint<const N: usize>(pub usize);
|
||||
|
||||
impl Uint<0> {
|
||||
pub const MAX: usize = i32::MAX as usize;
|
||||
}
|
||||
|
||||
impl<const N: usize> Parsable for Uint<N> {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let (first_token, i, _) = parse_integer(input)?;
|
||||
if i < 0 || i as usize >= N {
|
||||
input.error(OutOfBoundsError::<N> {
|
||||
first_token,
|
||||
got: i,
|
||||
})?;
|
||||
Ok(Uint(0))
|
||||
} else {
|
||||
Ok(Uint(i as usize))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OutOfBoundsError<const N: usize> {
|
||||
first_token: token::Token,
|
||||
got: i32,
|
||||
}
|
||||
|
||||
impl<const N: usize> error::TexError for OutOfBoundsError<N> {
|
||||
fn kind(&self) -> error::Kind {
|
||||
error::Kind::Token(self.first_token)
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
format!(
|
||||
"expected an integer in the range [0, {}), got {}",
|
||||
N, self.got
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for char {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let u1 = Uint::<{ char::MAX as usize }>::parse(input)?;
|
||||
let u2: u32 = u1.0.try_into().unwrap();
|
||||
Ok(char::from_u32(u2).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move to types/catcode.rs
|
||||
impl Parsable for types::CatCode {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let (token, i, _) = parse_integer(input)?;
|
||||
if let Ok(val_u8) = u8::try_from(i) {
|
||||
if let Ok(cat_code) = types::CatCode::try_from(val_u8) {
|
||||
return Ok(cat_code);
|
||||
}
|
||||
}
|
||||
input.error(parse::Error {
|
||||
expected: "a category code number (an integer in the range [0, 15])".into(),
|
||||
got: Some(token),
|
||||
got_override: format!["got the integer {i}"],
|
||||
annotation_override: "this is where the number started".into(),
|
||||
guidance: "".into(),
|
||||
additional_notes: vec![],
|
||||
})?;
|
||||
Ok(types::CatCode::try_from(0).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
const GUIDANCE_BEGINNING: &str =
|
||||
"a number begins with zero or more minus signs followed by one of the following:
|
||||
- A decimal digit (0-9), which begins a decimal number.
|
||||
- The character ', which indicates the beginning of an octal number
|
||||
- The character \", which indicates the beginning of a hexadecimal number
|
||||
- The character `, followed by a character token. The character is converted into its UTF-8 number.
|
||||
- A command that references a variable, like \\year.
|
||||
";
|
||||
|
||||
/// TeX.2021.440 (scan_int)
|
||||
pub(crate) fn parse_integer<S: TexlangState>(
|
||||
stream: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<(token::Token, i32, Option<u8>)> {
|
||||
let sign = parse_optional_signs(stream)?;
|
||||
let first_token = stream.next_or_err(NumberEndOfInputError {})?;
|
||||
let (result, radix) = match first_token.value() {
|
||||
Value::Other('0') => (parse_constant::<S, 10>(stream, 0)?, Some(10_u8)),
|
||||
Value::Other('1') => (parse_constant::<S, 10>(stream, 1)?, Some(10_u8)),
|
||||
Value::Other('2') => (parse_constant::<S, 10>(stream, 2)?, Some(10_u8)),
|
||||
Value::Other('3') => (parse_constant::<S, 10>(stream, 3)?, Some(10_u8)),
|
||||
Value::Other('4') => (parse_constant::<S, 10>(stream, 4)?, Some(10_u8)),
|
||||
Value::Other('5') => (parse_constant::<S, 10>(stream, 5)?, Some(10_u8)),
|
||||
Value::Other('6') => (parse_constant::<S, 10>(stream, 6)?, Some(10_u8)),
|
||||
Value::Other('7') => (parse_constant::<S, 10>(stream, 7)?, Some(10_u8)),
|
||||
Value::Other('8') => (parse_constant::<S, 10>(stream, 8)?, Some(10_u8)),
|
||||
Value::Other('9') => (parse_constant::<S, 10>(stream, 9)?, Some(10_u8)),
|
||||
Value::Other('\'') => (parse_constant::<S, 8>(stream, 0)?, Some(8_u8)),
|
||||
Value::Other('"') => (parse_constant::<S, 16>(stream, 0)?, Some(16_u8)),
|
||||
Value::Other('`') => (parse_character(stream)?, None),
|
||||
Value::CommandRef(command_ref) => (
|
||||
parse_internal_number(stream, first_token, command_ref)?.integer(),
|
||||
None,
|
||||
),
|
||||
// TeX.2021.446
|
||||
_ => {
|
||||
stream.back(first_token);
|
||||
stream.error(parse::Error::new(
|
||||
"the beginning of a number",
|
||||
Some(first_token),
|
||||
GUIDANCE_BEGINNING,
|
||||
))?;
|
||||
(0, None)
|
||||
}
|
||||
};
|
||||
let result = match sign {
|
||||
None => result,
|
||||
// The only i32 that is not safe to multiply by -1 is i32::MIN.
|
||||
// Experimentally we observe in this case that TeX wraps and the result
|
||||
// is i32::MIN again.
|
||||
Some(_) => result.wrapping_mul(-1),
|
||||
};
|
||||
Ok((first_token, result, radix))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum InternalNumber {
|
||||
Integer(i32),
|
||||
Dimen(common::Scaled),
|
||||
Glue(common::Glue),
|
||||
MuGlue(crate::types::MuGlue),
|
||||
}
|
||||
|
||||
impl InternalNumber {
|
||||
pub(crate) fn integer(&self) -> i32 {
|
||||
use InternalNumber::*;
|
||||
match self {
|
||||
Integer(i) => *i,
|
||||
Dimen(scaled) => scaled.0,
|
||||
Glue(glue) => glue.width.0,
|
||||
MuGlue(glue) => glue.0.width.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This function reimplements TeX.2021.413 (scan_something_internal) under the following
|
||||
/// conditions:
|
||||
///
|
||||
/// - level is int_val, dimen_val, glue_val or mu_val; i.e., the call to this function
|
||||
/// is looking for a number, not a token list or font. The token list or font cases
|
||||
/// are handled elsewhere.
|
||||
///
|
||||
/// - negative is false. The negative=true case is handled by the caller to this function.
|
||||
///
|
||||
/// - The logic around casting between types (i.e. TeX.2021.429) is omitted. Instead
|
||||
/// callers of this function perform the casting. The motivation is to make the code
|
||||
/// more explicit and avoid parameters that change logic and/or return types.
|
||||
pub(crate) fn parse_internal_number<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
first_token: token::Token,
|
||||
command_ref: CommandRef,
|
||||
) -> txl::Result<InternalNumber> {
|
||||
let cmd = input.commands_map().get_command(&command_ref);
|
||||
match cmd {
|
||||
Some(command::Command::Variable(cmd)) => {
|
||||
match cmd.clone().value(first_token, input)? {
|
||||
variable::ValueRef::Int(i) => Ok(InternalNumber::Integer(*i)),
|
||||
variable::ValueRef::SmallInt(c) => Ok(InternalNumber::Integer(*c as i32)),
|
||||
variable::ValueRef::CatCode(c) => Ok(InternalNumber::Integer(*c as i32)),
|
||||
variable::ValueRef::MathCode(c) => Ok(InternalNumber::Integer(c.0 as i32)),
|
||||
variable::ValueRef::Dimen(d) => Ok(InternalNumber::Dimen(*d)),
|
||||
variable::ValueRef::Glue(g) => Ok(InternalNumber::Glue(*g)),
|
||||
variable::ValueRef::MuGlue(g) => Ok(InternalNumber::MuGlue(*g)),
|
||||
variable::ValueRef::Font(_) => {
|
||||
// This case behaves identically to the TokenListCase
|
||||
todo!("scan a font into an int?");
|
||||
}
|
||||
variable::ValueRef::TokenList(_) => Err(input.fatal_error(
|
||||
parse::Error::new(
|
||||
"the beginning of a number",
|
||||
Some(first_token),
|
||||
GUIDANCE_BEGINNING,
|
||||
)
|
||||
.with_annotation_override("token list variable"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
Some(command::Command::Character(c)) => Ok(InternalNumber::Integer(*c as i32)),
|
||||
Some(command::Command::MathCharacter(c)) => Ok(InternalNumber::Integer(c.0 as i32)),
|
||||
Some(command::Command::UnicodeMathCharacter {
|
||||
class,
|
||||
family,
|
||||
character,
|
||||
}) => {
|
||||
let packed =
|
||||
(u32::from(*family) << 24) | (u32::from(*class) << 21) | (*character as u32);
|
||||
Ok(InternalNumber::Integer(packed as i32))
|
||||
}
|
||||
None
|
||||
| Some(
|
||||
command::Command::Execution(..)
|
||||
| command::Command::Expansion(..)
|
||||
| command::Command::Macro(..)
|
||||
| command::Command::CharacterTokenAlias(..)
|
||||
| command::Command::Font(..),
|
||||
) => {
|
||||
let err = parse::Error::new(
|
||||
"the beginning of a number",
|
||||
Some(first_token),
|
||||
GUIDANCE_BEGINNING,
|
||||
)
|
||||
.with_annotation_override(match cmd {
|
||||
None => "undefined control sequence".to_string(),
|
||||
Some(cmd) => format!["control sequence referencing {cmd}"],
|
||||
});
|
||||
input.expansions_mut().push(first_token);
|
||||
Err(input.fatal_error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NumberEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for NumberEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a number".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![GUIDANCE_BEGINNING.into()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses optional signs and spaces.
|
||||
///
|
||||
/// If the combination of the signs is positive, [None] is returned.
|
||||
/// Otherwise, the Token corresponding to the last negative sign is returned.
|
||||
///
|
||||
/// This is TeX.2021.441.
|
||||
pub fn parse_optional_signs<S: TexlangState>(
|
||||
stream: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Option<token::Token>> {
|
||||
let mut result = None;
|
||||
while let Some((sign, token)) = get_optional_element_with_token![
|
||||
stream,
|
||||
Value::Other('+') => true,
|
||||
Value::Other('-') => false,
|
||||
Value::Space(_) => true,
|
||||
] {
|
||||
result = match (result, sign) {
|
||||
(None, false) => Some(token),
|
||||
(Some(_), false) => None,
|
||||
(result, true) => result,
|
||||
};
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// TeX.2021.442
|
||||
fn parse_character<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<i32> {
|
||||
// BUG: should be from the unexpanded stream
|
||||
let c = {
|
||||
let token = input.next_or_err(CharacterError {})?;
|
||||
match token.value() {
|
||||
Value::CommandRef(token::CommandRef::ControlSequence(cs_name)) => {
|
||||
let name = input.vm().cs_name_interner().resolve(cs_name).unwrap();
|
||||
let mut iter = name.chars();
|
||||
match (iter.next(), iter.count()) {
|
||||
// (None, 0) => ?! TODO: add a test for this.
|
||||
// Should be something like:
|
||||
// \expandafter \i \expandafter ` \csname\endcsname
|
||||
(Some(c), 0) => c,
|
||||
_ => {
|
||||
input.error(parse::Error::new(
|
||||
"a character",
|
||||
Some(token),
|
||||
"a character is a character token or single-character control sequence like \\a",
|
||||
))?;
|
||||
'0'
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => token.char().unwrap(),
|
||||
}
|
||||
};
|
||||
super::OptionalSpace::parse(input)?;
|
||||
Ok(c as i32)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CharacterError;
|
||||
|
||||
impl error::EndOfInputError for CharacterError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a character".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![
|
||||
r"a character is a character token or single-character control sequence like \a".into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// TeX.2021.444-445
|
||||
// TODO: why is the radix a const parameter?
|
||||
fn parse_constant<S: TexlangState, const RADIX: i32>(
|
||||
stream: &mut vm::ExpandedStream<S>,
|
||||
mut result: i32,
|
||||
) -> txl::Result<i32> {
|
||||
let mut started = RADIX == 10;
|
||||
let mut too_big = false;
|
||||
loop {
|
||||
let next = match stream.next()? {
|
||||
None => break,
|
||||
Some(next) => next,
|
||||
};
|
||||
let lsd_or = match next.value() {
|
||||
token::Value::Other(c) => {
|
||||
let d = (c as u32).wrapping_sub('0' as u32);
|
||||
if d < 10 && d < (RADIX as u32) {
|
||||
Some(d as i32)
|
||||
} else if RADIX == 16 {
|
||||
let d = (c as u32).wrapping_sub('A' as u32);
|
||||
if d < 6 {
|
||||
Some(d as i32 + 10)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
token::Value::Letter(c) => {
|
||||
let d = (c as u32).wrapping_sub('A' as u32);
|
||||
if RADIX == 16 && d < 6 {
|
||||
Some(d as i32 + 10)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let lsd = match lsd_or {
|
||||
None => {
|
||||
stream.back(next);
|
||||
break;
|
||||
}
|
||||
Some(lsd) => lsd,
|
||||
};
|
||||
started = true;
|
||||
result = match add_lsd::<RADIX>(result, lsd) {
|
||||
Some(n) => n,
|
||||
None => {
|
||||
if !too_big {
|
||||
stream.error(add_lsd_error::<RADIX>(next, result, lsd))?;
|
||||
too_big = true;
|
||||
}
|
||||
i32::MAX
|
||||
}
|
||||
}
|
||||
}
|
||||
if !started {
|
||||
let (expected, guidance) = match RADIX {
|
||||
8 => {
|
||||
("an octal digit",
|
||||
"an octal digit is a token with value 0-7 and category other")
|
||||
},
|
||||
16 => {
|
||||
("a hexadecimal digit",
|
||||
"a hexadecimal digit is either:\n- A character token with value 0-9 and category other, or\n- A character token with value A-F and category letter or other")
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let got = stream.peek()?;
|
||||
stream.error(parse::Error::new(expected, got, guidance))?;
|
||||
}
|
||||
super::OptionalSpace::parse(stream)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn add_lsd<const RADIX: i32>(n: i32, lsd: i32) -> Option<i32> {
|
||||
match n.checked_mul(RADIX) {
|
||||
None => None,
|
||||
Some(n) => n.checked_add(lsd),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_lsd_error<const RADIX: i32>(token: token::Token, n: i32, lsd: i32) -> parse::Error {
|
||||
let (got, range) = match RADIX {
|
||||
8 => (
|
||||
format!["got '{n:o}{lsd:o}"],
|
||||
format!["'{:o}, '{:o}", i32::MIN, i32::MAX],
|
||||
),
|
||||
10 => (
|
||||
format!["got {n}{lsd}"],
|
||||
format!["{}, {}", i32::MIN, i32::MAX],
|
||||
),
|
||||
16 => (
|
||||
format!["got 0x{n:X}{lsd:X}"],
|
||||
format!["0x{:X}, 0x{:X}", i32::MIN, i32::MAX],
|
||||
),
|
||||
_ => panic!("radix must be 8, 10 or 16"),
|
||||
};
|
||||
parse::Error {
|
||||
expected: format!["a number in the range [{range}]"],
|
||||
got: Some(token),
|
||||
got_override: got,
|
||||
annotation_override: "this digit makes the number too big".into(),
|
||||
guidance: "".into(),
|
||||
additional_notes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
parse_success_tests![
|
||||
(octal_0, "'0", 0),
|
||||
(octal_1, "'1", 1),
|
||||
(octal_2, "'2", 2),
|
||||
(octal_3, "'3", 3),
|
||||
(octal_4, "'4", 4),
|
||||
(octal_5, "'5", 5),
|
||||
(octal_6, "'6", 6),
|
||||
(octal_7, "'7", 7),
|
||||
(octal_8, "'10", 8),
|
||||
(octal_9, "'11", 9),
|
||||
(octal_19, "'12", 10),
|
||||
(octal_11, "'13", 11),
|
||||
(octal_12, "'14", 12),
|
||||
(octal_13, "'15", 13),
|
||||
(octal_14, "'16", 14),
|
||||
(octal_15, "'17", 15),
|
||||
(octal_129, "'201", 129),
|
||||
(octal_max, "'17777777777", 2147483647),
|
||||
(octal_min, "-'17777777777", -2147483647),
|
||||
(decimal_0, "0", 0),
|
||||
(decimal_1, "1", 1),
|
||||
(decimal_2, "2", 2),
|
||||
(decimal_3, "3", 3),
|
||||
(decimal_4, "4", 4),
|
||||
(decimal_5, "5", 5),
|
||||
(decimal_6, "6", 6),
|
||||
(decimal_7, "7", 7),
|
||||
(decimal_8, "8", 8),
|
||||
(decimal_9, "9", 9),
|
||||
(decimal_10, "10", 10),
|
||||
(decimal_11, "11", 11),
|
||||
(decimal_12, "12", 12),
|
||||
(decimal_13, "13", 13),
|
||||
(decimal_14, "14", 14),
|
||||
(decimal_15, "15", 15),
|
||||
(decimal_16, "16", 16),
|
||||
(decimal_17, "17", 17),
|
||||
(decimal_18, "18", 18),
|
||||
(decimal_19, "19", 19),
|
||||
(decimal_1_with_0_padding, "00019", 19),
|
||||
(decimal_201, "201", 201),
|
||||
(decimal_max, "2147483647", 2147483647),
|
||||
(decimal_min, "-2147483647", -2147483647),
|
||||
(hexadecimal_0, "\"0", 0),
|
||||
(hexadecimal_1, "\"1", 1),
|
||||
(hexadecimal_2, "\"2", 2),
|
||||
(hexadecimal_3, "\"3", 3),
|
||||
(hexadecimal_4, "\"4", 4),
|
||||
(hexadecimal_5, "\"5", 5),
|
||||
(hexadecimal_6, "\"6", 6),
|
||||
(hexadecimal_7, "\"7", 7),
|
||||
(hexadecimal_8, "\"8", 8),
|
||||
(hexadecimal_9, "\"9", 9),
|
||||
(hexadecimal_10, "\"A", 10),
|
||||
(hexadecimal_11, "\"B", 11),
|
||||
(hexadecimal_12, "\"C", 12),
|
||||
(hexadecimal_13, "\"D", 13),
|
||||
(hexadecimal_14, "\"E", 14),
|
||||
(hexadecimal_15, "\"F", 15),
|
||||
(hexadecimal_16, "\"10", 16),
|
||||
(hexadecimal_17, "\"11", 17),
|
||||
(hexadecimal_18, "\"12", 18),
|
||||
(hexadecimal_19, "\"13", 19),
|
||||
(hexadecimal_20, "\"14", 20),
|
||||
(hexadecimal_21, "\"15", 21),
|
||||
(hexadecimal_22, "\"16", 22),
|
||||
(hexadecimal_23, "\"17", 23),
|
||||
(hexadecimal_24, "\"18", 24),
|
||||
(hexadecimal_25, "\"19", 25),
|
||||
(hexadecimal_26, "\"1A", 26),
|
||||
(hexadecimal_27, "\"1B", 27),
|
||||
(hexadecimal_28, "\"1C", 28),
|
||||
(hexadecimal_29, "\"1D", 29),
|
||||
(hexadecimal_30, "\"1E", 30),
|
||||
(hexadecimal_31, "\"1F", 31),
|
||||
(hexadecimal_513, "\"201", 513),
|
||||
(hexadecimal_max, "\"7FFFFFFF", 2147483647),
|
||||
(hexadecimal_min, "-\"7FFFFFFF", -2147483647),
|
||||
(number_from_character, "`A", 65),
|
||||
(number_from_length_1_control_sequence, r"`\A", 65),
|
||||
(number_from_character_non_ascii, "`ö", 0x00F6),
|
||||
(
|
||||
number_from_length_1_control_sequence_non_ascii,
|
||||
r"`\ö",
|
||||
0x00F6
|
||||
),
|
||||
(signs_plus, r"+4", 4),
|
||||
(signs_minus, r"-4", -4),
|
||||
(signs_plus_minus, r"+-4", -4),
|
||||
(signs_minus_minus, r"--4", 4),
|
||||
(signs_minus_minus_spaces, r" - - 4", 4),
|
||||
];
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {
|
||||
fn cat_code(&self, c: char) -> types::CatCode {
|
||||
if c == '9' {
|
||||
return types::CatCode::Letter;
|
||||
}
|
||||
types::CatCode::PLAIN_TEX_DEFAULTS
|
||||
.get(c as usize)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
parse_failure_tests![
|
||||
i32,
|
||||
State,
|
||||
(number_with_letter_catcode, "9"),
|
||||
(octal_too_big, "'177777777770", i32::MAX),
|
||||
(octal_empty, "'"),
|
||||
(decimal_too_big_1, "2147483648", i32::MAX),
|
||||
(decimal_too_big_2, "500000000000000", i32::MAX),
|
||||
(decimal_too_negative_1, "-2147483648", -1 * i32::MAX),
|
||||
(decimal_too_negative_2, "-5000000000000", -1 * i32::MAX),
|
||||
(hexadecimal_too_big, "\"7FFFFFFF0", i32::MAX),
|
||||
(hexadecimal_empty, "\""),
|
||||
(character, "A"),
|
||||
// TODO: the test is messed up because a space gets appended to the input
|
||||
// (character_missing, r"`", '0' as i32),
|
||||
(control_sequence_too_big, r"`\BC", '0' as i32),
|
||||
];
|
||||
|
||||
parse_failure_tests![
|
||||
Uint::<16>,
|
||||
State,
|
||||
(number_too_big, "16"),
|
||||
(number_is_negative, "-1"),
|
||||
];
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
use crate::prelude as txl;
|
||||
use crate::token;
|
||||
use crate::traits::*;
|
||||
use crate::vm;
|
||||
|
||||
/// Parses a keyword from the input stream.
|
||||
///
|
||||
/// TeX.2021.407 scan_keyword
|
||||
pub fn parse_keyword<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
keyword: &str,
|
||||
) -> txl::Result<bool> {
|
||||
let Some(c) = keyword.chars().next() else {
|
||||
// keyword is empty
|
||||
return Ok(true);
|
||||
};
|
||||
let Some(token) = input.next()? else {
|
||||
// input ended, keyword does not match
|
||||
return Ok(false);
|
||||
};
|
||||
if token.value() != token::Value::Letter(c.to_ascii_lowercase())
|
||||
&& token.value() != token::Value::Letter(c.to_ascii_uppercase())
|
||||
{
|
||||
input.back(token);
|
||||
return Ok(false);
|
||||
}
|
||||
// this character matched; now try to match the result of keyword
|
||||
let result = parse_keyword(input, &keyword[c.len_utf8()..]);
|
||||
if let Ok(false) = result {
|
||||
// some later character did not match, reverse consuming the token.
|
||||
input.back(token);
|
||||
}
|
||||
result
|
||||
}
|
||||
Vendored
+370
@@ -0,0 +1,370 @@
|
||||
//! Logic for parsing elements of the TeX grammar from token streams.
|
||||
//!
|
||||
//! This parsing module is based around the [Parsable] trait, which is the most important type in the module.
|
||||
//! This trait is implemented by Rust types that correspond to elements of the TeX grammar.
|
||||
//! The trait implementation provides a way to parse grammar elements out of the input stream.
|
||||
//!
|
||||
//! The module contains implementations of [Parsable] for tuples where each element is parsable.
|
||||
//! This allows expressions like `<integer><relation><integer>` to be parsed by one invocation
|
||||
//! of [Parsable::parse], in this case on the type `(i32, std::cmp::Ordering, i32)`.
|
||||
//!
|
||||
//! The second most important thing is the collection of custom Rust types like [OptionalEquals] and
|
||||
//! [FileLocation] which correspond to Rust grammar elements.
|
||||
//!
|
||||
//! Finally this module contains some functions for special situation like parsing lists of tokens.
|
||||
|
||||
#[macro_use]
|
||||
mod helpers;
|
||||
|
||||
mod dimen;
|
||||
mod filelocation;
|
||||
mod glue;
|
||||
mod integer;
|
||||
mod keyword;
|
||||
mod muglue;
|
||||
mod relation;
|
||||
#[cfg(test)]
|
||||
mod testing;
|
||||
mod variable;
|
||||
|
||||
pub use filelocation::FileLocation;
|
||||
pub use integer::Uint;
|
||||
pub use keyword::parse_keyword;
|
||||
pub use relation::Ordering;
|
||||
pub use variable::OptionalEquals;
|
||||
pub use variable::OptionalEqualsUnexpanded;
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::types::CatCode;
|
||||
use crate::*;
|
||||
|
||||
/// Implementations of this trait are elements of the TeX grammar than can be parsed from a stream of tokens.
|
||||
pub trait Parsable: Sized {
|
||||
/// Parses a value from an input stream.
|
||||
///
|
||||
/// This method just delegates to [Parsable::parse_impl].
|
||||
#[inline]
|
||||
fn parse<S: TexlangState, I>(input: &mut I) -> txl::Result<Self>
|
||||
where
|
||||
I: AsMut<vm::ExpandedStream<S>>,
|
||||
{
|
||||
Parsable::parse_impl(input.as_mut())
|
||||
}
|
||||
|
||||
/// Parses a value from the [vm::ExpandedStream].
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error {
|
||||
pub expected: String,
|
||||
pub got: Option<token::Token>,
|
||||
pub got_override: String,
|
||||
pub annotation_override: String,
|
||||
pub guidance: String,
|
||||
pub additional_notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl error::TexError for Error {
|
||||
fn kind(&self) -> error::Kind {
|
||||
match self.got {
|
||||
None => error::Kind::EndOfInput,
|
||||
Some(token) => error::Kind::Token(token),
|
||||
}
|
||||
}
|
||||
|
||||
fn title(&self) -> String {
|
||||
let got = if self.got_override.is_empty() {
|
||||
match self.got {
|
||||
None => "the input ended".to_string(),
|
||||
Some(token) => match token.value() {
|
||||
token::Value::Letter(c) => format!["found the letter {c}"],
|
||||
token::Value::Other(c) => format!["found a non-letter character {c}"],
|
||||
_ => match (token.char(), token.cat_code()) {
|
||||
(Some(c), Some(code)) => {
|
||||
format!["found a token with value {c} and category code {code}"]
|
||||
}
|
||||
_ => "found a control sequence".to_string(),
|
||||
},
|
||||
},
|
||||
}
|
||||
} else {
|
||||
self.got_override.clone()
|
||||
};
|
||||
format!["expected {}, instead {}", self.expected, got]
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![self.guidance.clone().into()]
|
||||
}
|
||||
|
||||
fn source_annotation(&self) -> String {
|
||||
if !self.annotation_override.is_empty() {
|
||||
return self.annotation_override.clone();
|
||||
}
|
||||
error::TexError::default_source_annotation(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
pub fn new<T: Into<String>, R: Into<String>>(
|
||||
expected: T,
|
||||
got: Option<token::Token>,
|
||||
guidance: R,
|
||||
) -> Self {
|
||||
Error {
|
||||
expected: expected.into(),
|
||||
got,
|
||||
got_override: "".into(),
|
||||
annotation_override: "".into(),
|
||||
guidance: guidance.into(),
|
||||
additional_notes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_got_override<T: Into<String>>(mut self, got_override: T) -> Self {
|
||||
self.got_override = got_override.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_annotation_override<T: Into<String>>(mut self, annotation_override: T) -> Self {
|
||||
self.annotation_override = annotation_override.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! generate_tuple_impls {
|
||||
( $first: ident ) => {};
|
||||
( $first: ident, $( $name: ident ),+ ) => {
|
||||
generate_tuple_impls![ $( $name ),+];
|
||||
|
||||
impl<$first : Parsable, $( $name : Parsable ),+> Parsable for ($first, $( $name ),+) {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
Ok(($first::parse(input)?, $( $name::parse(input)? ),+))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
generate_tuple_impls![T1, T2, T3, T4, T5];
|
||||
|
||||
impl Parsable for Option<token::CommandRef> {
|
||||
// TeX.2021.get_r_token
|
||||
// TeX.2021.1215
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// Implements get_r_token
|
||||
while let Some(found_equals) = get_optional_element![
|
||||
input.unexpanded(),
|
||||
token::Value::Space(_) => true,
|
||||
] {
|
||||
if found_equals {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ref_or = get_required_element![
|
||||
input.unexpanded(),
|
||||
"a control sequence or active character",
|
||||
"a command must be a control sequence or an active character",
|
||||
token::Value::CommandRef(command_ref) => command_ref,
|
||||
];
|
||||
Ok(ref_or)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LeftBrace;
|
||||
|
||||
impl Parsable for LeftBrace {
|
||||
// TeX.2021.403 scan_left_brace
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
get_required_element![
|
||||
input.unexpanded(),
|
||||
"an opening brace",
|
||||
"a balanced token list must start with an opening brace",
|
||||
token::Value::BeginGroup(_) => (),
|
||||
];
|
||||
Ok(LeftBrace {})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UnexpandedTokenList(pub Vec<token::Token>);
|
||||
|
||||
impl Parsable for UnexpandedTokenList {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let mut result = input.checkout_token_buffer();
|
||||
LeftBrace::parse(input)?;
|
||||
finish_parsing_balanced_tokens(input.unexpanded(), &mut result)?;
|
||||
Ok(UnexpandedTokenList(result))
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for Vec<token::Token> {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let mut result = input.checkout_token_buffer();
|
||||
let first_token = input.next_or_err(TokenStreamEndOfInputError {})?;
|
||||
let got = match first_token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match input.commands_map().get_command(&command_ref) {
|
||||
Some(command::Command::Variable(cmd)) => {
|
||||
if let crate::variable::ValueRef::TokenList(token_list) =
|
||||
cmd.clone().value(first_token, input)?
|
||||
{
|
||||
result.extend(token_list.iter());
|
||||
return Ok(result);
|
||||
};
|
||||
"a variable command of the wrong type (wanted a token list)"
|
||||
}
|
||||
Some(_) => "a command that is not a variable command",
|
||||
None => "an undefined command",
|
||||
}
|
||||
}
|
||||
token::Value::BeginGroup(_) => {
|
||||
finish_parsing_balanced_tokens(input, &mut result)?;
|
||||
return Ok(result);
|
||||
}
|
||||
_ => "a non-command, non-opening brace token",
|
||||
};
|
||||
input.return_token_buffer(result);
|
||||
Err(input.fatal_error(
|
||||
parse::Error::new(
|
||||
"an opening brace or a variable of type token list",
|
||||
Some(first_token),
|
||||
"",
|
||||
)
|
||||
.with_got_override(format!("got {got}"))
|
||||
.with_annotation_override(got),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TokenStreamEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for TokenStreamEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a token list".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses balanced tokens from the stream.
|
||||
///
|
||||
/// This function assumes the the initial opening brace has ready been consumed.
|
||||
/// It returns false if the input ends before balanced tokens completed.
|
||||
///
|
||||
/// This function is somewhat analogous to `scan_toks` in Knuth's TeX.
|
||||
/// For us the `xpand` parameter can be controlled by providing a different token stream.
|
||||
pub fn finish_parsing_balanced_tokens<S: vm::TokenStream>(
|
||||
stream: &mut S,
|
||||
result: &mut Vec<token::Token>,
|
||||
) -> txl::Result<()> {
|
||||
let mut scope_depth = 0;
|
||||
loop {
|
||||
let token = stream.next_or_err(TokenStreamEndOfInputError {})?;
|
||||
match token.value() {
|
||||
token::Value::BeginGroup(_) => {
|
||||
scope_depth += 1;
|
||||
}
|
||||
token::Value::EndGroup(_) => {
|
||||
if scope_depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
scope_depth -= 1;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
result.push(token);
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an arbitrary number of spaces from the input stream
|
||||
///
|
||||
/// TODO: we should audit all places Knuth uses this, and ensure we're using it too.
|
||||
///
|
||||
/// TeX.2021.406
|
||||
pub struct Spaces;
|
||||
|
||||
impl Parsable for Spaces {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Space(_) => {
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Spaces {})
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an arbitrary number of spaces from the unexpanded input stream
|
||||
pub struct SpacesUnexpanded;
|
||||
|
||||
impl Parsable for SpacesUnexpanded {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let input = input.unexpanded();
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Space(_) => {
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(SpacesUnexpanded {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for Option<char> {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let Some(token) = input.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let c = match token.value() {
|
||||
token::Value::BeginGroup(_)
|
||||
| token::Value::EndGroup(_)
|
||||
| token::Value::MathShift(_)
|
||||
| token::Value::AlignmentTab(_)
|
||||
| token::Value::Parameter(_)
|
||||
| token::Value::Superscript(_)
|
||||
| token::Value::Subscript(_)
|
||||
| token::Value::Space(_) => {
|
||||
input.back(token);
|
||||
return Ok(None);
|
||||
}
|
||||
token::Value::Letter(c) => c,
|
||||
token::Value::Other(c) => c,
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match input.commands_map().get_command(&command_ref) {
|
||||
Some(command::Command::Character(c)) => *c,
|
||||
_ => {
|
||||
input.back(token);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(Some(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an optional space from the token stream.
|
||||
pub struct OptionalSpace;
|
||||
|
||||
impl Parsable for OptionalSpace {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// TeX.2021.443
|
||||
if let Some(next) = input.next()? {
|
||||
if next.cat_code() != Some(CatCode::Space) {
|
||||
input.back(next);
|
||||
}
|
||||
}
|
||||
Ok(OptionalSpace {})
|
||||
}
|
||||
}
|
||||
Vendored
+136
@@ -0,0 +1,136 @@
|
||||
use common::{Glue, GlueOrder, Scaled, ScaledUnit};
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
use super::keyword::parse_keyword;
|
||||
|
||||
impl Parsable for types::MuGlue {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
if let Some(glue) = S::scan_mu_glue(input)? {
|
||||
return Ok(glue);
|
||||
}
|
||||
let negative = super::integer::parse_optional_signs(input)?.is_some();
|
||||
if let Some(first_token) = input.next()? {
|
||||
if let token::Value::CommandRef(command_ref) = first_token.value() {
|
||||
if let super::integer::InternalNumber::MuGlue(glue) =
|
||||
super::integer::parse_internal_number(input, first_token, command_ref)?
|
||||
{
|
||||
return Ok(if negative {
|
||||
types::MuGlue(glue.0 * -1)
|
||||
} else {
|
||||
glue
|
||||
});
|
||||
}
|
||||
}
|
||||
input.back(first_token);
|
||||
}
|
||||
let width = scan_mu_dimen(input, None)?;
|
||||
let mut glue = Glue {
|
||||
width,
|
||||
..Glue::default()
|
||||
};
|
||||
if parse_keyword(input, "plus")? {
|
||||
glue.stretch = scan_mu_dimen(input, Some(&mut glue.stretch_order))?;
|
||||
}
|
||||
if parse_keyword(input, "minus")? {
|
||||
glue.shrink = scan_mu_dimen(input, Some(&mut glue.shrink_order))?;
|
||||
}
|
||||
if negative {
|
||||
glue = glue * -1;
|
||||
}
|
||||
Ok(types::MuGlue(glue))
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_mu_dimen<S: TexlangState>(
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
mut glue_order: Option<&mut GlueOrder>,
|
||||
) -> txl::Result<Scaled> {
|
||||
let negative = super::integer::parse_optional_signs(input)?.is_some();
|
||||
let first_token = input.next_or_err(MuGlueEndOfInputError {})?;
|
||||
let (integer_part, fractional_part) = match first_token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
match super::integer::parse_internal_number(input, first_token, command_ref)? {
|
||||
super::integer::InternalNumber::MuGlue(glue) => {
|
||||
let width = glue.0.width;
|
||||
return Ok(if negative { -width } else { width });
|
||||
}
|
||||
super::integer::InternalNumber::Integer(value) => (value.abs(), Scaled::ZERO),
|
||||
_ => {
|
||||
input.error(parse::Error::new(
|
||||
"a math glue value",
|
||||
Some(first_token),
|
||||
"math glue assignments require values measured in mu",
|
||||
))?;
|
||||
return Ok(Scaled::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => super::dimen::scan_constant_dimen(input, first_token)?,
|
||||
};
|
||||
|
||||
let unit_found = match glue_order.as_deref_mut() {
|
||||
Some(order) if parse_keyword(input, "fil")? => {
|
||||
*order = GlueOrder::Fil;
|
||||
while let Some(token) = input.next()? {
|
||||
match token.value() {
|
||||
token::Value::Letter('l' | 'L') => match order.next() {
|
||||
Some(next) => *order = next,
|
||||
None => {
|
||||
input.error(parse::Error::new(
|
||||
"an infinite glue order",
|
||||
Some(token),
|
||||
"too many l characters in the glue order",
|
||||
))?;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
input.back(token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
super::OptionalSpace::parse(input)?;
|
||||
true
|
||||
}
|
||||
_ => {
|
||||
let found = parse_keyword(input, "mu")?;
|
||||
if found {
|
||||
super::OptionalSpace::parse(input)?;
|
||||
}
|
||||
found
|
||||
}
|
||||
};
|
||||
if !unit_found {
|
||||
input.error(parse::Error::new(
|
||||
"a math unit (mu)",
|
||||
Some(first_token),
|
||||
"muskip values require mu units",
|
||||
))?;
|
||||
return Ok(Scaled::ZERO);
|
||||
}
|
||||
|
||||
let value = match Scaled::new(integer_part, fractional_part, ScaledUnit::Point) {
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
input.error(parse::Error::new(
|
||||
"a math glue value in TeX's supported range",
|
||||
Some(first_token),
|
||||
"the value is too large",
|
||||
))?;
|
||||
Scaled::MAX_DIMEN
|
||||
}
|
||||
};
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MuGlueEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for MuGlueEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing math glue".into()
|
||||
}
|
||||
}
|
||||
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
//! Parsing of relations (<, = and >)
|
||||
//!
|
||||
//! A relation is defined on p209 of the TeXBook to be a character token with
|
||||
//! catcode 12 (other) and value <, = or >.
|
||||
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::{token, types, vm};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Ordering(pub std::cmp::Ordering);
|
||||
|
||||
impl Default for Ordering {
|
||||
fn default() -> Self {
|
||||
Ordering(std::cmp::Ordering::Equal)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parsable for Ordering {
|
||||
// TeX.2021.503
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
super::Spaces::parse(input)?;
|
||||
let ordering_or = get_required_element![
|
||||
input,
|
||||
"a relation",
|
||||
format!["a relation is a token with character code {} and one of the following values: <, =, >", types::CatCode::Other],
|
||||
token::Value::Other('<') => Ordering(std::cmp::Ordering::Less),
|
||||
token::Value::Other('=') => Ordering(std::cmp::Ordering::Equal),
|
||||
token::Value::Other('>') => Ordering(std::cmp::Ordering::Greater),
|
||||
];
|
||||
Ok(ordering_or.unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parse::testing::*;
|
||||
|
||||
parse_success_tests![
|
||||
(less_than_1, r"<a", Ordering(std::cmp::Ordering::Less)),
|
||||
(less_than_2, r"<a", Ordering(std::cmp::Ordering::Less)),
|
||||
(equals, r"=a", Ordering(std::cmp::Ordering::Equal)),
|
||||
(greater_than, r">a", Ordering(std::cmp::Ordering::Greater)),
|
||||
];
|
||||
|
||||
#[derive(Default)]
|
||||
struct State;
|
||||
|
||||
impl TexlangState for State {
|
||||
fn cat_code(&self, c: char) -> types::CatCode {
|
||||
if c == '<' {
|
||||
return types::CatCode::Letter;
|
||||
}
|
||||
types::CatCode::PLAIN_TEX_DEFAULTS
|
||||
.get(c as usize)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
parse_failure_tests![
|
||||
Ordering,
|
||||
State,
|
||||
(empty_input, ""),
|
||||
(letter, "a"),
|
||||
(control_sequence, r"\A"),
|
||||
(incorrect_catcode, "<"),
|
||||
];
|
||||
}
|
||||
Vendored
+121
@@ -0,0 +1,121 @@
|
||||
use crate::traits::*;
|
||||
use crate::types;
|
||||
use crate::vm;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub(crate) fn run_parse_success_test<S: TexlangState + Default, T: Parsable + Debug + Eq>(
|
||||
source: &str,
|
||||
want: T,
|
||||
) {
|
||||
let mut vm = vm::VM::<S>::new_with_built_in_commands(HashMap::new());
|
||||
vm.push_source("".to_string(), source.to_string()).unwrap();
|
||||
let input = vm::ExecutionInput::new(&mut vm);
|
||||
let got = T::parse(input).unwrap();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
pub(crate) fn run_parse_failure_test<S: TexlangState + Default, T: Parsable + Debug>(source: &str) {
|
||||
let mut vm = vm::VM::<S>::new_with_built_in_commands(HashMap::new());
|
||||
vm.push_source("".to_string(), source.to_string()).unwrap();
|
||||
let input = vm::ExecutionInput::new(&mut vm);
|
||||
let result = T::parse(input);
|
||||
if let Ok(value) = result {
|
||||
panic![
|
||||
"Successfully parsed a value '{value:?}' of type '{}' from invalid input '{source}'",
|
||||
std::any::type_name::<T>()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_parse_failure_recovery_test<
|
||||
S: TexlangState + Default,
|
||||
T: Parsable + Debug + Eq,
|
||||
>(
|
||||
source: &str,
|
||||
want: T,
|
||||
) {
|
||||
let mut vm = vm::VM::<WrappedState<S>>::new_with_built_in_commands(HashMap::new());
|
||||
vm.state.recover_from_errors = true;
|
||||
vm.push_source("".to_string(), source.to_string()).unwrap();
|
||||
let input = vm::ExecutionInput::new(&mut vm);
|
||||
let got = T::parse(input).unwrap();
|
||||
assert_eq!(got, want);
|
||||
let got_num_errors = *vm.state.num_errors.borrow();
|
||||
assert_eq!(
|
||||
got_num_errors, 1,
|
||||
"expected 1 TeX error, found {} TeX errors",
|
||||
got_num_errors
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WrappedState<S> {
|
||||
inner: S,
|
||||
recover_from_errors: bool,
|
||||
num_errors: RefCell<usize>,
|
||||
}
|
||||
|
||||
impl<S: TexlangState> TexlangState for WrappedState<S> {
|
||||
fn cat_code(&self, c: char) -> types::CatCode {
|
||||
self.inner.cat_code(c)
|
||||
}
|
||||
fn end_line_char(&self) -> Option<char> {
|
||||
self.inner.end_line_char()
|
||||
}
|
||||
fn recoverable_error_hook(
|
||||
&self,
|
||||
recoverable_error: crate::error::TracedTexError,
|
||||
) -> Result<(), Box<dyn crate::error::TexError>> {
|
||||
let mut num_errors = self.num_errors.borrow_mut();
|
||||
*num_errors = *num_errors + 1;
|
||||
if self.recover_from_errors {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(recoverable_error.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! parse_success_tests {
|
||||
($( ($name: ident, $input: expr, $expected: expr $(,)? ) ),+ $(,)? ) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
let source = $input;
|
||||
let want = $expected;
|
||||
run_parse_success_test::<(), _>(&source, want);
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use parse_success_tests;
|
||||
|
||||
macro_rules! parse_failure_tests {
|
||||
( $parsable_type: ty, $state: ty, $( ($name: ident, $input: expr $( , $want: expr )? ), )+) => {
|
||||
$(
|
||||
mod $name {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn recovery_disabled() {
|
||||
let input = $input;
|
||||
run_parse_failure_test::<$state, $parsable_type>(&input);
|
||||
}
|
||||
#[test]
|
||||
fn recovery_enabled() {
|
||||
let source = $input;
|
||||
#[allow(unused_mut,unused_assignments)]
|
||||
let mut want: $parsable_type = Default::default();
|
||||
$(
|
||||
want = $want;
|
||||
)?
|
||||
run_parse_failure_recovery_test::<$state, $parsable_type>(&source, want);
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use parse_failure_tests;
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
use crate::*;
|
||||
|
||||
/// When parsed, this type consumes an optional equals from the token stream.
|
||||
pub struct OptionalEquals;
|
||||
|
||||
impl Parsable for OptionalEquals {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// scan_optional_equals
|
||||
parse_optional_equals(input)?;
|
||||
Ok(OptionalEquals {})
|
||||
}
|
||||
}
|
||||
|
||||
/// When parsed, this type consumes an optional equals from the token stream without performing expansion.
|
||||
pub struct OptionalEqualsUnexpanded;
|
||||
|
||||
impl Parsable for OptionalEqualsUnexpanded {
|
||||
fn parse_impl<S: TexlangState>(input: &mut vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
parse_optional_equals(input.unexpanded())?;
|
||||
Ok(OptionalEqualsUnexpanded {})
|
||||
}
|
||||
}
|
||||
|
||||
// Corresponds to the `scan_optional_equals` procedure in Knuth's TeX (405)
|
||||
fn parse_optional_equals<S: TexlangState, I: TokenStream<S = S>>(input: &mut I) -> txl::Result<()> {
|
||||
while let Some(found_equals) = get_optional_element![
|
||||
input,
|
||||
token::Value::Other('=') => true,
|
||||
token::Value::Space(_) => false,
|
||||
] {
|
||||
if found_equals {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// TODO: this is not correct: this function should not scan spaces after the equals.
|
||||
// A separate routine corresponding to Knuth TeX 404 needs to be added and used instead
|
||||
// at the right call sites.
|
||||
while get_optional_element![
|
||||
input,
|
||||
token::Value::Space(_) => (),
|
||||
]
|
||||
.is_some()
|
||||
{}
|
||||
Ok(())
|
||||
}
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
//! Texlang prelude.
|
||||
//!
|
||||
//! This is just an idea.
|
||||
//! We may get rid of the prelude and just make all of the public
|
||||
//! aliases at the crate level.
|
||||
|
||||
/// Result type in Texlang.
|
||||
pub type Result<T> = std::result::Result<T, crate::vm::ShutdownSignal>;
|
||||
Vendored
+500
@@ -0,0 +1,500 @@
|
||||
//! Implementation of TeX user defined macros.
|
||||
|
||||
use crate::error;
|
||||
use crate::parse;
|
||||
use crate::prelude as txl;
|
||||
use crate::token;
|
||||
use crate::token::Token;
|
||||
use crate::token::Value;
|
||||
use crate::traits::*;
|
||||
use crate::vm;
|
||||
use texcraft_stdext::algorithms::substringsearch::Matcher;
|
||||
use texcraft_stdext::color::Colorize;
|
||||
|
||||
/// A TeX Macro.
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Macro {
|
||||
prefix: Vec<Token>,
|
||||
parameters: Vec<Parameter>,
|
||||
replacements: Vec<Replacement>,
|
||||
}
|
||||
|
||||
impl Macro {
|
||||
pub fn replacements(&self) -> &[Replacement] {
|
||||
&self.replacements
|
||||
}
|
||||
}
|
||||
|
||||
/// A token list or parameter in a replacement text.
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Replacement {
|
||||
/// A list of tokens.
|
||||
Tokens(Vec<Token>),
|
||||
|
||||
/// A parameter.
|
||||
///
|
||||
/// In order to be valid, the parameters index must be less than the number
|
||||
/// of parameters in the macro.
|
||||
Parameter(usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Parameter {
|
||||
Undelimited,
|
||||
Delimited(Matcher<Value>),
|
||||
/// An optional argument delimited by square brackets, with tokens to use
|
||||
/// when the argument is omitted.
|
||||
Optional { default: Vec<Token> },
|
||||
}
|
||||
|
||||
// Input type for macro hooks
|
||||
pub struct HookInput<'a, S> {
|
||||
pub vm: &'a vm::VM<S>,
|
||||
pub token: Token,
|
||||
pub tex_macro: &'a Macro,
|
||||
pub arguments: &'a [&'a [Token]],
|
||||
pub reverse_expansion: &'a [Token],
|
||||
}
|
||||
|
||||
pub fn no_op_hook<S>(_: HookInput<S>) {}
|
||||
|
||||
impl Macro {
|
||||
pub fn call<S: TexlangState>(
|
||||
&self,
|
||||
token: Token,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
) -> txl::Result<()> {
|
||||
let prefix_matched = remove_tokens_from_stream(&self.prefix, input.unexpanded())?;
|
||||
if !prefix_matched {
|
||||
return Ok(());
|
||||
}
|
||||
let mut argument_indices: Vec<(usize, usize)> = Default::default();
|
||||
let mut argument_tokens = input.checkout_token_buffer();
|
||||
for (i, parameter) in self.parameters.iter().enumerate() {
|
||||
let start_index = argument_tokens.len();
|
||||
let trim_outer_braces = parameter.parse_argument(input, i, &mut argument_tokens)?;
|
||||
let element = match trim_outer_braces {
|
||||
true => (start_index + 1, argument_tokens.len() - 1),
|
||||
false => (start_index, argument_tokens.len()),
|
||||
};
|
||||
argument_indices.push(element);
|
||||
}
|
||||
|
||||
let mut arguments: Vec<&[Token]> = Default::default();
|
||||
for (i, j) in &argument_indices {
|
||||
let slice = argument_tokens.get(*i..*j).unwrap();
|
||||
arguments.push(slice);
|
||||
}
|
||||
|
||||
let result = input.expansions_mut();
|
||||
let num_tokens = Macro::perform_replacement(&self.replacements, &arguments, result);
|
||||
|
||||
// To keep the borrow checker happy we need to downgrade result to a shared reference.
|
||||
let result = input.expansions();
|
||||
S::post_macro_expansion_hook(
|
||||
token,
|
||||
input,
|
||||
self,
|
||||
&arguments,
|
||||
&result[result.len() - num_tokens..result.len()],
|
||||
);
|
||||
|
||||
input.return_token_buffer(argument_tokens);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn doc(&self, interner: &token::CsNameInterner) -> String {
|
||||
let mut d = String::default();
|
||||
d.push_str("User defined macro\n\n");
|
||||
d.push_str(&format![
|
||||
"{}\n{}",
|
||||
"Parameters definition".italic(),
|
||||
pretty_print_prefix_and_parameters(&self.prefix, &self.parameters, interner),
|
||||
]);
|
||||
d.push_str(&format![
|
||||
"\n\n{} `{}`\n",
|
||||
"Replacement definition:".italic(),
|
||||
pretty_print_replacement_text(&self.replacements),
|
||||
]);
|
||||
d
|
||||
}
|
||||
|
||||
/// Create a new macro.
|
||||
pub fn new(
|
||||
prefix: Vec<Token>,
|
||||
parameters: Vec<Parameter>,
|
||||
replacement_text: Vec<Replacement>,
|
||||
) -> Macro {
|
||||
Macro {
|
||||
prefix,
|
||||
parameters,
|
||||
replacements: replacement_text,
|
||||
}
|
||||
}
|
||||
|
||||
fn perform_replacement(
|
||||
replacements: &[Replacement],
|
||||
arguments: &[&[Token]],
|
||||
result: &mut Vec<Token>,
|
||||
) -> usize {
|
||||
let mut output_size = 0;
|
||||
for replacement in replacements.iter() {
|
||||
output_size += match replacement {
|
||||
Replacement::Tokens(tokens) => tokens.len(),
|
||||
Replacement::Parameter(i) => arguments.get(*i).unwrap().len(),
|
||||
};
|
||||
}
|
||||
result.reserve(output_size);
|
||||
for replacement in replacements.iter().rev() {
|
||||
match replacement {
|
||||
Replacement::Tokens(tokens) => {
|
||||
result.extend(tokens);
|
||||
}
|
||||
Replacement::Parameter(i) => {
|
||||
result.extend(arguments.get(*i).unwrap().iter().rev().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
output_size
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameter {
|
||||
pub fn parse_argument<S: TexlangState>(
|
||||
&self,
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
index: usize,
|
||||
result: &mut Vec<Token>,
|
||||
) -> txl::Result<bool> {
|
||||
match self {
|
||||
Parameter::Undelimited => {
|
||||
Parameter::parse_undelimited_argument(input, index + 1, result)?;
|
||||
Ok(false)
|
||||
}
|
||||
Parameter::Delimited(matcher_factory) => Parameter::parse_delimited_argument(
|
||||
input.unexpanded(),
|
||||
matcher_factory,
|
||||
index + 1,
|
||||
result,
|
||||
),
|
||||
Parameter::Optional { default } => {
|
||||
Parameter::parse_optional_argument(input, index + 1, default, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optional_argument<S: TexlangState>(
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
param_num: usize,
|
||||
default: &[Token],
|
||||
result: &mut Vec<Token>,
|
||||
) -> txl::Result<bool> {
|
||||
let opening = loop {
|
||||
match input.unexpanded().next()? {
|
||||
Some(token) if matches!(token.value(), Value::Space(_)) => continue,
|
||||
Some(token) => break Some(token),
|
||||
None => break None,
|
||||
}
|
||||
};
|
||||
let Some(opening) = opening else {
|
||||
result.extend_from_slice(default);
|
||||
return Ok(false);
|
||||
};
|
||||
if !matches!(opening.value(), Value::Other('[')) {
|
||||
input.unexpanded().back(opening);
|
||||
result.extend_from_slice(default);
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut group_depth = 0usize;
|
||||
loop {
|
||||
let token = input
|
||||
.unexpanded()
|
||||
.next_or_err(OptionalArgumentEndOfInputError { param_num })?;
|
||||
match token.value() {
|
||||
Value::BeginGroup(_) => {
|
||||
group_depth += 1;
|
||||
result.push(token);
|
||||
}
|
||||
Value::EndGroup(_) if group_depth > 0 => {
|
||||
group_depth -= 1;
|
||||
result.push(token);
|
||||
}
|
||||
Value::EndGroup(_) => {
|
||||
return Err(input.unexpanded().fatal_error(error::SimpleTokenError::new(
|
||||
token,
|
||||
"unexpected closing group in optional macro argument",
|
||||
)));
|
||||
}
|
||||
Value::Other(']') if group_depth == 0 => return Ok(false),
|
||||
_ => result.push(token),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_delimited_argument<S: TexlangState>(
|
||||
stream: &mut vm::UnexpandedStream<S>,
|
||||
matcher_factory: &Matcher<Value>,
|
||||
param_num: usize,
|
||||
result: &mut Vec<Token>,
|
||||
) -> txl::Result<bool> {
|
||||
let mut matcher = matcher_factory.start();
|
||||
let mut scope_depth = 0;
|
||||
|
||||
// This handles the case of a macro whose argument ends with the special #{ tokens. In this special case the parsing
|
||||
// will end with a scope depth of 1, because the last token parsed will be the { and all braces before that will
|
||||
// be balanced.
|
||||
let closing_scope_depth = match matcher_factory.substring().last() {
|
||||
token::Value::BeginGroup(_) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
let start_index = result.len();
|
||||
loop {
|
||||
let token = stream.next_or_err(DelimitedArgumentEndOfInputError { param_num })?;
|
||||
match token.value() {
|
||||
token::Value::BeginGroup(_) => {
|
||||
scope_depth += 1;
|
||||
}
|
||||
token::Value::EndGroup(_) => {
|
||||
scope_depth -= 1;
|
||||
}
|
||||
_ => (),
|
||||
};
|
||||
let matches_delimiter = matcher.next(&token.value());
|
||||
result.push(token);
|
||||
if scope_depth == closing_scope_depth && matches_delimiter {
|
||||
// Remove the suffix.
|
||||
for _ in 0..matcher_factory.substring().len() {
|
||||
result.pop();
|
||||
}
|
||||
return Ok(Parameter::should_trim_outer_braces_if_present(
|
||||
&result[start_index..],
|
||||
));
|
||||
}
|
||||
}
|
||||
/*
|
||||
TODO
|
||||
.add_note(format![
|
||||
"this argument is delimited and must be suffixed by the tokens `{}`",
|
||||
matcher_factory.substring()
|
||||
]);
|
||||
if let Some(first_token) = result.first() {
|
||||
e = e.add_token_context(first_token, "the argument started here:");
|
||||
e = e.add_note(format![
|
||||
"{} tokens were read for the argument so far",
|
||||
result.len()
|
||||
]);
|
||||
} else {
|
||||
e = e.add_note("no tokens were read for the argument so far");
|
||||
}
|
||||
Err(e
|
||||
.add_token_context(macro_token, "the macro invocation started here:")
|
||||
.cast())
|
||||
*/
|
||||
}
|
||||
|
||||
fn should_trim_outer_braces_if_present(list: &[Token]) -> bool {
|
||||
if list.len() <= 1 {
|
||||
return false;
|
||||
}
|
||||
match list[0].value() {
|
||||
token::Value::BeginGroup(_) => (),
|
||||
_ => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
match list[list.len() - 1].value() {
|
||||
token::Value::EndGroup(_) => (),
|
||||
_ => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn parse_undelimited_argument<S: TexlangState>(
|
||||
input: &mut vm::ExpansionInput<S>,
|
||||
param_num: usize,
|
||||
result: &mut Vec<Token>,
|
||||
) -> txl::Result<()> {
|
||||
parse::SpacesUnexpanded::parse(input)?;
|
||||
let input = input.unexpanded();
|
||||
let token = input.next_or_err(UnDelimitedArgumentEndOfInputError { param_num })?;
|
||||
match token.value() {
|
||||
token::Value::BeginGroup(_) => token,
|
||||
_ => {
|
||||
result.push(token);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
parse::finish_parsing_balanced_tokens(input, result)?;
|
||||
Ok(())
|
||||
/* TODO
|
||||
.add_note(format![
|
||||
"this argument started with a `{opening_brace}` and must be finished with a matching closing brace"
|
||||
])
|
||||
.add_token_context(&opening_brace, "the argument started here:")
|
||||
.add_token_context(macro_token, "the macro invocation started here:")
|
||||
.cast()),
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DelimitedArgumentEndOfInputError {
|
||||
param_num: usize,
|
||||
}
|
||||
|
||||
impl error::EndOfInputError for DelimitedArgumentEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing a delimited argument for a macro".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![format!("this is argument number {} for this macro", self.param_num).into()]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct UnDelimitedArgumentEndOfInputError {
|
||||
param_num: usize,
|
||||
}
|
||||
|
||||
impl error::EndOfInputError for UnDelimitedArgumentEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing an undelimited argument for a macro".into()
|
||||
}
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![format!("this is argument number {} for this macro", self.param_num).into()]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OptionalArgumentEndOfInputError {
|
||||
param_num: usize,
|
||||
}
|
||||
|
||||
impl error::EndOfInputError for OptionalArgumentEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"parsing an optional argument for a macro".into()
|
||||
}
|
||||
|
||||
fn notes(&self) -> Vec<error::display::Note> {
|
||||
vec![format!("this is argument number {} for this macro", self.param_num).into()]
|
||||
}
|
||||
}
|
||||
|
||||
fn colored_parameter_number(n: usize) -> String {
|
||||
let color = match n {
|
||||
1 => |s: String| s.bright_yellow(),
|
||||
_ => |s: String| s.bright_blue(),
|
||||
};
|
||||
format![
|
||||
"{}{}",
|
||||
color("#".to_string()).bold(),
|
||||
color(n.to_string()).bold()
|
||||
]
|
||||
}
|
||||
|
||||
pub fn pretty_print_prefix_and_parameters(
|
||||
prefix: &[Token],
|
||||
parameters: &[Parameter],
|
||||
interner: &token::CsNameInterner,
|
||||
) -> String {
|
||||
let mut d = String::default();
|
||||
if prefix.is_empty() {
|
||||
d.push_str(" . No prefix\n");
|
||||
} else {
|
||||
d.push_str(&format![
|
||||
" . Prefix: `{}`\n",
|
||||
token::write_tokens(prefix, interner)
|
||||
]);
|
||||
}
|
||||
|
||||
d.push_str(&format![" . Parameters ({}):\n", parameters.len()]);
|
||||
for (i, parameter) in parameters.iter().enumerate() {
|
||||
let parameter_number = i + 1;
|
||||
match parameter {
|
||||
Parameter::Undelimited => {
|
||||
d.push_str(&format![
|
||||
" {}: undelimited\n",
|
||||
colored_parameter_number(parameter_number),
|
||||
]);
|
||||
}
|
||||
Parameter::Delimited(factory) => {
|
||||
d.push_str(&format![
|
||||
" {}: delimited by `{}`\n",
|
||||
colored_parameter_number(parameter_number),
|
||||
token::write_token_values(factory.substring(), interner)
|
||||
]);
|
||||
}
|
||||
Parameter::Optional { default } => {
|
||||
d.push_str(&format![
|
||||
" {}: optional, default `{}`\n",
|
||||
colored_parameter_number(parameter_number),
|
||||
token::write_tokens(default, interner),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
d.push_str(" . Full argument specification: `");
|
||||
d.push_str(&token::write_tokens(prefix, interner));
|
||||
for (i, parameter) in parameters.iter().enumerate() {
|
||||
let parameter_number = i + 1;
|
||||
d.push_str(&colored_parameter_number(parameter_number));
|
||||
match parameter {
|
||||
Parameter::Delimited(factory) => {
|
||||
d.push_str(token::write_token_values(factory.substring(), interner).as_str());
|
||||
}
|
||||
Parameter::Optional { .. } => d.push_str("[optional]"),
|
||||
Parameter::Undelimited => {}
|
||||
}
|
||||
}
|
||||
d.push('`');
|
||||
d
|
||||
}
|
||||
|
||||
pub fn pretty_print_replacement_text(replacements: &[Replacement]) -> String {
|
||||
let mut b = String::default();
|
||||
for replacement in replacements.iter() {
|
||||
match replacement {
|
||||
Replacement::Parameter(i) => {
|
||||
b.push_str(colored_parameter_number(*i + 1).as_str());
|
||||
}
|
||||
Replacement::Tokens(_) => {
|
||||
b.push_str("TODO");
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Removes the provided vector of tokens from the front of the stream.
|
||||
pub fn remove_tokens_from_stream<S: TexlangState>(
|
||||
tokens: &[Token],
|
||||
stream: &mut vm::UnexpandedStream<S>,
|
||||
) -> txl::Result<bool> {
|
||||
for prefix_token in tokens.iter() {
|
||||
let stream_token = stream.next_or_err(PrefixEndOfInputError {})?;
|
||||
if stream_token.value() != prefix_token.value() {
|
||||
stream.error(error::SimpleTokenError::new(
|
||||
stream_token,
|
||||
"unexpected token while matching the prefix for a user-defined macro",
|
||||
))?;
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PrefixEndOfInputError;
|
||||
|
||||
impl error::EndOfInputError for PrefixEndOfInputError {
|
||||
fn doing(&self) -> String {
|
||||
"matching the prefix of a user-defined macro".into()
|
||||
}
|
||||
}
|
||||
Vendored
+1246
File diff suppressed because it is too large.
Load diff
Vendored
+539
@@ -0,0 +1,539 @@
|
||||
//! TeX tokens and category codes.
|
||||
|
||||
pub mod lexer;
|
||||
pub mod trace;
|
||||
use crate::types::CatCode;
|
||||
use std::{fmt::Display, num};
|
||||
use texcraft_stdext::collections::interner;
|
||||
|
||||
/// String type used to represent control sequence names in Texlang.
|
||||
///
|
||||
/// The implementation of this type is opaque so that it can be performance optimized
|
||||
/// without worrying about downstream consumers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct CsName(num::NonZeroU32);
|
||||
|
||||
impl CsName {
|
||||
#[inline]
|
||||
pub fn to_usize(&self) -> usize {
|
||||
self.0.get() as usize
|
||||
}
|
||||
|
||||
pub fn try_from_usize(u: usize) -> Option<CsName> {
|
||||
let u = match u32::try_from(u) {
|
||||
Ok(u) => u,
|
||||
Err(_) => return None,
|
||||
};
|
||||
num::NonZeroU32::new(u).map(CsName)
|
||||
}
|
||||
}
|
||||
|
||||
/// String interner for control sequence names.
|
||||
pub type CsNameInterner = interner::Interner<CsName>;
|
||||
|
||||
impl interner::Key for CsName {
|
||||
fn try_from_usize(index: usize) -> Option<Self> {
|
||||
num::NonZeroU32::try_from_usize(index).map(CsName)
|
||||
}
|
||||
|
||||
fn into_usize(self) -> usize {
|
||||
self.0.into_usize()
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a token.
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum Value {
|
||||
BeginGroup(char),
|
||||
EndGroup(char),
|
||||
MathShift(char),
|
||||
AlignmentTab(char),
|
||||
Parameter(char),
|
||||
Superscript(char),
|
||||
Subscript(char),
|
||||
Space(char),
|
||||
Letter(char),
|
||||
Other(char),
|
||||
CommandRef(CommandRef),
|
||||
}
|
||||
|
||||
/// The value of a token that references a command
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum CommandRef {
|
||||
ControlSequence(CsName),
|
||||
ActiveCharacter(char),
|
||||
}
|
||||
|
||||
impl CommandRef {
|
||||
pub fn to_string(&self, cs_name_interner: &CsNameInterner) -> String {
|
||||
match self {
|
||||
CommandRef::ControlSequence(cs_name) => {
|
||||
format!("\\{}", cs_name_interner.resolve(*cs_name).unwrap())
|
||||
}
|
||||
CommandRef::ActiveCharacter(c) => format!("{c}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn new(c: char, cat_code: CatCode) -> Value {
|
||||
match cat_code {
|
||||
CatCode::BeginGroup => Value::BeginGroup(c),
|
||||
CatCode::EndGroup => Value::EndGroup(c),
|
||||
CatCode::MathShift => Value::MathShift(c),
|
||||
CatCode::AlignmentTab => Value::AlignmentTab(c),
|
||||
CatCode::Parameter => Value::Parameter(c),
|
||||
CatCode::Superscript => Value::Superscript(c),
|
||||
CatCode::Subscript => Value::Subscript(c),
|
||||
CatCode::Space => Value::Space(c),
|
||||
CatCode::Letter => Value::Letter(c),
|
||||
CatCode::Other => Value::Other(c),
|
||||
CatCode::Active => Value::CommandRef(CommandRef::ActiveCharacter(c)),
|
||||
_ => panic!("raw cat code not allowed"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn char(&self) -> Option<char> {
|
||||
Some(self.char_and_cat_code()?.0)
|
||||
}
|
||||
|
||||
pub fn cat_code(&self) -> Option<CatCode> {
|
||||
Some(self.char_and_cat_code()?.1)
|
||||
}
|
||||
|
||||
pub fn char_and_cat_code(&self) -> Option<(char, CatCode)> {
|
||||
let (c, code) = match self {
|
||||
Value::BeginGroup(c) => (c, CatCode::BeginGroup),
|
||||
Value::EndGroup(c) => (c, CatCode::EndGroup),
|
||||
Value::MathShift(c) => (c, CatCode::MathShift),
|
||||
Value::AlignmentTab(c) => (c, CatCode::AlignmentTab),
|
||||
Value::Parameter(c) => (c, CatCode::Parameter),
|
||||
Value::Superscript(c) => (c, CatCode::Superscript),
|
||||
Value::Subscript(c) => (c, CatCode::Subscript),
|
||||
Value::Space(c) => (c, CatCode::Space),
|
||||
Value::Letter(c) => (c, CatCode::Letter),
|
||||
Value::Other(c) => (c, CatCode::Other),
|
||||
Value::CommandRef(command_ref) => match command_ref {
|
||||
CommandRef::ControlSequence(_) => return None,
|
||||
CommandRef::ActiveCharacter(c) => (c, CatCode::Active),
|
||||
},
|
||||
};
|
||||
Some((*c, code))
|
||||
}
|
||||
}
|
||||
|
||||
/// A TeX token.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Token {
|
||||
value: Value,
|
||||
trace_key: trace::Key,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Token {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.value {
|
||||
Value::CommandRef(_) => {
|
||||
write![f, "todo"] // TODO
|
||||
}
|
||||
_ => {
|
||||
write![f, "{}", self.char().unwrap()]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! token_constructor {
|
||||
($name: ident, $value: expr) => {
|
||||
pub fn $name(c: char, trace_key: trace::Key) -> Token {
|
||||
Token {
|
||||
value: $value(c),
|
||||
trace_key,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl Token {
|
||||
token_constructor!(new_begin_group, Value::BeginGroup);
|
||||
token_constructor!(new_end_group, Value::EndGroup);
|
||||
token_constructor!(new_math_shift, Value::MathShift);
|
||||
token_constructor!(new_alignment_tab, Value::AlignmentTab);
|
||||
token_constructor!(new_parameter, Value::Parameter);
|
||||
token_constructor!(new_superscript, Value::Superscript);
|
||||
token_constructor!(new_subscript, Value::Subscript);
|
||||
token_constructor!(new_space, Value::Space);
|
||||
token_constructor!(new_letter, Value::Letter);
|
||||
token_constructor!(new_other, Value::Other);
|
||||
|
||||
pub fn new_command_ref(command_ref: CommandRef, trace_key: trace::Key) -> Token {
|
||||
Token {
|
||||
value: Value::CommandRef(command_ref),
|
||||
trace_key,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_active_character(c: char, trace_key: trace::Key) -> Token {
|
||||
Token {
|
||||
value: Value::CommandRef(CommandRef::ActiveCharacter(c)),
|
||||
trace_key,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_control_sequence(name: CsName, trace_key: trace::Key) -> Token {
|
||||
Token {
|
||||
value: Value::CommandRef(CommandRef::ControlSequence(name)),
|
||||
trace_key,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_from_value(value: Value, trace_key: trace::Key) -> Token {
|
||||
Token { value, trace_key }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn value(&self) -> Value {
|
||||
self.value
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn trace_key(&self) -> trace::Key {
|
||||
self.trace_key
|
||||
}
|
||||
|
||||
pub fn char(&self) -> Option<char> {
|
||||
self.value.char()
|
||||
}
|
||||
|
||||
pub fn cat_code(&self) -> Option<CatCode> {
|
||||
self.value.cat_code()
|
||||
}
|
||||
pub fn char_and_cat_code(&self) -> Option<(char, CatCode)> {
|
||||
self.value.char_and_cat_code()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
enum PendingWhitespace {
|
||||
#[default]
|
||||
NotStarted,
|
||||
None,
|
||||
Space,
|
||||
Newlines(usize),
|
||||
}
|
||||
|
||||
impl PendingWhitespace {
|
||||
fn reset(&mut self) {
|
||||
*self = PendingWhitespace::None;
|
||||
}
|
||||
|
||||
fn add_space(&mut self) {
|
||||
*self = match self {
|
||||
PendingWhitespace::NotStarted => PendingWhitespace::NotStarted,
|
||||
PendingWhitespace::None => PendingWhitespace::Space,
|
||||
PendingWhitespace::Space => PendingWhitespace::Space,
|
||||
PendingWhitespace::Newlines(n) => PendingWhitespace::Newlines(*n),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_newline(&mut self) {
|
||||
*self = match self {
|
||||
PendingWhitespace::NotStarted => PendingWhitespace::NotStarted,
|
||||
PendingWhitespace::None => PendingWhitespace::Newlines(1),
|
||||
PendingWhitespace::Space => PendingWhitespace::Newlines(1),
|
||||
PendingWhitespace::Newlines(n) => PendingWhitespace::Newlines(*n + 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_paragraph(&mut self) {
|
||||
*self = match self {
|
||||
PendingWhitespace::NotStarted => PendingWhitespace::NotStarted,
|
||||
PendingWhitespace::None | PendingWhitespace::Space | PendingWhitespace::Newlines(1) => {
|
||||
PendingWhitespace::Newlines(2)
|
||||
}
|
||||
PendingWhitespace::Newlines(n) => PendingWhitespace::Newlines(*n),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for PendingWhitespace {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PendingWhitespace::NotStarted | PendingWhitespace::None => Ok(()),
|
||||
PendingWhitespace::Space => {
|
||||
write!(f, " ")
|
||||
}
|
||||
PendingWhitespace::Newlines(n) => {
|
||||
for _ in 0..*n {
|
||||
writeln!(f)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Data structure for writing tokens
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Writer {
|
||||
pending_whitespace: PendingWhitespace,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// Write a token.
|
||||
pub fn write(
|
||||
&mut self,
|
||||
io_writer: &mut dyn std::io::Write,
|
||||
interner: &CsNameInterner,
|
||||
value: Value,
|
||||
) -> Result<(), std::io::Error> {
|
||||
match &value {
|
||||
Value::CommandRef(CommandRef::ControlSequence(s)) => {
|
||||
write!(
|
||||
io_writer,
|
||||
"{}\\{}",
|
||||
self.pending_whitespace,
|
||||
interner.resolve(*s).unwrap()
|
||||
)?;
|
||||
self.pending_whitespace.reset();
|
||||
}
|
||||
Value::Space(_) => self.pending_whitespace.add_space(),
|
||||
_ => {
|
||||
write!(
|
||||
io_writer,
|
||||
"{}{}",
|
||||
self.pending_whitespace,
|
||||
value.char().unwrap()
|
||||
)?;
|
||||
self.pending_whitespace.reset();
|
||||
}
|
||||
}
|
||||
io_writer.flush()
|
||||
}
|
||||
|
||||
pub fn add_newline(&mut self) {
|
||||
self.pending_whitespace.add_newline();
|
||||
}
|
||||
|
||||
pub fn start_paragraph(&mut self) {
|
||||
self.pending_whitespace.new_paragraph();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a collection of tokens to a string.
|
||||
pub fn write_tokens<'a, T>(tokens: T, interner: &CsNameInterner) -> String
|
||||
where
|
||||
T: IntoIterator<Item = &'a Token>,
|
||||
{
|
||||
let mut buffer: Vec<u8> = Default::default();
|
||||
let mut writer: Writer = Default::default();
|
||||
for token in tokens.into_iter() {
|
||||
writer.write(&mut buffer, interner, token.value()).unwrap();
|
||||
}
|
||||
std::str::from_utf8(&buffer).unwrap().into()
|
||||
}
|
||||
|
||||
/// Write a collection of token values to a string.
|
||||
pub fn write_token_values<'a, T>(values: T, interner: &CsNameInterner) -> String
|
||||
where
|
||||
T: IntoIterator<Item = &'a Value>,
|
||||
{
|
||||
let mut buffer: Vec<u8> = Default::default();
|
||||
let mut writer: Writer = Default::default();
|
||||
for value in values.into_iter() {
|
||||
writer.write(&mut buffer, interner, *value).unwrap();
|
||||
}
|
||||
std::str::from_utf8(&buffer).unwrap().into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
enum Instruction {
|
||||
ControlSequence(&'static str),
|
||||
Character(char, CatCode),
|
||||
Newline,
|
||||
NewParagraph,
|
||||
}
|
||||
|
||||
fn writer_test(input: Vec<Instruction>, want: &str) {
|
||||
let mut buffer: Vec<u8> = Default::default();
|
||||
let mut writer: Writer = Default::default();
|
||||
let mut interner = CsNameInterner::default();
|
||||
for pre_interned_token in input {
|
||||
match pre_interned_token {
|
||||
Instruction::ControlSequence(name) => {
|
||||
let cs_name = interner.get_or_intern(name);
|
||||
let token = Token::new_control_sequence(cs_name, trace::Key::dummy());
|
||||
writer.write(&mut buffer, &interner, token.value()).unwrap();
|
||||
}
|
||||
Instruction::Character(c, code) => {
|
||||
let token = Token::new_from_value(Value::new(c, code), trace::Key::dummy());
|
||||
writer.write(&mut buffer, &interner, token.value()).unwrap();
|
||||
}
|
||||
Instruction::Newline => {
|
||||
writer.add_newline();
|
||||
}
|
||||
Instruction::NewParagraph => {
|
||||
writer.start_paragraph();
|
||||
}
|
||||
};
|
||||
}
|
||||
let got: String = std::str::from_utf8(&buffer).unwrap().into();
|
||||
let want = want.to_string();
|
||||
|
||||
if got != want {
|
||||
println!("Output is different:");
|
||||
println!("------[got]-------");
|
||||
println!("{}", got);
|
||||
println!("------[want]------");
|
||||
println!("{}", want);
|
||||
println!("-----------------");
|
||||
panic!("write_tokens test failed");
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! write_tokens_tests {
|
||||
($( ($name: ident, $input: expr, $want: expr), )+) => {
|
||||
$(
|
||||
#[test]
|
||||
fn $name() {
|
||||
writer_test($input, $want);
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
write_tokens_tests!(
|
||||
(blank, vec!(), ""),
|
||||
(
|
||||
trim_whitespace_from_start,
|
||||
vec![
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
],
|
||||
"H"
|
||||
),
|
||||
(
|
||||
trim_whitespace_from_end,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
],
|
||||
"H"
|
||||
),
|
||||
(
|
||||
trim_whitespace_from_middle_1,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Character(' ', CatCode::Space),
|
||||
Instruction::Character(' ', CatCode::Space),
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H W"
|
||||
),
|
||||
(
|
||||
trim_whitespace_from_middle_2,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character(' ', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H W"
|
||||
),
|
||||
(
|
||||
trim_whitespace_from_middle_3,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('\n', CatCode::Space),
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H W"
|
||||
),
|
||||
(
|
||||
control_sequence,
|
||||
vec![Instruction::ControlSequence("HelloWorld"),],
|
||||
"\\HelloWorld"
|
||||
),
|
||||
(
|
||||
newline_1,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Newline,
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H\nW"
|
||||
),
|
||||
(
|
||||
newline_2,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Newline,
|
||||
Instruction::Character(' ', CatCode::Space),
|
||||
Instruction::Newline,
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H\n\nW"
|
||||
),
|
||||
(
|
||||
newline_3,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::Newline,
|
||||
Instruction::Character(' ', CatCode::Space),
|
||||
Instruction::Newline,
|
||||
Instruction::Character(' ', CatCode::Space),
|
||||
Instruction::Newline,
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H\n\n\nW"
|
||||
),
|
||||
(
|
||||
par_1,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::NewParagraph,
|
||||
Instruction::NewParagraph,
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H\n\nW"
|
||||
),
|
||||
(
|
||||
par_2,
|
||||
vec![
|
||||
Instruction::Character('H', CatCode::Letter),
|
||||
Instruction::NewParagraph,
|
||||
Instruction::NewParagraph,
|
||||
Instruction::NewParagraph,
|
||||
Instruction::Character('W', CatCode::Letter),
|
||||
],
|
||||
"H\n\nW"
|
||||
),
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn token_size() {
|
||||
assert_eq!(std::mem::size_of::<CommandRef>(), 8);
|
||||
assert_eq!(std::mem::size_of::<Value>(), 8);
|
||||
assert_eq!(std::mem::size_of::<Token>(), 12);
|
||||
assert_eq!(std::mem::size_of::<Result<Token, ()>>(), 12);
|
||||
assert_eq!(std::mem::size_of::<Result<Option<Token>, ()>>(), 12);
|
||||
assert_eq!(std::mem::size_of::<crate::prelude::Result<Token>>(), 12);
|
||||
assert_eq!(
|
||||
std::mem::size_of::<crate::prelude::Result<Option<Token>>>(),
|
||||
12
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+508
@@ -0,0 +1,508 @@
|
||||
//! Token tracing system
|
||||
//!
|
||||
//! This module implements a [Tracer] that determines the origins of tokens.
|
||||
//! When building helpful error messages we need to know the token came from -
|
||||
//! e.g., the file and line number.
|
||||
//! The tracing functionality here enables obtaining this information in the form of a [SourceCodeTrace].
|
||||
//!
|
||||
//! Rather than the custom system here,
|
||||
//! a simpler solution would be to include this information on the token itself.
|
||||
//! The token could include a line position number and a reference
|
||||
//! counting pointer to some data structure containing information about the line.
|
||||
//! The problem with this solution is that it makes the [Token] type very large, and
|
||||
//! this causes unacceptably poor performance in Texlang's tight inner loops.
|
||||
//! With the tracer here, each token only needs to hold onto a 32-bit [Key] which is enough
|
||||
//! to perform a full trace.
|
||||
//!
|
||||
//! # How the tracer works
|
||||
//!
|
||||
//! When adding source code to the input, the tracer is informed using the
|
||||
//! [register_source_code](Tracer::register_source_code) method.
|
||||
//! The tracer allocates a contiguous range of [Keys](Key) that is large enough
|
||||
//! to give each UTF-8 character in the input a unique key.
|
||||
//! These keys are returned using the opaque [KeyRange] type, which enables the caller to retrieve
|
||||
//! these keys.
|
||||
//! It is assumed that the caller will assign keys in order to each UTF-8 character in the source code.
|
||||
//!
|
||||
//! In addition to returning the range, the tracer associates the key range with the source code in an
|
||||
//! internal data structure.
|
||||
//!
|
||||
//! When tracing a token (using [trace](Tracer::trace)), the token's key is used to identify
|
||||
//! which key range the key came from.
|
||||
//! This key range is then used to identify the source code associated to the token.
|
||||
//! The difference between the token's key and the first key for the source code is the UTF-8 offset
|
||||
//! into the source code.
|
||||
//! Thus we can uniquely identify the UTF-8 character the token is a associated to.
|
||||
use crate::token::{CsNameInterner, Token, Value};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Bound::Included;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::CommandRef;
|
||||
|
||||
/// Key attached to tokens to enable tracing them.
|
||||
///
|
||||
/// This type is 32 bits.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Key(u32);
|
||||
|
||||
impl Key {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dummy() -> Key {
|
||||
Key(u32::MAX)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn as_u32(&self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Range of free keys that may be assigned to tokens.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct KeyRange {
|
||||
next: u32,
|
||||
limit: u32,
|
||||
}
|
||||
|
||||
impl KeyRange {
|
||||
/// Get the next trace [Key].
|
||||
///
|
||||
/// Panics if all of the keys in this range have been used.
|
||||
#[allow(clippy::should_implement_trait)]
|
||||
pub fn next(&mut self) -> Key {
|
||||
if self.next >= self.limit {
|
||||
panic!["requested more trace keys than are in the range"]
|
||||
}
|
||||
let n = self.next;
|
||||
self.next += 1;
|
||||
Key(n)
|
||||
}
|
||||
|
||||
/// Peek at the next trace [Key].
|
||||
///
|
||||
/// Panics if all of the keys in this range have been used.
|
||||
pub fn peek(&mut self) -> Key {
|
||||
if self.next >= self.limit {
|
||||
panic!["requested more trace keys than are in the range"]
|
||||
}
|
||||
Key(self.next)
|
||||
}
|
||||
|
||||
/// Advances the range forward by the provided offset.
|
||||
///
|
||||
/// Panics if the provided offset cannot be cast to u32.
|
||||
pub fn advance_by(&mut self, u: usize) {
|
||||
self.next = self.next.checked_add(u.try_into().unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyRange {
|
||||
pub fn empty() -> KeyRange {
|
||||
KeyRange { next: 0, limit: 0 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn for_testing() -> KeyRange {
|
||||
KeyRange {
|
||||
next: 0,
|
||||
limit: u32::MAX,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A token trace
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct SourceCodeTrace {
|
||||
/// Origin of the source code this token came from.
|
||||
pub origin: Origin,
|
||||
/// Content of the line this token came from.
|
||||
pub line_content: String,
|
||||
/// Number of the line within the file, starting at 1.
|
||||
pub line_number: usize,
|
||||
/// Index within the line that the token starts.
|
||||
pub index: usize,
|
||||
/// Value of the token.
|
||||
pub value: String,
|
||||
/// If this is for a token, the value of the token.
|
||||
/// Otherwise this is an end of input snippet.
|
||||
pub token: Option<Token>,
|
||||
}
|
||||
|
||||
/// Data structure that records information for token tracing
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Tracer {
|
||||
checkpoints: BTreeMap<u32, Checkpoint>,
|
||||
next_key: u32,
|
||||
line_number_offsets: BTreeMap<u32, usize>,
|
||||
|
||||
// A key use to get the last file that was inputted manually; i.e., not via an \input
|
||||
// or other command in a TeX file
|
||||
last_external_input: Option<u32>,
|
||||
}
|
||||
|
||||
/// Enum describing the possible origins of source code
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub enum Origin {
|
||||
File(PathBuf),
|
||||
Terminal,
|
||||
}
|
||||
|
||||
impl Tracer {
|
||||
/// Registers source code with the tracer.
|
||||
///
|
||||
/// The returned [KeyRange] should be used to assign [Keys](Key) to the tokens that
|
||||
/// are lexed from the referenced source code.
|
||||
/// The tracer assumes that the first key is assigned to token corresponding to the
|
||||
/// first UTF-8 character in their source code,
|
||||
/// the second key to the second UTF-8 character, and so on.
|
||||
pub fn register_source_code(
|
||||
&mut self,
|
||||
token: Option<Token>,
|
||||
origin: Origin,
|
||||
source_code: &str,
|
||||
) -> KeyRange {
|
||||
self.register_source_code_with_line_offset(token, origin, source_code, 0)
|
||||
}
|
||||
|
||||
/// Registers source code whose first line follows `line_number_offset` lines in its file.
|
||||
pub fn register_source_code_with_line_offset(
|
||||
&mut self,
|
||||
token: Option<Token>,
|
||||
origin: Origin,
|
||||
source_code: &str,
|
||||
line_number_offset: usize,
|
||||
) -> KeyRange {
|
||||
let first_key = self.next_key;
|
||||
let len = match u32::try_from(source_code.len()) {
|
||||
Err(_) => {
|
||||
panic!(
|
||||
"source code too big ({} bytes); max is 2^32={} bytes",
|
||||
source_code.len(),
|
||||
u32::MAX
|
||||
)
|
||||
}
|
||||
// For empty files, we still assign one key because this allows us to trace end of input errors.
|
||||
Ok(0) => 1_u32,
|
||||
// We add 1 to handle the case when the file does not end in a newline character. In this case
|
||||
// the extra key will be used to refer to a character added using the \endlinechar mechanism.
|
||||
Ok(limit) => limit + 1,
|
||||
};
|
||||
let range = KeyRange {
|
||||
next: self.next_key,
|
||||
limit: self.next_key + len,
|
||||
};
|
||||
self.checkpoints.insert(
|
||||
range.next,
|
||||
Checkpoint::SourceCode {
|
||||
origin,
|
||||
content: source_code.to_string(),
|
||||
},
|
||||
);
|
||||
self.line_number_offsets
|
||||
.insert(first_key, line_number_offset);
|
||||
if token.is_none() {
|
||||
self.last_external_input = Some(self.next_key);
|
||||
}
|
||||
self.next_key = range.limit;
|
||||
range
|
||||
}
|
||||
|
||||
/// Return a trace for the provided token.
|
||||
pub fn trace(&self, token: Token, cs_name_interner: &CsNameInterner) -> SourceCodeTrace {
|
||||
let value = match token.value() {
|
||||
Value::CommandRef(CommandRef::ControlSequence(cs_name)) => {
|
||||
format!["\\{}", cs_name_interner.resolve(cs_name).unwrap()]
|
||||
}
|
||||
// TODO: maybe have a cs or char method?
|
||||
_ => token.char().unwrap().to_string(),
|
||||
};
|
||||
|
||||
let (&first_key, checkpoint) = self
|
||||
.checkpoints
|
||||
.range((Included(&0), Included(&token.trace_key.0)))
|
||||
.next_back()
|
||||
.unwrap();
|
||||
|
||||
match checkpoint {
|
||||
Checkpoint::SourceCode { origin, content } => {
|
||||
let char_offset = (token.trace_key().0 - first_key) as usize;
|
||||
let mut line_number = 1;
|
||||
let mut byte_line_start = 0;
|
||||
let mut char_line_start = 0;
|
||||
for (char_index, (byte_index, c)) in content.char_indices().enumerate() {
|
||||
if char_index == char_offset {
|
||||
break;
|
||||
}
|
||||
if c == '\n' {
|
||||
byte_line_start = byte_index + 1;
|
||||
char_line_start = char_index + 1;
|
||||
line_number += 1;
|
||||
}
|
||||
}
|
||||
let position = char_offset - char_line_start;
|
||||
let tail = &content[byte_line_start..];
|
||||
let line_content = match tail.split_once('\n') {
|
||||
None => tail.to_string(),
|
||||
Some((a, _)) => a.to_string(),
|
||||
};
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content,
|
||||
line_number: line_number
|
||||
+ self.line_number_offsets.get(&first_key).copied().unwrap_or(0),
|
||||
index: position,
|
||||
value,
|
||||
token: Some(token),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trace_end_of_input(&self) -> SourceCodeTrace {
|
||||
let first_key = self.last_external_input.unwrap();
|
||||
let line_number_offset = self
|
||||
.line_number_offsets
|
||||
.get(&first_key)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
let f = self.checkpoints.get(&first_key).unwrap();
|
||||
match f {
|
||||
Checkpoint::SourceCode { origin, content } => {
|
||||
// (line index, byte index of first character)
|
||||
let mut last_line: (usize, usize) = (0, 0);
|
||||
let mut last_non_empty_line: (usize, usize) = (0, 0);
|
||||
for (i, c) in content.char_indices() {
|
||||
if !c.is_whitespace() {
|
||||
last_non_empty_line = last_line;
|
||||
} else if c == '\n' {
|
||||
last_line.0 += 1;
|
||||
last_line.1 = i + 1;
|
||||
}
|
||||
}
|
||||
let last_line = content[last_non_empty_line.1..].trim_end();
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: last_line.to_string(),
|
||||
line_number: last_non_empty_line.0 + 1 + line_number_offset,
|
||||
index: last_line.len(),
|
||||
value: " ".to_string(),
|
||||
token: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
enum Checkpoint {
|
||||
SourceCode {
|
||||
origin: Origin,
|
||||
content: String, // TODO: should be rc::Rc<str>?
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_source_code() {
|
||||
let file_name: PathBuf = "input.tex".into();
|
||||
let origin = Origin::File(file_name);
|
||||
let line_1 = "hël".to_string();
|
||||
let line_2 = "wor\\cömmand".to_string();
|
||||
let line_3 = "hël".to_string();
|
||||
let source_code = format!("{}\n{}\n{}", line_1, line_2, line_3);
|
||||
|
||||
let mut tracer: Tracer = Default::default();
|
||||
let mut interner: CsNameInterner = Default::default();
|
||||
let command = interner.get_or_intern("command");
|
||||
let mut range = tracer.register_source_code(None, origin.clone(), &source_code);
|
||||
let mut tokens = vec![
|
||||
Token::new_letter('h', range.next()),
|
||||
Token::new_letter('e', range.next()),
|
||||
Token::new_letter('l', range.next()),
|
||||
Token::new_space('\n', range.next()),
|
||||
Token::new_letter('w', range.next()),
|
||||
Token::new_letter('o', range.next()),
|
||||
Token::new_letter('r', range.next()),
|
||||
Token::new_control_sequence(command, range.next()),
|
||||
];
|
||||
for _ in 0.."command".len() {
|
||||
range.next();
|
||||
}
|
||||
let mut extra_tokens = vec![
|
||||
Token::new_space('\n', range.next()),
|
||||
Token::new_letter('h', range.next()),
|
||||
Token::new_letter('e', range.next()),
|
||||
Token::new_letter('l', range.next()),
|
||||
];
|
||||
tokens.append(&mut extra_tokens);
|
||||
|
||||
let got_traces: Vec<SourceCodeTrace> = tokens
|
||||
.iter()
|
||||
.map(|token| tracer.trace(*token, &interner))
|
||||
.collect();
|
||||
|
||||
let want_traces = vec![
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_1.clone(),
|
||||
line_number: 1,
|
||||
index: 0,
|
||||
value: "h".to_string(),
|
||||
token: Some(tokens[0]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_1.clone(),
|
||||
line_number: 1,
|
||||
index: 1,
|
||||
value: "e".to_string(),
|
||||
token: Some(tokens[1]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_1.clone(),
|
||||
line_number: 1,
|
||||
index: 2,
|
||||
value: "l".to_string(),
|
||||
token: Some(tokens[2]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_1.clone(),
|
||||
line_number: 1,
|
||||
index: 3,
|
||||
value: "\n".to_string(),
|
||||
token: Some(tokens[3]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_2.clone(),
|
||||
line_number: 2,
|
||||
index: 0,
|
||||
value: "w".to_string(),
|
||||
token: Some(tokens[4]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_2.clone(),
|
||||
line_number: 2,
|
||||
index: 1,
|
||||
value: "o".to_string(),
|
||||
token: Some(tokens[5]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_2.clone(),
|
||||
line_number: 2,
|
||||
index: 2,
|
||||
value: "r".to_string(),
|
||||
token: Some(tokens[6]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_2.clone(),
|
||||
line_number: 2,
|
||||
index: 3,
|
||||
value: "\\command".to_string(),
|
||||
token: Some(tokens[7]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_2.clone(),
|
||||
line_number: 2,
|
||||
index: 11,
|
||||
value: "\n".to_string(),
|
||||
token: Some(tokens[8]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_3.clone(),
|
||||
line_number: 3,
|
||||
index: 0,
|
||||
value: "h".to_string(),
|
||||
token: Some(tokens[9]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_3.clone(),
|
||||
line_number: 3,
|
||||
index: 1,
|
||||
value: "e".to_string(),
|
||||
token: Some(tokens[10]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: origin.clone(),
|
||||
line_content: line_3.clone(),
|
||||
line_number: 3,
|
||||
index: 2,
|
||||
value: "l".to_string(),
|
||||
token: Some(tokens[11]),
|
||||
},
|
||||
];
|
||||
assert_eq!(want_traces, got_traces);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_source_code() {
|
||||
let mut tokens = Vec::new();
|
||||
let mut tracer: Tracer = Default::default();
|
||||
let interner: CsNameInterner = Default::default();
|
||||
|
||||
let file_1 = Origin::File("a.tex".into());
|
||||
let file_1_content = "a".to_string();
|
||||
let mut range = tracer.register_source_code(None, file_1.clone(), &file_1_content);
|
||||
tokens.push(Token::new_letter('a', range.next()));
|
||||
|
||||
let file_2 = Origin::File("b.tex".into());
|
||||
let file_2_content = "b".to_string();
|
||||
let mut range = tracer.register_source_code(None, file_2.clone(), &file_2_content);
|
||||
tokens.push(Token::new_letter('b', range.next()));
|
||||
|
||||
let file_3 = Origin::Terminal;
|
||||
let file_3_content = "c".to_string();
|
||||
let mut range = tracer.register_source_code(None, file_3.clone(), &file_3_content);
|
||||
tokens.push(Token::new_letter('c', range.next()));
|
||||
|
||||
let got_traces: Vec<SourceCodeTrace> = tokens
|
||||
.iter()
|
||||
.map(|token| tracer.trace(*token, &interner))
|
||||
.collect();
|
||||
|
||||
let want_traces = vec![
|
||||
SourceCodeTrace {
|
||||
origin: file_1,
|
||||
line_content: file_1_content,
|
||||
line_number: 1,
|
||||
index: 0,
|
||||
value: "a".to_string(),
|
||||
token: Some(tokens[0]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: file_2,
|
||||
line_content: file_2_content,
|
||||
line_number: 1,
|
||||
index: 0,
|
||||
value: "b".to_string(),
|
||||
token: Some(tokens[1]),
|
||||
},
|
||||
SourceCodeTrace {
|
||||
origin: file_3,
|
||||
line_content: file_3_content,
|
||||
line_number: 1,
|
||||
index: 0,
|
||||
value: "c".to_string(),
|
||||
token: Some(tokens[2]),
|
||||
},
|
||||
];
|
||||
assert_eq!(want_traces, got_traces);
|
||||
}
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
pub use texrra_core::CatCode;
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
use crate::prelude as txl;
|
||||
use crate::{parse, traits::*};
|
||||
|
||||
pub use texrra_core::MathCode;
|
||||
|
||||
impl Parsable for MathCode {
|
||||
fn parse_impl<S: TexlangState>(input: &mut crate::vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
let raw = parse::Uint::<{ MathCode::MAX + 1 }>::parse(input)?;
|
||||
Ok(MathCode(raw.0.try_into().unwrap()))
|
||||
}
|
||||
}
|
||||
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
//! TeX types supported by Texlang
|
||||
|
||||
mod catcode;
|
||||
mod mathcode;
|
||||
mod muglue;
|
||||
use crate::command;
|
||||
use crate::parse;
|
||||
use crate::prelude as txl;
|
||||
use crate::traits::*;
|
||||
pub use catcode::CatCode;
|
||||
use common::font;
|
||||
pub use mathcode::MathCode;
|
||||
pub use muglue::MuGlue;
|
||||
|
||||
impl Parsable for font::Id {
|
||||
fn parse_impl<S: TexlangState>(input: &mut crate::vm::ExpandedStream<S>) -> txl::Result<Self> {
|
||||
// Corresponds to scan_font_ident in TeX.2021.577.
|
||||
match parse_font_or(input)? {
|
||||
None => {
|
||||
let token_or = input.peek()?;
|
||||
input.error(
|
||||
parse::Error::new(
|
||||
"a font reference",
|
||||
token_or,
|
||||
r"a font reference can either be the current font (e.g. \font), a font variable (e.g. \textfont 1) or the result of loading a font (e.g. \a after \font \a path/to/font)",
|
||||
)
|
||||
)?;
|
||||
Ok(font::Id::NULL)
|
||||
}
|
||||
Some(font) => Ok(font),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_font_or<S: TexlangState>(
|
||||
input: &mut crate::vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Option<font::Id>> {
|
||||
let Some(token) = input.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let crate::token::Value::CommandRef(command_ref) = token.value() else {
|
||||
input.back(token);
|
||||
return Ok(None);
|
||||
};
|
||||
match input.commands_map().get_command(&command_ref) {
|
||||
Some(command::Command::Font(f)) => {
|
||||
let f = *f;
|
||||
Ok(Some(f))
|
||||
}
|
||||
Some(command::Command::Variable(var)) => {
|
||||
let var = var.clone();
|
||||
match var.resolve_type::<font::Id>(token, input)? {
|
||||
None => {
|
||||
input.back(token);
|
||||
Ok(None)
|
||||
}
|
||||
Some(typed_variable) => Ok(Some(*typed_variable.get(input.state()))),
|
||||
}
|
||||
}
|
||||
Some(command::Command::Execution(_, Some(tag))) => {
|
||||
if input.state().is_current_font_command(*tag) {
|
||||
Ok(Some(input.vm().current_font()))
|
||||
} else {
|
||||
input.back(token);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
input.back(token);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
use common::Glue;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Glue whose dimensions are measured in math units.
|
||||
///
|
||||
/// The values in the wrapped glue are fixed point numbers where one is one mu.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct MuGlue(pub Glue);
|
||||
|
||||
impl Hash for MuGlue {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.0.width.hash(state);
|
||||
self.0.stretch.hash(state);
|
||||
(self.0.stretch_order as u8).hash(state);
|
||||
self.0.shrink.hash(state);
|
||||
(self.0.shrink_order as u8).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl MuGlue {
|
||||
pub fn wrapping_add(self, rhs: Self) -> Self {
|
||||
Self(self.0.wrapping_add(rhs.0))
|
||||
}
|
||||
|
||||
pub fn checked_add(self, rhs: Self) -> Option<Self> {
|
||||
Some(Self(self.0.checked_add(rhs.0)?))
|
||||
}
|
||||
|
||||
pub fn checked_mul(self, rhs: i32) -> Option<Self> {
|
||||
Some(Self(self.0.checked_mul(rhs)?))
|
||||
}
|
||||
|
||||
pub fn wrapping_mul(self, rhs: i32) -> Self {
|
||||
Self(self.0.wrapping_mul(rhs))
|
||||
}
|
||||
|
||||
pub fn checked_div(self, rhs: i32) -> Option<Self> {
|
||||
Some(Self(self.0.checked_div(rhs)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for MuGlue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}mu", self.0.width.display_no_units())?;
|
||||
if !self.0.stretch.is_zero() {
|
||||
write!(
|
||||
f,
|
||||
" plus {}{}",
|
||||
self.0.stretch.display_no_units(),
|
||||
self.0.stretch_order
|
||||
)?;
|
||||
}
|
||||
if !self.0.shrink.is_zero() {
|
||||
write!(
|
||||
f,
|
||||
" minus {}{}",
|
||||
self.0.shrink.display_no_units(),
|
||||
self.0.shrink_order
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Vendored
+829
@@ -0,0 +1,829 @@
|
||||
//! Texlang variables API
|
||||
//!
|
||||
//! The documentation website contains
|
||||
//! [a tutorial specifically about Texlang's variables API](https://texcraft.dev/texlang/07-variables.html).
|
||||
//! See that documentation for an overview of the API.
|
||||
//! As usual, the documentation here is meant as reference.
|
||||
|
||||
use crate::command;
|
||||
use crate::error;
|
||||
use crate::parse::OptionalEquals;
|
||||
use crate::prelude as txl;
|
||||
use crate::token;
|
||||
use crate::traits::*;
|
||||
use crate::types;
|
||||
use crate::vm;
|
||||
use common::font;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use texcraft_stdext::collections::groupingmap;
|
||||
|
||||
/// Function signature for a variable's immutable getter.
|
||||
///
|
||||
/// In Texcraft all [Variable]s are built from an immutable getter and a mutable getter.
|
||||
/// This type alias just defines the signature of immutable getters.
|
||||
/// The first argument is the state, and the second argument is the index of the variable.
|
||||
pub type RefFn<S, T> = fn(state: &S, index: Index) -> &T;
|
||||
|
||||
/// Function signature for a variable's mutable getters.
|
||||
///
|
||||
/// In Texcraft all [Variable]s are built from an immutable getter and a mutable getter.
|
||||
/// This type alias just defines the signature of mutable getters.
|
||||
/// The first argument is the state, and the second argument is the index of the variable.
|
||||
pub type MutRefFn<S, T> = fn(state: &mut S, index: Index) -> &mut T;
|
||||
|
||||
/// Index of a variable within an array.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||
pub struct Index(pub usize);
|
||||
|
||||
impl From<usize> for Index {
|
||||
fn from(value: usize) -> Self {
|
||||
Index(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Specification for how the index of an array variable is determined.
|
||||
///
|
||||
/// Obtaining a variable from a command involves determining the variable's [Index].
|
||||
/// This index is ultimately passed into the variable's getters to get a reference or mutable reference
|
||||
/// to the underlying Rust value.
|
||||
pub enum IndexResolver<S> {
|
||||
/// A static index, provided in the enum variant.
|
||||
///
|
||||
/// This resolver is used for commands that point to a specific entry in a array.
|
||||
/// For example, after executing `\countdef\A 30`, the `\A` control sequence points
|
||||
/// at the count register with index 30.
|
||||
/// The command backing `\A` uses a static resolver with index 30.
|
||||
Static(Index),
|
||||
/// A dynamic index that is determined by reading the input token stream.
|
||||
///
|
||||
/// For example, in `\count 4` the index of `4` is determined by parsing a number
|
||||
/// from the input token stream.
|
||||
Dynamic(fn(token::Token, &mut vm::ExpandedStream<S>) -> txl::Result<Index>),
|
||||
}
|
||||
|
||||
impl<S> IndexResolver<S> {
|
||||
/// Determine the index of a variable using the input token stream.
|
||||
fn resolve(
|
||||
&self,
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Index> {
|
||||
match self {
|
||||
IndexResolver::Static(addr) => Ok(*addr),
|
||||
// TODO: we should add support for propagation information here.
|
||||
// We need to add to the execution stack
|
||||
IndexResolver::Dynamic(f) => f(token, input),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A TeX variable command.
|
||||
///
|
||||
/// Variable commands are _resolved_ to obtain a [Variable].
|
||||
///
|
||||
/// A command consists of three parts.
|
||||
///
|
||||
/// The first two parts are an immutable getter (of type [RefFn])
|
||||
/// and a mutable getter (of type [MutRefFn]).
|
||||
/// Both of these getters accept a reference to the state (where the variable's value lives)
|
||||
/// and an [Index].
|
||||
/// The index can be used by the getters to return different values in memory.
|
||||
/// For example, if the getters read from an array, the index may be just the index in the array.
|
||||
/// This mechanism allows users of Texlang to write one pair of getters that can be used in many variables.
|
||||
///
|
||||
/// The third part of a command is an [IndexResolver] that is used to determine the aforementioned index
|
||||
/// of a variable at runtime.
|
||||
/// The process of resolving a command involves determining the [Index] and returning a [Variable] type,
|
||||
/// which under the hood is just the two getters and this index.
|
||||
pub struct Command<S> {
|
||||
getters: Getters<S>,
|
||||
index_resolver: Option<IndexResolver<S>>,
|
||||
use_vm_save_stack: bool,
|
||||
}
|
||||
|
||||
impl<S> Command<S> {
|
||||
/// Create a new variable command.
|
||||
pub fn new_singleton<T: SupportedType>(
|
||||
ref_fn: RefFn<S, T>,
|
||||
ref_mut_fn: MutRefFn<S, T>,
|
||||
) -> Command<S> {
|
||||
SupportedType::new_command(ref_fn, ref_mut_fn, None)
|
||||
}
|
||||
|
||||
/// Create a new variable command.
|
||||
pub fn new_array<T: SupportedType>(
|
||||
ref_fn: RefFn<S, T>,
|
||||
ref_mut_fn: MutRefFn<S, T>,
|
||||
index_resolver: IndexResolver<S>,
|
||||
) -> Command<S> {
|
||||
SupportedType::new_command(ref_fn, ref_mut_fn, Some(index_resolver))
|
||||
}
|
||||
|
||||
/// Create a singleton variable command whose grouping is managed by the state getters.
|
||||
///
|
||||
/// The mutable getter must record the previous value and restore it when the corresponding
|
||||
/// group ends. The VM will not add assignments to its own save stack.
|
||||
pub fn new_singleton_with_external_grouping<T: SupportedType>(
|
||||
ref_fn: RefFn<S, T>,
|
||||
ref_mut_fn: MutRefFn<S, T>,
|
||||
) -> Command<S> {
|
||||
let mut command = Self::new_singleton(ref_fn, ref_mut_fn);
|
||||
command.use_vm_save_stack = false;
|
||||
command
|
||||
}
|
||||
|
||||
/// Create an array variable command whose grouping is managed by the state getters.
|
||||
///
|
||||
/// The mutable getter must record the previous value and restore it when the corresponding
|
||||
/// group ends. The VM will not add assignments to its own save stack.
|
||||
pub fn new_array_with_external_grouping<T: SupportedType>(
|
||||
ref_fn: RefFn<S, T>,
|
||||
ref_mut_fn: MutRefFn<S, T>,
|
||||
index_resolver: IndexResolver<S>,
|
||||
) -> Command<S> {
|
||||
let mut command = Self::new_array(ref_fn, ref_mut_fn, index_resolver);
|
||||
command.use_vm_save_stack = false;
|
||||
command
|
||||
}
|
||||
|
||||
/// Create a new getter provider.
|
||||
///
|
||||
/// A getter provider is a variable command that is not intended to be invoked directly -
|
||||
/// in fact, the variable command will panic the program if it is invoked.
|
||||
/// Instead the provider is included in a VM's initial commands so that
|
||||
/// the VM has a reference to the getters inside the command.
|
||||
/// If a variable with the same getters is subsequently inserted into the commands map
|
||||
/// (for example, by a `\countdef` type command), the VM can still serialize that
|
||||
/// variable using the getters provided here.
|
||||
pub fn new_getter_provider<T: SupportedType>(
|
||||
ref_fn: RefFn<S, T>,
|
||||
ref_mut_fn: MutRefFn<S, T>,
|
||||
) -> Command<S> {
|
||||
SupportedType::new_command(
|
||||
ref_fn,
|
||||
ref_mut_fn,
|
||||
Some(IndexResolver::Dynamic(|_, _| panic!())),
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a command that points to a specific element in the array referenced by this command.
|
||||
pub(crate) fn new_array_element(&self, index: Index) -> Self {
|
||||
Self {
|
||||
getters: self.getters.clone(),
|
||||
index_resolver: Some(IndexResolver::Static(index)),
|
||||
use_vm_save_stack: self.use_vm_save_stack,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the variable command corresponds to arithmetic variable(s) (e.g. integer or glue).
|
||||
///
|
||||
/// TODO: we should just expose the type.
|
||||
pub fn is_arithmetic(&self) -> bool {
|
||||
match self.getters {
|
||||
Getters::Int(_, _)
|
||||
| Getters::SmallInt(_, _)
|
||||
| Getters::Dimen(_, _)
|
||||
| Getters::Glue(_, _)
|
||||
| Getters::MuGlue(_, _) => true,
|
||||
Getters::CatCode(_, _)
|
||||
| Getters::MathCode(_, _)
|
||||
| Getters::TokenList(_, _)
|
||||
| Getters::Font(_, _) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> Command<S> {
|
||||
/// Resolve the command to obtain a [Variable].
|
||||
pub fn resolve(
|
||||
&self,
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Variable<S>> {
|
||||
let index = match &self.index_resolver {
|
||||
None => Index(0),
|
||||
Some(index_resolver) => {
|
||||
input
|
||||
.vm_mut()
|
||||
.stack_push(token, error::OperationKind::VariableIndex);
|
||||
let err_or = index_resolver.resolve(token, input);
|
||||
input.vm_mut().stack_pop();
|
||||
err_or?
|
||||
}
|
||||
};
|
||||
Ok(new_variable(&self.getters, index, self.use_vm_save_stack))
|
||||
}
|
||||
|
||||
/// Resolve the command to obtain a [Variable] of a specific type.
|
||||
pub fn resolve_type<T: SupportedType>(
|
||||
&self,
|
||||
token: token::Token,
|
||||
input: &mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<Option<TypedVariable<S, T>>> {
|
||||
let Some((ref_fn, ref_mut_fn)) = T::try_cast(self) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let index = match &self.index_resolver {
|
||||
None => Index(0),
|
||||
Some(index_resolver) => index_resolver.resolve(token, input)?,
|
||||
};
|
||||
Ok(Some(TypedVariable {
|
||||
ref_fn,
|
||||
ref_mut_fn,
|
||||
index,
|
||||
use_vm_save_stack: self.use_vm_save_stack,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Command<S> {
|
||||
pub(crate) fn key(&self) -> CommandKey {
|
||||
let getters_key = self.getters.key();
|
||||
match &self.index_resolver {
|
||||
None => CommandKey::Singleton(getters_key, self.use_vm_save_stack),
|
||||
Some(index_resolver) => match index_resolver {
|
||||
IndexResolver::Static(a) => {
|
||||
CommandKey::ArrayStatic(getters_key, *a, self.use_vm_save_stack)
|
||||
}
|
||||
IndexResolver::Dynamic(f) => {
|
||||
CommandKey::ArrayDynamic(getters_key, *f as usize, self.use_vm_save_stack)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> Command<S> {
|
||||
/// Resolve the command to a variable and return the value of the variable.
|
||||
pub fn value<'a>(
|
||||
&self,
|
||||
token: token::Token,
|
||||
input: &'a mut vm::ExpandedStream<S>,
|
||||
) -> txl::Result<ValueRef<'a>> {
|
||||
Ok(self.resolve(token, input)?.value(input.state()))
|
||||
}
|
||||
|
||||
/// Resolve the command to a variable and set the value of the variable using the following tokens in the input stream.
|
||||
///
|
||||
/// This function is used in TeX code like `\variable = 3`.
|
||||
/// In this case `\variable` is a command which resolves to a variable without consuming any more input.
|
||||
/// The variable is populated using the input `= 3` that follows.
|
||||
pub(crate) fn set_value_using_input(
|
||||
&self,
|
||||
token: token::Token,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
scope: groupingmap::Scope,
|
||||
) -> txl::Result<()> {
|
||||
let variable = self.resolve(token, input.as_mut())?;
|
||||
input
|
||||
.vm_mut()
|
||||
.stack_push(token, error::OperationKind::VariableAssignment);
|
||||
let err_or = variable.set_value_using_input(input, scope);
|
||||
input.vm_mut().stack_pop();
|
||||
err_or
|
||||
}
|
||||
}
|
||||
|
||||
/// A key that uniquely identifies commands. If two commands have the same command key, they are the same command.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum CommandKey {
|
||||
Singleton(GettersKey, bool),
|
||||
ArrayStatic(GettersKey, Index, bool),
|
||||
ArrayDynamic(GettersKey, usize, bool),
|
||||
}
|
||||
|
||||
impl CommandKey {
|
||||
pub(crate) fn getter_key(&self) -> GettersKey {
|
||||
match self {
|
||||
CommandKey::Singleton(k, _) => *k,
|
||||
CommandKey::ArrayStatic(k, _, _) => *k,
|
||||
CommandKey::ArrayDynamic(k, _, _) => *k,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A key that uniquely identifies the getters ([RefFn] and [MutRefFn]) in a command or variable.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) struct GettersKey(usize, usize);
|
||||
|
||||
/// A TeX variable of a specific Rust type `T`.
|
||||
pub struct TypedVariable<S, T> {
|
||||
ref_fn: RefFn<S, T>,
|
||||
ref_mut_fn: MutRefFn<S, T>,
|
||||
index: Index,
|
||||
use_vm_save_stack: bool,
|
||||
}
|
||||
|
||||
impl<S, T> Copy for TypedVariable<S, T> {}
|
||||
|
||||
impl<S, T> Clone for TypedVariable<S, T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T> TypedVariable<S, T> {
|
||||
/// Returns an immutable reference to the variable's value.
|
||||
pub fn get<'a>(&self, state: &'a S) -> &'a T {
|
||||
(self.ref_fn)(state, self.index)
|
||||
}
|
||||
|
||||
fn key(&self) -> (usize, usize, Index, bool) {
|
||||
(
|
||||
self.ref_fn as usize,
|
||||
self.ref_mut_fn as usize,
|
||||
self.index,
|
||||
self.use_vm_save_stack,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T> TypedVariable<S, T>
|
||||
where
|
||||
S: TexlangState,
|
||||
T: SupportedType,
|
||||
{
|
||||
/// Sets the value of the variable.
|
||||
///
|
||||
/// The input and scope must be passed because of TeX's grouping semantics.
|
||||
/// When the current group ends, any variable assignments made in the group
|
||||
/// are rolled back.
|
||||
/// Thus this function generally saves the current value of the variable in the VM so that it
|
||||
/// can be restored later.
|
||||
/// This is why the full input must be provided, and not just the state.
|
||||
pub fn set(&self, input: &mut vm::ExecutionInput<S>, scope: groupingmap::Scope, value: T) {
|
||||
let r: &mut T = (self.ref_mut_fn)(input.state_mut(), self.index);
|
||||
let overwritten_value = std::mem::replace(r, value);
|
||||
// We guard the function call behind this conditional to make the current function small
|
||||
// to make it beneficial to inline it.
|
||||
if self.use_vm_save_stack && !input.groups().is_empty() {
|
||||
SupportedType::update_save_stack(input, self, scope, overwritten_value);
|
||||
} else {
|
||||
SupportedType::recycle(input, overwritten_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<S, T> TypedVariable<S, T>
|
||||
where
|
||||
S: TexlangState,
|
||||
T: SupportedType,
|
||||
{
|
||||
fn set_using_input(
|
||||
&self,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
scope: groupingmap::Scope,
|
||||
) -> txl::Result<()> {
|
||||
let (_, value) = <(OptionalEquals, T)>::parse(input)?;
|
||||
self.set(input, scope, value);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T> PartialEq for TypedVariable<S, T> {
|
||||
fn eq(&self, rhs: &TypedVariable<S, T>) -> bool {
|
||||
self.key() == rhs.key()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T> Eq for TypedVariable<S, T> {}
|
||||
|
||||
impl<S, T> Hash for TypedVariable<S, T> {
|
||||
fn hash<H>(&self, state: &mut H)
|
||||
where
|
||||
H: Hasher,
|
||||
{
|
||||
self.key().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait satisfied by all Rust types that can be used as TeX variables.
|
||||
///
|
||||
/// It exists to make the variables API more ergonomic.
|
||||
/// For example, it is used to provide a uniform constructor [Command::new_array] for commands.
|
||||
/// The trait cannot be implemented for new types.
|
||||
pub trait SupportedType: Sized + Debug + Parsable {
|
||||
/// Create a new command of this type with the provided reference functions and index resolver.
|
||||
fn new_command<S>(
|
||||
ref_fn: RefFn<S, Self>,
|
||||
ref_mut_fn: MutRefFn<S, Self>,
|
||||
index_resolver: Option<IndexResolver<S>>,
|
||||
) -> Command<S>;
|
||||
|
||||
/// Update the VM's save stack after a variable assignment.
|
||||
fn update_save_stack<S>(
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
variable: &TypedVariable<S, Self>,
|
||||
scope: groupingmap::Scope,
|
||||
overwritten_value: Self,
|
||||
) {
|
||||
(_, _, _, _) = (input, variable, scope, overwritten_value);
|
||||
}
|
||||
|
||||
/// Recycle a value that's about to be dropped.
|
||||
///
|
||||
/// This method is intended for token lists, in which case the vector is returned
|
||||
/// to the buffers pool.
|
||||
fn recycle<S>(input: &mut vm::ExecutionInput<S>, overwritten_value: Self) {
|
||||
(_, _) = (input, overwritten_value)
|
||||
}
|
||||
|
||||
/// Create a new typed variable of this type from the getters in the command and the provided index.
|
||||
///
|
||||
/// Return `None` if the command has a different type to `Self`.
|
||||
fn new_typed_variable<S>(command: &Command<S>, index: Index) -> Option<TypedVariable<S, Self>>;
|
||||
|
||||
/// Try to cast a variable command to this type.
|
||||
fn try_cast<S>(command: &Command<S>) -> Option<(RefFn<S, Self>, MutRefFn<S, Self>)>;
|
||||
}
|
||||
|
||||
/// This function is used to implement the [SupportedType::update_save_stack] method.
|
||||
///
|
||||
/// It's a bit janky to implement the logic as a free function, rather than, say, as
|
||||
/// a default trait implementation.
|
||||
/// The main problem is that the implementation calls into the save stack, which is an
|
||||
/// internal VM data structure.
|
||||
/// Any way that does this on the trait directly requires making some of the save stack
|
||||
/// type public, because [SupportedType] is public.
|
||||
fn update_save_stack<S, T: Clone + SupportedType, F>(
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
variable: &TypedVariable<S, T>,
|
||||
scope: groupingmap::Scope,
|
||||
overwritten_value: T,
|
||||
map_getter: F,
|
||||
) where
|
||||
F: Fn(&mut SaveStackElement<S>) -> &mut SaveStackMap<S, T>,
|
||||
{
|
||||
match scope {
|
||||
groupingmap::Scope::Global => {
|
||||
let n = input.groups().len();
|
||||
for _ in 0..n {
|
||||
let group = &mut input.groups()[0];
|
||||
if let Some(stale_value) = map_getter(group).remove(variable) {
|
||||
SupportedType::recycle(input, stale_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
groupingmap::Scope::Local => {
|
||||
if let Some((group, _)) = input.current_group_mut() {
|
||||
if let Some(stale_value) = map_getter(group).save(*variable, overwritten_value) {
|
||||
SupportedType::recycle(input, stale_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! supported_type_impl {
|
||||
( $(
|
||||
{
|
||||
rust_type: $rust_type: path,
|
||||
enum_variant: $enum_variant: ident,
|
||||
$( save_stack_field: $save_stack_field: ident, )?
|
||||
$( recycle_fn: $recycle_fn: ident, )?
|
||||
},
|
||||
)+ ) => {
|
||||
|
||||
/// Immutable reference to the value of a variable.
|
||||
pub enum ValueRef<'a> {
|
||||
$(
|
||||
$enum_variant(&'a $rust_type),
|
||||
)+
|
||||
}
|
||||
|
||||
/// TeX variable of any type.
|
||||
///
|
||||
/// A variable uniquely identifies a Rust value in the state, like an `i32`.
|
||||
/// Operations on this value (like reading or setting the value) can be done in two ways:
|
||||
///
|
||||
/// 1. (Easy, less flexible) Use the methods directly on this type like [Variable::value]
|
||||
/// to read the value.
|
||||
/// These methods are really ergonomic.
|
||||
/// The problem with the value method specifically is that the result
|
||||
/// is a reference which keeps the borrow of the state alive.
|
||||
/// Thus, while holding onto the result of the value, you can't do anything this the
|
||||
/// input stream like reading an argument.
|
||||
/// This is especially a problem when you need to perform a different action depending on the concrete type of the variable.
|
||||
///
|
||||
/// 2. (Trickier, more flexible) Match on the type's enum variants to determine the
|
||||
/// concrete type of the variable.
|
||||
/// The [TypedVariable] value obtained in this way can be used to perform operations on the value.
|
||||
/// The main benefit of this approach is that after matching on the type, you can still use the input
|
||||
/// stream to do things because there is not borrow alive.
|
||||
///
|
||||
pub enum Variable<S> {
|
||||
$(
|
||||
$enum_variant(TypedVariable<S, $rust_type>),
|
||||
)+
|
||||
}
|
||||
|
||||
fn new_variable<S>(getters: &Getters<S>, index: Index, use_vm_save_stack: bool) -> Variable<S> {
|
||||
match getters {
|
||||
$(
|
||||
Getters::$enum_variant(a, b) => Variable::$enum_variant(TypedVariable {
|
||||
ref_fn: *a,
|
||||
ref_mut_fn: *b,
|
||||
index,
|
||||
use_vm_save_stack,
|
||||
}),
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> Variable<S> {
|
||||
/// Return a reference to the value of the variable.
|
||||
pub fn value<'a>(&self, state: &'a S) -> ValueRef<'a> {
|
||||
match self {
|
||||
$(
|
||||
Variable::$enum_variant(variable) => ValueRef::$enum_variant(variable.get(state)),
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the value of a variable using the following tokens in the input stream.
|
||||
fn set_value_using_input(
|
||||
&self,
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
scope: groupingmap::Scope,
|
||||
) -> txl::Result<()> {
|
||||
match self {
|
||||
$(
|
||||
Variable::$enum_variant(variable) => variable.set_using_input(input, scope),
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Getters<S> {
|
||||
$(
|
||||
$enum_variant(RefFn<S, $rust_type>, MutRefFn<S, $rust_type>),
|
||||
)+
|
||||
}
|
||||
|
||||
impl<S> Clone for Getters<S> {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
$(
|
||||
Self::$enum_variant(a, b) => Self::$enum_variant(*a, *b),
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Getters<S> {
|
||||
fn key(&self) -> GettersKey {
|
||||
match self {
|
||||
$(
|
||||
Getters::$enum_variant(a, b) => GettersKey(*a as usize, *b as usize),
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$(
|
||||
impl SupportedType for $rust_type {
|
||||
fn new_command<S>(
|
||||
ref_fn: RefFn<S, Self>,
|
||||
ref_mut_fn: MutRefFn<S, Self>,
|
||||
index_resolver: Option<IndexResolver<S>>,
|
||||
) -> Command<S> {
|
||||
Command {
|
||||
getters: Getters::$enum_variant(ref_fn, ref_mut_fn),
|
||||
index_resolver,
|
||||
use_vm_save_stack: true,
|
||||
}
|
||||
}
|
||||
$(
|
||||
fn update_save_stack<S>(
|
||||
input: &mut vm::ExecutionInput<S>,
|
||||
variable: &TypedVariable<S, Self>,
|
||||
scope: groupingmap::Scope,
|
||||
overwritten_value: Self,
|
||||
) {
|
||||
update_save_stack(input, variable, scope, overwritten_value, |element| {
|
||||
&mut element.$save_stack_field
|
||||
})
|
||||
}
|
||||
)?
|
||||
$(
|
||||
fn recycle<S>(input: &mut vm::ExecutionInput<S>, overwritten_value: Self) {
|
||||
$recycle_fn(input, overwritten_value)
|
||||
}
|
||||
)?
|
||||
fn new_typed_variable<S>(
|
||||
command: &Command<S>,
|
||||
index: Index,
|
||||
) -> Option<TypedVariable<S, Self>> {
|
||||
match command.getters {
|
||||
Getters::$enum_variant(a, b) => Some(TypedVariable {
|
||||
ref_fn: a,
|
||||
ref_mut_fn: b,
|
||||
index,
|
||||
use_vm_save_stack: command.use_vm_save_stack,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn try_cast<S>(command: &Command<S>) -> Option<(RefFn<S, Self>, MutRefFn<S, Self>)> {
|
||||
match command.getters {
|
||||
Getters::$enum_variant(a, b) => Some((a,b)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
)+
|
||||
|
||||
/// Internal VM data structure used to implement TeX's grouping semantics.
|
||||
pub(crate) struct SaveStackElement<S> {
|
||||
$( $(
|
||||
$save_stack_field: SaveStackMap<S, $rust_type>,
|
||||
)? )+
|
||||
}
|
||||
|
||||
impl<S> Default for SaveStackElement<S> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
$( $(
|
||||
$save_stack_field: Default::default(),
|
||||
)? )+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> SaveStackElement<S> {
|
||||
pub(crate) fn restore(self, input: &mut vm::ExecutionInput<S>) {
|
||||
$( $(
|
||||
self.$save_stack_field.restore(input);
|
||||
)? )+
|
||||
}
|
||||
|
||||
pub(crate) fn serializable<'a>(
|
||||
&'a self,
|
||||
built_ins: &HashMap<GettersKey, token::CsName>,
|
||||
) -> SerializableSaveStackElement<'a> {
|
||||
SerializableSaveStackElement {
|
||||
$( $(
|
||||
$save_stack_field: self.$save_stack_field.serializable(built_ins),
|
||||
)? )+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
|
||||
pub(crate) struct SerializableSaveStackElement<'a> {
|
||||
$( $(
|
||||
$save_stack_field: Vec<(token::CsName, usize, Cow<'a, $rust_type>)>,
|
||||
)? )+
|
||||
}
|
||||
|
||||
impl<'a> SerializableSaveStackElement<'a> {
|
||||
pub(crate) fn finish_deserialization<S>(
|
||||
self,
|
||||
built_ins: &HashMap<token::CsName, command::BuiltIn<S>>,
|
||||
) -> SaveStackElement<S> {
|
||||
SaveStackElement {
|
||||
$( $(
|
||||
$save_stack_field: SaveStackMap::from_deserialized(self.$save_stack_field, built_ins),
|
||||
)? )+
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
supported_type_impl!(
|
||||
{
|
||||
rust_type: i32,
|
||||
enum_variant: Int,
|
||||
save_stack_field: i32,
|
||||
},
|
||||
{
|
||||
rust_type: u8,
|
||||
enum_variant: SmallInt,
|
||||
save_stack_field: u8,
|
||||
},
|
||||
{
|
||||
rust_type: common::Scaled,
|
||||
enum_variant: Dimen,
|
||||
save_stack_field: dimen,
|
||||
},
|
||||
{
|
||||
rust_type: common::Glue,
|
||||
enum_variant: Glue,
|
||||
save_stack_field: glue,
|
||||
},
|
||||
{
|
||||
rust_type: types::MuGlue,
|
||||
enum_variant: MuGlue,
|
||||
save_stack_field: mu_glue,
|
||||
},
|
||||
{
|
||||
rust_type: types::CatCode,
|
||||
enum_variant: CatCode,
|
||||
save_stack_field: catcode,
|
||||
},
|
||||
{
|
||||
rust_type: types::MathCode,
|
||||
enum_variant: MathCode,
|
||||
save_stack_field: math_code,
|
||||
},
|
||||
{
|
||||
rust_type: Vec<token::Token>,
|
||||
enum_variant: TokenList,
|
||||
save_stack_field: token_list,
|
||||
recycle_fn: recycle_token_list,
|
||||
},
|
||||
{
|
||||
rust_type: font::Id,
|
||||
enum_variant: Font,
|
||||
save_stack_field: font,
|
||||
},
|
||||
// {
|
||||
// rust_type: FontParam,
|
||||
// enum_variant: FontParam,
|
||||
// // no save_stack_field because font params are global
|
||||
// }
|
||||
);
|
||||
|
||||
fn recycle_token_list<S>(input: &mut vm::ExecutionInput<S>, overwritten_value: Vec<token::Token>) {
|
||||
input.return_token_buffer(overwritten_value);
|
||||
}
|
||||
|
||||
/// Internal VM data structure used to implement TeX's grouping semantics.
|
||||
struct SaveStackMap<S, T>(HashMap<TypedVariable<S, T>, T>);
|
||||
|
||||
impl<S, T> Default for SaveStackMap<S, T> {
|
||||
fn default() -> Self {
|
||||
Self(HashMap::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T: Clone + SupportedType> SaveStackMap<S, T> {
|
||||
fn save(&mut self, variable: TypedVariable<S, T>, value: T) -> Option<T> {
|
||||
match self.0.entry(variable) {
|
||||
std::collections::hash_map::Entry::Occupied(_) => Some(value),
|
||||
std::collections::hash_map::Entry::Vacant(v) => {
|
||||
v.insert(value);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, variable: &TypedVariable<S, T>) -> Option<T> {
|
||||
self.0.remove(variable)
|
||||
}
|
||||
|
||||
fn restore(self, input: &mut vm::ExecutionInput<S>) {
|
||||
for (v, restored_value) in self.0 {
|
||||
let dest = (v.ref_mut_fn)(input.state_mut(), v.index);
|
||||
let overwritten_value = std::mem::replace(dest, restored_value);
|
||||
SupportedType::recycle(input, overwritten_value);
|
||||
}
|
||||
}
|
||||
|
||||
fn serializable<'a>(
|
||||
&'a self,
|
||||
built_ins: &HashMap<GettersKey, token::CsName>,
|
||||
) -> Vec<(token::CsName, usize, Cow<'a, T>)> {
|
||||
self.0
|
||||
.iter()
|
||||
.map(|(typed_variable, value): (&TypedVariable<S, T>, &T)| {
|
||||
let key = GettersKey(
|
||||
typed_variable.ref_fn as usize,
|
||||
typed_variable.ref_mut_fn as usize,
|
||||
);
|
||||
let cs_name = built_ins.get(&key).unwrap();
|
||||
(*cs_name, typed_variable.index.0, Cow::Borrowed(value))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T: SupportedType + Clone> SaveStackMap<S, T> {
|
||||
fn from_deserialized<'a>(
|
||||
deserialized: Vec<(token::CsName, usize, Cow<'a, T>)>,
|
||||
built_ins: &HashMap<token::CsName, command::BuiltIn<S>>,
|
||||
) -> Self {
|
||||
let m = deserialized
|
||||
.into_iter()
|
||||
.map(
|
||||
|(cs_name, index, value): (token::CsName, usize, Cow<'a, T>)| {
|
||||
// TODO: surface error here
|
||||
let built_in = built_ins.get(&cs_name).unwrap();
|
||||
let typed_variable = match built_in.cmd() {
|
||||
command::Command::Variable(variable_command) => {
|
||||
// TODO: error instead of unwrap
|
||||
SupportedType::new_typed_variable(variable_command, Index(index))
|
||||
.unwrap()
|
||||
}
|
||||
_ => panic!("wrong type of built in TODO return an error here"),
|
||||
};
|
||||
(typed_variable, value.into_owned())
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
Self(m)
|
||||
}
|
||||
}
|
||||
Vendored
+1271
File diff suppressed because it is too large.
Load diff
Vendored
+127
@@ -0,0 +1,127 @@
|
||||
//! Serialization and deserialization of VMs
|
||||
//!
|
||||
//! Texcraft's documentation website has a
|
||||
//! [dedicated page about serializing and deserializing VMs](https://texcraft.dev/texlang/11-serde.html).
|
||||
//! The documentation here is for reference.
|
||||
//!
|
||||
//! ## Serialization
|
||||
//!
|
||||
//! If the state type `S` implements [`::serde::Serialize`] then
|
||||
//! the Texlang VM `vm::V<S>` satisfies the [`::serde::Serialize`] trait too.
|
||||
//! VMs can thus be serialized using the standard Serde infrastructure.
|
||||
//!
|
||||
//! ## Deserialization
|
||||
//!
|
||||
//! If the state `S` implements [`::serde::Deserialize`] and
|
||||
//! the Texlang trait [`super::HasDefaultBuiltInCommands`],
|
||||
//! the Texlang VM `vm::V<S>` satisfies the [`::serde::Deserialize`] trait too.
|
||||
//!
|
||||
//! If the state doesn't implement the Texlang trait, deserialization is slightly more complicated
|
||||
//! because the set of built-in primitives needs to be provided at deserialization time.
|
||||
//! This is because the built-in primitives which are regular Rust functions,
|
||||
//! and it is not possible to fully serialize and deserialize Rust functions.
|
||||
//! Deserialization of VMs is thus a two-step process:
|
||||
//!
|
||||
//! 1. Deserialize the bytes to a [`DeserializedVM`] type.
|
||||
//!
|
||||
//! 2. Invoke [`finish_deserialization`] with the deserialized VM
|
||||
//! and a map of built-in commands in order to recover the regular Texlang VM.
|
||||
//!
|
||||
//! The Texlang VM has a [`deserialize_with_built_in_commands` convenience method](super::VM::deserialize_with_built_in_commands)
|
||||
//! which performs both of these steps at once.
|
||||
|
||||
use crate::*;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct SerializableVM<'a, S> {
|
||||
state: &'a S,
|
||||
commands_map: &'a command::Map<S>,
|
||||
internal: &'a vm::Internal<S>,
|
||||
save_stack: Vec<variable::SerializableSaveStackElement<'a>>,
|
||||
}
|
||||
|
||||
impl<'a, S> SerializableVM<'a, S> {
|
||||
fn new(vm: &'a vm::VM<S>) -> Self {
|
||||
let variable_key_to_built_in = vm.commands_map.getters_key_to_built_in();
|
||||
Self {
|
||||
state: &vm.state,
|
||||
commands_map: &vm.commands_map,
|
||||
internal: &vm.internal,
|
||||
save_stack: vm
|
||||
.internal
|
||||
.save_stack
|
||||
.iter()
|
||||
.map(|element| element.serializable(&variable_key_to_built_in))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<State: serde::Serialize> Serialize for vm::VM<State> {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let serializable_vm = SerializableVM::new(self);
|
||||
serializable_vm.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
/// A VM that has been deserialized.
|
||||
///
|
||||
/// In order to recover a regular [Texlang `VM`](super::VM) it is necessary to
|
||||
/// call the [`finish_deserialization`] function with the relevant built-in commands.
|
||||
#[derive(Deserialize)]
|
||||
pub struct DeserializedVM<'a, S> {
|
||||
state: S,
|
||||
commands_map: command::map::SerializableMap<'a>,
|
||||
internal: vm::Internal<S>,
|
||||
save_stack: Vec<variable::SerializableSaveStackElement<'a>>,
|
||||
}
|
||||
|
||||
/// Finish the deserialization of a VM.
|
||||
///
|
||||
/// This function accepts a [`DeserializedVM`] and a collection of built-in commands
|
||||
/// and returns a regular [Texlang `VM`](super::VM).
|
||||
pub fn finish_deserialization<S>(
|
||||
#[allow(clippy::boxed_local)] mut deserialized: Box<DeserializedVM<'_, S>>,
|
||||
built_in_commands: HashMap<&str, command::BuiltIn<S>>,
|
||||
) -> vm::VM<S> {
|
||||
let built_in_commands = built_in_commands
|
||||
.into_iter()
|
||||
.map(|(key, value)| {
|
||||
let cs_name = deserialized.internal.cs_name_interner.get_or_intern(key);
|
||||
(cs_name, value)
|
||||
})
|
||||
.collect();
|
||||
deserialized.internal.save_stack = deserialized
|
||||
.save_stack
|
||||
.into_iter()
|
||||
.map(|element| element.finish_deserialization(&built_in_commands))
|
||||
.collect();
|
||||
let commands_map = deserialized
|
||||
.commands_map
|
||||
.finish_deserialization(built_in_commands, &deserialized.internal.cs_name_interner);
|
||||
vm::VM {
|
||||
state: deserialized.state,
|
||||
commands_map,
|
||||
working_directory: match std::env::current_dir() {
|
||||
Ok(path_buf) => Some(path_buf),
|
||||
Err(err) => {
|
||||
println!("failed to determine the working directory: {err}");
|
||||
None
|
||||
}
|
||||
},
|
||||
internal: deserialized.internal,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn deserialize<'de, D: Deserializer<'de>, S: serde::Deserialize<'de>>(
|
||||
deserializer: D,
|
||||
built_in_commands: HashMap<&str, command::BuiltIn<S>>,
|
||||
) -> Result<vm::VM<S>, D::Error> {
|
||||
let deserialized_vm: Box<DeserializedVM<S>> = Deserialize::deserialize(deserializer)?;
|
||||
Ok(finish_deserialization(deserialized_vm, built_in_commands))
|
||||
}
|
||||
Vendored
+738
@@ -0,0 +1,738 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::TexlangState;
|
||||
use crate::prelude as txl;
|
||||
use crate::token::trace;
|
||||
use crate::token::Token;
|
||||
use crate::*;
|
||||
|
||||
/// A stream of tokens generated on demand.
|
||||
///
|
||||
/// This trait describes a general stream of tokens where the front of the stream may
|
||||
/// retrieved using [TokenStream::next] or peeked at using [TokenStream::peek].
|
||||
/// In practice, all [TokenStreams](TokenStream) in Texlang
|
||||
/// are either [ExecutionInput], [ExpansionInput] or [UnexpandedStream].
|
||||
/// This trait exists to allow a generic function to accept any of these types.
|
||||
///
|
||||
/// # Note on lazy loading
|
||||
///
|
||||
/// The simplest example of a stream is a vector of tokens. However, streams are more general
|
||||
/// than this and can encompass situations in which the full contents cannot be determined in
|
||||
/// advance. This can be thought of as "lazy loading" for the tokens.
|
||||
/// The classic example of this kind of stream comes from the following LaTeX
|
||||
/// snippet:
|
||||
/// ```tex
|
||||
/// \makeatletter \do@
|
||||
/// ```
|
||||
/// Assuming the default TeX catcode map, if we were to parse this input all at once we would
|
||||
/// get three tokens: the control sequence `makeatletter`, the control sequence `do`, and a
|
||||
/// single character token with value `@` and catcode "other". This is not the correct result,
|
||||
/// though: the first control sequence changes the tokenization rules such that `@` is now
|
||||
/// an admissible character in the name of a control sequence. The correct input is thus
|
||||
/// the control sequence `makeatletter` followed by the control sequence `do@`.
|
||||
pub trait TokenStream {
|
||||
/// The type of the custom state in the VM.
|
||||
type S: TexlangState;
|
||||
|
||||
/// Gets the next token in the stream or error if the stream is exhausted.
|
||||
///
|
||||
/// This method is almost the same
|
||||
/// as the `next` method in Rust's iterator trait, except a stream can return an error.
|
||||
fn next_or_err<E: error::EndOfInputError>(&mut self, err: E) -> txl::Result<Token> {
|
||||
match self.next() {
|
||||
Ok(None) => Err(self.fatal_error(error::EofError::new(err))),
|
||||
Ok(Some(token)) => Ok(token),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the next token in the stream or `Ok(None)` if the stream is exhausted.
|
||||
fn next(&mut self) -> txl::Result<Option<Token>>;
|
||||
|
||||
fn peek(&mut self) -> txl::Result<Option<Token>> {
|
||||
let token_or = self.next()?;
|
||||
if let Some(token) = token_or {
|
||||
self.back(token);
|
||||
}
|
||||
Ok(token_or)
|
||||
}
|
||||
|
||||
/// Returns a token to the front of the token stream.
|
||||
fn back(&mut self, token: Token);
|
||||
|
||||
/// Returns a reference to the VM.
|
||||
fn vm(&self) -> &vm::VM<Self::S>;
|
||||
|
||||
/// Informs the VM that a fatal error has occurred.
|
||||
///
|
||||
/// This fatal error causes the VM to shutdown.
|
||||
///
|
||||
/// The returned shutdown signal must be propagated
|
||||
/// by returning `Err(shutdown_signal)` to the calling code.
|
||||
/// If the shutdown signal is ignored, the VM will eventually panic.
|
||||
/// See [`super::ShutdownSignal`] for more information.
|
||||
#[must_use]
|
||||
fn fatal_error<E: error::TexError>(&mut self, err: E) -> super::ShutdownSignal;
|
||||
|
||||
/// Informs the VM that a recoverable error has occurred.
|
||||
///
|
||||
/// The VM responds either with `Ok(())`,
|
||||
/// indicating that the error should be recovered from,
|
||||
/// or `Err(ShutdownSignal{})`,
|
||||
/// indicating that the error is fatal and the VM is shutting down.
|
||||
///
|
||||
/// In the error case,
|
||||
/// the returned shutdown signal must be propagated using Rust's `?` operator.
|
||||
/// If the shutdown signal is ignored, the VM will eventually panic.
|
||||
/// See [`super::ShutdownSignal`] for more information.
|
||||
fn error<E: error::TexError>(&mut self, err: E) -> txl::Result<()>;
|
||||
|
||||
/// Returns a reference to the commands map.
|
||||
#[inline]
|
||||
fn commands_map(&self) -> &command::Map<Self::S> {
|
||||
&self.vm().commands_map
|
||||
}
|
||||
|
||||
/// Returns a reference to the custom state.
|
||||
#[inline]
|
||||
fn state(&self) -> &Self::S {
|
||||
&self.vm().state
|
||||
}
|
||||
}
|
||||
|
||||
/// A [TokenStream] that performs expansion.
|
||||
///
|
||||
/// The unexpanded tokens are retrieved from the unexpanded stream returned by the
|
||||
/// [unexpanded](ExpandedStream::unexpanded) method.
|
||||
#[repr(transparent)]
|
||||
pub struct ExpandedStream<S>(UnexpandedStream<S>);
|
||||
|
||||
impl<S> std::convert::AsMut<ExpandedStream<S>> for ExpandedStream<S> {
|
||||
fn as_mut(&mut self) -> &mut ExpandedStream<S> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> ExpandedStream<S> {
|
||||
/// Returns the underlying unexpanded stream.
|
||||
pub fn unexpanded(&mut self) -> &mut UnexpandedStream<S> {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
/// Expand the next token in the input.
|
||||
///
|
||||
/// This method only expands a single token. If, after the expansion, the next token
|
||||
/// is expandable it will not be expanded.
|
||||
pub fn expand_once(&mut self) -> txl::Result<bool> {
|
||||
stream::expand_once(self.vm_mut())
|
||||
}
|
||||
|
||||
pub fn checkout_token_buffer(&mut self) -> Vec<Token> {
|
||||
self.0 .0.internal.token_buffers.pop().unwrap_or_default().0
|
||||
}
|
||||
|
||||
/// Return a token buffer, allowing it to be reused.
|
||||
pub fn return_token_buffer(&mut self, mut token_buffer: Vec<Token>) {
|
||||
token_buffer.clear();
|
||||
self.0
|
||||
.0
|
||||
.internal
|
||||
.token_buffers
|
||||
.push(super::TokenBuffer(token_buffer))
|
||||
}
|
||||
|
||||
pub(crate) fn vm_mut(&mut self) -> &mut vm::VM<S> {
|
||||
&mut self.0 .0
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the expanded tokens stack for the current input source.
|
||||
///
|
||||
/// The tokens are a stack, so the next token is the last token in the vector.
|
||||
#[inline]
|
||||
pub fn expansions_mut(&mut self) -> &mut Vec<Token> {
|
||||
self.0 .0.internal.expansions_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> TokenStream for ExpandedStream<S> {
|
||||
type S = S;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> txl::Result<Option<Token>> {
|
||||
stream::next_expanded(&mut self.unexpanded().0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn vm(&self) -> &vm::VM<Self::S> {
|
||||
&self.0 .0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn back(&mut self, token: Token) {
|
||||
self.0.back(token)
|
||||
}
|
||||
fn fatal_error<E: error::TexError>(&mut self, err: E) -> super::ShutdownSignal {
|
||||
self.0 .0.fatal_error(err)
|
||||
}
|
||||
fn error<E: error::TexError>(&mut self, err: E) -> txl::Result<()> {
|
||||
self.0 .0.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stream that returns input tokens without performing expansion.
|
||||
///
|
||||
/// The unexpanded stream is used when reading tokens without performing expansion;
|
||||
/// e.g., when reading the replacement text for a macro defined using `\def`.
|
||||
///
|
||||
/// It be obtained from either the [ExecutionInput] or the [ExpansionInput]
|
||||
/// using the [ExpandedStream] trait methods.
|
||||
#[repr(transparent)]
|
||||
pub struct UnexpandedStream<S>(vm::VM<S>);
|
||||
|
||||
impl<S: TexlangState> TokenStream for UnexpandedStream<S> {
|
||||
type S = S;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> txl::Result<Option<Token>> {
|
||||
stream::next_unexpanded(&mut self.0)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn vm(&self) -> &vm::VM<S> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn back(&mut self, token: Token) {
|
||||
self.0.internal.expansions_mut().push(token)
|
||||
}
|
||||
fn fatal_error<E: error::TexError>(&mut self, err: E) -> super::ShutdownSignal {
|
||||
self.0.fatal_error(err)
|
||||
}
|
||||
fn error<E: error::TexError>(&mut self, err: E) -> txl::Result<()> {
|
||||
self.0.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Input type for expansion primitives.
|
||||
///
|
||||
/// This type provides:
|
||||
///
|
||||
/// - Access to the input stream (with or without expansion). Its implementation of the [TokenStream]
|
||||
/// trait returns expanded tokens.
|
||||
/// To read the input stream without performing expansion, use the
|
||||
/// [unexpanded](ExpandedStream::unexpanded) method.
|
||||
///
|
||||
/// - Read-only VM access, with mutable access to the engine state for
|
||||
/// engine-owned expansion frames.
|
||||
///
|
||||
/// - The ability to push source code or token expansions to the front of the input stream.
|
||||
/// For source code use [ExpansionInput::push_source];
|
||||
/// for tokens use [ExpansionInput::push_expansion] or [ExpansionInput::expansions_mut].
|
||||
///
|
||||
/// - Access to token buffers using the [ExpansionInput::checkout_token_buffer] and
|
||||
/// [ExpansionInput::return_token_buffer] methods.
|
||||
///
|
||||
/// This type is also used in the parsing code for situations where both an
|
||||
/// [ExpansionInput] or [ExecutionInput] is accepted. We use this type because
|
||||
/// it does not expose mutable VM internals; mutable access is limited to the
|
||||
/// engine's custom state.
|
||||
#[repr(transparent)]
|
||||
// TODO: should this be in the command module, not in the vm module?
|
||||
pub struct ExpansionInput<S>(ExpandedStream<S>);
|
||||
|
||||
impl<S> std::convert::AsMut<ExpandedStream<S>> for ExpansionInput<S> {
|
||||
fn as_mut(&mut self) -> &mut ExpandedStream<S> {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> TokenStream for ExpansionInput<S> {
|
||||
type S = S;
|
||||
|
||||
fn next(&mut self) -> txl::Result<Option<Token>> {
|
||||
self.0.next()
|
||||
}
|
||||
|
||||
fn vm(&self) -> &vm::VM<Self::S> {
|
||||
self.0.vm()
|
||||
}
|
||||
|
||||
fn back(&mut self, token: Token) {
|
||||
self.0.back(token);
|
||||
}
|
||||
fn fatal_error<E: error::TexError>(&mut self, err: E) -> super::ShutdownSignal {
|
||||
self.0 .0 .0.fatal_error(err)
|
||||
}
|
||||
fn error<E: error::TexError>(&mut self, err: E) -> txl::Result<()> {
|
||||
self.0 .0 .0.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> ExpansionInput<S> {
|
||||
/// Creates a mutable reference to this type from the [VM](vm::VM) type.
|
||||
#[inline]
|
||||
pub fn new(vm: &mut vm::VM<S>) -> &mut ExpansionInput<S> {
|
||||
unsafe { &mut *(vm as *mut vm::VM<S> as *mut ExpansionInput<S>) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> ExpansionInput<S> {
|
||||
/// Returns mutable access to the engine state while expanding tokens.
|
||||
#[inline]
|
||||
pub fn state_mut(&mut self) -> &mut S {
|
||||
&mut self.0 .0 .0.state
|
||||
}
|
||||
|
||||
/// Push source code to the front of the input stream.
|
||||
#[inline]
|
||||
pub fn push_source(
|
||||
&mut self,
|
||||
token: Token,
|
||||
file_name: PathBuf,
|
||||
source_code: String,
|
||||
) -> txl::Result<()> {
|
||||
let vm = &mut self.0 .0 .0;
|
||||
if vm
|
||||
.state
|
||||
.push_external_source(&token, &file_name, &source_code, 0)
|
||||
{
|
||||
vm.internal.push_external_source_frame();
|
||||
return Ok(());
|
||||
}
|
||||
vm.internal
|
||||
.push_source(Some(token), file_name, source_code, 0)
|
||||
}
|
||||
|
||||
/// End the current file.
|
||||
///
|
||||
/// This method is used by `\endinput` primitive.
|
||||
pub fn end_current_file(&mut self) {
|
||||
let vm = &mut self.0 .0 .0;
|
||||
if !vm.state.end_external_source() {
|
||||
vm.internal.end_current_file()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_string_tokens(&mut self, token: Token, s: &str) {
|
||||
let trace_key = token.trace_key();
|
||||
for c in s.chars().rev() {
|
||||
let token = match c {
|
||||
' ' => token::Token::new_space(' ', trace_key),
|
||||
_ => token::Token::new_letter(c, trace_key),
|
||||
};
|
||||
self.expansions_mut().push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> ExpansionInput<S> {
|
||||
#[inline]
|
||||
pub fn unexpanded(&mut self) -> &mut UnexpandedStream<S> {
|
||||
&mut self.0 .0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn expanded(&mut self) -> &mut ExpandedStream<S> {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
/// Push tokens to the front of the input stream.
|
||||
///
|
||||
/// The first token in the provided slice will be the next token read.
|
||||
// TODO: destroy
|
||||
#[inline]
|
||||
pub fn push_expansion(&mut self, expansion: &[Token]) {
|
||||
self.0 .0 .0.internal.push_expansion(expansion)
|
||||
}
|
||||
|
||||
/// Returns a reference to the expanded tokens stack for the current input source.
|
||||
///
|
||||
/// The tokens are a stack, so the next token is the last token in the vector.
|
||||
///
|
||||
/// Adding tokens to the front of the input using this method can be more efficient
|
||||
/// than using [ExpansionInput::push_expansion] because an allocation is avoided.
|
||||
#[inline]
|
||||
pub fn expansions(&self) -> &Vec<Token> {
|
||||
self.0 .0 .0.internal.expansions()
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the expanded tokens stack for the current input source.
|
||||
///
|
||||
/// The tokens are a stack, so the next token is the last token in the vector.
|
||||
///
|
||||
/// Adding tokens to the front of the input using this method can be more efficient
|
||||
/// than using [ExpansionInput::push_expansion] because an allocation is avoided.
|
||||
#[inline]
|
||||
pub fn expansions_mut(&mut self) -> &mut Vec<Token> {
|
||||
self.0 .0 .0.internal.expansions_mut()
|
||||
}
|
||||
|
||||
/// Returns the control-sequence interner used to materialize tokens at an
|
||||
/// engine adapter boundary.
|
||||
#[inline]
|
||||
pub fn cs_name_interner_mut(&mut self) -> &mut token::CsNameInterner {
|
||||
&mut self.0 .0 .0.internal.cs_name_interner
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn state_and_expansions_mut(&mut self) -> (&S, &mut Vec<Token>) {
|
||||
(&self.0 .0 .0.state, self.0 .0 .0.internal.expansions_mut())
|
||||
}
|
||||
|
||||
/// Returns a vector than can be used as a token buffer, potentially without allocating memory.
|
||||
///
|
||||
/// The returned vector is empty, but will generally have non-zero capacity from previous uses of the buffer.
|
||||
/// Reusing the allocated memory results in fewer allocations overall.
|
||||
/// This buffer mechanism was first introduced in a successful attempt to improve the performance of the
|
||||
/// TeX macros implementation.
|
||||
///
|
||||
/// When finished with the buffer, please return it using [return_token_buffer](ExpansionInput::return_token_buffer).
|
||||
///
|
||||
/// This API may feel a bit awkward - it would seem nicer to return a mutable reference to a buffer instead.
|
||||
/// Doing this while keeping the borrow checker happy is very difficult and (as is often the case) for good reason.
|
||||
/// Token buffers are often used in macro expansion, and at any point in time multiple macros may be in
|
||||
/// the process of expansion.
|
||||
/// This getting "the" token buffer to use for expansion would be incorrect, as the multiple expansions
|
||||
/// would step on each other.
|
||||
pub fn checkout_token_buffer(&mut self) -> Vec<Token> {
|
||||
self.0
|
||||
.0
|
||||
.0
|
||||
.internal
|
||||
.token_buffers
|
||||
.pop()
|
||||
.unwrap_or_default()
|
||||
.0
|
||||
}
|
||||
|
||||
/// Return a token buffer, allowing it to be reused.
|
||||
pub fn return_token_buffer(&mut self, mut token_buffer: Vec<Token>) {
|
||||
token_buffer.clear();
|
||||
self.0
|
||||
.0
|
||||
.0
|
||||
.internal
|
||||
.token_buffers
|
||||
.push(super::TokenBuffer(token_buffer))
|
||||
}
|
||||
}
|
||||
|
||||
/// Input type for execution primitives.
|
||||
///
|
||||
/// This type provides:
|
||||
///
|
||||
/// - Access to the input stream (with or without expansion). Its implementation of the [TokenStream]
|
||||
/// trait returns expanded tokens.
|
||||
/// To read the input stream without performing expansion, use the
|
||||
/// [unexpanded](ExpandedStream::unexpanded) method.
|
||||
///
|
||||
/// - Mutable access to the state and the commands map
|
||||
/// the [ExecutionInput::state_mut]
|
||||
/// and [ExecutionInput::commands_map_mut] methods.
|
||||
#[repr(transparent)]
|
||||
pub struct ExecutionInput<S>(ExpandedStream<S>);
|
||||
|
||||
impl<S> std::convert::AsMut<ExpandedStream<S>> for ExecutionInput<S> {
|
||||
fn as_mut(&mut self) -> &mut ExpandedStream<S> {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> TokenStream for ExecutionInput<S> {
|
||||
type S = S;
|
||||
|
||||
fn next(&mut self) -> txl::Result<Option<Token>> {
|
||||
self.0.next()
|
||||
}
|
||||
|
||||
fn vm(&self) -> &vm::VM<Self::S> {
|
||||
self.0.vm()
|
||||
}
|
||||
|
||||
fn back(&mut self, token: Token) {
|
||||
self.0.back(token);
|
||||
}
|
||||
fn fatal_error<E: error::TexError>(&mut self, err: E) -> super::ShutdownSignal {
|
||||
self.0 .0 .0.fatal_error(err)
|
||||
}
|
||||
fn error<E: error::TexError>(&mut self, err: E) -> txl::Result<()> {
|
||||
self.0 .0 .0.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> ExecutionInput<S> {
|
||||
/// Shutdown the VM.
|
||||
pub fn shutdown(&mut self) -> super::ShutdownSignal {
|
||||
self.0 .0 .0.shutdown()
|
||||
}
|
||||
|
||||
/// Push source code to the front of the input stream.
|
||||
///
|
||||
/// The pushed source is processed before the remainder of the current source.
|
||||
#[inline]
|
||||
pub fn push_source(
|
||||
&mut self,
|
||||
token: Token,
|
||||
file_name: PathBuf,
|
||||
source_code: String,
|
||||
) -> txl::Result<()> {
|
||||
let vm = &mut self.0 .0 .0;
|
||||
if vm
|
||||
.state
|
||||
.push_external_source(&token, &file_name, &source_code, 0)
|
||||
{
|
||||
vm.internal.push_external_source_frame();
|
||||
return Ok(());
|
||||
}
|
||||
vm.internal
|
||||
.push_source(Some(token), file_name, source_code, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> ExecutionInput<S> {
|
||||
/// Creates a mutable reference to this type from the [VM](vm::VM) type.
|
||||
#[inline]
|
||||
pub fn new(vm: &mut vm::VM<S>) -> &mut ExecutionInput<S> {
|
||||
unsafe { &mut *(vm as *mut vm::VM<S> as *mut ExecutionInput<S>) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn unexpanded(&mut self) -> &mut UnexpandedStream<S> {
|
||||
&mut self.0 .0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn commands_map_mut(&mut self) -> &mut command::Map<S> {
|
||||
&mut self.0 .0 .0.commands_map
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the state.
|
||||
#[inline]
|
||||
pub fn state_mut(&mut self) -> &mut S {
|
||||
&mut self.0 .0 .0.state
|
||||
}
|
||||
/// Returns a mutable reference to the tracer.
|
||||
pub fn tracer_mut(&mut self) -> &mut trace::Tracer {
|
||||
&mut self.0 .0 .0.internal.tracer
|
||||
}
|
||||
/// Returns a [vm::Parts] struct contains mutable references to different parts of the VM.
|
||||
#[inline]
|
||||
pub fn vm_parts(&mut self) -> vm::Parts<'_, S> {
|
||||
let vm = &mut self.0 .0 .0;
|
||||
vm::Parts {
|
||||
state: &mut vm.state,
|
||||
cs_name_interner: &mut vm.internal.cs_name_interner,
|
||||
tracer: &mut vm.internal.tracer,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: pass in the token and keep it as a reference
|
||||
pub fn begin_group(&mut self) {
|
||||
self.0 .0 .0.begin_group()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn groups(&mut self) -> &mut [variable::SaveStackElement<S>] {
|
||||
&mut self.0 .0 .0.internal.save_stack
|
||||
}
|
||||
|
||||
pub(crate) fn current_group_mut(&mut self) -> Option<(&mut variable::SaveStackElement<S>, &S)> {
|
||||
match self.0 .0 .0.internal.save_stack.last_mut() {
|
||||
None => None,
|
||||
Some(g) => Some((g, &self.0 .0 .0.state)),
|
||||
}
|
||||
}
|
||||
pub(crate) fn vm_mut(&mut self) -> &mut vm::VM<S> {
|
||||
&mut self.0 .0 .0
|
||||
}
|
||||
|
||||
/// Run an operation while attaching its token and kind to VM diagnostics.
|
||||
pub fn with_operation<T>(
|
||||
&mut self,
|
||||
token: Token,
|
||||
kind: error::OperationKind,
|
||||
operation: impl FnOnce(&mut Self) -> T,
|
||||
) -> T {
|
||||
self.vm_mut().stack_push(token, kind);
|
||||
let result = operation(self);
|
||||
self.vm_mut().stack_pop();
|
||||
result
|
||||
}
|
||||
|
||||
/// Return a token buffer, allowing it to be reused.
|
||||
pub fn return_token_buffer(&mut self, mut token_buffer: Vec<Token>) {
|
||||
token_buffer.clear();
|
||||
self.0
|
||||
.0
|
||||
.0
|
||||
.internal
|
||||
.token_buffers
|
||||
.push(super::TokenBuffer(token_buffer))
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TexlangState> ExecutionInput<S> {
|
||||
pub fn end_group(&mut self, token: Token) -> txl::Result<()> {
|
||||
self.0 .0 .0.end_group(token)
|
||||
}
|
||||
}
|
||||
|
||||
mod stream {
|
||||
use super::*;
|
||||
use crate::token::lexer;
|
||||
use crate::token::lexer::Config;
|
||||
|
||||
impl<T: TexlangState> Config for T {
|
||||
#[inline]
|
||||
fn cat_code(&self, c: char) -> crate::types::CatCode {
|
||||
self.cat_code(c)
|
||||
}
|
||||
#[inline]
|
||||
fn end_line_char(&self) -> Option<char> {
|
||||
self.end_line_char()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn next_unexpanded<S: TexlangState>(vm: &mut vm::VM<S>) -> txl::Result<Option<Token>> {
|
||||
if let Some(token) = vm.internal.current_source.expansions.pop() {
|
||||
return Ok(Some(token));
|
||||
}
|
||||
if vm.state.has_priority_external_input() {
|
||||
let result = vm.state.next_priority_external_input_token(
|
||||
&mut vm.internal.cs_name_interner,
|
||||
&mut vm.internal.tracer,
|
||||
);
|
||||
if let Some(token) = result.map_err(|error| vm.fatal_error(error))? {
|
||||
return Ok(Some(token));
|
||||
}
|
||||
if vm.state.stop_at_priority_external_input_end() {
|
||||
return Ok(None);
|
||||
}
|
||||
vm.internal.pop_source();
|
||||
return next_unexpanded(vm);
|
||||
}
|
||||
match vm.internal.current_source.root.next(
|
||||
&vm.state,
|
||||
&mut vm.internal.cs_name_interner,
|
||||
false,
|
||||
) {
|
||||
lexer::Result::Token(token) => {
|
||||
return Ok(Some(token));
|
||||
}
|
||||
lexer::Result::InvalidCharacter(c, trace_key) => {
|
||||
return Err(build_invalid_character_error(vm, c, trace_key));
|
||||
}
|
||||
// The EndOfLine case is never returned from the lexer but we silently handle it.
|
||||
lexer::Result::EndOfLine | lexer::Result::EndOfInput => {}
|
||||
}
|
||||
if !vm.internal.pop_source() {
|
||||
let result = vm.state.next_external_input_token(
|
||||
&mut vm.internal.cs_name_interner,
|
||||
&mut vm.internal.tracer,
|
||||
);
|
||||
return result.map_err(|error| vm.fatal_error(error));
|
||||
}
|
||||
next_unexpanded(vm)
|
||||
}
|
||||
|
||||
fn build_invalid_character_error<S: TexlangState>(
|
||||
vm: &mut vm::VM<S>,
|
||||
c: char,
|
||||
trace_key: trace::Key,
|
||||
) -> vm::ShutdownSignal {
|
||||
vm.fatal_error(lexer::InvalidCharacterError::new(vm, c, trace_key))
|
||||
}
|
||||
|
||||
pub fn next_expanded<S: TexlangState>(vm: &mut vm::VM<S>) -> txl::Result<Option<Token>> {
|
||||
let (token, command) = match next_unexpanded(vm)? {
|
||||
None => return Ok(None),
|
||||
Some(token) => match token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
vm.stack_push(token, error::OperationKind::Expansion);
|
||||
let macro_expansion = S::macro_expansion_hook(token, ExpansionInput::new(vm));
|
||||
vm.stack_pop();
|
||||
if macro_expansion? {
|
||||
return next_expanded(vm);
|
||||
}
|
||||
(token, vm.commands_map.get_command(&command_ref))
|
||||
}
|
||||
_ => return Ok(Some(token)),
|
||||
},
|
||||
};
|
||||
match command {
|
||||
Some(command::Command::Expansion(command, tag)) => {
|
||||
let command = *command;
|
||||
let tag = *tag;
|
||||
match S::expansion_override_hook(token, ExpansionInput::new(vm), tag) {
|
||||
Ok(None) => (),
|
||||
Ok(Some(override_expansion)) => {
|
||||
return Ok(Some(override_expansion));
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
vm.stack_push(token, error::OperationKind::Expansion);
|
||||
let err_or = command(token, ExpansionInput::new(vm));
|
||||
vm.stack_pop();
|
||||
err_or?;
|
||||
next_expanded(vm)
|
||||
}
|
||||
Some(command::Command::Macro(command)) => {
|
||||
let command = command.clone();
|
||||
command.call(token, ExpansionInput::new(vm))?;
|
||||
next_expanded(vm)
|
||||
}
|
||||
_ => Ok(Some(token)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expand_once<S: TexlangState>(vm: &mut vm::VM<S>) -> txl::Result<bool> {
|
||||
let (token, command) = match next_unexpanded(vm)? {
|
||||
None => return Ok(false),
|
||||
Some(token) => match token.value() {
|
||||
token::Value::CommandRef(command_ref) => {
|
||||
vm.stack_push(token, error::OperationKind::Expansion);
|
||||
let macro_expansion = S::macro_expansion_hook(token, ExpansionInput::new(vm));
|
||||
vm.stack_pop();
|
||||
if macro_expansion? {
|
||||
return Ok(true);
|
||||
}
|
||||
(token, vm.commands_map.get_command(&command_ref))
|
||||
}
|
||||
_ => {
|
||||
vm.internal.expansions_mut().push(token);
|
||||
return Ok(false);
|
||||
}
|
||||
},
|
||||
};
|
||||
match command {
|
||||
Some(command::Command::Expansion(command, tag)) => {
|
||||
let command = *command;
|
||||
let tag = *tag;
|
||||
match S::expansion_override_hook(token, ExpansionInput::new(vm), tag) {
|
||||
Ok(None) => (),
|
||||
Ok(Some(override_expansion)) => {
|
||||
vm.internal.expansions_mut().push(override_expansion);
|
||||
return Ok(true);
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
vm.stack_push(token, error::OperationKind::Expansion);
|
||||
let err_or = command(token, ExpansionInput::new(vm));
|
||||
vm.stack_pop();
|
||||
err_or?;
|
||||
Ok(true)
|
||||
}
|
||||
Some(command::Command::Macro(command)) => {
|
||||
let command = command.clone();
|
||||
command.call(token, ExpansionInput::new(vm))?;
|
||||
Ok(true)
|
||||
}
|
||||
_ => {
|
||||
vm.internal.expansions_mut().push(token);
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user