techy 0.2.0

A fast, extensible LaTeX parser for Rust
Documentation
//! The specials-scan interface: how the tokenizer asks the language (preset) whether a
//! callable-triggering character sequence starts at the current position.
//!
//! Specials trigger strings are the one part of tokenization that is *not* plain
//! [`TokenRules`](super::TokenRules) data: a language may have many trigger strings in
//! scope, and which ones they are changes as scopes are pushed and popped, so
//! recognizing them is delegated to a [`Lang`](crate::core::Lang) hook
//! (`Lang::scan_specials`) instead of being enumerated in the rules.
//!
//! Recognition and resolution happen in one call: a [`SpecialsMatch`] holds the
//! resolved spec, and the matched text *is* the name, so scanning and lookup cannot
//! disagree about normalization or scoping.
//!
//! [`TriggerChars`] keeps the hook off the hot path: it is the set of characters that may
//! start a specials trigger, reported by `Lang::specials_trigger_chars` and cached per
//! parsing state (rebuilt only at state transitions, like the
//! [`PrefixTable`](super::PrefixTable)). The hook is consulted only when the current
//! character is in the set.

use alloc::string::String;
use alloc::sync::Arc;
use core::fmt;

use crate::source::Span;
use crate::spec::CallableSpec;
use crate::state::Lang;

use super::error::TokenErrorKind;

/// A successful specials scan: a callable trigger matched at the scanned position.
///
/// Returned by `Lang::scan_specials(state, content, pos)`, and by
/// [`scan_specials_trigger`](super::scan_specials_trigger), which calls that hook.
/// Positions are absolute byte offsets into `content` (not relative to the scanned tail),
/// so spans in errors and in the resulting token need no offset arithmetic.
pub struct SpecialsMatch<L: Lang> {
    /// Byte offset one past the end of the matched trigger.
    ///
    /// The matched text is `content[pos..end]`, and that text *is* the specials name
    /// the reader records on the token — which is why the match carries no separate
    /// name.
    ///
    /// **Contract:** the match must be non-empty and boundary-aligned — `end` must
    /// satisfy `pos < end <= content.len()` and fall on a `char` boundary. A
    /// zero-width match would produce a token that never advances the parse (an
    /// infinite loop); an out-of-range or mid-codepoint `end` would produce an invalid
    /// span. The standard reader validates the contract at the call site and reports a
    /// violation as an unrecoverable implementation error — never a panic.
    pub end: usize,
    /// The invocation form the trigger resolved to.
    ///
    /// It is recorded on the token, and the parser needs it to build the invocation it
    /// dispatches. Together with `spec` it is the same *(callable type, spec)* pair a
    /// [`ResolvedCallable`](crate::core::specs::ResolvedCallable) holds.
    pub callable_type: L::CallableTypeId,
    /// The resolved behavior spec. Never absent: unknown-name policy (fallback specs) is
    /// the scan implementation's business, applied *before* returning a match.
    pub spec: Arc<dyn CallableSpec<L>>,
}

impl<L: Lang> fmt::Debug for SpecialsMatch<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SpecialsMatch")
            .field("end", &self.end)
            .field("callable_type", &self.callable_type)
            .field("spec", &self.spec)
            .finish()
    }
}

/// An error that [`Lang::scan_specials`](crate::core::Lang::scan_specials) returns when it
/// fails to scan a specials trigger.
///
/// A specials scan error contains the condition that describes the error
/// ([`kind`](Self::kind)) and the byte range of the scanned content where the error
/// occurred ([`span`](Self::span)). The standard token reader converts it into a
/// [`TokenError`](super::TokenError) whose span lies in the source that the reader reads.
/// The hook receives only the parsing state, the content and the scan position, so it
/// cannot describe how to continue past the error. Therefore the token error has no
/// [`TokenRecovery`](super::TokenRecovery), and it stops the parse, also in a tolerant
/// parse.
///
/// [`scan_specials_trigger`](super::scan_specials_trigger) also returns a specials scan
/// error when the hook returns a match end or an error span that lies outside the scanned
/// content or not on a character boundary. Its condition is then an
/// [`ImplementationError`](crate::core::constructs::ImplementationError), and its span is
/// the empty range at the scan position.
///
/// To report a problem in the document that the parse can continue past, the hook returns
/// a [`SpecialsMatch`] whose spec has a parser that reports the problem.
#[derive(Debug, Clone)]
pub struct SpecialsScanError {
    /// The condition that describes the error.
    pub kind: TokenErrorKind,
    /// The byte range of the scanned content where the error occurred.
    pub span: Span,
}

impl fmt::Display for SpecialsScanError {
    /// Writes the message of the condition, followed by the byte range of the scanned
    /// content where the error occurred.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} (at bytes {}..{})", self.kind, self.span.start(), self.span.end())
    }
}

impl core::error::Error for SpecialsScanError {}

/// The characters that may start a specials trigger in some parsing state.
///
/// A language reports it from `Lang::specials_trigger_chars(&StateData<L>)`; the parsing
/// state computes it once, when it is built, and caches it. Every scan of a specials
/// trigger is gated by it, so the scan hook runs only at characters that could start
/// one. A hook whose triggers cannot be summarized by their first characters (fully
/// dynamic recognition) returns [`TriggerChars::Any`] — correct, but it pays for the scan
/// at every character.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TriggerChars {
    /// Only these characters can start a trigger; the empty string means "no specials at
    /// all" (the default — the scan hook is then never consulted).
    Only(String),
    /// Any character may start a trigger; the scan hook is consulted at every content
    /// position. Conservative fallback for dynamic scanners.
    Any,
}

impl TriggerChars {
    /// Whether a trigger could start with `c` (i.e. whether the scan hook must be asked).
    pub fn may_start(&self, c: char) -> bool {
        match self {
            TriggerChars::Only(chars) => chars.contains(c),
            TriggerChars::Any => true,
        }
    }

    /// The union of two filters: a character may start a trigger in the union exactly
    /// when it may in either operand, and [`Any`](TriggerChars::Any) unioned with
    /// anything is `Any`.
    ///
    /// A parsing state caches one filter for its whole
    /// [`ScopeStack`](crate::core::specs::ScopeStack) by combining the filters of the
    /// providers in it with this method.
    #[must_use]
    pub fn union(&self, other: &TriggerChars) -> TriggerChars {
        match (self, other) {
            (TriggerChars::Any, _) | (_, TriggerChars::Any) => TriggerChars::Any,
            (TriggerChars::Only(a), TriggerChars::Only(b)) => {
                let mut chars = a.clone();
                chars.extend(b.chars().filter(|&c| !a.contains(c)));
                TriggerChars::Only(chars)
            }
        }
    }
}

impl Default for TriggerChars {
    /// No specials: the scan hook is never consulted.
    fn default() -> Self {
        TriggerChars::Only(String::new())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn trigger_chars_membership() {
        let none = TriggerChars::default();
        assert!(!none.may_start('~'));

        let some = TriggerChars::Only("~&".into());
        assert!(some.may_start('~'));
        assert!(some.may_start('&'));
        assert!(!some.may_start('x'));

        assert!(TriggerChars::Any.may_start('x'));
    }
}