use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;
use hashbrown::HashMap;
use crate::constructs::{
ConstructParser, ConstructParserResult, ImplementationError, ImplementationErrorKind,
Invocation, ParseContext,
};
use crate::error::{Diagnostic, DiagnosticInfo, Diagnostics};
use crate::node::{BuildId, NodeKind};
use crate::serialize::SerializableObject;
use crate::source::{Source, SourceSpan, Span};
use crate::spec::{CallableSpec, IntoCallableSpec};
use crate::state::{
ClosedVocabulary, FeaturePresence, Lang, LangFeatures, LangHasScopes, ParsingState,
ParsingStateDelta,
};
use crate::token::{
SpecialsMatch, SpecialsScanError, TokenErrorKind, TriggerChars,
};
mod provenance;
pub use provenance::{DefinitionKey, SpecProvenance};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallableSyntax {
Command {
escape_char: char,
},
Specials,
Other,
}
pub struct CallableQuery<'a, L: Lang> {
pub callable_type: L::CallableTypeId,
pub name: &'a str,
pub syntax: CallableSyntax,
}
impl<'a, L: Lang> CallableQuery<'a, L> {
pub fn new(
callable_type: L::CallableTypeId,
name: &'a str,
syntax: CallableSyntax,
) -> CallableQuery<'a, L> {
CallableQuery { callable_type, name, syntax }
}
}
impl<L: Lang> Clone for CallableQuery<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for CallableQuery<'_, L> {}
impl<L: Lang> fmt::Debug for CallableQuery<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CallableQuery")
.field("callable_type", &self.callable_type)
.field("name", &self.name)
.field("syntax", &self.syntax)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProviderError {
NotMutable,
UndefinedName {
name: Box<str>,
},
Failed(Box<str>),
}
impl fmt::Display for ProviderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProviderError::NotMutable => write!(
f,
"Read-only definition provider: definitions may not be added or removed"
),
ProviderError::UndefinedName { name } => {
write!(f, "Missing definition of ‘{name}’")
}
ProviderError::Failed(message) => write!(f, "{message}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeStackError {
pub provider: Box<str>,
pub error: ProviderError,
}
impl fmt::Display for ScopeStackError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let provider = &self.provider;
match &self.error {
ProviderError::NotMutable => write!(
f,
"Read-only definition provider ‘{provider}’: definitions may not be \
added or removed"
),
ProviderError::UndefinedName { name } => write!(
f,
"Missing definition of ‘{name}’ in definition provider ‘{provider}’"
),
ProviderError::Failed(message) => {
write!(f, "Definition provider ‘{provider}’ failed: {message}")
}
}
}
}
impl core::error::Error for ProviderError {}
impl core::error::Error for ScopeStackError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
Some(&self.error)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeOpError {
UnknownProvider {
name: Box<str>,
},
Provider(ScopeStackError),
ScopesAbsent,
}
impl fmt::Display for ScopeOpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ScopeOpError::UnknownProvider { name } => {
write!(f, "Missing definition provider ‘{name}’ on the scope stack")
}
ScopeOpError::Provider(error) => fmt::Display::fmt(error, f),
ScopeOpError::ScopesAbsent => write!(
f,
"Invalid scope operation: the language has no scope stack"
),
}
}
}
impl core::error::Error for ScopeOpError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
ScopeOpError::UnknownProvider { .. } => None,
ScopeOpError::Provider(error) => Some(error),
ScopeOpError::ScopesAbsent => None,
}
}
}
pub enum DefinitionOp<L: Lang> {
Define {
callable_type: L::CallableTypeId,
name: Box<str>,
spec: Arc<dyn CallableSpec<L>>,
},
Remove {
callable_type: L::CallableTypeId,
name: Box<str>,
},
}
impl<L: Lang> Clone for DefinitionOp<L> {
fn clone(&self) -> Self {
match self {
DefinitionOp::Define { callable_type, name, spec } => DefinitionOp::Define {
callable_type: *callable_type,
name: name.clone(),
spec: Arc::clone(spec),
},
DefinitionOp::Remove { callable_type, name } => {
DefinitionOp::Remove { callable_type: *callable_type, name: name.clone() }
}
}
}
}
impl<L: Lang> fmt::Debug for DefinitionOp<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DefinitionOp::Define { callable_type, name, spec } => f
.debug_struct("Define")
.field("callable_type", callable_type)
.field("name", name)
.field("spec", spec)
.finish(),
DefinitionOp::Remove { callable_type, name } => f
.debug_struct("Remove")
.field("callable_type", callable_type)
.field("name", name)
.finish(),
}
}
}
pub enum ScopeOp<L: Lang> {
Push(Arc<dyn SpecsProvider<L>>),
Unload {
name: Box<str>,
},
Replace {
name: Box<str>,
provider: Arc<dyn SpecsProvider<L>>,
},
ReplaceStack(Vec<Arc<dyn SpecsProvider<L>>>),
Define {
scope: Box<str>,
callable_type: L::CallableTypeId,
name: Box<str>,
spec: Arc<dyn CallableSpec<L>>,
},
Remove {
scope: Box<str>,
callable_type: L::CallableTypeId,
name: Box<str>,
},
}
impl<L: Lang> Clone for ScopeOp<L> {
fn clone(&self) -> Self {
match self {
ScopeOp::Push(provider) => ScopeOp::Push(Arc::clone(provider)),
ScopeOp::Unload { name } => ScopeOp::Unload { name: name.clone() },
ScopeOp::Replace { name, provider } => {
ScopeOp::Replace { name: name.clone(), provider: Arc::clone(provider) }
}
ScopeOp::ReplaceStack(providers) => ScopeOp::ReplaceStack(providers.clone()),
ScopeOp::Define { scope, callable_type, name, spec } => ScopeOp::Define {
scope: scope.clone(),
callable_type: *callable_type,
name: name.clone(),
spec: Arc::clone(spec),
},
ScopeOp::Remove { scope, callable_type, name } => ScopeOp::Remove {
scope: scope.clone(),
callable_type: *callable_type,
name: name.clone(),
},
}
}
}
impl<L: Lang> fmt::Debug for ScopeOp<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ScopeOp::Push(provider) => f.debug_tuple("Push").field(provider).finish(),
ScopeOp::Unload { name } => {
f.debug_struct("Unload").field("name", name).finish()
}
ScopeOp::Replace { name, provider } => f
.debug_struct("Replace")
.field("name", name)
.field("provider", provider)
.finish(),
ScopeOp::ReplaceStack(providers) => {
f.debug_tuple("ReplaceStack").field(providers).finish()
}
ScopeOp::Define { scope, callable_type, name, spec } => f
.debug_struct("Define")
.field("scope", scope)
.field("callable_type", callable_type)
.field("name", name)
.field("spec", spec)
.finish(),
ScopeOp::Remove { scope, callable_type, name } => f
.debug_struct("Remove")
.field("scope", scope)
.field("callable_type", callable_type)
.field("name", name)
.finish(),
}
}
}
pub trait SpecsProvider<L: Lang>: fmt::Debug + Send + Sync + Any + SerializableObject<L> {
fn name(&self) -> &str;
fn retrieve_spec(
&self,
query: &CallableQuery<'_, L>,
state: &ParsingState<L>,
) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError>;
fn scan_specials(
&self,
state: &ParsingState<L>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
let _ = (state, content, pos);
Ok(None)
}
fn specials_trigger_chars(&self) -> TriggerChars {
TriggerChars::default()
}
fn with_definitions(
&self,
ops: &[DefinitionOp<L>],
) -> Result<Arc<dyn SpecsProvider<L>>, ProviderError> {
let _ = ops;
Err(ProviderError::NotMutable)
}
fn iter_symbols(
&self,
callable_type: L::CallableTypeId,
mode: L::ModeId,
) -> Option<Box<dyn Iterator<Item = SymbolEntry<'_, L>> + '_>> {
let _ = (callable_type, mode);
None
}
}
mod sealed {
use super::{Lang, Package, SpecsProvider};
use alloc::sync::Arc;
pub trait SealedProvider<L: Lang> {}
impl<L: Lang> SealedProvider<L> for Package<L> {}
impl<L: Lang, P: SpecsProvider<L> + 'static> SealedProvider<L> for Arc<P> {}
impl<L: Lang> SealedProvider<L> for Arc<dyn SpecsProvider<L>> {}
}
pub trait IntoSpecsProvider<L: Lang>: sealed::SealedProvider<L> {
fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>>;
}
impl<L: Lang> IntoSpecsProvider<L> for Package<L> {
fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>> {
Arc::new(self)
}
}
impl<L: Lang, P: SpecsProvider<L> + 'static> IntoSpecsProvider<L> for Arc<P> {
fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>> {
self
}
}
impl<L: Lang> IntoSpecsProvider<L> for Arc<dyn SpecsProvider<L>> {
fn into_specs_provider(self) -> Arc<dyn SpecsProvider<L>> {
self
}
}
pub struct SymbolEntry<'a, L: Lang> {
pub callable_type: L::CallableTypeId,
pub name: &'a str,
pub spec: &'a Arc<dyn CallableSpec<L>>,
}
impl<L: Lang> Clone for SymbolEntry<'_, L> {
fn clone(&self) -> Self {
*self
}
}
impl<L: Lang> Copy for SymbolEntry<'_, L> {}
impl<L: Lang> fmt::Debug for SymbolEntry<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SymbolEntry")
.field("callable_type", &self.callable_type)
.field("name", &self.name)
.field("spec", &self.spec)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.provider-commands-shadowed-by-escape")]
pub struct ProviderCommandsShadowedByEscape {
pub provider: String,
pub callable_type: String,
pub count: usize,
pub example: String,
pub escape_chars: String,
}
impl fmt::Display for ProviderCommandsShadowedByEscape {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Misconfigured provider ‘{}’: ", self.provider)?;
if self.count == 1 {
write!(
f,
"its only ‘{}’ definition ‘{}’ begins with ",
self.callable_type, self.example,
)?;
} else {
write!(
f,
"all {} ‘{}’ definitions begin with ",
self.count, self.callable_type,
)?;
}
let mut escape_chars = self.escape_chars.chars();
match (escape_chars.next(), escape_chars.next()) {
(Some(escape_char), None) => {
write!(f, "the escape character ‘{escape_char}’")?
}
_ => {
f.write_str("one of the escape characters ")?;
for (i, escape_char) in self.escape_chars.chars().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "‘{escape_char}’")?;
}
}
}
if self.count > 1 {
write!(f, " (e.g. ‘{}’)", self.example)?;
}
f.write_str("; names must be registered without their escape character")
}
}
pub fn check_provider_commands_shadowed_by_escape<L: Lang>(
state: &ParsingState<L>,
source: &Arc<Source<L::SourceOrigin>>,
diagnostics: &mut Diagnostics<L::SourceOrigin>,
) where
L::CallableTypeId: ClosedVocabulary,
L::ModeId: ClosedVocabulary,
{
let rules = state.rules();
if !rules.commands_enabled() || rules.command_rules().is_empty() {
return;
}
let escape_chars: Vec<char> =
rules.command_rules().iter().map(|rule| rule.escape_char).collect();
let shadowed = |name: &str| {
let mut chars = name.chars();
chars.next().is_some_and(|first| escape_chars.contains(&first))
&& chars.next().is_some()
};
for provider in state.scopes().providers().iter().rev() {
'tables: for &callable_type in L::CallableTypeId::ALL {
let mut names: Vec<&str> = Vec::new();
for &mode in L::ModeId::ALL {
let Some(symbols) = provider.iter_symbols(callable_type, mode) else {
continue; };
for entry in symbols {
if !shadowed(entry.name) {
continue 'tables;
}
names.push(entry.name);
}
}
if names.is_empty() {
continue;
}
names.sort_unstable();
names.dedup();
let mut offending_escapes: Vec<char> = names
.iter()
.filter_map(|name| name.chars().next())
.collect();
offending_escapes.sort_unstable();
offending_escapes.dedup();
diagnostics.push(Diagnostic::warning(
ProviderCommandsShadowedByEscape {
provider: provider.name().into(),
callable_type: alloc::format!("{callable_type:?}"),
count: names.len(),
example: names[0].into(),
escape_chars: offending_escapes.into_iter().collect(),
},
SourceSpan::new(source, Span::empty(0)),
));
}
}
}
struct PackageSpecials<L: Lang> {
trigger: Box<str>,
callable_type: L::CallableTypeId,
spec: Arc<dyn CallableSpec<L>>,
visible_modes: Option<Vec<L::ModeId>>,
}
impl<L: Lang> Clone for PackageSpecials<L> {
fn clone(&self) -> Self {
PackageSpecials {
trigger: self.trigger.clone(),
callable_type: self.callable_type,
spec: Arc::clone(&self.spec),
visible_modes: self.visible_modes.clone(),
}
}
}
struct PackageEntry<L: Lang> {
spec: Arc<dyn CallableSpec<L>>,
visible_modes: Option<Vec<L::ModeId>>,
}
impl<L: Lang> Clone for PackageEntry<L> {
fn clone(&self) -> Self {
PackageEntry {
spec: Arc::clone(&self.spec),
visible_modes: self.visible_modes.clone(),
}
}
}
fn modes_admit<M: Eq>(visible_modes: &Option<Vec<M>>, mode: &M) -> bool {
match visible_modes {
None => true,
Some(modes) => modes.contains(mode),
}
}
pub struct Package<L: Lang> {
name: Box<str>,
specs: HashMap<L::CallableTypeId, HashMap<Box<str>, PackageEntry<L>>>,
specials: Vec<PackageSpecials<L>>,
visible_modes: Option<Vec<L::ModeId>>,
self_weak: Option<Weak<dyn SpecsProvider<L>>>,
}
impl<L: Lang> Package<L> {
pub fn new(name: impl Into<Box<str>>) -> Package<L> {
Package {
name: name.into(),
specs: HashMap::new(),
specials: Vec::new(),
visible_modes: None,
self_weak: None,
}
}
pub fn new_shared(
name: impl Into<Box<str>>,
build: impl FnOnce(&mut Package<L>),
) -> Arc<Package<L>> {
Arc::new_cyclic(|weak: &Weak<Package<L>>| {
let mut package = Package::new(name);
package.self_weak = Some(Weak::clone(weak) as Weak<dyn SpecsProvider<L>>);
build(&mut package);
package
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn is_shared(&self) -> bool {
self.self_weak.is_some()
}
pub fn provenance_for(
&self,
callable_type: L::CallableTypeId,
name: impl Into<Box<str>>,
) -> Option<SpecProvenance<L>> {
let provider = self.self_weak.as_ref()?;
Some(SpecProvenance::new(Weak::clone(provider), callable_type, DefinitionKey::Name(name.into())))
}
pub fn provenance_for_specials(
&self,
callable_type: L::CallableTypeId,
trigger: impl Into<Box<str>>,
) -> Option<SpecProvenance<L>> {
let provider = self.self_weak.as_ref()?;
Some(SpecProvenance::new(
Weak::clone(provider),
callable_type,
DefinitionKey::Trigger(trigger.into()),
))
}
pub fn insert<M>(
&mut self,
callable_type: L::CallableTypeId,
name: impl Into<Box<str>>,
spec: impl IntoCallableSpec<L, M>,
) -> Option<Arc<dyn CallableSpec<L>>> {
self.insert_in_modes(callable_type, name, spec, None)
}
pub fn insert_in_modes<M>(
&mut self,
callable_type: L::CallableTypeId,
name: impl Into<Box<str>>,
spec: impl IntoCallableSpec<L, M>,
visible_modes: Option<Vec<L::ModeId>>,
) -> Option<Arc<dyn CallableSpec<L>>> {
self.specs
.entry(callable_type)
.or_default()
.insert(
name.into(),
PackageEntry { spec: spec.into_callable_spec(), visible_modes },
)
.map(|previous| previous.spec)
}
pub fn insert_specials<M>(
&mut self,
callable_type: L::CallableTypeId,
trigger: impl Into<Box<str>>,
spec: impl IntoCallableSpec<L, M>,
) -> Option<Arc<dyn CallableSpec<L>>> {
self.insert_specials_in_modes(callable_type, trigger, spec, None)
}
pub fn insert_specials_in_modes<M>(
&mut self,
callable_type: L::CallableTypeId,
trigger: impl Into<Box<str>>,
spec: impl IntoCallableSpec<L, M>,
visible_modes: Option<Vec<L::ModeId>>,
) -> Option<Arc<dyn CallableSpec<L>>> {
let spec = spec.into_callable_spec();
let trigger = trigger.into();
if let Some(existing) =
self.specials.iter_mut().find(|entry| entry.trigger == trigger)
{
existing.callable_type = callable_type;
existing.visible_modes = visible_modes;
return Some(core::mem::replace(&mut existing.spec, spec));
}
self.specials.push(PackageSpecials { trigger, callable_type, spec, visible_modes });
self.specials.sort_by_key(|entry| core::cmp::Reverse(entry.trigger.len()));
None
}
pub fn set_visible_modes(&mut self, modes: Option<Vec<L::ModeId>>) {
self.visible_modes = modes;
}
pub fn get(
&self,
callable_type: L::CallableTypeId,
name: &str,
) -> Option<&Arc<dyn CallableSpec<L>>> {
self.specs.get(&callable_type)?.get(name).map(|entry| &entry.spec)
}
pub fn get_specials(
&self,
callable_type: L::CallableTypeId,
trigger: &str,
) -> Option<&Arc<dyn CallableSpec<L>>> {
self.specials
.iter()
.find(|entry| entry.callable_type == callable_type && &*entry.trigger == trigger)
.map(|entry| &entry.spec)
}
pub fn len(&self) -> usize {
self.specs.values().map(HashMap::len).sum::<usize>() + self.specials.len()
}
pub fn is_empty(&self) -> bool {
self.specs.values().all(HashMap::is_empty) && self.specials.is_empty()
}
fn visible_in(&self, mode: L::ModeId) -> bool {
modes_admit(&self.visible_modes, &mode)
}
}
impl<L: Lang> SpecsProvider<L> for Package<L> {
fn name(&self) -> &str {
&self.name
}
fn retrieve_spec(
&self,
query: &CallableQuery<'_, L>,
state: &ParsingState<L>,
) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError> {
if !self.visible_in(state.mode()) {
return Ok(None);
}
let Some(entry) =
self.specs.get(&query.callable_type).and_then(|defs| defs.get(query.name))
else {
return Ok(None);
};
if !modes_admit(&entry.visible_modes, &state.mode()) {
return Ok(None);
}
Ok(Some(Arc::clone(&entry.spec)))
}
fn scan_specials(
&self,
state: &ParsingState<L>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
let Some(rest) = content.get(pos..) else {
let detail = if pos > content.len() {
alloc::format!(
"Invalid position {pos} passed to ‘Package::scan_specials’: \
the position exceeds the content length ({})",
content.len()
)
} else {
alloc::format!(
"Invalid position {pos} passed to ‘Package::scan_specials’: \
the position is not a character boundary"
)
};
return Err(SpecialsScanError {
kind: TokenErrorKind::Custom(Box::new(
ImplementationError::new(detail)
.with_kind(ImplementationErrorKind::InvalidPosition),
)),
span: Span::empty(pos.min(content.len())),
});
};
if !self.visible_in(state.mode()) {
return Ok(None);
}
for entry in &self.specials {
if !modes_admit(&entry.visible_modes, &state.mode()) {
continue;
}
if rest.starts_with(&*entry.trigger) {
let end = pos + entry.trigger.len();
return Ok(Some(SpecialsMatch {
end,
callable_type: entry.callable_type,
spec: Arc::clone(&entry.spec),
}));
}
}
Ok(None)
}
fn specials_trigger_chars(&self) -> TriggerChars {
let mut chars = String::new();
for entry in &self.specials {
if let Some(first) = entry.trigger.chars().next() {
if !chars.contains(first) {
chars.push(first);
}
}
}
TriggerChars::Only(chars)
}
fn iter_symbols(
&self,
callable_type: L::CallableTypeId,
mode: L::ModeId,
) -> Option<Box<dyn Iterator<Item = SymbolEntry<'_, L>> + '_>> {
if !self.visible_in(mode) {
return Some(Box::new(core::iter::empty()));
}
let named = self
.specs
.get(&callable_type)
.into_iter()
.flat_map(HashMap::iter)
.filter(move |(_, entry)| modes_admit(&entry.visible_modes, &mode))
.map(move |(name, entry)| SymbolEntry {
callable_type,
name,
spec: &entry.spec,
});
let specials = self
.specials
.iter()
.filter(move |entry| {
entry.callable_type == callable_type && modes_admit(&entry.visible_modes, &mode)
})
.map(move |entry| SymbolEntry {
callable_type,
name: &entry.trigger,
spec: &entry.spec,
});
Some(Box::new(named.chain(specials)))
}
}
impl<L: Lang> Clone for Package<L> {
fn clone(&self) -> Self {
Package {
name: self.name.clone(),
specs: self.specs.clone(),
specials: self.specials.clone(),
visible_modes: self.visible_modes.clone(),
self_weak: None,
}
}
}
impl<L: Lang> fmt::Debug for Package<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Package")
.field("name", &self.name)
.field("definitions", &self.len())
.field("visible_modes", &self.visible_modes)
.field("shared", &self.is_shared())
.finish()
}
}
pub struct Scope<L: Lang> {
name: Box<str>,
#[allow(clippy::type_complexity)]
specs: BTreeMap<L::CallableTypeId, BTreeMap<Box<str>, Arc<dyn CallableSpec<L>>>>,
}
impl<L: Lang> Scope<L> {
pub fn new(name: impl Into<Box<str>>) -> Scope<L> {
Scope { name: name.into(), specs: BTreeMap::new() }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn insert(
&mut self,
callable_type: L::CallableTypeId,
name: impl Into<Box<str>>,
spec: Arc<dyn CallableSpec<L>>,
) -> Option<Arc<dyn CallableSpec<L>>> {
self.specs.entry(callable_type).or_default().insert(name.into(), spec)
}
pub fn remove(
&mut self,
callable_type: L::CallableTypeId,
name: &str,
) -> Option<Arc<dyn CallableSpec<L>>> {
self.specs.get_mut(&callable_type)?.remove(name)
}
pub fn get(
&self,
callable_type: L::CallableTypeId,
name: &str,
) -> Option<&Arc<dyn CallableSpec<L>>> {
self.specs.get(&callable_type)?.get(name)
}
pub fn len(&self) -> usize {
self.specs.values().map(BTreeMap::len).sum()
}
pub fn is_empty(&self) -> bool {
self.specs.values().all(BTreeMap::is_empty)
}
pub fn definitions(
&self,
) -> impl Iterator<Item = (L::CallableTypeId, &str, &Arc<dyn CallableSpec<L>>)> + '_ {
self.specs.iter().flat_map(|(callable_type, definitions)| {
definitions.iter().map(move |(name, spec)| (*callable_type, &**name, spec))
})
}
}
impl<L: Lang> SpecsProvider<L> for Scope<L> {
fn name(&self) -> &str {
&self.name
}
fn retrieve_spec(
&self,
query: &CallableQuery<'_, L>,
_state: &ParsingState<L>,
) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError> {
Ok(self.get(query.callable_type, query.name).cloned())
}
fn with_definitions(
&self,
ops: &[DefinitionOp<L>],
) -> Result<Arc<dyn SpecsProvider<L>>, ProviderError> {
let mut fresh = self.clone();
for op in ops {
match op {
DefinitionOp::Define { callable_type, name, spec } => {
fresh.insert(*callable_type, name.clone(), Arc::clone(spec));
}
DefinitionOp::Remove { callable_type, name } => {
if fresh.remove(*callable_type, name).is_none() {
return Err(ProviderError::UndefinedName { name: name.clone() });
}
}
}
}
Ok(Arc::new(fresh))
}
fn iter_symbols(
&self,
callable_type: L::CallableTypeId,
mode: L::ModeId,
) -> Option<Box<dyn Iterator<Item = SymbolEntry<'_, L>> + '_>> {
let _ = mode;
let entries = self
.specs
.get(&callable_type)
.into_iter()
.flat_map(BTreeMap::iter)
.map(move |(name, spec)| SymbolEntry { callable_type, name, spec });
Some(Box::new(entries))
}
}
impl<L: Lang> Clone for Scope<L> {
fn clone(&self) -> Self {
Scope { name: self.name.clone(), specs: self.specs.clone() }
}
}
impl<L: Lang> fmt::Debug for Scope<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Scope")
.field("name", &self.name)
.field("definitions", &self.len())
.finish()
}
}
pub struct FallbackProvider<L: Lang> {
name: Box<str>,
fallbacks: BTreeMap<L::CallableTypeId, Arc<dyn CallableSpec<L>>>,
}
impl<L: Lang> FallbackProvider<L> {
pub fn new(name: impl Into<Box<str>>) -> FallbackProvider<L> {
FallbackProvider { name: name.into(), fallbacks: BTreeMap::new() }
}
pub fn set(
&mut self,
callable_type: L::CallableTypeId,
spec: Arc<dyn CallableSpec<L>>,
) -> Option<Arc<dyn CallableSpec<L>>> {
self.fallbacks.insert(callable_type, spec)
}
pub fn get(&self, callable_type: L::CallableTypeId) -> Option<&Arc<dyn CallableSpec<L>>> {
self.fallbacks.get(&callable_type)
}
pub fn fallbacks(&self) -> impl Iterator<Item = (L::CallableTypeId, &Arc<dyn CallableSpec<L>>)> + '_ {
self.fallbacks.iter().map(|(callable_type, spec)| (*callable_type, spec))
}
}
impl<L: Lang> SpecsProvider<L> for FallbackProvider<L> {
fn name(&self) -> &str {
&self.name
}
fn retrieve_spec(
&self,
query: &CallableQuery<'_, L>,
_state: &ParsingState<L>,
) -> Result<Option<Arc<dyn CallableSpec<L>>>, ProviderError> {
Ok(self.fallbacks.get(&query.callable_type).cloned())
}
}
impl<L: Lang> Clone for FallbackProvider<L> {
fn clone(&self) -> Self {
FallbackProvider { name: self.name.clone(), fallbacks: self.fallbacks.clone() }
}
}
impl<L: Lang> fmt::Debug for FallbackProvider<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FallbackProvider")
.field("name", &self.name)
.field("callable_types", &self.fallbacks.len())
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.callable-defined-as-error")]
pub struct CallableDefinedAsError {
pub name: String,
pub detail: Option<String>,
}
impl fmt::Display for CallableDefinedAsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "‘{}’ may not be used", self.name)?;
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct ErrorCallableSpec {
pub detail: Option<Box<str>>,
}
impl ErrorCallableSpec {
pub fn new() -> ErrorCallableSpec {
ErrorCallableSpec { detail: None }
}
pub fn with_detail(detail: impl Into<Box<str>>) -> ErrorCallableSpec {
ErrorCallableSpec { detail: Some(detail.into()) }
}
}
impl<L: Lang> CallableSpec<L> for ErrorCallableSpec {
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, L>,
) -> Result<
Box<dyn ConstructParser<L, Output = BuildId> + 'a>,
crate::error::ParseError<L::SourceOrigin>,
>
{
Ok(Box::new(ErrorInvocationParser { invocation, detail: self.detail.as_deref() }))
}
}
struct ErrorInvocationParser<'a, L: Lang> {
invocation: Invocation<'a, L>,
detail: Option<&'a str>,
}
impl<L: Lang> ConstructParser<L> for ErrorInvocationParser<'_, L> {
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
) -> ConstructParserResult<L, (BuildId, Option<Box<ParsingStateDelta<L>>>)> {
let span = cx.tokens.source_span_of(self.invocation.token);
cx.recover(
CallableDefinedAsError {
name: self.invocation.name.into(),
detail: self.detail.map(String::from),
},
span.clone(),
)?;
let id = cx
.stage_node(
NodeKind::chars(span.span()),
span.clone(),
Arc::clone(&cx.state),
Vec::new(),
)
.map_err(|error| cx.staging_error(error, span))?;
Ok((id, None))
}
}
pub struct ScopeStack<L: Lang> {
#[allow(clippy::type_complexity)]
stack: <<L::Features as LangFeatures>::Scopes as FeaturePresence>::Store<
Vec<Arc<dyn SpecsProvider<L>>>,
>,
}
impl<L: Lang> ScopeStack<L> {
pub fn new() -> ScopeStack<L> {
ScopeStack { stack: <L::Features as LangFeatures>::Scopes::store_with(Vec::new) }
}
pub(crate) fn from_providers(providers: Vec<Arc<dyn SpecsProvider<L>>>) -> Option<ScopeStack<L>> {
if !<L::Features as LangFeatures>::Scopes::PRESENT && !providers.is_empty() {
return None;
}
Some(ScopeStack { stack: <L::Features as LangFeatures>::Scopes::store_with(|| providers) })
}
fn entries(&self) -> &[Arc<dyn SpecsProvider<L>>] {
<L::Features as LangFeatures>::Scopes::store_get(&self.stack)
.map_or(&[], |providers| providers.as_slice())
}
pub fn push(&mut self, provider: Arc<dyn SpecsProvider<L>>)
where
L: LangHasScopes,
{
self.stack.push(provider);
}
pub fn providers(&self) -> &[Arc<dyn SpecsProvider<L>>] {
self.entries()
}
pub fn provider_names(&self) -> impl Iterator<Item = &str> + '_ {
self.entries().iter().rev().map(|provider| provider.name())
}
pub fn searched_providers(&self) -> SearchedProviders<'_, L> {
SearchedProviders { stack: self }
}
pub fn len(&self) -> usize {
self.entries().len()
}
pub fn is_empty(&self) -> bool {
self.entries().is_empty()
}
pub fn retrieve_spec(
&self,
query: &CallableQuery<'_, L>,
state: &ParsingState<L>,
) -> Result<Option<Arc<dyn CallableSpec<L>>>, ScopeStackError> {
for provider in self.entries().iter().rev() {
match provider.retrieve_spec(query, state) {
Ok(Some(spec)) => return Ok(Some(spec)),
Ok(None) => {}
Err(error) => {
return Err(ScopeStackError { provider: provider.name().into(), error })
}
}
}
Ok(None)
}
pub fn scan_specials(
&self,
state: &ParsingState<L>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<L>>, SpecialsScanError> {
let mut best: Option<SpecialsMatch<L>> = None;
for provider in self.entries().iter().rev() {
if let Some(matched) = provider.scan_specials(state, content, pos)? {
if best.as_ref().is_none_or(|current| matched.end > current.end) {
best = Some(matched);
}
}
}
Ok(best)
}
pub fn specials_trigger_chars(&self) -> TriggerChars {
let mut union = TriggerChars::default();
for provider in self.entries() {
union = union.union(&provider.specials_trigger_chars());
}
union
}
pub fn iter_symbols(
&self,
callable_type: L::CallableTypeId,
mode: L::ModeId,
) -> Vec<SymbolEntry<'_, L>> {
let mut seen: hashbrown::HashSet<&str> = hashbrown::HashSet::new();
let mut symbols = Vec::new();
for provider in self.entries().iter().rev() {
let Some(entries) = provider.iter_symbols(callable_type, mode) else {
continue;
};
for entry in entries {
if seen.insert(entry.name) {
symbols.push(entry);
}
}
}
symbols
}
pub fn apply_op(&mut self, op: &ScopeOp<L>) -> Result<(), ScopeOpError> {
let Some(stack) =
<L::Features as LangFeatures>::Scopes::store_get_mut(&mut self.stack)
else {
return Err(ScopeOpError::ScopesAbsent);
};
match op {
ScopeOp::Push(provider) => {
stack.push(Arc::clone(provider));
Ok(())
}
ScopeOp::Unload { name } => {
let index = Self::innermost_position(stack, name).ok_or_else(|| {
ScopeOpError::UnknownProvider { name: name.clone() }
})?;
stack.remove(index);
Ok(())
}
ScopeOp::Replace { name, provider } => {
let index = Self::innermost_position(stack, name).ok_or_else(|| {
ScopeOpError::UnknownProvider { name: name.clone() }
})?;
stack[index] = Arc::clone(provider);
Ok(())
}
ScopeOp::ReplaceStack(providers) => {
*stack = providers.clone();
Ok(())
}
ScopeOp::Define { scope, callable_type, name, spec } => {
let op = DefinitionOp::Define {
callable_type: *callable_type,
name: name.clone(),
spec: Arc::clone(spec),
};
match Self::innermost_position(stack, scope) {
Some(index) => Self::route_definition(stack, index, scope, op),
None => {
let mut fresh = Scope::new(scope.clone());
fresh.insert(*callable_type, name.clone(), Arc::clone(spec));
stack.push(Arc::new(fresh));
Ok(())
}
}
}
ScopeOp::Remove { scope, callable_type, name } => {
let op = DefinitionOp::Remove {
callable_type: *callable_type,
name: name.clone(),
};
let index = Self::innermost_position(stack, scope).ok_or_else(|| {
ScopeOpError::UnknownProvider { name: scope.clone() }
})?;
Self::route_definition(stack, index, scope, op)
}
}
}
fn route_definition(
stack: &mut [Arc<dyn SpecsProvider<L>>],
index: usize,
scope: &str,
op: DefinitionOp<L>,
) -> Result<(), ScopeOpError> {
match stack[index].with_definitions(&[op]) {
Ok(fresh) => {
stack[index] = fresh;
Ok(())
}
Err(error) => Err(ScopeOpError::Provider(ScopeStackError {
provider: scope.into(),
error,
})),
}
}
fn innermost_position(
stack: &[Arc<dyn SpecsProvider<L>>],
name: &str,
) -> Option<usize> {
stack.iter().rposition(|provider| provider.name() == name)
}
}
impl<L: Lang> Default for ScopeStack<L> {
fn default() -> Self {
ScopeStack::new()
}
}
impl<L: Lang> Clone for ScopeStack<L> {
fn clone(&self) -> Self {
ScopeStack { stack: self.stack.clone() }
}
}
impl<L: Lang> fmt::Debug for ScopeStack<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScopeStack").field("providers", &self.stack).finish()
}
}
pub struct SearchedProviders<'a, L: Lang> {
stack: &'a ScopeStack<L>,
}
impl<L: Lang> fmt::Display for SearchedProviders<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.stack.is_empty() {
return write!(f, "missing definition providers on the scope stack");
}
let noun = if self.stack.len() == 1 { "provider" } else { "providers" };
write!(f, "no definition in {noun} ")?;
for (i, name) in self.stack.provider_names().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "‘{name}’")?;
}
Ok(())
}
}
impl<L: Lang> fmt::Debug for SearchedProviders<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::spec::StdCallableSpec;
use crate::state::StateData;
use crate::token::{
CommandRules, CommentRules, ForbiddenCharsRules, GroupRules, ParagraphRules,
SpecialsRules, TokenErrorKind, TokenRules, WhitespaceRules,
};
use alloc::string::{String, ToString};
use alloc::vec;
const MACRO: u32 = 0;
const ENVIRONMENT: u32 = 1;
#[derive(Debug, Clone, Copy)]
struct PlainLang;
impl crate::state::TrivialLang for PlainLang {}
fn min_rules<L: Lang<Features = crate::state::AllLangFeatures>>() -> TokenRules<L> {
TokenRules {
whitespace: WhitespaceRules::empty(),
paragraphs: ParagraphRules { enabled: false },
groups: GroupRules {
enabled: true,
rules: vec![],
temporary: vec![],
expecting_close: None,
},
commands: CommandRules {
enabled: true,
rules: vec![],
},
comments: CommentRules {
enabled: true,
rules: vec![],
},
specials: SpecialsRules { enabled: true },
forbidden_chars: ForbiddenCharsRules { chars: "".into() },
}
}
fn state_with(scopes: ScopeStack<PlainLang>) -> ParsingState<PlainLang> {
ParsingState::new(StateData { rules: min_rules(), scopes, mode: (), ext: () })
}
fn new_spec<L: Lang>() -> Arc<dyn CallableSpec<L>> {
Arc::new(StdCallableSpec::default())
}
fn macro_query(name: &str) -> CallableQuery<'_, PlainLang> {
CallableQuery::new(MACRO, name, CallableSyntax::Command { escape_char: '\\' })
}
fn package_with(name: &str, definitions: &[(&str, &Arc<dyn CallableSpec<PlainLang>>)]) -> Package<PlainLang> {
let mut package = Package::new(name);
for (defined, spec) in definitions {
package.insert(MACRO, *defined, Arc::clone(spec));
}
package
}
#[test]
fn dyn_specs_provider_downcasts_to_its_concrete_type() {
let provider: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(Package::new("mypkg"));
let any: &dyn Any = &*provider;
let package = any.downcast_ref::<Package<PlainLang>>().expect("downcast to Package");
assert_eq!(package.name(), "mypkg");
}
#[test]
fn package_insert_get_replace() {
let mut package: Package<PlainLang> = Package::new("test");
assert!(package.is_empty());
let first = new_spec();
let second = new_spec();
assert!(package.insert(MACRO, "foo", first.clone()).is_none());
assert!(Arc::ptr_eq(package.get(MACRO, "foo").unwrap(), &first));
let previous = package.insert(MACRO, "foo", second.clone()).unwrap();
assert!(Arc::ptr_eq(&previous, &first));
assert!(package.get(ENVIRONMENT, "foo").is_none());
assert_eq!(package.len(), 1);
}
#[test]
fn specs_are_flyweights_across_names() {
let mut package: Package<PlainLang> = Package::new("test");
let shared = new_spec();
package.insert(MACRO, "emph", shared.clone());
package.insert(MACRO, "textit", shared.clone());
let a = package.get(MACRO, "emph").unwrap();
let b = package.get(MACRO, "textit").unwrap();
assert!(Arc::ptr_eq(a, b));
}
#[test]
fn a_shared_package_may_build_another_shared_package_inside_its_own_build() {
let mut outer_stamp = None;
let mut inner = None;
let outer = Package::<PlainLang>::new_shared("outer", |package| {
let stamp = package.provenance_for(MACRO, "outer-macro").expect("a shared package stamps");
assert!(stamp.provider().is_none());
package.insert(MACRO, "outer-macro", new_spec());
let nested = Package::<PlainLang>::new_shared("inner", |nested| {
let nested_stamp = nested.provenance_for(MACRO, "inner-macro").expect("a shared package stamps");
assert!(nested_stamp.provider().is_none());
nested.insert(MACRO, "inner-macro", new_spec());
});
assert!(nested.is_shared());
let nested_stamp = nested.provenance_for(MACRO, "inner-macro").unwrap();
assert_eq!(nested_stamp.provider().expect("the inner package is finished").name(), "inner");
outer_stamp = Some(stamp);
inner = Some(nested);
});
assert!(outer.is_shared());
let inner = inner.unwrap();
assert!(inner.is_shared());
assert!(inner.get(MACRO, "inner-macro").is_some());
assert!(outer.get(MACRO, "outer-macro").is_some());
let provider = outer_stamp.unwrap().provider().expect("the outer package is finished");
assert_eq!(provider.name(), "outer");
let outer_provider: Arc<dyn SpecsProvider<PlainLang>> = outer.clone();
assert!(Arc::ptr_eq(&provider, &outer_provider));
let nested_stamp = inner.provenance_for(MACRO, "inner-macro").unwrap();
let inner_provider: Arc<dyn SpecsProvider<PlainLang>> = inner.clone();
assert!(Arc::ptr_eq(&nested_stamp.provider().unwrap(), &inner_provider));
}
#[test]
fn stack_retrieval_innermost_wins() {
let outer_spec = new_spec();
let inner_spec = new_spec();
let outer = package_with("outer", &[("foo", &outer_spec), ("bar", &outer_spec)]);
let inner = package_with("inner", &[("foo", &inner_spec)]);
let mut stack = ScopeStack::new();
stack.push(Arc::new(outer));
stack.push(Arc::new(inner));
let st = state_with(ScopeStack::new());
let foo = stack.retrieve_spec(¯o_query("foo"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&foo, &inner_spec));
let bar = stack.retrieve_spec(¯o_query("bar"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&bar, &outer_spec));
assert!(stack.retrieve_spec(¯o_query("nope"), &st).unwrap().is_none());
}
#[test]
fn fallback_provider_is_ordinary_bottom_of_stack_policy() {
let defined = new_spec();
let unknown_macro = new_spec();
let mut fallbacks: FallbackProvider<PlainLang> = FallbackProvider::new("fallbacks");
assert!(fallbacks.set(MACRO, unknown_macro.clone()).is_none());
assert!(Arc::ptr_eq(fallbacks.get(MACRO).unwrap(), &unknown_macro));
let mut stack = ScopeStack::new();
stack.push(Arc::new(fallbacks)); stack.push(Arc::new(package_with("outer", &[("known", &defined)])));
let st = state_with(ScopeStack::new());
let known = stack.retrieve_spec(¯o_query("known"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&known, &defined));
let a = stack.retrieve_spec(¯o_query("nope"), &st).unwrap().unwrap();
let b = stack.retrieve_spec(¯o_query("also-nope"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&a, &unknown_macro));
assert!(Arc::ptr_eq(&a, &b));
let env_query =
CallableQuery::new(ENVIRONMENT, "nope", CallableSyntax::Command { escape_char: '\\' });
assert!(stack.retrieve_spec(&env_query, &st).unwrap().is_none());
}
#[test]
fn error_spec_shadowing_suppresses_lower_entries_and_fallback() {
let real = new_spec();
let error_spec: Arc<dyn CallableSpec<PlainLang>> =
Arc::new(ErrorCallableSpec::with_detail("removed on purpose"));
let mut fallbacks: FallbackProvider<PlainLang> = FallbackProvider::new("fallbacks");
fallbacks.set(MACRO, new_spec());
let mut shadow: Scope<PlainLang> = Scope::new("shadow");
shadow.insert(MACRO, "gone", Arc::clone(&error_spec));
let mut stack = ScopeStack::new();
stack.push(Arc::new(fallbacks));
stack.push(Arc::new(package_with("outer", &[("gone", &real)])));
stack.push(Arc::new(shadow));
let st = state_with(ScopeStack::new());
let resolved = stack.retrieve_spec(¯o_query("gone"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&resolved, &error_spec));
}
#[test]
fn provider_error_aborts_retrieval_with_the_providers_name() {
#[derive(Debug)]
struct Failing;
impl SerializableObject<PlainLang> for Failing {}
impl SpecsProvider<PlainLang> for Failing {
fn name(&self) -> &str {
"failing"
}
fn retrieve_spec(
&self,
_query: &CallableQuery<'_, PlainLang>,
_state: &ParsingState<PlainLang>,
) -> Result<Option<Arc<dyn CallableSpec<PlainLang>>>, ProviderError> {
Err(ProviderError::Failed("backing store unavailable".into()))
}
}
let answer = new_spec();
let mut stack = ScopeStack::new();
stack.push(Arc::new(package_with("outer", &[("foo", &answer)])));
stack.push(Arc::new(Failing)); let st = state_with(ScopeStack::new());
let error = stack.retrieve_spec(¯o_query("foo"), &st).unwrap_err();
assert_eq!(&*error.provider, "failing");
assert_eq!(error.error, ProviderError::Failed("backing store unavailable".into()));
assert!(error.to_string().contains("failing"));
}
#[test]
fn searched_providers_reports_innermost_first() {
let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
assert_eq!(stack.provider_names().count(), 0);
stack.push(Arc::new(package_with("outer", &[])));
stack.push(Arc::new(package_with("inner", &[])));
assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["inner", "outer"]);
let rendered = stack.searched_providers().to_string();
let inner = rendered.find("inner").expect("names the inner provider");
let outer = rendered.find("outer").expect("names the outer provider");
assert!(inner < outer, "{rendered}");
}
#[test]
fn provider_can_dispatch_on_syntax() {
#[derive(Debug)]
struct BySyntax {
backslash: Arc<dyn CallableSpec<PlainLang>>,
hash: Arc<dyn CallableSpec<PlainLang>>,
}
impl SerializableObject<PlainLang> for BySyntax {}
impl SpecsProvider<PlainLang> for BySyntax {
fn name(&self) -> &str {
"by-syntax"
}
fn retrieve_spec(
&self,
query: &CallableQuery<'_, PlainLang>,
_state: &ParsingState<PlainLang>,
) -> Result<Option<Arc<dyn CallableSpec<PlainLang>>>, ProviderError> {
Ok(match query.syntax {
CallableSyntax::Command { escape_char: '\\' } => Some(self.backslash.clone()),
CallableSyntax::Command { escape_char: '#' } => Some(self.hash.clone()),
_ => None,
})
}
}
let by_syntax = BySyntax { backslash: new_spec(), hash: new_spec() };
let backslash_spec = by_syntax.backslash.clone();
let hash_spec = by_syntax.hash.clone();
let mut stack = ScopeStack::new();
stack.push(Arc::new(by_syntax));
let st = state_with(ScopeStack::new());
let via_backslash = stack.retrieve_spec(¯o_query("foo"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&via_backslash, &backslash_spec));
let hash_query =
CallableQuery::new(MACRO, "foo", CallableSyntax::Command { escape_char: '#' });
let via_hash = stack.retrieve_spec(&hash_query, &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&via_hash, &hash_spec));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, core::hash::Hash, Default)]
enum Mode {
#[default]
Text,
Math,
}
#[derive(Debug, Clone, Copy)]
struct ModedLang;
impl Lang for ModedLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = Mode;
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = crate::engine::StdParseDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
fn moded_state(scopes: ScopeStack<ModedLang>, mode: Mode) -> ParsingState<ModedLang> {
ParsingState::new(StateData { rules: min_rules(), scopes, mode, ext: () })
}
#[test]
fn package_mode_visibility_is_checked_by_the_package_itself() {
let math_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let text_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let mut math_pkg: Package<ModedLang> = Package::new("math-only");
math_pkg.insert(MACRO, "vec", Arc::clone(&math_spec));
math_pkg.insert_specials(MACRO, "&", Arc::clone(&math_spec));
math_pkg.set_visible_modes(Some(vec![Mode::Math]));
let mut base: Package<ModedLang> = Package::new("allmodes");
base.insert(MACRO, "vec", Arc::clone(&text_spec));
let mut stack = ScopeStack::new();
stack.push(Arc::new(base));
stack.push(Arc::new(math_pkg)); let text_state = moded_state(stack.clone(), Mode::Text);
let math_state = moded_state(stack.clone(), Mode::Math);
let query: CallableQuery<'_, ModedLang> =
CallableQuery::new(MACRO, "vec", CallableSyntax::Command { escape_char: '\\' });
let in_text = stack.retrieve_spec(&query, &text_state).unwrap().unwrap();
assert!(Arc::ptr_eq(&in_text, &text_spec));
let in_math = stack.retrieve_spec(&query, &math_state).unwrap().unwrap();
assert!(Arc::ptr_eq(&in_math, &math_spec));
assert!(stack.scan_specials(&text_state, "&x", 0).unwrap().is_none());
assert!(stack.scan_specials(&math_state, "&x", 0).unwrap().is_some());
assert_eq!(stack.specials_trigger_chars(), TriggerChars::Only("&".into()));
}
#[test]
fn per_entry_mode_visibility_gates_within_a_package() {
let text_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let any_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let mut pkg: Package<ModedLang> = Package::new("mixed");
pkg.insert_in_modes(MACRO, "emph", Arc::clone(&text_spec), Some(vec![Mode::Text]));
pkg.insert(MACRO, "vec", Arc::clone(&any_spec)); pkg.insert_specials_in_modes(MACRO, "--", Arc::clone(&text_spec), Some(vec![Mode::Text]));
pkg.insert_specials(MACRO, "~", Arc::clone(&any_spec));
let mut stack = ScopeStack::new();
stack.push(Arc::new(pkg));
let text_state = moded_state(stack.clone(), Mode::Text);
let math_state = moded_state(stack.clone(), Mode::Math);
let emph: CallableQuery<'_, ModedLang> =
CallableQuery::new(MACRO, "emph", CallableSyntax::Command { escape_char: '\\' });
let vec_q: CallableQuery<'_, ModedLang> =
CallableQuery::new(MACRO, "vec", CallableSyntax::Command { escape_char: '\\' });
assert!(stack.retrieve_spec(&emph, &text_state).unwrap().is_some());
assert!(stack.retrieve_spec(&emph, &math_state).unwrap().is_none());
assert!(stack.retrieve_spec(&vec_q, &text_state).unwrap().is_some());
assert!(stack.retrieve_spec(&vec_q, &math_state).unwrap().is_some());
assert!(stack.scan_specials(&text_state, "--x", 0).unwrap().is_some());
assert!(stack.scan_specials(&math_state, "--x", 0).unwrap().is_none());
assert!(stack.scan_specials(&text_state, "~x", 0).unwrap().is_some());
assert!(stack.scan_specials(&math_state, "~x", 0).unwrap().is_some());
}
#[test]
fn scope_with_definitions_is_functional_and_atomic() {
let original_spec = new_spec();
let mut scope: Scope<PlainLang> = Scope::new("user");
scope.insert(MACRO, "foo", Arc::clone(&original_spec));
let scope: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(scope);
let st = state_with(ScopeStack::new());
let added = new_spec();
let fresh = scope
.with_definitions(&[DefinitionOp::Define {
callable_type: MACRO,
name: "bar".into(),
spec: Arc::clone(&added),
}])
.unwrap();
assert!(fresh.retrieve_spec(¯o_query("bar"), &st).unwrap().is_some());
assert!(scope.retrieve_spec(¯o_query("bar"), &st).unwrap().is_none());
let removed = fresh
.with_definitions(&[DefinitionOp::Remove { callable_type: MACRO, name: "foo".into() }])
.unwrap();
assert!(removed.retrieve_spec(¯o_query("foo"), &st).unwrap().is_none());
let error = removed
.with_definitions(&[DefinitionOp::Remove { callable_type: MACRO, name: "foo".into() }])
.unwrap_err();
assert_eq!(error, ProviderError::UndefinedName { name: "foo".into() });
let error = scope
.with_definitions(&[
DefinitionOp::Define {
callable_type: MACRO,
name: "baz".into(),
spec: new_spec(),
},
DefinitionOp::Remove { callable_type: MACRO, name: "absent".into() },
])
.unwrap_err();
assert_eq!(error, ProviderError::UndefinedName { name: "absent".into() });
assert!(scope.retrieve_spec(¯o_query("baz"), &st).unwrap().is_none());
}
#[test]
fn immutable_providers_refuse_definition_ops() {
let package: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("pkg", &[]));
let error = package
.with_definitions(&[DefinitionOp::Remove { callable_type: MACRO, name: "x".into() }])
.unwrap_err();
assert_eq!(error, ProviderError::NotMutable);
}
#[test]
fn apply_op_stack_shapes() {
let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
let a: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("a", &[]));
let b: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("b", &[]));
let b2: Arc<dyn SpecsProvider<PlainLang>> = Arc::new(package_with("b", &[]));
stack.apply_op(&ScopeOp::Push(Arc::clone(&a))).unwrap();
stack.apply_op(&ScopeOp::Push(Arc::clone(&b))).unwrap();
assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["b", "a"]);
stack.apply_op(&ScopeOp::Replace { name: "b".into(), provider: Arc::clone(&b2) }).unwrap();
assert!(Arc::ptr_eq(&stack.providers()[1], &b2));
stack.apply_op(&ScopeOp::Unload { name: "b".into() }).unwrap();
assert_eq!(stack.len(), 1);
let error = stack.apply_op(&ScopeOp::Unload { name: "b".into() }).unwrap_err();
assert_eq!(error, ScopeOpError::UnknownProvider { name: "b".into() });
let error = stack
.apply_op(&ScopeOp::Replace { name: "zz".into(), provider: Arc::clone(&b2) })
.unwrap_err();
assert_eq!(error, ScopeOpError::UnknownProvider { name: "zz".into() });
stack.apply_op(&ScopeOp::ReplaceStack(vec![Arc::clone(&b2)])).unwrap();
assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["b"]);
}
#[test]
fn apply_op_define_routes_cow_and_lazily_creates() {
let st = state_with(ScopeStack::new());
let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
let mut user: Scope<PlainLang> = Scope::new("user");
user.insert(MACRO, "foo", new_spec());
stack.push(Arc::new(user));
stack.push(Arc::new(package_with("pkg", &[])));
let before = stack.clone();
let added = new_spec();
stack
.apply_op(&ScopeOp::Define {
scope: "user".into(),
callable_type: MACRO,
name: "bar".into(),
spec: Arc::clone(&added),
})
.unwrap();
let bar = stack.retrieve_spec(¯o_query("bar"), &st).unwrap().unwrap();
assert!(Arc::ptr_eq(&bar, &added));
assert!(before.retrieve_spec(¯o_query("bar"), &st).unwrap().is_none());
assert!(!Arc::ptr_eq(&stack.providers()[0], &before.providers()[0]));
assert!(Arc::ptr_eq(&stack.providers()[1], &before.providers()[1]));
stack
.apply_op(&ScopeOp::Define {
scope: "local".into(),
callable_type: MACRO,
name: "baz".into(),
spec: new_spec(),
})
.unwrap();
assert_eq!(stack.provider_names().collect::<Vec<_>>(), vec!["local", "pkg", "user"]);
assert!(stack.retrieve_spec(¯o_query("baz"), &st).unwrap().is_some());
let error = stack
.apply_op(&ScopeOp::Define {
scope: "pkg".into(),
callable_type: MACRO,
name: "x".into(),
spec: new_spec(),
})
.unwrap_err();
assert_eq!(
error,
ScopeOpError::Provider(ScopeStackError {
provider: "pkg".into(),
error: ProviderError::NotMutable,
})
);
stack
.apply_op(&ScopeOp::Remove {
scope: "user".into(),
callable_type: MACRO,
name: "bar".into(),
})
.unwrap();
assert!(stack.retrieve_spec(¯o_query("bar"), &st).unwrap().is_none());
let error = stack
.apply_op(&ScopeOp::Remove {
scope: "nowhere".into(),
callable_type: MACRO,
name: "bar".into(),
})
.unwrap_err();
assert_eq!(error, ScopeOpError::UnknownProvider { name: "nowhere".into() });
}
fn specials_package(
name: &str,
triggers: &[(&str, &Arc<dyn CallableSpec<PlainLang>>)],
) -> Package<PlainLang> {
let mut package = Package::new(name);
for (trigger, spec) in triggers {
package.insert_specials(MACRO, *trigger, Arc::clone(spec));
}
package
}
#[test]
fn package_specials_match_longest_within_the_package() {
let short = new_spec();
let long = new_spec();
let mut package = specials_package("lig", &[("--", &short), ("---", &long)]);
let st = state_with(ScopeStack::new());
let matched = package.scan_specials(&st, "---x", 0).unwrap().unwrap();
assert_eq!(matched.end, 3);
assert!(Arc::ptr_eq(&matched.spec, &long));
let matched = package.scan_specials(&st, "--x", 0).unwrap().unwrap();
assert_eq!(matched.end, 2);
assert!(package.scan_specials(&st, "x--", 0).unwrap().is_none());
let matched = package.scan_specials(&st, "a--b", 1).unwrap().unwrap();
assert_eq!(matched.end, 3);
let replacement = new_spec();
let previous = package.insert_specials(MACRO, "---", Arc::clone(&replacement)).unwrap();
assert!(Arc::ptr_eq(&previous, &long));
let matched = package.scan_specials(&st, "---", 0).unwrap().unwrap();
assert!(Arc::ptr_eq(&matched.spec, &replacement));
assert_eq!(package.specials_trigger_chars(), TriggerChars::Only("-".into()));
}
#[test]
fn package_scan_specials_rejects_invalid_positions_with_an_error() {
let spec = new_spec();
let package = specials_package("lig", &[("--", &spec)]);
let st = state_with(ScopeStack::new());
let is_implementation_error = |kind: &TokenErrorKind| match kind {
TokenErrorKind::Custom(data) => {
data.downcast_ref::<crate::constructs::ImplementationError>().map(|e| e.kind)
== Some(ImplementationErrorKind::InvalidPosition)
}
_ => false,
};
let error = package.scan_specials(&st, "--", 7).unwrap_err();
assert!(is_implementation_error(&error.kind), "{:?}", error);
assert_eq!(error.span, crate::source::Span::empty(2));
let error = package.scan_specials(&st, "é--", 1).unwrap_err();
assert!(is_implementation_error(&error.kind), "{:?}", error);
assert_eq!(error.span, crate::source::Span::empty(1));
assert!(package.scan_specials(&st, "x--", 1).unwrap().is_some());
assert!(package.scan_specials(&st, "--", 2).unwrap().is_none());
assert!(package.scan_specials(&st, "é--", 2).unwrap().is_some());
}
#[test]
fn stack_specials_fold_longest_wins_ties_innermost() {
let inner_short = new_spec();
let outer_long = new_spec();
let outer_short = new_spec();
let inner = specials_package("inner", &[("--", &inner_short)]);
let outer = specials_package("outer", &[("--", &outer_short), ("---", &outer_long)]);
let mut stack = ScopeStack::new();
stack.push(Arc::new(outer));
stack.push(Arc::new(inner));
let st = state_with(ScopeStack::new());
let matched = stack.scan_specials(&st, "---", 0).unwrap().unwrap();
assert_eq!(matched.end, 3);
assert!(Arc::ptr_eq(&matched.spec, &outer_long));
let matched = stack.scan_specials(&st, "--x", 0).unwrap().unwrap();
assert!(Arc::ptr_eq(&matched.spec, &inner_short));
assert_eq!(stack.specials_trigger_chars(), TriggerChars::Only("-".into()));
}
#[test]
fn stack_specials_fold_propagates_provider_scan_errors() {
#[derive(Debug)]
struct FailingScan;
impl SerializableObject<PlainLang> for FailingScan {}
impl SpecsProvider<PlainLang> for FailingScan {
fn name(&self) -> &str {
"failing-scan"
}
fn retrieve_spec(
&self,
_query: &CallableQuery<'_, PlainLang>,
_state: &ParsingState<PlainLang>,
) -> Result<Option<Arc<dyn CallableSpec<PlainLang>>>, ProviderError> {
Ok(None)
}
fn scan_specials(
&self,
_state: &ParsingState<PlainLang>,
_content: &str,
_pos: usize,
) -> Result<Option<SpecialsMatch<PlainLang>>, SpecialsScanError> {
Err(SpecialsScanError {
kind: TokenErrorKind::Custom(Box::new(
crate::constructs::ImplementationError::new("scan broke".to_string()),
)),
span: crate::source::Span::new(0, 1),
})
}
fn specials_trigger_chars(&self) -> TriggerChars {
TriggerChars::Any
}
}
let ok = new_spec();
let mut stack = ScopeStack::new();
stack.push(Arc::new(specials_package("outer", &[("-", &ok)])));
stack.push(Arc::new(FailingScan));
let st = state_with(ScopeStack::new());
let error = stack.scan_specials(&st, "-", 0).unwrap_err();
let TokenErrorKind::Custom(data) = &error.kind else {
panic!("the provider's own error kind: {:?}", error);
};
let condition = data
.downcast_ref::<crate::constructs::ImplementationError>()
.expect("the provider's own condition");
assert_eq!(condition.detail, "scan broke");
assert_eq!(error.span, crate::source::Span::new(0, 1));
assert_eq!(stack.specials_trigger_chars(), TriggerChars::Any);
}
fn names_of<'a, L: Lang>(symbols: &[SymbolEntry<'a, L>]) -> Vec<&'a str> {
symbols.iter().map(|entry| entry.name).collect()
}
#[test]
fn package_enumerates_by_callable_type_including_specials() {
let spec = new_spec();
let mut pkg: Package<PlainLang> = Package::new("p");
pkg.insert(MACRO, "alpha", Arc::clone(&spec));
pkg.insert(ENVIRONMENT, "itemize", Arc::clone(&spec));
pkg.insert_specials(MACRO, "--", Arc::clone(&spec));
let mut macros = names_of(&pkg.iter_symbols(MACRO, ()).unwrap().collect::<Vec<_>>());
macros.sort_unstable();
assert_eq!(macros, ["--", "alpha"]);
let environments =
names_of(&pkg.iter_symbols(ENVIRONMENT, ()).unwrap().collect::<Vec<_>>());
assert_eq!(environments, ["itemize"]);
let row = pkg.iter_symbols(ENVIRONMENT, ()).unwrap().next().unwrap();
assert_eq!(row.callable_type, ENVIRONMENT);
assert!(Arc::ptr_eq(row.spec, &spec));
}
#[test]
fn package_iter_symbols_applies_both_visibility_gates() {
let spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let mut pkg: Package<ModedLang> = Package::new("mixed");
pkg.insert(MACRO, "vec", Arc::clone(&spec)); pkg.insert_in_modes(MACRO, "emph", Arc::clone(&spec), Some(vec![Mode::Text]));
pkg.insert_specials_in_modes(MACRO, "--", Arc::clone(&spec), Some(vec![Mode::Text]));
let mut in_text = names_of(&pkg.iter_symbols(MACRO, Mode::Text).unwrap().collect::<Vec<_>>());
in_text.sort_unstable();
assert_eq!(in_text, ["--", "emph", "vec"]);
assert_eq!(
names_of(&pkg.iter_symbols(MACRO, Mode::Math).unwrap().collect::<Vec<_>>()),
["vec"]
);
let mut gated: Package<ModedLang> = Package::new("math-only");
gated.insert(MACRO, "frac", new_spec());
gated.set_visible_modes(Some(vec![Mode::Math]));
assert_eq!(gated.iter_symbols(MACRO, Mode::Text).unwrap().count(), 0);
assert_eq!(gated.iter_symbols(MACRO, Mode::Math).unwrap().count(), 1);
}
#[test]
fn scope_enumerates_ignoring_mode() {
let mut scope: Scope<ModedLang> = Scope::new("local");
scope.insert(MACRO, "beta", new_spec());
scope.insert(ENVIRONMENT, "quote", new_spec());
assert_eq!(names_of(&scope.iter_symbols(MACRO, Mode::Math).unwrap().collect::<Vec<_>>()), ["beta"]);
assert_eq!(names_of(&scope.iter_symbols(MACRO, Mode::Text).unwrap().collect::<Vec<_>>()), ["beta"]);
assert_eq!(
names_of(&scope.iter_symbols(ENVIRONMENT, Mode::Text).unwrap().collect::<Vec<_>>()),
["quote"]
);
}
#[test]
fn default_iter_symbols_is_not_enumerable() {
let mut fallback: FallbackProvider<PlainLang> = FallbackProvider::new("fallback");
fallback.set(MACRO, new_spec());
assert!(fallback.iter_symbols(MACRO, ()).is_none());
}
#[test]
fn stack_iter_symbols_dedups_innermost_first_and_skips_unenumerable() {
let outer_spec = new_spec();
let inner_spec = new_spec();
let mut outer: Package<PlainLang> = Package::new("outer");
outer.insert(MACRO, "alpha", Arc::clone(&outer_spec));
outer.insert(MACRO, "omega", Arc::clone(&outer_spec));
let mut inner: Scope<PlainLang> = Scope::new("inner");
inner.insert(MACRO, "alpha", Arc::clone(&inner_spec));
let mut fallback: FallbackProvider<PlainLang> = FallbackProvider::new("fallback");
fallback.set(MACRO, new_spec());
let mut stack: ScopeStack<PlainLang> = ScopeStack::new();
stack.push(Arc::new(fallback)); stack.push(Arc::new(outer));
stack.push(Arc::new(inner));
let symbols = stack.iter_symbols(MACRO, ());
let mut names = names_of(&symbols);
names.sort_unstable();
assert_eq!(names, ["alpha", "omega"]);
let alpha = symbols.iter().find(|entry| entry.name == "alpha").unwrap();
assert!(Arc::ptr_eq(alpha.spec, &inner_spec));
assert_eq!(names_of(&symbols)[0], "alpha");
let moded_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let text_spec: Arc<dyn CallableSpec<ModedLang>> = new_spec();
let mut math_pkg: Package<ModedLang> = Package::new("math-only");
math_pkg.insert(MACRO, "vec", Arc::clone(&moded_spec));
math_pkg.set_visible_modes(Some(vec![Mode::Math]));
let mut base: Package<ModedLang> = Package::new("allmodes");
base.insert(MACRO, "vec", Arc::clone(&text_spec));
let mut stack: ScopeStack<ModedLang> = ScopeStack::new();
stack.push(Arc::new(base));
stack.push(Arc::new(math_pkg));
let in_text = stack.iter_symbols(MACRO, Mode::Text);
assert!(Arc::ptr_eq(in_text[0].spec, &text_spec));
let in_math = stack.iter_symbols(MACRO, Mode::Math);
assert!(Arc::ptr_eq(in_math[0].spec, &moded_spec));
}
#[test]
fn escape_shadowing_check_reports_per_provider_and_type() {
use crate::latexlike::{
CallableType, EnvironmentSpec, Latexlike, MacroSpec,
};
use crate::source::Source;
assert_eq!(
ProviderCommandsShadowedByEscape::IDENTIFIER,
"core.specs.provider-commands-shadowed-by-escape"
);
let mut package: Package<Latexlike> = Package::new("mixed");
package.insert(CallableType::Macro, "good", Arc::new(MacroSpec::default()));
package.insert(
CallableType::Environment,
r"\align",
Arc::new(EnvironmentSpec::new(alloc::vec![])),
);
let state =
crate::state::ParsingState::<Latexlike>::lang_initial_with_packages([package])
.expect("seed state");
let source = Arc::new(Source::new("any content"));
let mut diagnostics = crate::error::Diagnostics::new();
check_provider_commands_shadowed_by_escape(&state, &source, &mut diagnostics);
assert_eq!(diagnostics.len(), 1);
let diagnostic = diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.severity(), crate::error::Severity::Warning);
let condition = diagnostic
.data()
.downcast_ref::<ProviderCommandsShadowedByEscape>()
.unwrap();
assert_eq!(condition.provider, "mixed");
assert_eq!(condition.callable_type, "Environment");
assert_eq!(condition.count, 1);
assert_eq!(condition.example, r"\align");
assert_eq!(condition.escape_chars, "\\");
}
#[test]
fn escape_shadowing_check_leaves_one_character_names_alone() {
use crate::latexlike::{CallableType, Latexlike, MacroSpec};
use crate::source::Source;
fn warnings(names: &[&str]) -> usize {
let mut package: Package<Latexlike> = Package::new("pkg");
for name in names {
package.insert(CallableType::Macro, *name, Arc::new(MacroSpec::default()));
}
let state =
crate::state::ParsingState::<Latexlike>::lang_initial_with_packages([package])
.expect("seed state");
let source = Arc::new(Source::new("any content"));
let mut diagnostics = crate::error::Diagnostics::new();
check_provider_commands_shadowed_by_escape(&state, &source, &mut diagnostics);
diagnostics.len()
}
assert_eq!(warnings(&["\\"]), 0);
assert_eq!(warnings(&["\\", r"\greet"]), 0);
assert_eq!(warnings(&["\\", "#"]), 0);
assert_eq!(warnings(&[r"\greet"]), 1);
assert_eq!(warnings(&[r"\x"]), 1);
assert_eq!(warnings(&[r"\greet", r"\x"]), 1);
}
#[test]
fn closed_vocabulary_drives_whole_scope_enumeration() {
use crate::state::ClosedVocabulary;
fn all_symbols<L: Lang>(stack: &ScopeStack<L>, mode: L::ModeId) -> Vec<(L::CallableTypeId, Box<str>)>
where
L::CallableTypeId: ClosedVocabulary,
{
let mut all = Vec::new();
for &callable_type in L::CallableTypeId::ALL {
for entry in stack.iter_symbols(callable_type, mode) {
all.push((entry.callable_type, Box::from(entry.name)));
}
}
all
}
use crate::latexlike::{CallableType, Latexlike, Mode as LMode};
let seed = crate::state::ParsingState::<Latexlike>::lang_initial_with_packages([
crate::latexlike::minidefs::minilatex_package(),
]).expect("seed state");
let symbols = all_symbols(&seed.scopes().clone(), LMode::Text);
let has = |ct: CallableType, name: &str| {
symbols.iter().any(|(t, n)| *t == ct && &**n == name)
};
assert!(has(CallableType::Macro, "begin"));
assert!(has(CallableType::Macro, "end"));
assert!(has(CallableType::Specials, "--"));
assert!(has(CallableType::Specials, "~"));
let in_math = all_symbols(&seed.scopes().clone(), LMode::Math);
assert!(!in_math.iter().any(|(t, n)| *t == CallableType::Specials && &**n == "--"));
assert_eq!(CallableType::ALL.len(), 3);
assert_eq!(<() as ClosedVocabulary>::ALL, &[()]);
}
}