Skip to main content

tabnas_hoover/
lib.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Block-delimited string *hoovering* for the
4//! [tabnas](https://github.com/tabnas/parser) parser engine.
5//!
6//! Hoovering vacuums up a run of source text, internal spaces and
7//! newlines included, between a start and an end delimiter, with
8//! optional escape handling and rule-context gating. The two canonical
9//! shapes are triple-quoted strings (`'''hello world'''`) and
10//! end-of-line values (an unquoted run of text up to a newline, `#`, `;`
11//! or the end of the input).
12//!
13//! This crate is **not a grammar**: it is a lexer-matcher plugin that
14//! extends the host grammar's `val` rule, so it is applied to a
15//! [`Tabnas`] instance that already carries a grammar defining `val`. It
16//! installs one custom lex matcher (`lex.match.hoover`, at order `4.5e6`,
17//! ahead of the string and number matchers) that emits a `#HV` token, and
18//! prepends a `val` alternate accepting that token.
19//!
20//! ```no_run
21//! use tabnas::Tabnas;
22//! use tabnas_hoover::{hoover, Block, HooverOptions};
23//!
24//! let mut parser = Tabnas::new();
25//! // ... install a host grammar that defines the `val` rule ...
26//! hoover(
27//!     &mut parser,
28//!     HooverOptions::new(vec![Block::delimited("triplequote", "'''", "'''")]),
29//! )?;
30//! let value = parser.parse("'''hello world'''")?; // "hello world"
31//! # Ok::<(), Box<dyn std::error::Error>>(())
32//! ```
33//!
34//! TypeScript is canonical: `ts/src/hoover.ts` defines behaviour, option
35//! names and defaults, and `go/hoover.go` is the sibling port. The shared
36//! fixtures in `test/spec/*.tsv` are the parity contract across all
37//! three.
38
39use std::collections::HashMap;
40use std::fmt;
41use std::sync::atomic::{AtomicUsize, Ordering};
42use std::sync::Arc;
43
44#[cfg(feature = "serde_json")]
45use serde_json::Value as JsonValue;
46use tabnas::{
47    ActionError, Context, GrammarError, GrammarSpec, ImperativeLexMatcher, Lexer, Options, Plugin,
48    PluginError, Rule, RuleState, Tabnas, Tin, Token, Value,
49};
50
51/// The README's Rust examples run as doctests, so a stale one fails the
52/// gate rather than misleading the reader. Its `text`, `toml` and `bash`
53/// fences are skipped; rustdoc runs only the `rust` ones.
54#[cfg(doctest)]
55#[doc = include_str!("../README.md")]
56mod readme_examples {}
57
58/// VERSION is this crate's version. It MUST equal `ts/package.json`
59/// "version" and the `version` field in `rs/Cargo.toml`: the release
60/// orchestrator rewrites all of them, and `tests/version_test.rs` fails
61/// the build if they drift. Mirrors `VERSION` in `ts/src/hoover.ts` and
62/// `const VERSION` in `go/hoover.go`.
63pub const VERSION: &str = "0.3.15";
64
65/// The default matcher order: before the string (`5e6`) and number
66/// (`7e6`) matchers. Mirrors `Hoover.defaults.lex.order` in TypeScript
67/// and `Defaults["lex"]["order"]` in Go.
68pub const DEFAULT_LEX_ORDER: f64 = 4.5e6;
69
70/// The default token name a block emits.
71pub const DEFAULT_TOKEN: &str = "#HV";
72
73/// The error code a committed block that never reaches an end
74/// delimiter is rejected with.
75pub const INVALID_TEXT: &str = "invalid_text";
76
77/// The error code a rejected escape (`allow_unknown_escape: false` and an
78/// escape not in the `escape` map) is rejected with.
79pub const INVALID_ESCAPE: &str = "invalid_escape";
80
81/// A registration failure: the host grammar defines no `val` rule, the
82/// host's alt filter removed the block alternate, the options could not
83/// be read, or the engine refused the grammar.
84///
85/// The TypeScript plugin *throws* for these; the Rust port returns them,
86/// exactly as the Go port does. The plugin itself never panics.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct HooverError(pub String);
89
90impl fmt::Display for HooverError {
91    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
92        formatter.write_str(&self.0)
93    }
94}
95
96impl std::error::Error for HooverError {}
97
98impl From<PluginError> for HooverError {
99    fn from(error: PluginError) -> Self {
100        Self(error.0)
101    }
102}
103
104impl From<GrammarError> for HooverError {
105    fn from(error: GrammarError) -> Self {
106        Self(error.0)
107    }
108}
109
110impl From<HooverError> for PluginError {
111    fn from(error: HooverError) -> Self {
112        Self(error.0)
113    }
114}
115
116/// The alternate action run when a block token is matched by the `val`
117/// rule, the Rust spelling of the TypeScript `action?: AltAction`
118/// option. It sees the rule whose open token is the block token (its
119/// `use` bag carries `{block: <name>}`) and the parse context.
120pub type ActionFn = Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync>;
121
122/// Include and exclude lists for one side of a rule-context filter.
123///
124/// An absent list imposes no constraint; an empty list is a constraint
125/// that nothing satisfies (`include`) or everything satisfies
126/// (`exclude`), exactly as in TypeScript.
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
128pub struct HooverRuleFilter {
129    pub include: Option<Vec<String>>,
130    pub exclude: Option<Vec<String>>,
131}
132
133impl HooverRuleFilter {
134    /// A filter that passes only the named rules.
135    pub fn include(names: &[&str]) -> Self {
136        Self {
137            include: Some(names.iter().map(|name| (*name).to_string()).collect()),
138            exclude: None,
139        }
140    }
141
142    /// A filter that rejects the named rules.
143    pub fn exclude(names: &[&str]) -> Self {
144        Self {
145            include: None,
146            exclude: Some(names.iter().map(|name| (*name).to_string()).collect()),
147        }
148    }
149
150    /// `name` is the empty string for the start rule's parent: TypeScript's
151    /// sentinel rule there is named `""`, so `""` is the one entry that
152    /// lists it.
153    fn passes(&self, name: &str, match_rule: &mut Option<bool>) {
154        let listed = |list: &[String]| list.iter().any(|entry| entry == name);
155        if let Some(include) = &self.include {
156            and_into(match_rule, listed(include));
157        }
158        if let Some(exclude) = &self.exclude {
159            and_into(match_rule, !listed(exclude));
160        }
161    }
162}
163
164/// The rule context a block start is gated on: filters on the current
165/// rule and its parent, plus the rule state.
166///
167/// `state` selects which rule states match: `"o"`, `"c"` or `"oc"`
168/// check the state; `None` defaults to `"o"` (open); `Some("")` means
169/// *do not check the state at all* (the TypeScript `state: ''` form,
170/// which Go spells `StateAny`).
171#[derive(Debug, Clone, Default, PartialEq, Eq)]
172pub struct HooverRuleSpec {
173    pub parent: Option<HooverRuleFilter>,
174    pub current: Option<HooverRuleFilter>,
175    pub state: Option<String>,
176}
177
178/// Whether a matched delimiter is consumed (removed from the value and
179/// the stream) or left in place. Mirrors the TypeScript
180/// `consume?: null | boolean | string[]` field.
181#[derive(Debug, Clone, Default, PartialEq, Eq)]
182pub enum Consume {
183    /// Consume every matched delimiter (the default; `null` or `true`).
184    #[default]
185    All,
186    /// Consume nothing (`false`): the delimiter stays in the stream, and a
187    /// start delimiter becomes part of the value.
188    Never,
189    /// Consume only the listed delimiters.
190    Only(Vec<String>),
191}
192
193impl Consume {
194    fn applies_to(&self, delimiter: &str) -> bool {
195        match self {
196            Consume::All => true,
197            Consume::Never => false,
198            Consume::Only(list) => list.iter().any(|entry| entry == delimiter),
199        }
200    }
201}
202
203/// How a block starts: optional fixed delimiters, whether a matched one
204/// is consumed, and the rule context the start is gated on.
205///
206/// With no `fixed` delimiters the block starts wherever its rule context
207/// matches.
208#[derive(Debug, Clone, Default, PartialEq, Eq)]
209pub struct StartSpec {
210    pub fixed: Option<Vec<String>>,
211    pub consume: Consume,
212    pub rule: Option<HooverRuleSpec>,
213}
214
215/// How a block ends: the delimiters it scans for, and whether a matched
216/// one is consumed. The empty string `""` names the end of the input.
217#[derive(Debug, Clone, Default, PartialEq, Eq)]
218pub struct EndSpec {
219    pub fixed: Vec<String>,
220    pub consume: Consume,
221}
222
223/// One block definition. Blocks are tried in the order they are listed
224/// in [`HooverOptions::block`], so that order is significant.
225///
226/// Once a block's start matches, the block is *committed*: failing to
227/// reach an end delimiter is an `invalid_text` error and a rejected
228/// escape is an `invalid_escape` error, never a fall-through to the next
229/// block or matcher.
230#[derive(Debug, Clone, Default, PartialEq, Eq)]
231pub struct Block {
232    /// The block name, carried on every token it emits as `use.block`.
233    pub name: String,
234    pub start: Option<StartSpec>,
235    pub end: EndSpec,
236    /// The token name the block emits; `None` means [`DEFAULT_TOKEN`].
237    pub token: Option<String>,
238    /// The escape character, when the block has one.
239    pub escape_char: Option<char>,
240    /// Replacements for escaped characters, keyed by the character
241    /// following the escape character.
242    pub escape: HashMap<String, String>,
243    /// Whether an escape absent from `escape` is allowed (the escape
244    /// character is dropped, or kept with `preserve_escape_char`);
245    /// `None` means `true`.
246    pub allow_unknown_escape: Option<bool>,
247    /// Keep the escape character in the value for an unknown escape.
248    pub preserve_escape_char: bool,
249    /// Trim the hoovered value with the JavaScript `String.prototype.trim`
250    /// character set.
251    pub trim: bool,
252}
253
254impl Block {
255    /// A block named `name` with no delimiters; fill the fields in.
256    pub fn new(name: impl Into<String>) -> Self {
257        Self {
258            name: name.into(),
259            ..Self::default()
260        }
261    }
262
263    /// A block bounded by one fixed start and one fixed end delimiter,
264    /// both consumed.
265    pub fn delimited(name: impl Into<String>, start: &str, end: &str) -> Self {
266        Self::new(name).with_start(&[start]).with_end(&[end])
267    }
268
269    /// Set the fixed start delimiters, keeping any rule context.
270    pub fn with_start(mut self, fixed: &[&str]) -> Self {
271        let start = self.start.get_or_insert_with(StartSpec::default);
272        start.fixed = Some(fixed.iter().map(|entry| (*entry).to_string()).collect());
273        self
274    }
275
276    /// Set the fixed end delimiters (`""` is the end of the input).
277    pub fn with_end(mut self, fixed: &[&str]) -> Self {
278        self.end.fixed = fixed.iter().map(|entry| (*entry).to_string()).collect();
279        self
280    }
281
282    /// Gate the block start on a rule context.
283    pub fn with_rule(mut self, rule: HooverRuleSpec) -> Self {
284        self.start.get_or_insert_with(StartSpec::default).rule = Some(rule);
285        self
286    }
287
288    /// Set the escape character.
289    pub fn with_escape_char(mut self, escape_char: char) -> Self {
290        self.escape_char = Some(escape_char);
291        self
292    }
293
294    /// Add an escape replacement.
295    pub fn with_escape(mut self, escaped: &str, replacement: &str) -> Self {
296        self.escape
297            .insert(escaped.to_string(), replacement.to_string());
298        self
299    }
300
301    fn token_name(&self) -> &str {
302        self.token.as_deref().unwrap_or(DEFAULT_TOKEN)
303    }
304
305    fn allow_unknown(&self) -> bool {
306        self.allow_unknown_escape.unwrap_or(true)
307    }
308}
309
310/// The plugin options: the ordered block list, the matcher order and
311/// the optional alternate action.
312///
313/// Typed rather than a serialized bag because the action is a Rust
314/// callback and no [`Value`] can carry one. The data shape the other
315/// runtimes accept (a JSON object with `block`, `lex.order`) is read by
316/// [`HooverOptions::from_json`].
317#[derive(Clone, Default)]
318pub struct HooverOptions {
319    /// The blocks, tried in order.
320    pub block: Vec<Block>,
321    /// The custom matcher's order; `None` means [`DEFAULT_LEX_ORDER`].
322    pub lex_order: Option<f64>,
323    /// The alternate action run when a block token is matched.
324    pub action: Option<ActionFn>,
325}
326
327impl fmt::Debug for HooverOptions {
328    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
329        formatter
330            .debug_struct("HooverOptions")
331            .field("block", &self.block)
332            .field("lex_order", &self.lex_order)
333            .field("action", &self.action.as_ref().map(|_| "<function>"))
334            .finish()
335    }
336}
337
338impl HooverOptions {
339    /// Options over the given blocks, with the default matcher order and
340    /// no action.
341    pub fn new(block: Vec<Block>) -> Self {
342        Self {
343            block,
344            lex_order: None,
345            action: None,
346        }
347    }
348
349    /// Set the custom matcher's order.
350    pub fn with_lex_order(mut self, order: f64) -> Self {
351        self.lex_order = Some(order);
352        self
353    }
354
355    /// Set the alternate action.
356    pub fn with_action(
357        mut self,
358        action: impl Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync + 'static,
359    ) -> Self {
360        self.action = Some(Arc::new(action));
361        self
362    }
363
364    /// Read the data shape the TypeScript plugin takes as an object
365    /// literal and the Go plugin takes as a map: `{"block": [...],
366    /// "lex": {"order": n}}`, with each block's fields spelled as in
367    /// TypeScript (`escapeChar`, `allowUnknownEscape`, ...). Keys are
368    /// matched case-insensitively, as in Go, so the Go field spellings
369    /// resolve too. `fixed` may be a string or a list, `consume` a
370    /// boolean or a list, and `"state": ""` means "do not check the
371    /// state".
372    ///
373    /// An `escapeChar` longer than one character, or a value of the
374    /// wrong type where the shape is fixed, is an error. Unknown keys are
375    /// ignored, as they are in both other runtimes.
376    ///
377    /// Available with the `serde_json` feature, which is off by default
378    /// so that the crate's only production dependency stays the engine.
379    #[cfg(feature = "serde_json")]
380    pub fn from_json(document: &JsonValue) -> Result<Self, HooverError> {
381        let map = document
382            .as_object()
383            .ok_or_else(|| HooverError("hoover: options must be an object".into()))?;
384        let mut options = Self::default();
385
386        if let Some(blocks) = field(map, "block") {
387            let blocks = blocks.as_array().ok_or_else(|| {
388                HooverError("hoover: options.block must be an array of blocks".into())
389            })?;
390            options.block = blocks
391                .iter()
392                .map(block_from_json)
393                .collect::<Result<Vec<_>, _>>()?;
394        }
395        if let Some(lex) = field(map, "lex").and_then(JsonValue::as_object) {
396            if let Some(order) = field(lex, "order") {
397                options.lex_order = Some(order.as_f64().ok_or_else(|| {
398                    HooverError("hoover: options.lex.order must be a number".into())
399                })?);
400            }
401        }
402        Ok(options)
403    }
404}
405
406/// Look a key up exactly, then case-insensitively, so both the TypeScript
407/// spelling (`escapeChar`) and the Go field name (`EscapeChar`) resolve.
408#[cfg(feature = "serde_json")]
409fn field<'a>(map: &'a serde_json::Map<String, JsonValue>, key: &str) -> Option<&'a JsonValue> {
410    map.get(key).or_else(|| {
411        map.iter()
412            .find(|(candidate, _)| candidate.eq_ignore_ascii_case(key))
413            .map(|(_, value)| value)
414    })
415}
416
417/// A `fixed`-style field: a single string or a list of them.
418#[cfg(feature = "serde_json")]
419fn strings_from_json(value: &JsonValue, label: &str) -> Result<Vec<String>, HooverError> {
420    match value {
421        JsonValue::String(text) => Ok(vec![text.clone()]),
422        JsonValue::Array(items) => items
423            .iter()
424            .map(|item| {
425                item.as_str()
426                    .map(str::to_string)
427                    .ok_or_else(|| HooverError(format!("hoover: {label} entries must be strings")))
428            })
429            .collect(),
430        _ => Err(HooverError(format!(
431            "hoover: {label} must be a string or a list of strings"
432        ))),
433    }
434}
435
436#[cfg(feature = "serde_json")]
437fn consume_from_json(
438    map: &serde_json::Map<String, JsonValue>,
439    label: &str,
440) -> Result<Consume, HooverError> {
441    match field(map, "consume") {
442        None | Some(JsonValue::Null) | Some(JsonValue::Bool(true)) => Ok(Consume::All),
443        Some(JsonValue::Bool(false)) => Ok(Consume::Never),
444        Some(list @ JsonValue::Array(_)) => Ok(Consume::Only(strings_from_json(
445            list,
446            &format!("{label}.consume"),
447        )?)),
448        Some(_) => Err(HooverError(format!(
449            "hoover: {label}.consume must be a boolean or a list of strings"
450        ))),
451    }
452}
453
454#[cfg(feature = "serde_json")]
455fn filter_from_json(value: &JsonValue, label: &str) -> Result<HooverRuleFilter, HooverError> {
456    let map = value
457        .as_object()
458        .ok_or_else(|| HooverError(format!("hoover: {label} must be an object")))?;
459    Ok(HooverRuleFilter {
460        include: field(map, "include")
461            .map(|list| strings_from_json(list, &format!("{label}.include")))
462            .transpose()?,
463        exclude: field(map, "exclude")
464            .map(|list| strings_from_json(list, &format!("{label}.exclude")))
465            .transpose()?,
466    })
467}
468
469#[cfg(feature = "serde_json")]
470fn rule_from_json(value: &JsonValue, label: &str) -> Result<HooverRuleSpec, HooverError> {
471    let map = value
472        .as_object()
473        .ok_or_else(|| HooverError(format!("hoover: {label} must be an object")))?;
474    Ok(HooverRuleSpec {
475        parent: field(map, "parent")
476            .map(|filter| filter_from_json(filter, &format!("{label}.parent")))
477            .transpose()?,
478        current: field(map, "current")
479            .map(|filter| filter_from_json(filter, &format!("{label}.current")))
480            .transpose()?,
481        // A JSON null is NOT the empty string: it means the key carries no
482        // value, so the "o" default applies. Only a string is a setting.
483        state: field(map, "state")
484            .and_then(JsonValue::as_str)
485            .map(str::to_string),
486    })
487}
488
489#[cfg(feature = "serde_json")]
490fn block_from_json(value: &JsonValue) -> Result<Block, HooverError> {
491    let map = value
492        .as_object()
493        .ok_or_else(|| HooverError("hoover: each block must be an object".into()))?;
494    let name = field(map, "name")
495        .and_then(JsonValue::as_str)
496        .unwrap_or("")
497        .to_string();
498    let label = format!("block {name:?}");
499    let mut block = Block::new(name);
500
501    if let Some(token) = field(map, "token").and_then(JsonValue::as_str) {
502        block.token = Some(token.to_string());
503    }
504    if let Some(escape_char) = field(map, "escapeChar").and_then(JsonValue::as_str) {
505        let mut chars = escape_char.chars();
506        block.escape_char = match (chars.next(), chars.next()) {
507            (None, _) => None,
508            (Some(first), None) => Some(first),
509            (Some(_), Some(_)) => {
510                return Err(HooverError(format!(
511                    "hoover: {label}.escapeChar must be a single character"
512                )))
513            }
514        };
515    }
516    if let Some(escape) = field(map, "escape").and_then(JsonValue::as_object) {
517        for (key, replacement) in escape {
518            if let Some(replacement) = replacement.as_str() {
519                block.escape.insert(key.clone(), replacement.to_string());
520            }
521        }
522    }
523    if let Some(allow) = field(map, "allowUnknownEscape").and_then(JsonValue::as_bool) {
524        block.allow_unknown_escape = Some(allow);
525    }
526    block.preserve_escape_char = field(map, "preserveEscapeChar")
527        .and_then(JsonValue::as_bool)
528        .unwrap_or(false);
529    block.trim = field(map, "trim")
530        .and_then(JsonValue::as_bool)
531        .unwrap_or(false);
532
533    // A present `start` or `end` of the wrong shape is a configuration
534    // error, not an absent one: silently dropping it would broaden the
535    // match to "no fixed delimiter" and hoover unrelated input.
536    if let Some(start) = field(map, "start") {
537        if !start.is_null() && !start.is_object() {
538            return Err(HooverError(format!(
539                "hoover: {label}.start must be an object"
540            )));
541        }
542    }
543    if let Some(end) = field(map, "end") {
544        if !end.is_null() && !end.is_object() {
545            return Err(HooverError(format!(
546                "hoover: {label}.end must be an object"
547            )));
548        }
549    }
550    if let Some(start) = field(map, "start").and_then(JsonValue::as_object) {
551        let start_label = format!("{label}.start");
552        block.start = Some(StartSpec {
553            fixed: field(start, "fixed")
554                .map(|fixed| strings_from_json(fixed, &format!("{start_label}.fixed")))
555                .transpose()?,
556            consume: consume_from_json(start, &start_label)?,
557            rule: field(start, "rule")
558                .map(|rule| rule_from_json(rule, &format!("{start_label}.rule")))
559                .transpose()?,
560        });
561    }
562    if let Some(end) = field(map, "end").and_then(JsonValue::as_object) {
563        let end_label = format!("{label}.end");
564        block.end = EndSpec {
565            fixed: field(end, "fixed")
566                .map(|fixed| strings_from_json(fixed, &format!("{end_label}.fixed")))
567                .transpose()?
568                .unwrap_or_default(),
569            consume: consume_from_json(end, &end_label)?,
570        };
571    }
572    Ok(block)
573}
574
575/// Build the hoover plugin for `options`.
576///
577/// The returned [`Plugin`] can be installed with [`Tabnas::use_plugin`]
578/// and, like every native plugin, re-runs against a derived instance.
579/// Most callers want [`hoover`].
580pub fn plugin(options: HooverOptions) -> Plugin {
581    Plugin::new("Hoover", move |parser, _plugin_options| {
582        install(parser, &options).map_err(PluginError::from)
583    })
584}
585
586/// Register hoover on `parser`, the Rust spelling of the TypeScript
587/// `tn.use(Hoover, options)` call.
588///
589/// The parser must already carry a grammar that defines the `val` rule:
590/// hoover extends that rule, and fails fast with a clear error when it is
591/// absent rather than creating an empty one and failing confusingly
592/// later. It also refuses when the host grammar's alt filter
593/// (`rule.include` / `rule.exclude`) would discard the block alternate.
594pub fn hoover(parser: &mut Tabnas, options: HooverOptions) -> Result<(), HooverError> {
595    parser
596        .use_plugin(plugin(options), None)
597        .map(|_| ())
598        .map_err(HooverError::from)
599}
600
601/// One block as the matcher sees it: the definition plus the token
602/// identity it emits.
603struct Prepared {
604    block: Block,
605    token_name: String,
606    tin: Tin,
607}
608
609/// The slice of the resolved lexer configuration `parse_to_end` reads:
610/// the TypeScript `cfg.value.lex` flag and `cfg.value.def` table.
611struct MatcherConfig {
612    value_lex: bool,
613    definitions: HashMap<String, Value>,
614}
615
616impl MatcherConfig {
617    fn from_options(options: &Options) -> Self {
618        Self {
619            value_lex: options.value.lex,
620            definitions: options
621                .value
622                .definitions
623                .iter()
624                .map(|(source, definition)| {
625                    (
626                        source.clone(),
627                        definition.val.clone().unwrap_or(Value::Undefined),
628                    )
629                })
630                .collect(),
631        }
632    }
633}
634
635/// Each install registers its own references, so two hoover
636/// registrations on one instance (or on a derived one) do not overwrite
637/// each other's action or matcher factory.
638static INSTALLS: AtomicUsize = AtomicUsize::new(0);
639
640/// Quote `text` as a JSON string literal for the grammar document.
641fn json_string(text: &str) -> String {
642    let mut out = String::with_capacity(text.len() + 2);
643    out.push('"');
644    for c in text.chars() {
645        match c {
646            '"' => out.push_str("\\\""),
647            '\\' => out.push_str("\\\\"),
648            '\n' => out.push_str("\\n"),
649            '\r' => out.push_str("\\r"),
650            '\t' => out.push_str("\\t"),
651            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
652            c => out.push(c),
653        }
654    }
655    out.push('"');
656    out
657}
658
659fn install(parser: &mut Tabnas, options: &HooverOptions) -> Result<(), HooverError> {
660    // Hoover extends the host grammar's `val` rule. Fail fast with a clear
661    // message if a grammar providing it has not been registered first.
662    if !parser.rule_names().iter().any(|name| name == "val") {
663        return Err(HooverError(
664            "tabnas-hoover: the 'val' rule is missing; \
665             register a grammar that defines it before the hoover plugin"
666                .into(),
667        ));
668    }
669
670    let id = INSTALLS.fetch_add(1, Ordering::Relaxed);
671    let make_ref = format!("@hoover-matcher-{id}");
672    let action_ref = format!("@hoover-action-{id}");
673
674    // The engine's `rule.include` filter keeps only those alts carrying
675    // one of its group tags, so an untagged alt added to a host that
676    // narrows itself (`@tabnas/json` uses `rule: { include: 'json' }`)
677    // would be silently discarded. Carrying the host's active tags says
678    // "this alt is part of the selected grammar", which is exactly what a
679    // deliberate registration means.
680    let config = parser.config();
681    let include: Vec<String> = listed(&config.rule.include).map(str::to_string).collect();
682    let groups = include.join(",");
683
684    let mut prepared: Vec<Prepared> = Vec::with_capacity(options.block.len());
685    let mut token_map: Vec<(String, Tin)> = Vec::new();
686    let mut alts: Vec<String> = Vec::new();
687
688    if let Some(action) = options.action.clone() {
689        parser.action_with_context(action_ref.clone(), move |rule, context| {
690            action(rule, context)
691        });
692    }
693
694    for block in &options.block {
695        let token_name = block.token_name().to_string();
696        // The alt is declared through the serialized document, where a
697        // token name is one whitespace-free word; refuse anything else
698        // here, with a message that names the cause, rather than let the
699        // alt filter check below report it as an exclusion.
700        if token_name.is_empty() || token_name.chars().any(char::is_whitespace) {
701            return Err(HooverError(format!(
702                "tabnas-hoover: block {:?} has the token name {:?}; \
703                 a token name is a non-empty word without whitespace",
704                block.name, token_name
705            )));
706        }
707        let tin = parser.token(token_name.clone());
708
709        // Only the first occurrence of each token name adds a `val`
710        // alternate. Each is PREPENDED, as `rs.open(...)` does in
711        // TypeScript, so the alts are listed in reverse block order.
712        if !token_map.iter().any(|(name, _)| *name == token_name) {
713            let mut alt = format!("{{\"s\":{}", json_string(&token_name));
714            if options.action.is_some() {
715                alt.push_str(&format!(",\"a\":{}", json_string(&action_ref)));
716            }
717            if !groups.is_empty() {
718                alt.push_str(&format!(",\"g\":{}", json_string(&groups)));
719            }
720            alt.push('}');
721            alts.insert(0, alt);
722            token_map.push((token_name.clone(), tin));
723        }
724
725        prepared.push(Prepared {
726            block: block.clone(),
727            token_name,
728            tin,
729        });
730    }
731
732    let blocks = Arc::new(prepared);
733    parser.lex_match_factory_ref(make_ref.clone(), move |resolved: &Options| {
734        let config = Arc::new(MatcherConfig::from_options(resolved));
735        let blocks = Arc::clone(&blocks);
736        let matcher: ImperativeLexMatcher = Arc::new(
737            move |lexer: &mut Lexer<'_>, rule: &mut Rule, _context: &mut Context| {
738                hoover_matcher(lexer, rule, &blocks, &config)
739            },
740        );
741        Some(matcher)
742    });
743
744    let order = options.lex_order.unwrap_or(DEFAULT_LEX_ORDER);
745    if !order.is_finite() {
746        return Err(HooverError(
747            "hoover: lex.order must be a finite number".into(),
748        ));
749    }
750    // Written as JSON text rather than built with serde_json, so the
751    // engine stays this crate's only production dependency.
752    let document = format!(
753        "{{\"options\":{{\"lex\":{{\"match\":{{\"hoover\":{{\"order\":{order},\"make\":{make}}}}}}}}},\
754         \"rule\":{{\"val\":{{\"open\":[{alts}]}}}}}}",
755        make = json_string(&make_ref),
756        alts = alts.join(",")
757    );
758    let spec = GrammarSpec::from_json(&document)?;
759    parser.grammar(&spec)?;
760
761    // Check rather than assume that the alts survive the host's alt
762    // filter: the failure mode is silent, a working lexer feeding a rule
763    // that cannot accept its token, and it surfaces to the user as an
764    // `unexpected` error on their own source, pointing nowhere near the
765    // cause.
766    let config = parser.config();
767    let survivors = parser
768        .rule_specs()
769        .into_iter()
770        .find(|spec| spec.name == "val")
771        .map(|spec| spec.open.clone())
772        .unwrap_or_default();
773    let missing: Vec<&str> = token_map
774        .iter()
775        .filter(|(_, tin)| {
776            !survivors.iter().any(|alt| {
777                alt.s.iter().any(|position| position.contains(tin))
778                    && groups_enabled(&alt.g, &config.rule.include, &config.rule.exclude)
779            })
780        })
781        .map(|(name, _)| name.as_str())
782        .collect();
783    if !missing.is_empty() {
784        return Err(HooverError(format!(
785            "tabnas-hoover: the block alternate was removed from the 'val' rule by the \
786             host grammar's alt filter (rule.include={:?}, rule.exclude={:?}); \
787             hoover cannot extend a grammar that excludes it",
788            include,
789            listed(&config.rule.exclude).collect::<Vec<_>>(),
790        )));
791    }
792
793    Ok(())
794}
795
796/// Split a comma-separated group list, dropping empty entries: the
797/// engine's own reading of `rule.include` and `rule.exclude`.
798fn listed(list: &str) -> impl Iterator<Item = &str> {
799    list.split(',')
800        .map(str::trim)
801        .filter(|entry| !entry.is_empty())
802}
803
804/// The engine's alt filter, as `parser.rs` applies it: with neither list
805/// set every alt is enabled; otherwise an alt must carry one of the
806/// included groups (when any are listed) and none of the excluded ones.
807fn groups_enabled(alt_groups: &str, include: &str, exclude: &str) -> bool {
808    if include.is_empty() && exclude.is_empty() {
809        return true;
810    }
811    let declares = |wanted: &str| listed(alt_groups).any(|group| group == wanted);
812    let included = listed(include).next().is_none() || listed(include).any(declares);
813    included && !listed(exclude).any(declares)
814}
815
816/// `matchRule = value && (null === matchRule ? true : matchRule)`: each
817/// evaluated condition ANDs itself into the tri-state result.
818fn and_into(match_rule: &mut Option<bool>, value: bool) {
819    *match_rule = Some(value && match_rule.unwrap_or(true));
820}
821
822/// The lex matcher: try each block in order; the first whose start
823/// matches is committed.
824///
825/// A block is read from the text the lexer holds: the whole source, or in
826/// a parse from a reader a window of it (`lex.window`, admin ADR-30), which
827/// [`Lexer::window`] gives from the cursor on. A start delimiter the window
828/// ends inside, or a scan that reaches the window's end, may not be what
829/// the whole text gives, so the block is read again over a window asked for
830/// twice what it holds ([`Lexer::fill`]), a long block costing its length
831/// to read and not its square. Where the window does not grow, the source
832/// ends there, and the end of the window is the end of the source. In a
833/// whole text `fill` only answers.
834fn hoover_matcher(
835    lexer: &mut Lexer<'_>,
836    rule: &mut Rule,
837    blocks: &[Prepared],
838    config: &MatcherConfig,
839) -> Option<Token> {
840    let mut exhausted = !lexer.windowed();
841    'blocks: for prepared in blocks {
842        let block = &prepared.block;
843        let point = lexer.point();
844        loop {
845            let rest = lexer.window();
846            let scanned = match match_start(rest, rule, block, exhausted) {
847                Start::No => continue 'blocks,
848                Start::Edge => Err(Rejected::Edge),
849                Start::At(start) => parse_to_end(rest, start, block, config, exhausted),
850            };
851            match scanned {
852                Ok(Scanned { value, end }) => {
853                    let source = &rest[..end];
854                    let mut token =
855                        lexer.token(&prepared.token_name, prepared.tin, value, source, point);
856                    token
857                        .use_data_mut()
858                        .insert("block".to_string(), Value::String(block.name.clone()));
859                    let consumed = source.chars().count();
860                    lexer.advance_chars(consumed);
861                    return Some(token);
862                }
863                // The window ends inside the block: read on and try again.
864                Err(Rejected::Edge) => {
865                    let ahead = rest.len();
866                    let read = rest.chars().count();
867                    lexer.fill(read.saturating_mul(2).max(read + 1));
868                    if lexer.window().len() <= ahead {
869                        exhausted = true;
870                    }
871                }
872                // A rejected escape: the bad token spans the escape character.
873                Err(Rejected::Escape { at }) => {
874                    let position = point.site.pos + rest[..at].chars().count();
875                    return Some(lexer.bad_span(INVALID_ESCAPE, position, position + 1));
876                }
877                // Once a start matches, the block is committed: never
878                // reaching an end delimiter is an error, not a fall-through.
879                // The span is the start delimiter, as in TypeScript.
880                Err(Rejected::Unterminated { start }) => {
881                    let position = point.site.pos;
882                    let width = rest[..start].chars().count();
883                    return Some(lexer.bad_span(INVALID_TEXT, position, position + width));
884                }
885            }
886        }
887    }
888    None
889}
890
891/// What [`match_start`] found at the cursor.
892enum Start {
893    /// The block's start does not match here.
894    No,
895    /// The window ends inside a start delimiter that may yet match.
896    Edge,
897    /// The block's start matches, consuming this many bytes (zero when the
898    /// delimiter is kept or there is none).
899    At(usize),
900}
901
902/// Match a block's start against the rule context and the source at the
903/// cursor, `rest`. Unless `exhausted`, a delimiter that `rest` holds only
904/// the start of answers [`Start::Edge`].
905fn match_start(rest: &str, rule: &Rule, block: &Block, exhausted: bool) -> Start {
906    let start = block.start.as_ref();
907    let rulespec = start.and_then(|start| start.rule.as_ref());
908
909    // `None` means "no rule condition has been evaluated", which is not
910    // the same as "a condition failed": with no conditions there is
911    // nothing to constrain the match, so it passes.
912    let mut match_rule: Option<bool> = None;
913
914    // NOTE: the default rule state is open ('o'); there is no default
915    // parent or current filter, an absent filter imposes no constraint.
916    if let Some(rulespec) = rulespec {
917        if let Some(parent) = &rulespec.parent {
918            // The start rule has no parent here; in the canonical engine
919            // it has a sentinel one whose name is the empty string, so
920            // `""` is the one entry a list can name it by. Read the
921            // missing parent as that name so the two agree.
922            let parent_name = rule
923                .parent_rule
924                .as_deref()
925                .map_or("", |parent| parent.name.as_ref());
926            parent.passes(parent_name, &mut match_rule);
927        }
928        if let Some(current) = &rulespec.current {
929            current.passes(rule.name.as_ref(), &mut match_rule);
930        }
931    }
932
933    // '': don't check; 'oc' | 'c' | 'o' check; default 'o'.
934    let rulestate = rulespec
935        .and_then(|spec| spec.state.as_deref())
936        .unwrap_or("o");
937    if !rulestate.is_empty() {
938        let state = match rule.state {
939            RuleState::Open => 'o',
940            RuleState::Close => 'c',
941        };
942        and_into(&mut match_rule, rulestate.contains(state));
943    }
944
945    // Resolve "no condition evaluated" to a pass.
946    if !match_rule.unwrap_or(true) {
947        return Start::No;
948    }
949
950    let Some(fixed) = start.and_then(|start| start.fixed.as_ref()) else {
951        return Start::At(0);
952    };
953    let consume = start.map(|start| &start.consume);
954    for delimiter in fixed {
955        if rest.starts_with(delimiter.as_str()) {
956            let consumed = consume.is_none_or(|consume| consume.applies_to(delimiter));
957            return Start::At(if consumed { delimiter.len() } else { 0 });
958        }
959        // The window may end inside the delimiter, which then may match
960        // once it holds more, before any delimiter after it is tried.
961        if !exhausted && rest.len() < delimiter.len() && delimiter.starts_with(rest) {
962            return Start::Edge;
963        }
964    }
965    Start::No
966}
967
968/// The result of a completed scan: the value, and the byte offset in the
969/// remaining source just past everything the block consumed.
970struct Scanned {
971    value: Value,
972    end: usize,
973}
974
975enum Rejected {
976    /// An escape not in the map, with unknown escapes disallowed; `at` is
977    /// the byte offset of the escape character.
978    Escape { at: usize },
979    /// No end delimiter was reached; `start` is the byte length of the
980    /// start delimiter the block consumed.
981    Unterminated { start: usize },
982    /// The scan reached the end of the text the lexer holds while the
983    /// source may have more.
984    Edge,
985}
986
987/// Scan forward from `start` for one of the block's end delimiters,
988/// applying escapes, then trim and resolve the value. Unless `exhausted`,
989/// a scan that reaches the end of `rest`, the text the lexer holds,
990/// answers [`Rejected::Edge`]; with `exhausted`, the end of `rest` is the
991/// end of the source.
992fn parse_to_end(
993    rest: &str,
994    start: usize,
995    block: &Block,
996    config: &MatcherConfig,
997    exhausted: bool,
998) -> Result<Scanned, Rejected> {
999    let fixed = &block.end.fixed;
1000
1001    // The first character of each end delimiter and the tail that must
1002    // follow it. The `""` (end-of-input) delimiter has no first
1003    // character, which nothing in the source equals, so `None` is the
1004    // out-of-band marker TypeScript gets from `undefined`.
1005    let endchars: Vec<Option<char>> = fixed.iter().map(|end| end.chars().next()).collect();
1006    let endseqs: Vec<&str> = fixed
1007        .iter()
1008        .map(|end| end.chars().next().map_or("", |c| &end[c.len_utf8()..]))
1009        .collect();
1010
1011    let mut value = String::new();
1012    let mut index = start;
1013    let mut done = false;
1014    let mut end_index = index;
1015
1016    loop {
1017        let current = rest[index..].chars().next();
1018        if current.is_none() && !exhausted {
1019            return Err(Rejected::Edge);
1020        }
1021
1022        // Check for an end delimiter first, so an escape character that
1023        // is also an end character ends the block.
1024        if let Some(found) = endchars.iter().position(|end| *end == current) {
1025            let tail = endseqs[found];
1026            let after = index + current.map_or(0, char::len_utf8);
1027            if current.is_none() || tail.is_empty() {
1028                end_index = after;
1029                done = true;
1030                break;
1031            }
1032            // The window may end inside the tail.
1033            if !exhausted && rest.len() - after < tail.len() {
1034                return Err(Rejected::Edge);
1035            }
1036            if rest[after..].starts_with(tail) {
1037                end_index = after + tail.len();
1038                done = true;
1039                break;
1040            }
1041        }
1042
1043        let Some(c) = current else {
1044            break;
1045        };
1046
1047        if Some(c) == block.escape_char {
1048            let next = index + c.len_utf8();
1049            // An escape char as the final source character has nothing to
1050            // escape: the block never reaches an end delimiter and is
1051            // reported as unterminated.
1052            let Some(escaped) = rest[next..].chars().next() else {
1053                if !exhausted {
1054                    return Err(Rejected::Edge);
1055                }
1056                return Err(Rejected::Unterminated { start });
1057            };
1058            let after = next + escaped.len_utf8();
1059            // TypeScript reads one UTF-16 code unit here, so a character
1060            // outside the BMP can never match a key of the escape map and
1061            // always takes the unknown-escape path. Same here.
1062            let mapped = if (escaped as u32) <= 0xFFFF {
1063                block.escape.get(&escaped.to_string())
1064            } else {
1065                None
1066            };
1067            if let Some(replacement) = mapped {
1068                value.push_str(replacement);
1069            } else if block.allow_unknown() {
1070                if block.preserve_escape_char {
1071                    value.push(c);
1072                }
1073                value.push(escaped);
1074            } else {
1075                return Err(Rejected::Escape { at: index });
1076            }
1077            index = after;
1078        } else {
1079            value.push(c);
1080            index += c.len_utf8();
1081        }
1082    }
1083
1084    if !done {
1085        return Err(Rejected::Unterminated { start });
1086    }
1087
1088    let endfixed = &rest[index..end_index];
1089    if block.end.consume.applies_to(endfixed) {
1090        index = end_index;
1091    }
1092
1093    let text = if block.trim {
1094        js_trim(&value).to_string()
1095    } else {
1096        value
1097    };
1098
1099    let value = match config.definitions.get(&text) {
1100        Some(defined) if config.value_lex => defined.clone(),
1101        _ => Value::String(text),
1102    };
1103
1104    Ok(Scanned { value, end: index })
1105}
1106
1107/// Whether `c` is removed by JavaScript's `String.prototype.trim`, which
1108/// the canonical port calls for `trim: true`.
1109///
1110/// ECMA-262 defines the trimmed set as WhiteSpace plus LineTerminator:
1111/// TAB, VT, FF, ZWNBSP (U+FEFF), every Space_Separator (Zs) code point,
1112/// LF, CR, LS (U+2028) and PS (U+2029). That is NOT `char::is_whitespace`
1113/// (Unicode White_Space), in both directions: U+0085 NEL is White_Space
1114/// but not trimmed by JavaScript, and U+FEFF is trimmed by JavaScript but
1115/// not White_Space. The set is enumerated for exactly that reason.
1116fn is_trim_space(c: char) -> bool {
1117    matches!(
1118        c,
1119        '\u{0009}' // TAB
1120            | '\u{000A}' // LF
1121            | '\u{000B}' // VT
1122            | '\u{000C}' // FF
1123            | '\u{000D}' // CR
1124            | '\u{0020}' // SPACE
1125            | '\u{00A0}' // NO-BREAK SPACE
1126            | '\u{1680}' // OGHAM SPACE MARK
1127            | '\u{2000}' // EN QUAD
1128            | '\u{2001}' // EM QUAD
1129            | '\u{2002}' // EN SPACE
1130            | '\u{2003}' // EM SPACE
1131            | '\u{2004}' // THREE-PER-EM SPACE
1132            | '\u{2005}' // FOUR-PER-EM SPACE
1133            | '\u{2006}' // SIX-PER-EM SPACE
1134            | '\u{2007}' // FIGURE SPACE
1135            | '\u{2008}' // PUNCTUATION SPACE
1136            | '\u{2009}' // THIN SPACE
1137            | '\u{200A}' // HAIR SPACE
1138            | '\u{2028}' // LINE SEPARATOR
1139            | '\u{2029}' // PARAGRAPH SEPARATOR
1140            | '\u{202F}' // NARROW NO-BREAK SPACE
1141            | '\u{205F}' // MEDIUM MATHEMATICAL SPACE
1142            | '\u{3000}' // IDEOGRAPHIC SPACE
1143            | '\u{FEFF}' // ZWNBSP (BOM)
1144    )
1145}
1146
1147/// JavaScript's `String.prototype.trim`, exactly: strip leading and
1148/// trailing code points in the ECMA-262 trim set.
1149pub fn js_trim(text: &str) -> &str {
1150    text.trim_matches(is_trim_space)
1151}
1152
1153#[cfg(test)]
1154mod tests {
1155    use super::*;
1156
1157    #[test]
1158    fn js_trim_follows_ecma_262_not_unicode_white_space() {
1159        assert_eq!(js_trim("\u{FEFF} hello \u{FEFF}"), "hello");
1160        assert_eq!(js_trim("\u{0085}hello\u{0085}"), "\u{0085}hello\u{0085}");
1161        assert_eq!(js_trim("\u{200B}hello"), "\u{200B}hello");
1162        assert_eq!(js_trim("\u{FEFF} \u{3000}"), "");
1163    }
1164
1165    #[test]
1166    fn groups_enabled_mirrors_the_engine_filter() {
1167        assert!(groups_enabled("", "", ""));
1168        assert!(groups_enabled("mini", "mini", ""));
1169        assert!(!groups_enabled("", "mini", ""));
1170        assert!(!groups_enabled("mini", "mini", "mini"));
1171        assert!(groups_enabled("a,mini", "mini,json", "other"));
1172    }
1173}