use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use hashbrown::HashMap;
use crate::state::{FeaturePresence, Lang, LangFeatures};
use super::rules::{GroupRule, TokenRules};
pub struct PrefixEntry<L: Lang> {
delim: String,
open: Option<Arc<GroupRule<L>>>,
close: Option<Arc<GroupRule<L>>>,
}
impl<L: Lang> PrefixEntry<L> {
pub fn delim(&self) -> &str {
&self.delim
}
pub fn open(&self) -> Option<&Arc<GroupRule<L>>> {
self.open.as_ref()
}
pub fn close(&self) -> Option<&Arc<GroupRule<L>>> {
self.close.as_ref()
}
}
pub struct PrefixTable<L: Lang> {
entries: Vec<PrefixEntry<L>>,
}
impl<L: Lang> PrefixTable<L> {
pub fn for_rules(rules: &TokenRules<L>) -> PrefixTable<L> {
let mut entries: Vec<PrefixEntry<L>> = Vec::new();
if !<L::Features as LangFeatures>::Groups::PRESENT || !rules.groups_enabled() {
return PrefixTable { entries };
}
let mut by_delim: HashMap<&str, usize> = HashMap::new();
for rule in rules.temporary_group_rules().iter().chain(rules.group_rules()) {
for (delim, is_open) in [(&rule.open, true), (&rule.close, false)] {
if delim.is_empty() {
continue;
}
let index = *by_delim.entry(delim.as_str()).or_insert_with(|| {
entries.push(PrefixEntry { delim: String::from(delim), open: None, close: None });
entries.len() - 1
});
let entry = &mut entries[index];
let slot = if is_open { &mut entry.open } else { &mut entry.close };
if slot.is_none() {
*slot = Some(Arc::clone(rule));
}
}
}
entries.sort_by_key(|entry| core::cmp::Reverse(entry.delim.len()));
PrefixTable { entries }
}
pub fn match_at(&self, rest: &str) -> Option<&PrefixEntry<L>> {
self.entries.iter().find(|e| rest.starts_with(e.delim.as_str()))
}
pub fn entries(&self) -> &[PrefixEntry<L>] {
&self.entries
}
}
impl<L: Lang> Clone for PrefixEntry<L> {
fn clone(&self) -> Self {
PrefixEntry {
delim: self.delim.clone(),
open: self.open.clone(),
close: self.close.clone(),
}
}
}
impl<L: Lang> fmt::Debug for PrefixEntry<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PrefixEntry")
.field("delim", &self.delim)
.field("open", &self.open)
.field("close", &self.close)
.finish()
}
}
impl<L: Lang> PartialEq for PrefixEntry<L> {
fn eq(&self, other: &Self) -> bool {
self.delim == other.delim && self.open == other.open && self.close == other.close
}
}
impl<L: Lang> Eq for PrefixEntry<L> {}
impl<L: Lang> Clone for PrefixTable<L> {
fn clone(&self) -> Self {
PrefixTable { entries: self.entries.clone() }
}
}
impl<L: Lang> fmt::Debug for PrefixTable<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PrefixTable")
.field("entries", &self.entries)
.finish()
}
}
impl<L: Lang> PartialEq for PrefixTable<L> {
fn eq(&self, other: &Self) -> bool {
self.entries == other.entries
}
}
impl<L: Lang> Eq for PrefixTable<L> {}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::TrivialLang;
use crate::token::{
CommandRules, CommentRules, ForbiddenCharsRules, GroupRules, ParagraphRules,
SpecialsRules, WhitespaceRules,
};
use alloc::vec;
use alloc::vec::Vec;
#[derive(Debug, Clone, Copy)]
struct PlainLang;
impl TrivialLang for PlainLang {}
fn rules_with_groups(groups: Vec<Arc<GroupRule<PlainLang>>>) -> TokenRules<PlainLang> {
TokenRules {
whitespace: WhitespaceRules::empty(),
paragraphs: ParagraphRules { enabled: false },
groups: GroupRules {
enabled: true,
rules: groups,
temporary: Vec::new(),
expecting_close: None,
},
commands: CommandRules {
enabled: true,
rules: Vec::new(),
},
comments: CommentRules {
enabled: true,
rules: Vec::new(),
},
specials: SpecialsRules { enabled: true },
forbidden_chars: ForbiddenCharsRules { chars: "".into() },
}
}
fn group(group_type: u32, open: &str, close: &str) -> Arc<GroupRule<PlainLang>> {
Arc::new(GroupRule { group_type, open: open.into(), close: close.into() })
}
#[test]
fn braces_directional_entries() {
let rule = group(0, "{", "}");
let table = PrefixTable::for_rules(&rules_with_groups(vec![rule.clone()]));
let open = table.match_at("{x").unwrap();
assert_eq!(open.delim(), "{");
assert_eq!(open.open(), Some(&rule));
assert_eq!(open.close(), None);
let close = table.match_at("} y").unwrap();
assert_eq!(close.delim(), "}");
assert_eq!(close.open(), None);
assert_eq!(close.close(), Some(&rule));
assert!(table.match_at("plain").is_none());
}
#[test]
fn same_string_open_and_close_merges() {
let rule = group(2, "$", "$");
let table = PrefixTable::for_rules(&rules_with_groups(vec![rule.clone()]));
let entry = table.match_at("$x").unwrap();
assert_eq!(entry.open(), Some(&rule));
assert_eq!(entry.close(), Some(&rule));
}
#[test]
fn longest_delimiter_matches_first() {
let table = PrefixTable::for_rules(&rules_with_groups(vec![
group(2, "$", "$"),
group(3, "$$", "$$"),
]));
assert_eq!(table.match_at("$$x").unwrap().delim(), "$$");
assert_eq!(table.match_at("$x").unwrap().delim(), "$");
}
#[test]
fn conflicting_claims_earlier_rule_wins() {
let first = group(0, "{", "}");
let table = PrefixTable::for_rules(&rules_with_groups(vec![
first.clone(),
group(7, "{", "}"),
]));
let entry = table.match_at("{").unwrap();
assert_eq!(entry.open(), Some(&first));
}
#[test]
fn temporary_rules_win_same_spelling_ties() {
let permanent = group(0, "[", "]");
let temporary = group(9, "[", "]");
let mut rules = rules_with_groups(vec![permanent]);
rules.groups.temporary = vec![temporary.clone()];
let table = PrefixTable::for_rules(&rules);
assert_eq!(table.match_at("[x").unwrap().open(), Some(&temporary));
assert_eq!(table.match_at("]x").unwrap().close(), Some(&temporary));
}
#[test]
fn empty_delimiters_ignored() {
let table = PrefixTable::for_rules(&rules_with_groups(vec![group(0, "{", "")]));
assert_eq!(table.entries().len(), 1);
assert_eq!(table.entries()[0].delim(), "{");
}
#[test]
fn many_rules_build_in_one_pass() {
let mut groups = Vec::new();
for i in 0..20_000u32 {
groups.push(group(i, &alloc::format!("<{i}"), &alloc::format!("{i}>")));
}
for i in 0..20_000u32 {
groups.push(group(100_000 + i, "<0", "0>"));
}
let first = groups[0].clone();
let table = PrefixTable::for_rules(&rules_with_groups(groups));
assert_eq!(table.entries().len(), 40_000);
let entry = table.match_at("<0").unwrap();
assert_eq!(entry.open(), Some(&first));
assert_eq!(table.match_at("0>x").unwrap().close(), Some(&first));
assert_eq!(table.match_at("<19999").unwrap().delim(), "<19999");
}
}