//! 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 { values: Vec>, groups: Vec>>, } impl Default for ScopedVec { fn default() -> Self { Self { values: Vec::new(), groups: Vec::new(), } } } impl ScopedVec { fn get(&self, key: &usize) -> Option<&V> { self.values.get(*key).and_then(Option::as_ref) } fn iter(&self) -> impl Iterator { self.values .iter() .enumerate() .filter_map(|(key, value)| value.as_ref().map(|value| (key, value))) } fn backing_container(&self) -> &[Option] { &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 { 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) { if key >= self.values.len() { self.values.resize_with(key + 1, || None); } self.values[key] = value; } } impl FromIterator<(usize, V)> for ScopedVec { fn from_iter>(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 { values: HashMap, groups: Vec>>, } impl Default for ScopedHashMap { fn default() -> Self { Self { values: HashMap::new(), groups: Vec::new(), } } } impl ScopedHashMap { 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 { 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 and `Vec`. 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 { commands: ScopedVec>, active_char: ScopedHashMap>, built_in_commands: HashMap>, primitive_key_to_built_in_lazy: RefCell>>, getters_key_to_built_in_lazy: RefCell>>, } impl Map { pub(crate) fn new(built_in_commands: HashMap>) -> Map { 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> { 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 { 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> { &self.built_in_commands } pub fn get_command_slow(&self, command_ref: &token::CommandRef) -> Option> { 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, 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, 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> { 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> { 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> { 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, active_char: ScopedHashMap, macros: Vec>, } #[cfg(feature = "serde")] impl serde::Serialize for Map { fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { let serializable_map = SerializableMap::new(self); serializable_map.serialize(serializer) } } impl<'a> SerializableMap<'a> { fn new(map: &'a Map) -> Self { let mut macros_de_dup = HashMap::::new(); let mut macros: Vec> = 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| 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( self, built_in_commands: HashMap>, interner: &token::CsNameInterner, ) -> Map { let macros: Vec> = 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(), } } }