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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user