1use 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#[cfg(doctest)]
55#[doc = include_str!("../README.md")]
56mod readme_examples {}
57
58pub const VERSION: &str = "0.3.15";
64
65pub const DEFAULT_LEX_ORDER: f64 = 4.5e6;
69
70pub const DEFAULT_TOKEN: &str = "#HV";
72
73pub const INVALID_TEXT: &str = "invalid_text";
76
77pub const INVALID_ESCAPE: &str = "invalid_escape";
80
81#[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
116pub type ActionFn = Arc<dyn Fn(&mut Rule, &mut Context) -> Result<(), ActionError> + Send + Sync>;
121
122#[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 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 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 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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
182pub enum Consume {
183 #[default]
185 All,
186 Never,
189 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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
218pub struct EndSpec {
219 pub fixed: Vec<String>,
220 pub consume: Consume,
221}
222
223#[derive(Debug, Clone, Default, PartialEq, Eq)]
231pub struct Block {
232 pub name: String,
234 pub start: Option<StartSpec>,
235 pub end: EndSpec,
236 pub token: Option<String>,
238 pub escape_char: Option<char>,
240 pub escape: HashMap<String, String>,
243 pub allow_unknown_escape: Option<bool>,
247 pub preserve_escape_char: bool,
249 pub trim: bool,
252}
253
254impl Block {
255 pub fn new(name: impl Into<String>) -> Self {
257 Self {
258 name: name.into(),
259 ..Self::default()
260 }
261 }
262
263 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 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 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 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 pub fn with_escape_char(mut self, escape_char: char) -> Self {
290 self.escape_char = Some(escape_char);
291 self
292 }
293
294 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#[derive(Clone, Default)]
318pub struct HooverOptions {
319 pub block: Vec<Block>,
321 pub lex_order: Option<f64>,
323 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 pub fn new(block: Vec<Block>) -> Self {
342 Self {
343 block,
344 lex_order: None,
345 action: None,
346 }
347 }
348
349 pub fn with_lex_order(mut self, order: f64) -> Self {
351 self.lex_order = Some(order);
352 self
353 }
354
355 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 #[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#[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#[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 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 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
575pub fn plugin(options: HooverOptions) -> Plugin {
581 Plugin::new("Hoover", move |parser, _plugin_options| {
582 install(parser, &options).map_err(PluginError::from)
583 })
584}
585
586pub 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
601struct Prepared {
604 block: Block,
605 token_name: String,
606 tin: Tin,
607}
608
609struct 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
635static INSTALLS: AtomicUsize = AtomicUsize::new(0);
639
640fn 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 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 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 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 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 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 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
796fn listed(list: &str) -> impl Iterator<Item = &str> {
799 list.split(',')
800 .map(str::trim)
801 .filter(|entry| !entry.is_empty())
802}
803
804fn 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
816fn and_into(match_rule: &mut Option<bool>, value: bool) {
819 *match_rule = Some(value && match_rule.unwrap_or(true));
820}
821
822fn 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 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 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 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
891enum Start {
893 No,
895 Edge,
897 At(usize),
900}
901
902fn 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 let mut match_rule: Option<bool> = None;
913
914 if let Some(rulespec) = rulespec {
917 if let Some(parent) = &rulespec.parent {
918 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 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 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 if !exhausted && rest.len() < delimiter.len() && delimiter.starts_with(rest) {
962 return Start::Edge;
963 }
964 }
965 Start::No
966}
967
968struct Scanned {
971 value: Value,
972 end: usize,
973}
974
975enum Rejected {
976 Escape { at: usize },
979 Unterminated { start: usize },
982 Edge,
985}
986
987fn 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 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 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 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 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 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
1107fn is_trim_space(c: char) -> bool {
1117 matches!(
1118 c,
1119 '\u{0009}' | '\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0020}' | '\u{00A0}' | '\u{1680}' | '\u{2000}' | '\u{2001}' | '\u{2002}' | '\u{2003}' | '\u{2004}' | '\u{2005}' | '\u{2006}' | '\u{2007}' | '\u{2008}' | '\u{2009}' | '\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | '\u{FEFF}' )
1145}
1146
1147pub 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}