techy 0.1.0

A fast, extensible LaTeX parser for Rust
Documentation
//! The group-delimiter matching table a parsing state derives from its [`TokenRules`].
//!
//! [`PrefixTable`] is a cache, not something to configure. Every
//! [`ParsingState`](crate::core::ParsingState) builds one from its own group rules when
//! it is created and answers it from
//! [`prefix_table`](crate::core::ParsingState::prefix_table); to change what a table
//! contains, change the group rules. Read one to find out how a delimiter string will be
//! matched: [`PrefixTable::match_at`] answers with the [`PrefixEntry`] for a piece of
//! text.

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};

/// One delimiter string, with the group rule it opens and the group rule it closes.
///
/// A single string may do both — for the same rule (`$…$`) or for two different ones —
/// and the table merges those claims into one entry.
/// [`StdTokenReader`](super::StdTokenReader) settles the direction when it matches such
/// an entry: a close the state is waiting for
/// ([`TokenRules::expecting_group_close`]) wins, and otherwise the string is read as an
/// opening delimiter.
pub struct PrefixEntry<L: Lang> {
    delim: String,
    open: Option<Arc<GroupRule<L>>>,
    close: Option<Arc<GroupRule<L>>>,
}

impl<L: Lang> PrefixEntry<L> {
    /// The delimiter string.
    pub fn delim(&self) -> &str {
        &self.delim
    }

    /// The group rule this string opens, if any.
    pub fn open(&self) -> Option<&Arc<GroupRule<L>>> {
        self.open.as_ref()
    }

    /// The group rule this string closes, if any.
    pub fn close(&self) -> Option<&Arc<GroupRule<L>>> {
        self.close.as_ref()
    }
}

/// The group-delimiter matching table of one parsing state, derived from its
/// [`TokenRules`].
///
/// You do not normally build one:
/// [`ParsingState`](crate::core::ParsingState) derives its own table from its group
/// rules and answers it from
/// [`prefix_table`](crate::core::ParsingState::prefix_table). Ask it what a delimiter at
/// a position resolves to with [`match_at`](Self::match_at), or read the whole table
/// with [`entries`](Self::entries).
///
/// Entries are sorted longest delimiter first, so matching is greedy: with `$…$` and
/// `$$…$$` both declared, `$$` matches as one `$$` delimiter rather than twice as `$`.
/// Entries of equal length keep declaration order — [`TokenRules::temporary_group_rules`]
/// before [`TokenRules::group_rules`], each in list order — and when two rules claim the
/// same delimiter string in the same direction, the earlier one wins.
pub struct PrefixTable<L: Lang> {
    entries: Vec<PrefixEntry<L>>,
}

impl<L: Lang> PrefixTable<L> {
    /// Builds the table for the group rules of `rules`.
    ///
    /// A parsing state calls this for you when it is created; call it directly only to
    /// inspect what a given rules value would produce.
    ///
    /// [`temporary_group_rules`](TokenRules::temporary_group_rules) are added first,
    /// then [`group_rules`](TokenRules::group_rules), so a temporary rule wins a tie
    /// against a permanent rule spelled the same way. Empty delimiter strings contribute
    /// no entry.
    ///
    /// The table is empty when [`TokenRules::groups_enabled`] is off, and empty as well
    /// for a language that declares the groups feature absent
    /// ([`LangFeatures::Groups`]), which has no group rules data at all. Applying the
    /// gate here, once per state, is what keeps it out of the token-scanning loop. The
    /// expected group close ([`TokenRules::expecting_group_close`]) is not part of the
    /// table and not gated: the reader checks it separately.
    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 };
        }

        // Delimiter string → its entry's index: the merge is a hash lookup per
        // delimiter, so building the table is linear in the number of rules (a rule
        // list of any size — a deserialized state's, say — costs no more than a scan).
        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));
                }
                // An occupied slot is left alone: earlier rules win.
            }
        }

        // Longest first, for greedy matching; stable, so equal lengths keep declaration order.
        entries.sort_by_key(|entry| core::cmp::Reverse(entry.delim.len()));

        PrefixTable { entries }
    }

    /// Returns the entry with the longest delimiter that `rest` starts with, if any.
    ///
    /// `rest` is the text from the position being examined onward, so a match is always
    /// at its very beginning. The answer says which rule the delimiter opens and which
    /// it closes; the caller decides the direction.
    pub fn match_at(&self, rest: &str) -> Option<&PrefixEntry<L>> {
        self.entries.iter().find(|e| rest.starts_with(e.delim.as_str()))
    }

    /// The entries, longest delimiter first.
    pub fn entries(&self) -> &[PrefixEntry<L>] {
        &self.entries
    }
}

// Manual impls: derives would demand `L: Clone`/`L: Debug`/`L: PartialEq` although only
// `Arc`-shared rules (whose contents are bounded via `Lang`) are stored.

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 {} // GroupTypeId = u32

    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() {
        // `$…$`: the same string opens and closes one rule.
        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() {
        // Temporaries are added ahead of `groups` — the minted-rule "prepended wins"
        // semantics (an optional-argument `[` beats a language's own `[` pairing).
        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(), "{");
    }

    /// Building the table is linear in the number of rules (a rule list read from a
    /// serialized state can be as long as the wire says): many distinct rules plus
    /// many same-spelling ones merge in one pass, earlier rules still winning.
    #[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}>")));
        }
        // The same spelling claimed again and again: merged into the first claim.
        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");
    }
}