1#![allow(clippy::result_large_err)]
54
55use std::cell::{Cell, RefCell};
56use std::collections::HashMap;
57use std::fmt;
58use std::rc::Rc;
59use std::sync::{Arc, OnceLock};
60
61use indexmap::IndexMap;
62
63use tabnas::{
64 AltMatch, AltSpec, Context, ListRef, Plugin, PluginError, Rule, RuleSnapshot, RuleSpec, Tabnas,
65 TabnasError, Tin, Token, Value, TIN_CA, TIN_CB, TIN_CL, TIN_CS, TIN_NR, TIN_OB, TIN_OS, TIN_ST,
66 TIN_TX, TIN_VL, TIN_ZZ,
67};
68
69pub const VERSION: &str = "0.6.0";
75
76pub const PLUGIN_NAME: &str = "Expr";
78
79#[cfg(doctest)]
83#[doc = include_str!("../README.md")]
84mod readme_examples {}
85
86pub use tabnas::TabnasError as ExprError;
89
90mod tree;
92
93pub use tree::{
94 fold, key_op_of, make_key_map, FoldCycle, FoldDynamic, FoldEntry, FoldError, FoldEvaluate,
95 FoldHit, FoldOptions, FoldReport, Inherit, KeyMap, Load, Path, Positions, Recognise, Seg, Site,
96 FOLD_CYCLE, FOLD_DEPTH, FOLD_INHERIT, FOLD_KEY, FOLD_MAX_STACK, FOLD_OPTION,
97};
98
99pub const MIN_SAFE_INTEGER: i64 = -9_007_199_254_740_991;
102
103pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
106
107#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub struct PrevalDef {
116 pub active: bool,
117 pub required: bool,
118 pub allow: Option<Vec<String>>,
119}
120
121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
124pub struct ContentDef {
125 pub required: bool,
128 pub separated: bool,
133}
134
135#[derive(Clone)]
140pub struct Accept(Arc<dyn Fn(&Value) -> bool + Send + Sync>);
141
142impl Accept {
143 pub fn new(test: impl Fn(&Value) -> bool + Send + Sync + 'static) -> Self {
145 Accept(Arc::new(test))
146 }
147
148 pub fn accepts(&self, term: &Value) -> bool {
150 (self.0)(term)
151 }
152}
153
154impl fmt::Debug for Accept {
155 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
156 formatter.write_str("Accept(<function>)")
157 }
158}
159
160impl PartialEq for Accept {
162 fn eq(&self, other: &Self) -> bool {
163 Arc::ptr_eq(&self.0, &other.0)
164 }
165}
166
167#[derive(Debug, Clone, PartialEq)]
174pub struct OpDef {
175 pub src: Vec<String>,
176 pub osrc: String,
177 pub csrc: String,
178 pub left: Option<i64>,
179 pub right: Option<i64>,
180 pub prefix: bool,
181 pub suffix: bool,
182 pub infix: bool,
183 pub ternary: bool,
184 pub paren: bool,
185 pub preval: Option<PrevalDef>,
186 pub use_data: Value,
188 pub key: bool,
195 pub dynamic: bool,
199 pub content: ContentDef,
201 pub separator: bool,
207 pub cast: bool,
216 pub accept: Option<Accept>,
218}
219
220impl Default for OpDef {
221 fn default() -> Self {
222 OpDef {
223 src: Vec::new(),
224 osrc: String::new(),
225 csrc: String::new(),
226 left: None,
227 right: None,
228 prefix: false,
229 suffix: false,
230 infix: false,
231 ternary: false,
232 paren: false,
233 preval: None,
234 use_data: Value::Undefined,
235 key: false,
236 dynamic: false,
237 content: ContentDef::default(),
238 separator: false,
239 cast: false,
240 accept: None,
241 }
242 }
243}
244
245impl OpDef {
246 pub fn infix(src: impl Into<String>, left: i64, right: i64) -> Self {
248 OpDef {
249 src: vec![src.into()],
250 infix: true,
251 left: Some(left),
252 right: Some(right),
253 ..Default::default()
254 }
255 }
256
257 pub fn prefix(src: impl Into<String>, right: i64) -> Self {
259 OpDef {
260 src: vec![src.into()],
261 prefix: true,
262 right: Some(right),
263 ..Default::default()
264 }
265 }
266
267 pub fn suffix(src: impl Into<String>, left: i64) -> Self {
269 OpDef {
270 src: vec![src.into()],
271 suffix: true,
272 left: Some(left),
273 ..Default::default()
274 }
275 }
276
277 pub fn ternary(first: impl Into<String>, second: impl Into<String>) -> Self {
279 OpDef {
280 src: vec![first.into(), second.into()],
281 ternary: true,
282 ..Default::default()
283 }
284 }
285
286 pub fn paren(osrc: impl Into<String>, csrc: impl Into<String>) -> Self {
298 OpDef {
299 osrc: osrc.into(),
300 csrc: csrc.into(),
301 paren: true,
302 ..Default::default()
303 }
304 }
305
306 pub fn key(src: impl Into<String>) -> Self {
309 OpDef {
310 src: vec![src.into()],
311 key: true,
312 ..Default::default()
313 }
314 }
315
316 pub fn dynamic_key(src: impl Into<String>) -> Self {
319 OpDef {
320 dynamic: true,
321 ..OpDef::key(src)
322 }
323 }
324
325 pub fn cast(
328 osrc: impl Into<String>,
329 csrc: impl Into<String>,
330 right: i64,
331 accept: impl Fn(&Value) -> bool + Send + Sync + 'static,
332 ) -> Self {
333 OpDef {
334 osrc: osrc.into(),
335 csrc: csrc.into(),
336 right: Some(right),
337 cast: true,
338 accept: Some(Accept::new(accept)),
339 ..Default::default()
340 }
341 }
342
343 pub fn with_preval(mut self, preval: PrevalDef) -> Self {
345 self.preval = Some(preval);
346 self
347 }
348
349 pub fn with_left(mut self, left: i64) -> Self {
354 self.left = Some(left);
355 self
356 }
357
358 pub fn with_content(mut self, content: ContentDef) -> Self {
360 self.content = content;
361 self
362 }
363
364 pub fn with_separator(mut self) -> Self {
367 self.separator = true;
368 self
369 }
370
371 pub fn with_use(mut self, use_data: Value) -> Self {
373 self.use_data = use_data;
374 self
375 }
376}
377
378#[derive(Debug, Clone, PartialEq)]
381pub struct Op {
382 pub name: String,
383 pub src: String,
384 pub left: i64,
385 pub right: i64,
386 pub use_data: Value,
387 pub prefix: bool,
388 pub suffix: bool,
389 pub infix: bool,
390 pub ternary: bool,
391 pub paren: bool,
392 pub terms: usize,
393 pub tkn: String,
394 pub tin: Tin,
395 pub osrc: String,
396 pub csrc: String,
397 pub otkn: String,
398 pub otin: Tin,
399 pub ctkn: String,
400 pub ctin: Tin,
401 pub preval: PrevalDef,
402 pub ternary_index: Option<usize>,
405 pub key: bool,
408 pub dynamic: bool,
411 pub content: ContentDef,
413 pub separator: bool,
416 pub cast: bool,
419 pub accept: Option<Accept>,
421}
422
423impl Default for Op {
424 fn default() -> Self {
425 Op {
426 name: String::new(),
427 src: String::new(),
428 left: MIN_SAFE_INTEGER,
429 right: MAX_SAFE_INTEGER,
430 use_data: Value::Undefined,
431 prefix: false,
432 suffix: false,
433 infix: false,
434 ternary: false,
435 paren: false,
436 terms: 0,
437 tkn: String::new(),
438 tin: -1,
439 osrc: String::new(),
440 csrc: String::new(),
441 otkn: String::new(),
442 otin: -1,
443 ctkn: String::new(),
444 ctin: -1,
445 preval: PrevalDef::default(),
446 ternary_index: None,
447 key: false,
448 dynamic: false,
449 content: ContentDef::default(),
450 separator: false,
451 cast: false,
452 accept: None,
453 }
454 }
455}
456
457impl Op {
458 fn to_value(&self, token: Option<&Token>) -> Value {
462 let mut map: IndexMap<String, Value> = IndexMap::new();
463 map.insert("src".into(), Value::String(self.src.clone()));
464 map.insert("left".into(), number(self.left));
465 map.insert("right".into(), number(self.right));
466 map.insert("name".into(), Value::String(self.name.clone()));
467 map.insert("infix".into(), Value::Bool(self.infix));
468 map.insert("prefix".into(), Value::Bool(self.prefix));
469 map.insert("suffix".into(), Value::Bool(self.suffix));
470 map.insert("ternary".into(), Value::Bool(self.ternary));
471 map.insert("tkn".into(), Value::String(self.tkn.clone()));
472 map.insert("tin".into(), Value::Number(f64::from(self.tin)));
473 map.insert("terms".into(), Value::Number(self.terms as f64));
474 map.insert("use".into(), self.use_value());
475 map.insert("paren".into(), Value::Bool(self.paren));
476 map.insert("osrc".into(), Value::String(self.osrc.clone()));
477 map.insert("csrc".into(), Value::String(self.csrc.clone()));
478 map.insert("otkn".into(), Value::String(self.otkn.clone()));
479 map.insert("ctkn".into(), Value::String(self.ctkn.clone()));
480 map.insert("otin".into(), Value::Number(f64::from(self.otin)));
481 map.insert("ctin".into(), Value::Number(f64::from(self.ctin)));
482 map.insert("preval".into(), self.preval_value());
483 let mut content: IndexMap<String, Value> = IndexMap::new();
488 content.insert("required".into(), Value::Bool(self.content.required));
489 content.insert("separated".into(), Value::Bool(self.content.separated));
490 map.insert("content".into(), Value::object(content));
491 map.insert("separator".into(), Value::Bool(self.separator));
492 map.insert("cast".into(), Value::Bool(self.cast));
493 map.insert("key".into(), Value::Bool(self.key));
494 map.insert("dynamic".into(), Value::Bool(self.dynamic));
495 map.insert("token".into(), token_value(token));
496 Value::object(map)
497 }
498
499 fn use_value(&self) -> Value {
500 let mut used: IndexMap<String, Value> = match &self.use_data {
501 Value::Object(entries) => (**entries).clone(),
502 _ => IndexMap::new(),
503 };
504 if let Some(index) = self.ternary_index {
505 let mut ternary: IndexMap<String, Value> = IndexMap::new();
506 ternary.insert("opI".into(), Value::Number(index as f64));
507 used.insert("ternary".into(), Value::object(ternary));
508 }
509 Value::object(used)
510 }
511
512 fn preval_value(&self) -> Value {
513 let mut preval: IndexMap<String, Value> = IndexMap::new();
514 preval.insert("active".into(), Value::Bool(self.preval.active));
515 preval.insert("required".into(), Value::Bool(self.preval.required));
516 if let Some(allow) = &self.preval.allow {
517 preval.insert(
518 "allow".into(),
519 Value::array(allow.iter().cloned().map(Value::String).collect()),
520 );
521 }
522 Value::object(preval)
523 }
524}
525
526fn number(value: i64) -> Value {
530 Value::Number(value as f64)
531}
532
533fn token_value(token: Option<&Token>) -> Value {
536 let Some(token) = token else {
537 return Value::object(IndexMap::new());
538 };
539 let mut map: IndexMap<String, Value> = IndexMap::new();
540 map.insert("isToken".into(), Value::Bool(true));
541 map.insert("name".into(), Value::String(token.name.as_str().into()));
542 map.insert("tin".into(), Value::Number(f64::from(token.tin)));
543 map.insert("src".into(), Value::String(token.src.as_str().into()));
544 map.insert("len".into(), Value::Number(token.len as f64));
545 map.insert("sI".into(), Value::Number(token.site.pos as f64));
546 map.insert("rI".into(), Value::Number(token.site.ri as f64));
547 map.insert("cI".into(), Value::Number(token.site.ci as f64));
548 Value::object(map)
549}
550
551pub struct EvalSite<'a> {
564 rule: Option<Rc<RuleSnapshot>>,
565 context: Option<&'a mut Context>,
566 token: Option<Token>,
567}
568
569impl<'a> EvalSite<'a> {
570 pub fn detached() -> Self {
572 EvalSite {
573 rule: None,
574 context: None,
575 token: None,
576 }
577 }
578
579 pub fn new(rule: Option<Rc<RuleSnapshot>>, context: &'a mut Context) -> Self {
581 EvalSite {
582 rule,
583 context: Some(context),
584 token: None,
585 }
586 }
587
588 pub fn rule(&self) -> Option<&RuleSnapshot> {
590 self.rule.as_deref()
591 }
592
593 pub fn token(&self) -> Option<&Token> {
606 self.token.as_ref()
607 }
608
609 pub fn context(&mut self) -> Option<&mut Context> {
611 self.context.as_deref_mut()
612 }
613
614 pub fn flag(&self, name: &str) -> bool {
618 self.rule
619 .as_ref()
620 .is_some_and(|rule| matches!(rule.u.get(name), Some(Value::Bool(true))))
621 }
622
623 fn reborrow(&mut self) -> EvalSite<'_> {
627 EvalSite {
628 rule: self.rule.clone(),
629 context: self.context.as_deref_mut(),
630 token: None,
631 }
632 }
633}
634
635pub type Evaluate = Arc<dyn Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync>;
639
640#[derive(Clone, Default)]
647pub struct ExprOptions {
648 pub op: IndexMap<String, Option<OpDef>>,
649 pub evaluate: Option<Evaluate>,
650 pub juxtapose: Option<bool>,
657}
658
659impl fmt::Debug for ExprOptions {
660 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
661 formatter
662 .debug_struct("ExprOptions")
663 .field("op", &self.op)
664 .field("evaluate", &self.evaluate.as_ref().map(|_| "<function>"))
665 .field("juxtapose", &self.juxtapose)
666 .finish()
667 }
668}
669
670impl ExprOptions {
671 pub fn new() -> Self {
674 Self::default()
675 }
676
677 pub fn with_op(mut self, name: impl Into<String>, def: OpDef) -> Self {
679 self.op.insert(name.into(), Some(def));
680 self
681 }
682
683 pub fn without_op(mut self, name: impl Into<String>) -> Self {
685 self.op.insert(name.into(), None);
686 self
687 }
688
689 pub fn with_juxtapose(mut self, juxtapose: bool) -> Self {
692 self.juxtapose = Some(juxtapose);
693 self
694 }
695
696 pub fn with_evaluate(
698 mut self,
699 evaluate: impl Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync + 'static,
700 ) -> Self {
701 self.evaluate = Some(Arc::new(evaluate));
702 self
703 }
704
705 pub fn from_value(options: &Value) -> Self {
709 let mut resolved = ExprOptions::new();
710 if let Some(Value::Bool(juxtapose)) = object_get(options, "juxtapose") {
711 resolved.juxtapose = Some(*juxtapose);
712 }
713 let Some(op) = object_get(options, "op") else {
714 return resolved;
715 };
716 let Value::Object(entries) = op else {
717 return resolved;
718 };
719 for (name, def) in entries.iter() {
720 match def {
721 Value::Object(_) => {
722 resolved
723 .op
724 .insert(name.clone(), Some(op_def_from_value(def)));
725 }
726 _ => {
728 resolved.op.insert(name.clone(), None);
729 }
730 }
731 }
732 resolved
733 }
734}
735
736fn object_get<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
737 match value {
738 Value::Object(map) => map.get(key),
739 Value::MapRef(map) => map.value.get(key),
740 _ => None,
741 }
742}
743
744fn value_bool(value: Option<&Value>) -> bool {
745 matches!(value, Some(Value::Bool(true)))
746}
747
748fn value_i64(value: Option<&Value>) -> Option<i64> {
749 match value {
750 Some(Value::Number(number)) => Some(*number as i64),
751 _ => None,
752 }
753}
754
755fn value_string(value: Option<&Value>) -> String {
756 match value {
757 Some(Value::String(text)) => text.clone(),
758 Some(Value::Text(text)) => text.string.clone(),
759 _ => String::new(),
760 }
761}
762
763fn op_def_from_value(def: &Value) -> OpDef {
764 let mut out = OpDef {
765 osrc: value_string(object_get(def, "osrc")),
766 csrc: value_string(object_get(def, "csrc")),
767 left: value_i64(object_get(def, "left")),
768 right: value_i64(object_get(def, "right")),
769 prefix: value_bool(object_get(def, "prefix")),
770 suffix: value_bool(object_get(def, "suffix")),
771 infix: value_bool(object_get(def, "infix")),
772 ternary: value_bool(object_get(def, "ternary")),
773 paren: value_bool(object_get(def, "paren")),
774 use_data: object_get(def, "use").cloned().unwrap_or(Value::Undefined),
775 key: value_bool(object_get(def, "key")),
776 dynamic: value_bool(object_get(def, "dynamic")),
777 separator: value_bool(object_get(def, "separator")),
778 cast: value_bool(object_get(def, "cast")),
781 ..Default::default()
782 };
783 if let Some(content) = object_get(def, "content") {
784 out.content = ContentDef {
785 required: value_bool(object_get(content, "required")),
786 separated: value_bool(object_get(content, "separated")),
787 };
788 }
789 match object_get(def, "src") {
790 Some(Value::String(src)) => out.src = vec![src.clone()],
791 Some(Value::Array(srcs)) => {
792 out.src = srcs
793 .iter()
794 .map(|src| value_string(Some(src)))
795 .collect::<Vec<_>>()
796 }
797 _ => {}
798 }
799 out.preval = match object_get(def, "preval") {
800 None | Some(Value::Undefined) | Some(Value::Null) => None,
801 Some(Value::Bool(active)) => Some(PrevalDef {
802 active: *active,
803 required: false,
804 allow: None,
805 }),
806 Some(preval) => Some(PrevalDef {
807 active: match object_get(preval, "active") {
809 None | Some(Value::Undefined) | Some(Value::Null) => true,
810 Some(Value::Bool(active)) => *active,
811 Some(_) => true,
812 },
813 required: value_bool(object_get(preval, "required")),
814 allow: match object_get(preval, "allow") {
815 Some(Value::Array(allow)) => Some(
816 allow
817 .iter()
818 .map(|entry| value_string(Some(entry)))
819 .collect::<Vec<_>>(),
820 ),
821 _ => None,
822 },
823 }),
824 };
825 out
826}
827
828pub fn defaults() -> Value {
852 let mut ops: IndexMap<String, Value> = IndexMap::new();
853 ops.insert("positive".into(), prefix_value("+", 4_000_000));
854 ops.insert("negative".into(), prefix_value("-", 4_000_000));
855 ops.insert("addition".into(), infix_value("+", 2_000_000, 2_100_000));
858 ops.insert("subtraction".into(), infix_value("-", 2_000_000, 2_100_000));
859 ops.insert(
860 "multiplication".into(),
861 infix_value("*", 3_000_000, 3_100_000),
862 );
863 ops.insert("division".into(), infix_value("/", 3_000_000, 3_100_000));
864 ops.insert("remainder".into(), infix_value("%", 3_000_000, 3_100_000));
865 ops.insert("plain".into(), paren_value("(", ")"));
866
867 let mut map: IndexMap<String, Value> = IndexMap::new();
868 map.insert("op".into(), Value::object(ops));
869 Value::object(map)
870}
871
872fn prefix_value(src: &str, right: i64) -> Value {
873 let mut def: IndexMap<String, Value> = IndexMap::new();
874 def.insert("prefix".into(), Value::Bool(true));
875 def.insert("right".into(), number(right));
876 def.insert("src".into(), Value::String(src.into()));
877 Value::object(def)
878}
879
880fn infix_value(src: &str, left: i64, right: i64) -> Value {
881 let mut def: IndexMap<String, Value> = IndexMap::new();
882 def.insert("infix".into(), Value::Bool(true));
883 def.insert("left".into(), number(left));
884 def.insert("right".into(), number(right));
885 def.insert("src".into(), Value::String(src.into()));
886 Value::object(def)
887}
888
889fn paren_value(osrc: &str, csrc: &str) -> Value {
890 let mut def: IndexMap<String, Value> = IndexMap::new();
891 def.insert("paren".into(), Value::Bool(true));
892 def.insert("osrc".into(), Value::String(osrc.into()));
893 def.insert("csrc".into(), Value::String(csrc.into()));
894 Value::object(def)
895}
896
897fn default_ops() -> IndexMap<String, Option<OpDef>> {
899 ExprOptions::from_value(&defaults()).op
900}
901
902fn resolve_options(options: &ExprOptions) -> IndexMap<String, Option<OpDef>> {
906 let defaults = default_ops();
907 let mut resolved = defaults.clone();
908 for (name, def) in &options.op {
909 resolved.shift_remove(name);
910 match def {
911 Some(def) => {
912 resolved.insert(name.clone(), Some(def.clone()));
913 }
914 None => {
915 resolved.insert(name.clone(), None);
916 }
917 }
918 }
919
920 if let Some(Some(plain)) = resolved.get("plain") {
928 let claimed = Some(&Some(plain.clone())) == defaults.get("plain")
929 && resolved.iter().any(|(name, def)| {
930 "plain" != name
931 && def.as_ref().is_some_and(|def| {
932 def.paren && def.osrc == plain.osrc && def.csrc == plain.csrc
933 })
934 });
935 if claimed {
936 resolved.shift_remove("plain");
937 }
938 }
939 resolved
940}
941
942#[derive(Debug, Clone)]
971struct ExprNode {
972 op: Option<Arc<Op>>,
973 token: Option<Token>,
974 terms: Vec<Value>,
975 root: u64,
985 size: usize,
989}
990
991#[derive(Default)]
992struct Arena {
993 nodes: HashMap<u64, ExprNode>,
994 next_id: u64,
995 active: usize,
998}
999
1000thread_local! {
1001 static ARENA: RefCell<Arena> = RefCell::new(Arena::default());
1002 static OVER_LIMIT: Cell<bool> = const { Cell::new(false) };
1005}
1006
1007const EXPR_META: &str = "expr";
1009
1010pub const NODE_LIMIT: usize = 127;
1023
1024pub const RULE_LIMIT: usize = 1024;
1035
1036fn node_id(value: &Value) -> Option<u64> {
1038 let Value::ListRef(list) = value else {
1039 return None;
1040 };
1041 match list.meta.get(EXPR_META) {
1042 Some(Value::Number(id)) => Some(*id as u64),
1043 _ => None,
1044 }
1045}
1046
1047pub fn is_op(value: &Value) -> bool {
1050 op_of(value).is_some()
1051}
1052
1053fn node_length(value: &Value) -> usize {
1057 if let Some(length) = with_node(value, |entry| {
1058 entry.terms.len() + usize::from(entry.op.is_some())
1059 }) {
1060 return length;
1061 }
1062 match value {
1063 Value::Array(entries) => entries.len(),
1064 Value::ListRef(list) => list.value.len(),
1065 _ => 0,
1066 }
1067}
1068
1069fn is_op_kind(value: &Value, kind: fn(&Op) -> bool) -> bool {
1070 op_of(value).is_some_and(|op| kind(&op))
1071}
1072
1073fn is_paren_op(value: &Value) -> bool {
1074 is_op_kind(value, |op| op.paren)
1075}
1076
1077fn is_ternary_op(value: &Value) -> bool {
1078 is_op_kind(value, |op| op.ternary)
1079}
1080
1081pub fn op_of(value: &Value) -> Option<Arc<Op>> {
1083 let id = node_id(value)?;
1084 ARENA.with(|arena| {
1085 arena
1086 .borrow()
1087 .nodes
1088 .get(&id)
1089 .and_then(|node| node.op.clone())
1090 })
1091}
1092
1093pub fn terms_of(value: &Value) -> Option<Vec<Value>> {
1095 let id = node_id(value)?;
1096 ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.terms.clone()))
1097}
1098
1099fn new_node_under(
1102 op: Option<Arc<Op>>,
1103 token: Option<Token>,
1104 terms: Vec<Value>,
1105 under: Option<&Value>,
1106) -> Value {
1107 let inherited = under.and_then(root_id);
1108 let terms_taken = terms.clone();
1109 let id = ARENA.with(|arena| {
1110 let mut arena = arena.borrow_mut();
1111 arena.next_id += 1;
1112 let id = arena.next_id;
1113 arena.nodes.insert(
1114 id,
1115 ExprNode {
1116 op,
1117 token,
1118 terms,
1119 root: inherited.unwrap_or(id),
1120 size: 1,
1121 },
1122 );
1123 id
1124 });
1125 let handle = handle_for(id);
1126 if under.is_some() {
1127 grow(&handle, 1);
1128 }
1129 adopt_all(&handle, &terms_taken);
1130 handle
1131}
1132
1133fn new_node(op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) -> Value {
1134 new_node_under(op, token, terms, None)
1135}
1136
1137fn grow(node: &Value, count: usize) {
1140 let Some(root) = root_id(node) else {
1141 return;
1142 };
1143 let over = ARENA.with(|arena| {
1144 let mut arena = arena.borrow_mut();
1145 match arena.nodes.get_mut(&root) {
1146 Some(entry) => {
1147 entry.size += count;
1148 entry.size > NODE_LIMIT
1149 }
1150 None => false,
1151 }
1152 });
1153 if over {
1154 OVER_LIMIT.with(|flag| flag.set(true));
1155 }
1156}
1157
1158fn expression_size(node: &Value) -> usize {
1160 let Some(root) = root_id(node) else {
1161 return 0;
1162 };
1163 ARENA.with(|arena| {
1164 arena
1165 .borrow()
1166 .nodes
1167 .get(&root)
1168 .map_or(0, |entry| entry.size)
1169 })
1170}
1171
1172fn adopt(container: &Value, term: &Value) {
1176 let (Some(into), Some(from)) = (root_id(container), root_id(term)) else {
1177 return;
1178 };
1179 if into == from {
1180 return;
1181 }
1182 grow(container, expression_size(term));
1183}
1184
1185fn adopt_all(container: &Value, terms: &[Value]) {
1186 for term in terms {
1187 adopt(container, term);
1188 }
1189}
1190
1191fn handle_for(id: u64) -> Value {
1194 let mut meta: IndexMap<String, Value> = IndexMap::new();
1195 meta.insert(EXPR_META.into(), Value::Number(id as f64));
1196 Value::ListRef(Arc::new(ListRef {
1197 value: Vec::new(),
1198 implicit: false,
1199 child: None,
1200 meta,
1201 }))
1202}
1203
1204fn root_id(value: &Value) -> Option<u64> {
1206 let id = node_id(value)?;
1207 ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.root))
1208}
1209
1210fn root_node(value: &Value) -> Value {
1212 match root_id(value) {
1213 Some(id) => handle_for(id),
1214 None => value.clone(),
1215 }
1216}
1217
1218fn with_node<R>(value: &Value, read: impl FnOnce(&ExprNode) -> R) -> Option<R> {
1219 let id = node_id(value)?;
1220 ARENA.with(|arena| arena.borrow().nodes.get(&id).map(read))
1221}
1222
1223fn with_node_mut<R>(value: &Value, write: impl FnOnce(&mut ExprNode) -> R) -> Option<R> {
1224 let id = node_id(value)?;
1225 ARENA.with(|arena| arena.borrow_mut().nodes.get_mut(&id).map(write))
1226}
1227
1228fn update_expr_node(node: &Value, op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) {
1231 adopt_all(node, &terms);
1232 with_node_mut(node, |entry| {
1233 entry.op = op;
1234 entry.token = token;
1235 entry.terms = terms;
1236 });
1237}
1238
1239fn dup_node(node: &Value) -> Value {
1242 let Some((op, token, terms)) = with_node(node, |entry| {
1243 (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1244 }) else {
1245 return node.clone();
1246 };
1247 new_node_under(op, token, terms, Some(node))
1248}
1249
1250fn term_at(node: &Value, index: usize) -> Value {
1253 with_node(node, |entry| {
1254 entry
1255 .terms
1256 .get(index.saturating_sub(1))
1257 .cloned()
1258 .unwrap_or(Value::Undefined)
1259 })
1260 .unwrap_or(Value::Undefined)
1261}
1262
1263fn set_term(node: &Value, index: usize, value: Value) {
1266 adopt(node, &value);
1267 with_node_mut(node, |entry| {
1268 let slot = index.saturating_sub(1);
1269 while entry.terms.len() <= slot {
1270 entry.terms.push(Value::Undefined);
1271 }
1272 entry.terms[slot] = value;
1273 });
1274}
1275
1276fn push_term(node: &Value, value: Value) {
1278 adopt(node, &value);
1279 with_node_mut(node, |entry| entry.terms.push(value));
1280}
1281
1282fn term_count(node: &Value) -> usize {
1284 with_node(node, |entry| entry.terms.len()).unwrap_or(0)
1285}
1286
1287fn released_handle(id: u64) -> ! {
1301 panic!(
1302 "tabnas-expr: expression node {id} has been released. The value \
1303 holding this handle outlived its parse: realize it with \
1304 `tabnas_expr::realize` inside the `parse_scope` closure, or before \
1305 the next parse on this thread, and let the realized value escape \
1306 instead."
1307 )
1308}
1309
1310fn release_arena() {
1317 ARENA.with(|arena| {
1318 let mut arena = arena.borrow_mut();
1319 if 0 == arena.active {
1320 arena.nodes.clear();
1321 EVALUATED.with(|set| set.borrow_mut().clear());
1322 OVER_LIMIT.with(|flag| flag.set(false));
1323 }
1324 });
1325}
1326
1327struct ArenaGuard;
1330
1331impl ArenaGuard {
1332 fn enter() -> Self {
1333 ARENA.with(|arena| arena.borrow_mut().active += 1);
1334 OVER_LIMIT.with(|flag| flag.set(false));
1335 ArenaGuard
1336 }
1337}
1338
1339impl Drop for ArenaGuard {
1340 fn drop(&mut self) {
1341 ARENA.with(|arena| {
1342 let mut arena = arena.borrow_mut();
1343 arena.active = arena.active.saturating_sub(1);
1344 if 0 == arena.active {
1345 arena.nodes.clear();
1346 EVALUATED.with(|set| set.borrow_mut().clear());
1347 OVER_LIMIT.with(|flag| flag.set(false));
1348 }
1349 });
1350 }
1351}
1352
1353pub fn realize(value: &Value) -> Value {
1365 let mut open: Vec<u64> = Vec::new();
1366 realize_seen(value, &mut open)
1367}
1368
1369fn realize_seen(value: &Value, open: &mut Vec<u64>) -> Value {
1370 match value {
1371 Value::ListRef(list) => {
1372 let Some(id) = node_id(value) else {
1373 let mut out = (**list).clone();
1374 out.value = out
1375 .value
1376 .iter()
1377 .map(|entry| realize_seen(entry, open))
1378 .collect();
1379 return Value::ListRef(Arc::new(out));
1380 };
1381 if open.contains(&id) {
1385 return Value::String("[CIRCLE]".into());
1386 }
1387 let Some((op, token, terms)) = with_node(value, |entry| {
1388 (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1389 }) else {
1390 released_handle(id)
1391 };
1392 open.push(id);
1393 let mut out = Vec::with_capacity(terms.len() + 1);
1394 if let Some(op) = &op {
1395 out.push(op.to_value(token.as_ref()));
1396 }
1397 for term in &terms {
1398 out.push(realize_seen(term, open));
1399 }
1400 open.pop();
1401 Value::array(out)
1402 }
1403 Value::Array(entries) => Value::array(
1404 entries
1405 .iter()
1406 .map(|entry| realize_seen(entry, open))
1407 .collect(),
1408 ),
1409 Value::Object(entries) => Value::object(
1410 entries
1411 .iter()
1412 .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
1413 .collect(),
1414 ),
1415 Value::MapRef(map) => {
1416 let mut out = (**map).clone();
1417 out.value = out
1418 .value
1419 .iter()
1420 .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
1421 .collect();
1422 Value::MapRef(Arc::new(out))
1423 }
1424 other => other.clone(),
1425 }
1426}
1427
1428pub fn simplify(value: &Value) -> Value {
1435 let mut open: Vec<u64> = Vec::new();
1436 simplify_seen(value, &mut open)
1437}
1438
1439fn simplify_seen(value: &Value, open: &mut Vec<u64>) -> Value {
1440 match value {
1441 Value::ListRef(list) => {
1442 let Some(id) = node_id(value) else {
1443 return Value::array(
1444 list.value
1445 .iter()
1446 .map(|entry| simplify_seen(entry, open))
1447 .collect(),
1448 );
1449 };
1450 if open.contains(&id) {
1451 return Value::String("[CIRCLE]".into());
1452 }
1453 let Some((op, terms)) =
1454 with_node(value, |entry| (entry.op.clone(), entry.terms.clone()))
1455 else {
1456 released_handle(id)
1457 };
1458 open.push(id);
1459 let mut out = Vec::with_capacity(terms.len() + 1);
1460 if let Some(op) = &op {
1461 out.push(Value::String(op.src.clone()));
1464 }
1465 for term in &terms {
1466 if term.is_undefined() {
1469 continue;
1470 }
1471 out.push(simplify_seen(term, open));
1472 }
1473 open.pop();
1474 Value::array(out)
1475 }
1476 Value::Array(entries) if realized_source(entries.first()).is_some() => {
1480 let mut out = Vec::with_capacity(entries.len());
1481 out.push(Value::String(
1482 realized_source(entries.first()).unwrap_or_default(),
1483 ));
1484 for entry in entries.iter().skip(1) {
1485 if entry.is_undefined() {
1486 continue;
1487 }
1488 out.push(simplify_seen(entry, open));
1489 }
1490 Value::array(out)
1491 }
1492 Value::Array(entries) => Value::array(
1493 entries
1494 .iter()
1495 .map(|entry| simplify_seen(entry, open))
1496 .collect(),
1497 ),
1498 Value::Object(entries) => Value::object(
1499 entries
1500 .iter()
1501 .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
1502 .collect(),
1503 ),
1504 Value::MapRef(map) => Value::object(
1505 map.value
1506 .iter()
1507 .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
1508 .collect(),
1509 ),
1510 Value::Text(text) => Value::String(text.string.clone()),
1511 other => other.clone(),
1512 }
1513}
1514
1515fn realized_source(value: Option<&Value>) -> Option<String> {
1518 match object_get(value?, "src") {
1519 Some(Value::String(src)) if !src.is_empty() => Some(src.clone()),
1520 _ => None,
1521 }
1522}
1523
1524#[derive(Debug, Clone)]
1532pub struct OpRef {
1533 pub op: Arc<Op>,
1534 pub token: Option<Token>,
1535}
1536
1537impl OpRef {
1538 pub fn new(op: Op) -> Self {
1541 OpRef {
1542 op: Arc::new(opify(op)),
1543 token: None,
1544 }
1545 }
1546
1547 fn at(op: &Arc<Op>, token: Option<Token>) -> Self {
1548 OpRef {
1549 op: op.clone(),
1550 token,
1551 }
1552 }
1553
1554 pub fn node(&self, terms: Vec<Value>) -> Value {
1556 new_node(Some(self.op.clone()), self.token.clone(), terms)
1557 }
1558
1559 fn node_under(&self, terms: Vec<Value>, under: &Value) -> Value {
1561 new_node_under(
1562 Some(self.op.clone()),
1563 self.token.clone(),
1564 terms,
1565 Some(under),
1566 )
1567 }
1568}
1569
1570pub fn opify(mut op: Op) -> Op {
1574 if 0 == op.terms {
1575 op.terms = if op.ternary {
1576 3
1577 } else if op.infix {
1578 2
1579 } else {
1580 1
1581 };
1582 }
1583 op
1584}
1585
1586pub fn prattify(expr: &Value, op: &OpRef) -> Value {
1595 let mut out = expr.clone();
1596 let Some(expr_op) = op_of(expr) else {
1597 return out;
1598 };
1599 let new = &op.op;
1600
1601 if new.infix {
1602 if expr_op.suffix || new.left <= expr_op.right {
1603 let prior = dup_node(expr);
1606 update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
1607 } else {
1608 let end = expr_op.terms;
1610 let last = term_at(expr, end);
1611 let drill = op_of(&last).is_some_and(|last_op| last_op.right < new.left);
1612 if drill {
1613 out = prattify(&last, op);
1614 } else {
1615 out = op.node_under(vec![last], expr);
1616 set_term(expr, end, out.clone());
1617 }
1618 }
1619 } else if new.prefix {
1620 out = op.node_under(Vec::new(), expr);
1621 set_term(expr, expr_op.terms, out.clone());
1622 } else if new.suffix {
1623 if !expr_op.suffix && expr_op.right <= new.left {
1624 let end = expr_op.terms;
1625 let last = term_at(expr, end);
1626 let drill =
1630 op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left);
1631 if drill {
1632 prattify(&last, op);
1633 } else {
1634 set_term(expr, end, op.node_under(vec![last], expr));
1635 }
1636 } else {
1637 let prior = dup_node(expr);
1638 update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
1639 }
1640 }
1641
1642 out
1643}
1644
1645fn prior_expr(rule: &mut Rule, prior: Option<&Rc<RuleSnapshot>>, op: &OpRef) -> Value {
1648 let prior_value = prior.map_or(Value::Undefined, |prior| prior.node.borrow().clone());
1649
1650 let node = if is_op(&prior_value) && !op.op.prefix {
1651 let duplicate = dup_node(&prior_value);
1655 update_expr_node(
1656 &prior_value,
1657 Some(op.op.clone()),
1658 op.token.clone(),
1659 vec![duplicate],
1660 );
1661 prior_value
1662 } else {
1663 let terms = if op.op.prefix {
1668 Vec::new()
1669 } else {
1670 vec![prior_value]
1671 };
1672 let fresh = op.node(terms);
1673 if let Some(prior) = prior {
1674 *prior.node.borrow_mut() = fresh.clone();
1679 }
1680 fresh
1681 };
1682
1683 if let Some(prior) = prior {
1685 rule.parent_rule = Some(prior.clone());
1686 rule.parent_node = Some(prior.node.clone());
1687 }
1688
1689 node
1690}
1691
1692#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1698enum EvalKey {
1699 Node(u64),
1700 Shared(usize, usize),
1701}
1702
1703thread_local! {
1704 static EVALUATED: RefCell<Vec<EvalKey>> = const { RefCell::new(Vec::new()) };
1705}
1706
1707fn eval_key(value: &Value) -> Option<EvalKey> {
1708 if let Some(id) = node_id(value) {
1709 return Some(EvalKey::Node(id));
1710 }
1711 match value {
1712 Value::Array(entries) if !entries.is_empty() => Some(EvalKey::Shared(
1713 Arc::as_ptr(entries) as usize,
1714 entries.len(),
1715 )),
1716 Value::Object(entries) if !entries.is_empty() => Some(EvalKey::Shared(
1717 Arc::as_ptr(entries) as usize,
1718 entries.len(),
1719 )),
1720 Value::ListRef(list) => Some(EvalKey::Shared(
1721 Arc::as_ptr(list) as usize,
1722 list.value.len(),
1723 )),
1724 Value::MapRef(map) => Some(EvalKey::Shared(Arc::as_ptr(map) as usize, map.value.len())),
1725 _ => None,
1726 }
1727}
1728
1729fn evaluated_seen(value: &Value) -> bool {
1730 eval_key(value).is_some_and(|key| EVALUATED.with(|set| set.borrow().contains(&key)))
1731}
1732
1733fn evaluated_mark(value: &Value) {
1734 if let Some(key) = eval_key(value) {
1735 EVALUATED.with(|set| {
1736 let mut set = set.borrow_mut();
1737 if !set.contains(&key) {
1738 set.push(key);
1739 }
1740 });
1741 }
1742}
1743
1744#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1746pub struct EvaluationOptions {
1747 pub objects: bool,
1752}
1753
1754pub fn evaluation(site: &mut EvalSite<'_>, value: &Value, evaluate: &Evaluate) -> Value {
1764 evaluation_with(site, value, evaluate, EvaluationOptions::default())
1765}
1766
1767pub fn evaluation_with(
1770 site: &mut EvalSite<'_>,
1771 value: &Value,
1772 evaluate: &Evaluate,
1773 options: EvaluationOptions,
1774) -> Value {
1775 if value.is_undefined() || matches!(value, Value::Null) {
1776 return Value::Null;
1777 }
1778 if evaluated_seen(value) {
1779 return value.clone();
1780 }
1781
1782 let out = if is_op(value) {
1783 let Some((Some(op), token, terms)) = with_node(value, |entry| {
1784 (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1785 }) else {
1786 return value.clone();
1787 };
1788 let reduced: Vec<Value> = terms
1789 .iter()
1790 .map(|term| evaluation_with(&mut site.reborrow(), term, evaluate, options))
1791 .collect();
1792 let previous = std::mem::replace(&mut site.token, token);
1797 let reduction = evaluate(site, &op, &reduced);
1798 site.token = previous;
1799 reduction
1800 } else if let Value::Array(entries) = value {
1801 Value::array(
1807 entries
1808 .iter()
1809 .map(|entry| evaluation_with(&mut site.reborrow(), entry, evaluate, options))
1810 .collect(),
1811 )
1812 } else if options.objects && matches!(value, Value::Object(_) | Value::MapRef(_)) {
1813 let mut reduce = |entries: &IndexMap<String, Value>| -> IndexMap<String, Value> {
1815 entries
1816 .iter()
1817 .map(|(name, member)| {
1818 let member = evaluation_with(&mut site.reborrow(), member, evaluate, options);
1819 (name.clone(), member)
1820 })
1821 .collect()
1822 };
1823 match value {
1824 Value::MapRef(map) => {
1825 let mut out = (**map).clone();
1826 out.value = reduce(&map.value);
1827 Value::MapRef(Arc::new(out))
1828 }
1829 Value::Object(entries) => Value::object(reduce(entries)),
1830 _ => value.clone(),
1831 }
1832 } else {
1833 value.clone()
1834 };
1835
1836 if eval_key(&out) != eval_key(value) {
1840 evaluated_mark(&out);
1841 }
1842 out
1843}
1844
1845#[derive(Clone, Copy, PartialEq, Eq)]
1851enum Anyfix {
1852 Prefix,
1853 Suffix,
1854 Infix,
1855 Ternary,
1856}
1857
1858impl Anyfix {
1859 fn name(self) -> &'static str {
1860 match self {
1861 Anyfix::Prefix => "prefix",
1862 Anyfix::Suffix => "suffix",
1863 Anyfix::Infix => "infix",
1864 Anyfix::Ternary => "ternary",
1865 }
1866 }
1867
1868 fn selects(self, def: &OpDef) -> bool {
1869 match self {
1870 Anyfix::Prefix => def.prefix,
1871 Anyfix::Suffix => def.suffix,
1872 Anyfix::Infix => def.infix,
1873 Anyfix::Ternary => def.ternary,
1874 }
1875 }
1876
1877 fn terms(self) -> usize {
1878 match self {
1879 Anyfix::Ternary => 3,
1880 Anyfix::Infix => 2,
1881 _ => 1,
1882 }
1883 }
1884}
1885
1886fn operator_tin(parser: &mut Tabnas, src: &str) -> (Tin, String) {
1895 if let Some(tin) = parser.fixed(src) {
1896 let name = parser.token_name(tin);
1897 return (tin, name);
1898 }
1899 let name = format!("#E{src}");
1900 let tin = parser.token_with_source(name.clone(), src);
1901 (tin, name)
1902}
1903
1904fn binding_power(power: Option<i64>, unset: i64) -> i64 {
1914 match power {
1915 Some(0) | None => unset,
1916 Some(power) => power,
1917 }
1918}
1919
1920fn make_op_map(
1923 parser: &mut Tabnas,
1924 ops: &IndexMap<String, Option<OpDef>>,
1925 anyfix: Anyfix,
1926) -> IndexMap<Tin, Arc<Op>> {
1927 let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
1928 for (name, def) in ops {
1929 let Some(def) = def else { continue };
1930 if !anyfix.selects(def) {
1931 continue;
1932 }
1933 let src = def.src.first().cloned().unwrap_or_default();
1934 let (tin, tkn) = operator_tin(parser, &src);
1935
1936 let suffix = format!("-{}", anyfix.name());
1937 let op = Op {
1938 src: src.clone(),
1939 left: binding_power(def.left, MIN_SAFE_INTEGER),
1940 right: binding_power(def.right, MAX_SAFE_INTEGER),
1941 name: if name.ends_with(&suffix) {
1942 name.clone()
1943 } else {
1944 format!("{name}{suffix}")
1945 },
1946 infix: Anyfix::Infix == anyfix,
1947 prefix: Anyfix::Prefix == anyfix,
1948 suffix: Anyfix::Suffix == anyfix,
1949 ternary: Anyfix::Ternary == anyfix,
1950 tkn,
1951 tin,
1952 terms: anyfix.terms(),
1953 use_data: def.use_data.clone(),
1954 separator: Anyfix::Infix == anyfix && def.separator,
1955 ..Default::default()
1956 };
1957
1958 if Anyfix::Ternary == anyfix {
1959 let second = def.src.get(1).cloned().unwrap_or_default();
1962 let (second_tin, second_tkn) = operator_tin(parser, &second);
1963
1964 let mut first = op.clone();
1965 first.ternary_index = Some(0);
1966 map.insert(tin, Arc::new(first));
1967
1968 let mut last = op;
1969 last.src = second;
1970 last.ternary_index = Some(1);
1971 last.tkn = second_tkn;
1972 last.tin = second_tin;
1973 map.insert(second_tin, Arc::new(last));
1974 } else {
1975 map.insert(tin, Arc::new(op));
1976 }
1977 }
1978 map
1979}
1980
1981fn make_paren_ops(parser: &mut Tabnas, ops: &IndexMap<String, Option<OpDef>>) -> Vec<Arc<Op>> {
1986 let mut list: Vec<Arc<Op>> = Vec::new();
1987 for (name, def) in ops {
1988 let Some(def) = def else { continue };
1989 if !def.paren {
1990 continue;
1991 }
1992 let (otin, otkn) = operator_tin(parser, &def.osrc);
1993 let (ctin, ctkn) = operator_tin(parser, &def.csrc);
1994 let op = Op {
1995 name: format!("{name}-paren"),
1996 osrc: def.osrc.clone(),
1997 csrc: def.csrc.clone(),
1998 otkn,
1999 otin,
2000 ctkn,
2001 ctin,
2002 preval: def.preval.clone().unwrap_or_default(),
2003 paren: true,
2004 src: def.osrc.clone(),
2005 terms: 1,
2006 use_data: def.use_data.clone(),
2007 left: binding_power(def.left, MIN_SAFE_INTEGER),
2012 content: def.content,
2013 ..Default::default()
2014 };
2015 list.push(Arc::new(op));
2016 }
2017 list
2018}
2019
2020fn make_cast_ops(
2023 parser: &mut Tabnas,
2024 ops: &IndexMap<String, Option<OpDef>>,
2025) -> IndexMap<Tin, Arc<Op>> {
2026 let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
2027 for (name, def) in ops {
2028 let Some(def) = def else { continue };
2029 if !def.cast {
2030 continue;
2031 }
2032 let (otin, otkn) = operator_tin(parser, &def.osrc);
2033 let (ctin, ctkn) = operator_tin(parser, &def.csrc);
2034 let op = Op {
2035 name: if name.ends_with("-cast") {
2036 name.clone()
2037 } else {
2038 format!("{name}-cast")
2039 },
2040 src: def
2041 .src
2042 .first()
2043 .cloned()
2044 .unwrap_or_else(|| format!("{}{}", def.osrc, def.csrc)),
2045 left: MIN_SAFE_INTEGER,
2046 right: binding_power(def.right, MAX_SAFE_INTEGER),
2047 use_data: def.use_data.clone(),
2048 prefix: true,
2051 terms: 2,
2052 osrc: def.osrc.clone(),
2053 csrc: def.csrc.clone(),
2054 otkn,
2055 otin,
2056 ctkn,
2057 ctin,
2058 cast: true,
2059 accept: def.accept.clone(),
2060 ..Default::default()
2061 };
2062 map.insert(otin, Arc::new(op));
2063 }
2064 map
2065}
2066
2067struct Grammar {
2070 prefix: IndexMap<Tin, Arc<Op>>,
2071 suffix: IndexMap<Tin, Arc<Op>>,
2072 infix: IndexMap<Tin, Arc<Op>>,
2073 ternary: IndexMap<Tin, Arc<Op>>,
2074 parens: Vec<Arc<Op>>,
2076 paren_plain: IndexMap<Tin, Arc<Op>>,
2078 paren_preval: IndexMap<Tin, Arc<Op>>,
2080 tin_prefix: Vec<Tin>,
2081 tin_suffix: Vec<Tin>,
2082 tin_infix: Vec<Tin>,
2083 tin_tern0: Vec<Tin>,
2084 tin_tern1: Vec<Tin>,
2085 tin_open: Vec<Tin>,
2086 tin_close: Vec<Tin>,
2087 evaluate: Option<Evaluate>,
2088 cast: IndexMap<Tin, Arc<Op>>,
2090 tin_sep: Vec<Tin>,
2093 separating: bool,
2096 has_separator: bool,
2099 has_required: bool,
2101 has_bound: bool,
2103 no_juxtapose: bool,
2105}
2106
2107const VAL_TINS: [Tin; 4] = [TIN_TX, TIN_NR, TIN_ST, TIN_VL];
2110
2111impl Grammar {
2112 fn has_prefix(&self) -> bool {
2113 !self.tin_prefix.is_empty()
2114 }
2115
2116 fn has_infix(&self) -> bool {
2117 !self.tin_infix.is_empty()
2118 }
2119
2120 fn has_suffix(&self) -> bool {
2121 !self.tin_suffix.is_empty()
2122 }
2123
2124 fn has_ternary(&self) -> bool {
2125 !self.tin_tern0.is_empty() && !self.tin_tern1.is_empty()
2126 }
2127
2128 fn has_paren(&self) -> bool {
2129 !self.tin_open.is_empty() && !self.tin_close.is_empty()
2130 }
2131
2132 fn has_cast(&self) -> bool {
2133 !self.cast.is_empty()
2134 }
2135
2136 fn postfix_opener(&self, tin: Tin) -> bool {
2139 self.paren_preval.get(&tin).is_some_and(|op| bound(op))
2140 }
2141
2142 fn starts_value(&self, tin: Tin) -> bool {
2144 VAL_TINS.contains(&tin)
2145 || TIN_OB == tin
2146 || TIN_OS == tin
2147 || self.tin_open.contains(&tin)
2148 || self.tin_prefix.contains(&tin)
2149 }
2150
2151 fn op_use(map: &IndexMap<Tin, Arc<Op>>, token: Option<&Token>) -> Option<OpRef> {
2154 let token = token?;
2155 map.get(&token.tin)
2156 .map(|op| OpRef::at(op, Some(token.clone())))
2157 }
2158}
2159
2160fn counter(rule: &Rule, name: &str) -> i32 {
2166 rule.n.get(name).copied().unwrap_or(0)
2167}
2168
2169fn local_number(rule: &Rule, name: &str) -> i64 {
2171 match rule.u.get(name) {
2172 Some(Value::Number(number)) => *number as i64,
2173 _ => 0,
2174 }
2175}
2176
2177fn set_local_number(rule: &mut Rule, name: &str, value: i64) {
2178 rule.u_mut()
2179 .insert(name.to_string(), Value::Number(value as f64));
2180}
2181
2182fn set_node(rule: &mut Rule, value: Value) {
2188 rule.node = Rc::new(RefCell::new(value));
2189}
2190
2191fn node_of(rule: &Rule) -> Value {
2192 rule.node.borrow().clone()
2193}
2194
2195const ATTACH: &str = "expr_attach";
2199
2200const INNER: &str = "expr_inner";
2204
2205fn publish_expr(rule: &mut Rule, attach: Value) {
2219 set_node(rule, attach.clone());
2220 rule.u_mut().insert(ATTACH.to_string(), attach);
2221}
2222
2223fn publish(rule: &mut Rule, value: Value) {
2225 *rule.node.borrow_mut() = value;
2226}
2227
2228fn expression_root(rule: &Rule) -> Value {
2235 root_node(&node_of(rule))
2236}
2237
2238fn linked_node(link: Option<&Rc<RuleSnapshot>>) -> Value {
2246 let Some(link) = link else {
2247 return Value::Undefined;
2248 };
2249 if let Some(attach) = link.u.get(ATTACH) {
2250 if is_op(attach) {
2251 return attach.clone();
2252 }
2253 }
2254 link.node.borrow().clone()
2255}
2256
2257fn write_linked_node(link: Option<&Rc<RuleSnapshot>>, value: Value) {
2258 if let Some(link) = link {
2259 *link.node.borrow_mut() = value;
2260 }
2261}
2262
2263fn counters(pairs: &[(&str, i32)]) -> HashMap<String, i32> {
2264 pairs
2265 .iter()
2266 .map(|(name, value)| ((*name).to_string(), *value))
2267 .collect()
2268}
2269
2270fn locals(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
2271 pairs
2272 .iter()
2273 .map(|(name, value)| ((*name).to_string(), value.clone()))
2274 .collect()
2275}
2276
2277fn on(tins: &[Tin]) -> AltSpec {
2279 AltSpec {
2280 s: vec![tins.to_vec()],
2281 ..Default::default()
2282 }
2283}
2284
2285fn on2(first: &[Tin], second: &[Tin]) -> AltSpec {
2287 AltSpec {
2288 s: vec![first.to_vec(), second.to_vec()],
2289 ..Default::default()
2290 }
2291}
2292
2293fn always() -> AltSpec {
2295 AltSpec::default()
2296}
2297
2298fn group_has(tags: &str, tag: &str) -> bool {
2299 tags.split(',').any(|entry| entry.trim() == tag)
2300}
2301
2302fn prepend_open_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
2306 for alt in alts.into_iter().rev() {
2307 spec.prepend_open(alt);
2308 }
2309}
2310
2311fn prepend_close_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
2312 for alt in alts.into_iter().rev() {
2313 spec.prepend_close(alt);
2314 }
2315}
2316
2317const CAST_NEXT: &str = "expr_cast_next";
2324
2325const POSTFIX_NEXT: &str = "expr_postfix_next";
2328
2329const POSTFIX: &str = "expr_postfix";
2332
2333const PAREN_GROUP: &str = "expr_paren_group";
2336
2337const PAREN_ITEMS: &str = "expr_items";
2340const PAREN_MORE: &str = "expr_paren_more";
2341
2342fn bound(op: &Op) -> bool {
2344 MIN_SAFE_INTEGER != op.left
2345}
2346
2347fn flag(u: &HashMap<String, Value>, name: &str) -> bool {
2348 matches!(u.get(name), Some(Value::Bool(true)))
2349}
2350
2351fn enclosing(rule: &Rule) -> Option<Arc<Op>> {
2355 let parent = rule.parent_rule.as_ref()?;
2356 if "expr" != parent.name.as_ref() {
2357 return None;
2358 }
2359 let node = linked_node(Some(parent));
2360 if is_ternary_op(&node) || is_paren_op(&node) {
2361 return None;
2362 }
2363 op_of(&node)
2364}
2365
2366fn binds_here(rule: &Rule, op: &Op) -> bool {
2372 if !bound(op) {
2373 return true;
2374 }
2375 if rule
2376 .child_rule
2377 .as_ref()
2378 .is_some_and(|child| flag(&child.u, INNER))
2379 {
2380 return false;
2381 }
2382 enclosing(rule).is_none_or(|encl| encl.right <= op.left)
2383}
2384
2385fn cast_here(grammar: &Grammar, rule: &Rule) -> bool {
2389 let Some(child) = rule.child_rule.as_ref() else {
2390 return false;
2391 };
2392 if "paren" != child.name.as_ref() || !flag(&child.u, PAREN_GROUP) {
2393 return false;
2394 }
2395 let Some(Value::String(name)) = child.u.get(PAREN_OP) else {
2396 return false;
2397 };
2398 let Some(group) = grammar.parens.iter().find(|op| &op.name == name) else {
2399 return false;
2400 };
2401 let Some(cast) = grammar.cast.get(&group.otin) else {
2402 return false;
2403 };
2404 let Some(accept) = &cast.accept else {
2405 return false;
2406 };
2407 let node = rule.child_value();
2408 cast.ctin == group.ctin && is_op(&node) && 2 == node_length(&node) && {
2409 let content = term_at(&node, 1);
2410 accept.accepts(&content)
2411 }
2412}
2413
2414fn separated_here(rule: &Rule) -> bool {
2416 0 < counter(rule, "expr_sep")
2417}
2418
2419fn separated_paren(grammar: &Grammar, rule: &Rule) -> bool {
2421 opened_paren(grammar, rule).is_some_and(|op| op.content.separated)
2422}
2423
2424fn collect_paren_item(rule: &mut Rule, term: Value) {
2431 let items = match rule.u.get(PAREN_ITEMS) {
2432 Some(items) if node_id(items).is_some() => items.clone(),
2433 _ => {
2434 let items = new_node(None, None, Vec::new());
2435 rule.u_mut().insert(PAREN_ITEMS.to_string(), items.clone());
2436 items
2437 }
2438 };
2439 with_node_mut(&items, |entry| entry.terms.push(term));
2440}
2441
2442fn paren_items(rule: &Rule) -> Vec<Value> {
2444 rule.u
2445 .get(PAREN_ITEMS)
2446 .and_then(terms_of)
2447 .unwrap_or_default()
2448}
2449
2450fn paren_term(rule: &Rule) -> Value {
2453 let node = node_of(rule);
2454 if node.is_undefined() {
2455 rule.child_node.clone()
2456 } else {
2457 node
2458 }
2459}
2460
2461fn prattify_postfix(expr: &Value, op: &OpRef) -> Value {
2467 let Some(expr_op) = op_of(expr) else {
2468 return op.node(vec![expr.clone()]);
2469 };
2470 let new = &op.op;
2471 if !expr_op.suffix && expr_op.right <= new.left {
2472 let end = expr_op.terms;
2473 let last = term_at(expr, end);
2474 if op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left) {
2475 return prattify_postfix(&last, op);
2476 }
2477 let node = op.node_under(vec![last], expr);
2478 set_term(expr, end, node.clone());
2479 return node;
2480 }
2481 let prior = dup_node(expr);
2482 update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
2483 expr.clone()
2484}
2485
2486pub fn expr(parser: &mut Tabnas, options: &ExprOptions) -> Result<(), PluginError> {
2496 let rules = parser.rule_names();
2497
2498 if rules.iter().any(|name| "expr" == name) {
2502 return Ok(());
2503 }
2504
2505 if !rules.iter().any(|name| "val" == name) {
2509 return Err(PluginError(
2510 "tabnas-expr: the instance carries no `val` rule. This plugin layers on the \
2511 jsonic base grammar; install that first (tabnas_jsonic::jsonic, or \
2512 tabnas_expr::make)."
2513 .into(),
2514 ));
2515 }
2516
2517 let ops = resolve_options(options);
2518
2519 if let Err(error) = make_key_map(&ops) {
2524 return Err(PluginError(format!(
2525 "tabnas-expr: {error} [{}]",
2526 error.code()
2527 )));
2528 }
2529
2530 let prefix = make_op_map(parser, &ops, Anyfix::Prefix);
2531 let suffix = make_op_map(parser, &ops, Anyfix::Suffix);
2532 let infix = make_op_map(parser, &ops, Anyfix::Infix);
2533 let ternary = make_op_map(parser, &ops, Anyfix::Ternary);
2534 let parens = make_paren_ops(parser, &ops);
2543 let mut paren_plain: IndexMap<Tin, Arc<Op>> = IndexMap::new();
2544 let mut paren_preval: IndexMap<Tin, Arc<Op>> = IndexMap::new();
2545 for op in &parens {
2546 if op.preval.active {
2547 paren_preval.insert(op.otin, op.clone());
2548 }
2549 let group = paren_plain.get(&op.otin);
2550 if !op.preval.active
2551 || (!op.preval.required && group.is_none_or(|group| group.preval.active))
2552 {
2553 paren_plain.insert(op.otin, op.clone());
2554 }
2555 }
2556 let cast = make_cast_ops(parser, &ops);
2557 let mut tin_sep: Vec<Tin> = vec![TIN_CA];
2561 for op in infix.values() {
2562 if "," == op.src && !tin_sep.contains(&op.tin) {
2563 tin_sep.push(op.tin);
2564 }
2565 }
2566 let has_separator = infix.values().any(|op| op.separator);
2567 let separating = has_separator || parens.iter().any(|op| op.content.separated);
2568 let has_required = parens.iter().any(|op| op.content.required);
2569 let has_bound = paren_preval.values().any(|op| bound(op));
2570 let mut tin_open: Vec<Tin> = Vec::new();
2571 let mut tin_close: Vec<Tin> = Vec::new();
2572 for op in &parens {
2573 if !tin_open.contains(&op.otin) {
2574 tin_open.push(op.otin);
2575 }
2576 if !tin_close.contains(&op.ctin) {
2577 tin_close.push(op.ctin);
2578 }
2579 }
2580
2581 let grammar = Arc::new(Grammar {
2582 tin_prefix: prefix.keys().copied().collect(),
2583 tin_suffix: suffix.keys().copied().collect(),
2584 tin_infix: infix.keys().copied().collect(),
2585 tin_tern0: ternary
2586 .values()
2587 .filter(|op| Some(0) == op.ternary_index)
2588 .map(|op| op.tin)
2589 .collect(),
2590 tin_tern1: ternary
2591 .values()
2592 .filter(|op| Some(1) == op.ternary_index)
2593 .map(|op| op.tin)
2594 .collect(),
2595 tin_open,
2596 tin_close,
2597 prefix,
2598 suffix,
2599 infix,
2600 ternary,
2601 parens,
2602 paren_plain,
2603 paren_preval,
2604 evaluate: options.evaluate.clone(),
2605 cast,
2606 tin_sep,
2607 separating,
2608 has_separator,
2609 has_required,
2610 has_bound,
2611 no_juxtapose: Some(false) == options.juxtapose,
2612 });
2613
2614 comment_before_fixed(parser, &grammar);
2615
2616 parser.parse_prepare(|_context: &mut Context| release_arena());
2621
2622 bound_expression_size(parser);
2623
2624 install_val(parser, &grammar);
2625 install_list(parser, &grammar);
2626 install_map(parser, &grammar);
2627 install_elem(parser, &grammar);
2628 install_pair(parser, &grammar);
2629 install_expr(parser, &grammar);
2630 if grammar.has_paren() {
2631 install_paren(parser, &grammar);
2632 }
2633 if grammar.has_ternary() {
2634 install_ternary(parser, &grammar);
2635 }
2636
2637 Ok(())
2638}
2639
2640fn comment_before_fixed(parser: &mut Tabnas, grammar: &Grammar) {
2666 let options = parser.config();
2667 let markers: Vec<String> = options
2668 .comment
2669 .definitions
2670 .values()
2671 .filter(|def| def.lex)
2672 .map(|def| def.start.clone())
2673 .filter(|start| !start.is_empty())
2674 .collect();
2675 if markers.is_empty() {
2676 return;
2677 }
2678
2679 let sources: Vec<String> = grammar
2680 .prefix
2681 .values()
2682 .chain(grammar.suffix.values())
2683 .chain(grammar.infix.values())
2684 .chain(grammar.ternary.values())
2685 .map(|op| op.src.clone())
2686 .chain(
2687 grammar
2688 .parens
2689 .iter()
2690 .flat_map(|op| [op.osrc.clone(), op.csrc.clone()]),
2691 )
2692 .filter(|src| !src.is_empty())
2693 .collect();
2694
2695 let contested: Vec<String> = markers
2696 .into_iter()
2697 .filter(|marker| {
2698 sources
2699 .iter()
2700 .any(|src| src.len() < marker.len() && marker.starts_with(src.as_str()))
2701 })
2702 .collect();
2703 if contested.is_empty() {
2704 return;
2705 }
2706
2707 parser.lex_check_ref(COMMENT_FIRST, move |remaining: &str| {
2708 if contested
2709 .iter()
2710 .any(|marker| remaining.starts_with(marker.as_str()))
2711 {
2712 tabnas::LexCheckResult::Skip
2713 } else {
2714 tabnas::LexCheckResult::Continue
2715 }
2716 });
2717 let _ = parser.grammar_json(COMMENT_FIRST_DOCUMENT);
2718}
2719
2720fn bound_expression_size(parser: &mut Tabnas) {
2727 let budget = parser.config().parse.budget.clone();
2728 let existing = budget.on_check.clone();
2729 let every = match budget.check_every_n {
2730 0 => 32,
2731 set => set.min(32),
2732 };
2733 parser.parse_budget(every, move |context: &Context| {
2734 if OVER_LIMIT.with(Cell::get) {
2735 return false;
2736 }
2737 if context.rule_stack.len() > RULE_LIMIT {
2738 return false;
2739 }
2740 existing.as_ref().is_none_or(|check| check(context))
2741 });
2742}
2743
2744const COMMENT_FIRST: &str = "@expr-comment-before-fixed";
2745const COMMENT_FIRST_DOCUMENT: &str =
2746 r#"{"options":{"fixed":{"check":"@expr-comment-before-fixed"}}}"#;
2747
2748fn install_val(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2753 let grammar = grammar.clone();
2754 parser.define_rule("val", move |spec| {
2755 if grammar.has_ternary() && grammar.tin_tern1.contains(&TIN_CL) {
2758 for alt in spec.open.iter_mut().filter(|alt| group_has(&alt.g, "pair")) {
2759 let previous = alt.c_fn.clone();
2760 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2761 previous
2762 .as_ref()
2763 .is_none_or(|condition| condition(rule, context))
2764 && 0 == counter(rule, "expr_ternary")
2765 }));
2766 }
2767 }
2768
2769 if grammar.no_juxtapose {
2776 for alt in spec.close.iter_mut().filter(|alt| {
2777 group_has(&alt.g, "imp")
2778 && group_has(&alt.g, "space")
2779 && group_has(&alt.g, "jsonic")
2780 }) {
2781 let previous = alt.c_fn.clone();
2782 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2783 previous
2784 .as_ref()
2785 .is_none_or(|condition| condition(rule, context))
2786 && 0 == counter(rule, "expr_paren")
2787 && rule
2788 .child_rule
2789 .as_ref()
2790 .is_none_or(|child| "expr" != child.name.as_ref())
2791 }));
2792 }
2793 }
2794
2795 let mut open: Vec<AltSpec> = Vec::new();
2796
2797 if grammar.has_prefix() {
2799 let mut alt = on(&grammar.tin_prefix);
2800 alt.b = 1;
2801 alt.n = counters(&[("expr_prefix", 1), ("expr_suffix", 0)]);
2802 alt.p = Some("expr".into());
2803 alt.g = "expr,expr-prefix".into();
2804 alt.add_action(detach_node);
2805 open.push(alt);
2806 }
2807
2808 if grammar.has_paren() {
2810 let mut alt = on2(&VAL_TINS, &grammar.tin_open);
2811 alt.b = 1;
2812 alt.p = Some("expr".into());
2813 let condition = grammar.clone();
2814 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2815 let Some(pdef) = rule
2816 .o1()
2817 .and_then(|token| condition.paren_preval.get(&token.tin))
2818 .cloned()
2819 else {
2820 return false;
2821 };
2822 if let Some(allow) = &pdef.preval.allow {
2823 let preval = rule.resolve_open_value(0, context);
2824 if !allow.contains(&value_string(Some(&preval))) {
2825 return false;
2826 }
2827 }
2828 binds_here(rule, &pdef)
2829 }));
2830 alt.u = locals(&[("paren_preval", Value::Bool(true))]);
2831 alt.g = "expr,expr-paren,expr-paren-preval".into();
2832 alt.add_action(|rule: &mut Rule, context: &mut Context| {
2833 let preval = rule.resolve_open_value(0, context);
2834 set_node(rule, preval);
2835 });
2836 open.push(alt);
2837 }
2838
2839 if grammar.has_paren() {
2842 let mut alt = on(&grammar.tin_open);
2843 alt.b = 1;
2844 alt.p = Some("expr".into());
2845 let condition = grammar.clone();
2846 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2847 rule.o0()
2848 .is_some_and(|token| condition.paren_plain.contains_key(&token.tin))
2849 }));
2850 alt.g = "expr,expr-paren".into();
2851 alt.add_action(detach_node);
2852 open.push(alt);
2853 }
2854
2855 prepend_open_all(spec, open);
2856
2857 let mut close: Vec<AltSpec> = Vec::new();
2858
2859 if grammar.separating {
2862 let mut alt = on(&grammar.tin_sep);
2863 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2864 separated_here(rule)
2865 }));
2866 alt.b = 1;
2867 alt.g = "expr,expr-sep".into();
2868 close.push(alt);
2869 }
2870
2871 if grammar.has_infix() {
2878 let mut alt = on(&grammar.tin_infix);
2879 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2880 0 < counter(rule, "no_comma_op")
2881 && rule.c0().is_some_and(|token| "," == token.src.as_str())
2882 }));
2883 alt.b = 1;
2884 alt.g = "expr,no-comma-op-bail".into();
2885 close.push(alt);
2886 }
2887
2888 if grammar.has_ternary() {
2889 let mut alt = on(&grammar.tin_tern0);
2890 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2891 0 == counter(rule, "expr")
2892 }));
2893 alt.b = 1;
2894 alt.r = Some("ternary".into());
2895 alt.g = "expr,expr-ternary".into();
2896 close.push(alt);
2897 }
2898
2899 if grammar.has_infix() {
2901 let mut alt = on(&grammar.tin_infix);
2902 alt.b = 1;
2903 alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 0)]);
2904 alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2905 (0 == counter(rule, "expr")).then(|| "expr".to_string())
2906 }));
2907 alt.g = "expr,expr-infix".into();
2908 close.push(alt);
2909 }
2910
2911 if grammar.has_suffix() {
2913 let mut alt = on(&grammar.tin_suffix);
2914 alt.b = 1;
2915 alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 1)]);
2916 alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2917 (0 == counter(rule, "expr")).then(|| "expr".to_string())
2918 }));
2919 alt.g = "expr,expr-suffix".into();
2920 close.push(alt);
2921 }
2922
2923 if grammar.has_paren() {
2925 let mut alt = on(&grammar.tin_close);
2926 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2927 0 != counter(rule, "expr_paren")
2928 }));
2929 alt.b = 1;
2930 alt.g = "expr,expr-paren".into();
2931 close.push(alt);
2932 }
2933
2934 if grammar.has_paren() {
2948 let mut alt = on(&grammar.tin_open);
2949 alt.b = 1;
2950 let condition = grammar.clone();
2951 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2952 let Some(pdef) = rule
2953 .c0()
2954 .and_then(|token| condition.paren_preval.get(&token.tin))
2955 .cloned()
2956 else {
2957 return false;
2958 };
2959 let node = node_of(rule);
2960 if node.is_undefined() {
2961 return false;
2962 }
2963 if let Some(allow) = &pdef.preval.allow {
2964 if !allow.contains(&value_string(Some(&node))) {
2965 return false;
2966 }
2967 }
2968 binds_here(rule, &pdef)
2969 }));
2970 alt.p = Some("expr".into());
2971 alt.u = locals(&[("paren_preval", Value::Bool(true))]);
2972 alt.g = "expr,expr-paren,expr-paren-preval-chain".into();
2973 close.push(alt);
2974 }
2975
2976 if grammar.has_bound {
2980 let mut alt = on(&grammar.tin_open);
2981 alt.b = 1;
2982 let condition = grammar.clone();
2983 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2984 let Some(pdef) = rule
2985 .c0()
2986 .and_then(|token| condition.paren_preval.get(&token.tin))
2987 .cloned()
2988 else {
2989 return false;
2990 };
2991 bound(&pdef) && !node_of(rule).is_undefined() && !binds_here(rule, &pdef)
2992 }));
2993 alt.g = "expr,expr-paren,expr-postfix".into();
2994 close.push(alt);
2995 }
2996
2997 if grammar.has_ternary() {
2998 let mut alt = on(&grammar.tin_tern1);
2999 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3000 0 != counter(rule, "expr_ternary")
3001 }));
3002 alt.b = 1;
3003 alt.g = "expr,expr-ternary".into();
3004 close.push(alt);
3005 }
3006
3007 let mut comma = on(&[TIN_CA]);
3010 comma.c_fn = Some(Arc::new(no_implicit_in_expr));
3011 comma.b = 1;
3012 comma.g = "expr,list,val,imp,comma,top".into();
3013 close.push(comma);
3014
3015 let mut space = on(&VAL_TINS);
3018 space.c_fn = Some(Arc::new(no_implicit_in_expr));
3019 space.b = 1;
3020 space.g = "expr,list,val,imp,space,top".into();
3021 close.push(space);
3022
3023 prepend_close_all(spec, close);
3024 });
3025}
3026
3027fn detach_node(rule: &mut Rule, _context: &mut Context) {
3037 let node = node_of(rule);
3038 set_node(rule, node);
3039}
3040
3041fn no_implicit_in_expr(rule: &mut Rule, _context: &mut Context) -> bool {
3042 (1 == rule.d && (1 <= counter(rule, "expr") || 1 <= counter(rule, "expr_ternary")))
3043 || (1 <= counter(rule, "expr_ternary") && 1 <= counter(rule, "expr_paren"))
3044}
3045
3046fn clear_expr_counters(rule: &mut Rule) {
3051 let counters = rule.n_mut();
3052 counters.insert("expr".into(), 0);
3053 counters.insert("expr_prefix".into(), 0);
3054 counters.insert("expr_suffix".into(), 0);
3055 counters.insert("expr_paren".into(), 0);
3056 counters.insert("expr_ternary".into(), 0);
3057}
3058
3059fn install_list(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3060 let grammar = grammar.clone();
3061 parser.define_rule("list", move |spec| {
3062 let flags = grammar.clone();
3063 spec.prepend_bo(move |rule: &mut Rule, _context: &mut Context| {
3064 let implicit = rule
3067 .prev_rule
3068 .as_ref()
3069 .is_some_and(|prev| matches!(prev.u.get("implist"), Some(Value::Bool(true))));
3070 if !implicit {
3071 clear_expr_counters(rule);
3072 if flags.separating {
3076 let sep = i32::from(flags.has_separator);
3077 rule.n_mut().insert("expr_sep".into(), sep);
3078 }
3079 }
3080 });
3081
3082 let mut close: Vec<AltSpec> = Vec::new();
3083
3084 if grammar.has_paren() {
3085 let mut alt = on(&grammar.tin_close);
3086 alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3089 let square = rule.c0().is_some_and(|token| TIN_CS == token.tin);
3090 if square && 0 == counter(rule, "expr_paren") {
3091 0
3092 } else {
3093 1
3094 }
3095 }));
3096 alt.g = "expr".into();
3097 close.push(alt);
3098 }
3099
3100 if grammar.separating {
3103 let mut alt = on(&grammar.tin_sep);
3104 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3105 separated_here(rule)
3106 && rule
3107 .prev_rule
3108 .as_ref()
3109 .is_some_and(|prev| flag(&prev.u, "implist"))
3110 }));
3111 alt.b = 1;
3112 alt.g = "expr,expr-sep".into();
3113 close.push(alt);
3114 }
3115
3116 prepend_close_all(spec, close);
3117
3118 if grammar.has_paren() {
3119 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3120 propagate_to_paren(rule);
3121 });
3122 }
3123 });
3124}
3125
3126fn install_map(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3127 let grammar = grammar.clone();
3128 parser.define_rule("map", move |spec| {
3129 let flags = grammar.clone();
3132 spec.prepend_bo(move |rule: &mut Rule, _context: &mut Context| {
3133 clear_expr_counters(rule);
3134 if flags.separating {
3135 let sep = i32::from(flags.has_separator);
3136 rule.n_mut().insert("expr_sep".into(), sep);
3137 }
3138 });
3139
3140 if grammar.has_paren() {
3141 let mut alt = on(&grammar.tin_close);
3142 alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3145 let brace = rule.c0().is_some_and(|token| TIN_CB == token.tin);
3146 if brace && 0 == counter(rule, "expr_paren") {
3147 0
3148 } else {
3149 1
3150 }
3151 }));
3152 alt.g = "expr".into();
3153 prepend_close_all(spec, vec![alt]);
3154 }
3155 });
3156}
3157
3158fn install_elem(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3159 let grammar = grammar.clone();
3160 parser.define_rule("elem", move |spec| {
3161 let mut close: Vec<AltSpec> = Vec::new();
3162
3163 if grammar.separating {
3166 let mut alt = on(&grammar.tin_sep);
3167 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3168 separated_here(rule)
3169 && rule
3170 .parent_rule
3171 .as_ref()
3172 .and_then(|parent| parent.prev_rule.clone())
3173 .is_some_and(|prev| flag(&prev.u, "implist"))
3174 }));
3175 alt.b = 1;
3176 alt.g = "expr,expr-sep".into();
3177 close.push(alt);
3178 }
3179
3180 if !grammar.has_paren() {
3181 prepend_close_all(spec, close);
3182 return;
3183 }
3184
3185 let mut alt = on(&grammar.tin_close);
3187 alt.b = 1;
3188 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3189 0 != counter(rule, "expr_paren")
3190 }));
3191 alt.g = "expr,expr-paren,imp,close,list".into();
3192 close.push(alt);
3193
3194 let mut alt = on(&grammar.tin_open);
3196 alt.b = 1;
3197 alt.r = Some("elem".into());
3198 alt.g = "expr,expr-paren,imp,open,list".into();
3199 close.push(alt);
3200
3201 prepend_close_all(spec, close);
3202
3203 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3209 propagate_to_paren(rule);
3210 });
3211 });
3212}
3213
3214fn propagate_to_paren(rule: &mut Rule) {
3216 if 0 == counter(rule, "expr_paren") {
3217 return;
3218 }
3219 let node = node_of(rule);
3220 let mut cursor = rule.parent_rule.clone();
3221 while let Some(current) = cursor {
3222 if "paren" == current.name.as_ref() {
3223 *current.node.borrow_mut() = node;
3224 return;
3225 }
3226 cursor = current.parent_rule.clone();
3227 }
3228}
3229
3230fn install_pair(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3231 let grammar = grammar.clone();
3232 parser.define_rule("pair", move |spec| {
3233 if !grammar.has_paren() {
3234 return;
3235 }
3236 let mut alt = on(&grammar.tin_close);
3238 alt.b = 1;
3239 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3240 0 != counter(rule, "expr_paren") || 0 < counter(rule, "pk")
3241 }));
3242 alt.g = "expr,expr-paren,imp,map".into();
3243 prepend_close_all(spec, vec![alt]);
3244 });
3245}
3246
3247fn expr_root(rule: &Rule) -> Value {
3260 let parent = linked_node(rule.parent_rule.as_ref());
3261 if rule.parent_rule.is_some() && is_op(&parent) {
3262 return parent;
3263 }
3264
3265 let mut root: Option<Value> = None;
3268 if "expr" == rule.name.as_ref() {
3269 let node = node_of(rule);
3270 if is_op(&node) {
3271 root = Some(node);
3272 }
3273 }
3274 let mut cursor = rule.prev_rule.clone();
3275 while let Some(current) = cursor {
3276 if "expr" == current.name.as_ref() {
3277 let node = current.node.borrow().clone();
3278 if is_op(&node) {
3279 root = Some(node);
3280 }
3281 }
3282 cursor = current.prev_rule.clone();
3283 }
3284
3285 root.unwrap_or_else(|| node_of(rule))
3286}
3287
3288fn top_list(rule: &mut Rule) -> Value {
3296 let list = Value::array(vec![expr_root(rule)]);
3297
3298 if rule.parent_rule.is_some() {
3299 write_linked_node(rule.parent_rule.as_ref(), list.clone());
3300 return list;
3301 }
3302
3303 set_node(rule, list.clone());
3309 let mut cursor = rule.prev_rule.clone();
3310 while let Some(current) = cursor {
3311 *current.node.borrow_mut() = list.clone();
3312 cursor = current.prev_rule.clone();
3313 }
3314
3315 list
3316}
3317
3318fn implicit_list(mut matched: AltMatch, rule: &mut Rule, context: &mut Context) -> AltMatch {
3321 let mut paren: Option<Rc<RuleSnapshot>> = None;
3326 let mut paren_index = 0usize;
3327 for index in (0..context.rule_stack.len()).rev() {
3328 let frame = &context.rule_stack[index];
3329 let name = frame.name.as_ref();
3330 if "paren" == name {
3331 paren = Some(frame.clone());
3332 paren_index = index;
3333 break;
3334 }
3335 if "map" == name || "list" == name {
3336 return matched;
3337 }
3338 }
3339
3340 let Some(paren) = paren else {
3341 return matched;
3342 };
3343
3344 let expr_node = node_of(rule);
3350 let expr_node = if is_op(&expr_node) {
3351 expression_root(rule)
3352 } else {
3353 expr_node
3354 };
3355
3356 let paren_node = paren.node.borrow().clone();
3366 if matches!(&paren_node, Value::Array(members) if !members.is_empty()) {
3367 return matched;
3371 }
3372
3373 *paren.node.borrow_mut() = Value::array(vec![expr_node.clone()]);
3374 matched.r = Some("elem".into());
3375 matched.b = 0;
3376
3377 let list = paren.node.borrow().clone();
3378 set_node(rule, list.clone());
3379
3380 write_linked_node(rule.parent_rule.as_ref(), list.clone());
3386
3387 for index in (paren_index + 1)..context.rule_stack.len() {
3403 let frame = context.rule_stack[index].clone();
3404 let name = frame.name.as_ref().to_string();
3405 let node = frame.node.borrow().clone();
3406 let carries = "expr" == name
3407 || ("val" == name
3408 && (node.is_undefined()
3409 || matches!(node, Value::Null)
3410 || same_node(&node, &expr_node)
3411 || is_op(&node)));
3412 if carries {
3413 *frame.node.borrow_mut() = list.clone();
3414 }
3415 }
3416
3417 matched
3418}
3419
3420fn same_node(left: &Value, right: &Value) -> bool {
3422 match (node_id(left), node_id(right)) {
3423 (Some(left), Some(right)) => left == right,
3424 _ => false,
3425 }
3426}
3427
3428fn install_expr(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3429 let grammar = grammar.clone();
3430 parser.define_rule("expr", move |spec| {
3431 let mut open: Vec<AltSpec> = Vec::new();
3432
3433 if grammar.has_cast() {
3438 let mut alt = always();
3439 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3440 rule.prev_rule
3441 .as_ref()
3442 .is_some_and(|prev| flag(&prev.u, CAST_NEXT))
3443 }));
3444 alt.n = counters(&[
3445 ("expr", 1),
3446 ("expr_prefix", 1),
3447 ("expr_suffix", 0),
3448 ("dlist", 1),
3449 ("dmap", 1),
3450 ]);
3451 alt.p = Some("val".into());
3452 alt.g = "expr,expr-cast".into();
3453 let ops = grammar.clone();
3454 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3455 let group = linked_node(rule.prev_rule.as_ref());
3456 let Some(cast) = op_of(&group).and_then(|gop| ops.cast.get(&gop.otin).cloned())
3457 else {
3458 return;
3459 };
3460 let token = with_node(&group, |entry| entry.token.clone()).flatten();
3461 let op = OpRef::at(&cast, token);
3462 let prior = rule.parent_rule.clone();
3463 let node = prior_expr(rule, prior.as_ref(), &op);
3464 push_term(&node, term_at(&group, 1));
3465 publish_expr(rule, node.clone());
3466 write_linked_node(rule.prev_rule.as_ref(), node);
3470 });
3471 open.push(alt);
3472 }
3473
3474 if grammar.has_bound {
3480 let mut alt = on(&grammar.tin_open);
3481 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3482 rule.prev_rule
3483 .as_ref()
3484 .is_some_and(|prev| flag(&prev.u, POSTFIX_NEXT))
3485 }));
3486 alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
3487 alt.p = Some("paren".into());
3488 alt.b = 1;
3489 alt.g = "expr,expr-paren,expr-postfix".into();
3490 let ops = grammar.clone();
3491 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3492 let Some(op) = Grammar::op_use(&ops.paren_preval, rule.o0()) else {
3493 return;
3494 };
3495 let previous = linked_node(rule.prev_rule.as_ref());
3496 let node = if is_op(&previous) {
3497 prattify_postfix(&previous, &op)
3498 } else {
3499 let prior = rule.prev_rule.clone();
3500 prior_expr(rule, prior.as_ref(), &op)
3501 };
3502 publish_expr(rule, node.clone());
3503 rule.u_mut().insert(POSTFIX.to_string(), node);
3504 });
3505 open.push(alt);
3506 }
3507
3508 if grammar.has_paren() {
3510 let mut alt = on(&grammar.tin_open);
3511 alt.p = Some("paren".into());
3512 alt.b = 1;
3513 alt.g = "expr,expr-paren,expr-start".into();
3514 open.push(alt);
3515 }
3516
3517 if grammar.has_prefix() {
3518 let mut alt = on(&grammar.tin_prefix);
3519 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3520 0 != counter(rule, "expr_prefix")
3521 }));
3522 alt.n = counters(&[("expr", 1), ("dlist", 1), ("dmap", 1)]);
3523 alt.p = Some("val".into());
3524 alt.g = "expr,expr-prefix".into();
3525 let ops = grammar.clone();
3526 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3527 let Some(op) = Grammar::op_use(&ops.prefix, rule.o0()) else {
3528 return;
3529 };
3530 let parent = linked_node(rule.parent_rule.as_ref());
3531 if is_op(&parent) && !is_ternary_op(&parent) && !is_paren_op(&parent) {
3539 let attach = prattify(&parent, &op);
3540 publish_expr(rule, attach);
3541 rule.u_mut().insert(INNER.to_string(), Value::Bool(true));
3546 } else {
3547 let prior = rule.parent_rule.clone();
3548 let node = prior_expr(rule, prior.as_ref(), &op);
3549 publish_expr(rule, node);
3550 }
3551 });
3552 open.push(alt);
3553 }
3554
3555 if grammar.has_infix() {
3556 let mut alt = on(&grammar.tin_infix);
3557 alt.p = Some("val".into());
3558 alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
3559 alt.g = "expr,expr-infix".into();
3560 let ops = grammar.clone();
3561 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3562 let Some(op) = Grammar::op_use(&ops.infix, rule.o0()) else {
3563 return;
3564 };
3565 let parent = linked_node(rule.parent_rule.as_ref());
3566 let previous = linked_node(rule.prev_rule.as_ref());
3567
3568 if is_op(&parent) && !is_ternary_op(&parent) {
3570 let attach = prattify(&parent, &op);
3571 publish_expr(rule, attach);
3572 }
3573 else if is_op(&previous) {
3575 let attach = prattify(&previous, &op);
3576 if let Some(prev) = rule.prev_rule.clone() {
3577 rule.parent_node = Some(prev.node.clone());
3578 rule.parent_rule = Some(prev);
3579 }
3580 publish_expr(rule, attach);
3581 }
3582 else {
3584 let prior = rule.prev_rule.clone();
3585 let node = prior_expr(rule, prior.as_ref(), &op);
3586 publish_expr(rule, node);
3587 }
3588 });
3589 open.push(alt);
3590 }
3591
3592 if grammar.has_suffix() {
3593 let mut alt = on(&grammar.tin_suffix);
3594 alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
3595 alt.g = "expr,expr-suffix".into();
3596 let ops = grammar.clone();
3597 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3598 let Some(op) = Grammar::op_use(&ops.suffix, rule.o0()) else {
3599 return;
3600 };
3601 let previous = linked_node(rule.prev_rule.as_ref());
3602 if is_op(&previous) {
3603 let attach = prattify(&previous, &op);
3604 if let Some(prev) = rule.prev_rule.clone() {
3611 if "val" == prev.name.as_ref() {
3612 rule.parent_node = Some(prev.node.clone());
3613 rule.parent_rule = Some(prev);
3614 }
3615 }
3616 publish_expr(rule, attach);
3617 } else {
3618 let prior = rule.prev_rule.clone();
3619 let node = prior_expr(rule, prior.as_ref(), &op);
3620 publish_expr(rule, node);
3621 }
3622 });
3623 open.push(alt);
3624 }
3625
3626 prepend_open_all(spec, open);
3627
3628 spec.add_bc(|rule: &mut Rule, _context: &mut Context| {
3630 let node = node_of(rule);
3631 let Some(op) = op_of(&node) else {
3632 return;
3633 };
3634 let child = rule.child_node.clone();
3635 if term_count(&node) < op.terms && !same_node(&node, &child) {
3636 push_term(&node, child);
3637 }
3638 });
3639
3640 let mut close: Vec<AltSpec> = Vec::new();
3641
3642 if grammar.has_cast() {
3648 let mut alt = always();
3649 let condition = grammar.clone();
3650 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3651 cast_here(&condition, rule)
3652 }));
3653 alt.n = counters(&[("expr", 1)]);
3654 alt.r = Some("expr".into());
3655 alt.u = locals(&[(CAST_NEXT, Value::Bool(true))]);
3656 alt.g = "expr,expr-cast".into();
3657 close.push(alt);
3658 }
3659
3660 let mut alt = always();
3663 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3664 rule.child_rule
3665 .as_ref()
3666 .is_some_and(|child| "paren" == child.name.as_ref())
3667 && !rule.u.contains_key(POSTFIX)
3668 }));
3669 alt.n = counters(&[("expr", 0)]);
3670 alt.g = "expr,expr-end,expr-paren-end".into();
3671 close.push(alt);
3672
3673 if grammar.has_infix() {
3679 let mut alt = on(&grammar.tin_infix);
3680 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3681 0 < counter(rule, "no_comma_op")
3682 && rule.c0().is_some_and(|token| "," == token.src.as_str())
3683 }));
3684 alt.b = 1;
3685 alt.n = counters(&[("expr", 0)]);
3686 alt.g = "expr,no-comma-op-bail".into();
3687 close.push(alt);
3688 }
3689
3690 if grammar.separating {
3693 let mut alt = on(&grammar.tin_sep);
3694 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3695 separated_here(rule)
3696 }));
3697 alt.b = 1;
3698 alt.n = counters(&[("expr", 0)]);
3699 alt.g = "expr,expr-sep".into();
3700 close.push(alt);
3701 }
3702
3703 if grammar.has_infix() {
3704 let mut alt = on(&grammar.tin_infix);
3706 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3707 0 == counter(rule, "expr_prefix")
3708 }));
3709 alt.b = 1;
3710 alt.r = Some("expr".into());
3711 alt.g = "expr,expr-infix,expr-prefix".into();
3712 close.push(alt);
3713
3714 let mut alt = on(&grammar.tin_infix);
3715 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3716 0 != counter(rule, "expr_prefix")
3717 }));
3718 alt.b = 1;
3719 alt.g = "expr,expr-infix".into();
3720 close.push(alt);
3721 }
3722
3723 if grammar.has_suffix() {
3724 let mut alt = on(&grammar.tin_suffix);
3725 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3726 0 == counter(rule, "expr_prefix")
3727 }));
3728 alt.b = 1;
3729 alt.r = Some("expr".into());
3730 alt.g = "expr,expr-suffix,expr-prefix".into();
3731 close.push(alt);
3732
3733 let mut alt = on(&grammar.tin_suffix);
3742 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3743 0 != counter(rule, "expr_prefix")
3744 }));
3745 alt.b = 1;
3746 alt.g = "expr,expr-suffix,expr-prefix".into();
3747 close.push(alt);
3748 }
3749
3750 if grammar.has_bound {
3755 let mut alt = on(&grammar.tin_open);
3756 let condition = grammar.clone();
3757 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3758 rule.c0()
3759 .is_some_and(|token| condition.postfix_opener(token.tin))
3760 && 0 == counter(rule, "expr_prefix")
3761 }));
3762 alt.b = 1;
3763 alt.r = Some("expr".into());
3764 alt.u = locals(&[(POSTFIX_NEXT, Value::Bool(true))]);
3765 alt.g = "expr,expr-paren,expr-postfix".into();
3766 close.push(alt);
3767
3768 let mut alt = on(&grammar.tin_open);
3769 let condition = grammar.clone();
3770 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3771 rule.c0()
3772 .is_some_and(|token| condition.postfix_opener(token.tin))
3773 && 0 != counter(rule, "expr_prefix")
3774 }));
3775 alt.b = 1;
3776 alt.g = "expr,expr-paren,expr-postfix,expr-prefix".into();
3777 close.push(alt);
3778 }
3779
3780 if grammar.has_paren() {
3781 let mut alt = on(&grammar.tin_close);
3782 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3783 0 != counter(rule, "expr_paren")
3784 }));
3785 alt.b = 1;
3786 alt.g = "expr".into();
3787 close.push(alt);
3788 }
3789
3790 if grammar.has_ternary() {
3791 let mut alt = on(&grammar.tin_tern0);
3792 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3793 0 == counter(rule, "expr_prefix")
3794 }));
3795 alt.b = 1;
3796 alt.r = Some("ternary".into());
3797 alt.g = "expr,expr-ternary".into();
3798 close.push(alt);
3799 }
3800
3801 let mut alt = on(&[TIN_CA]);
3803 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3804 0 == rule.d
3805 }));
3806 alt.n = counters(&[("expr", 0)]);
3807 alt.r = Some("elem".into());
3808 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3809 let list = top_list(rule);
3810 set_node(rule, list);
3811 });
3812 alt.g = "expr,comma,list,top".into();
3813 close.push(alt);
3814
3815 let mut alt = on(&VAL_TINS);
3818 let no_juxtapose = grammar.no_juxtapose;
3819 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3820 0 == rule.d && !no_juxtapose
3821 }));
3822 alt.n = counters(&[("expr", 0)]);
3823 alt.b = 1;
3824 alt.r = Some("elem".into());
3825 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3826 let list = top_list(rule);
3827 set_node(rule, list);
3828 });
3829 alt.g = "expr,space,list,top".into();
3830 close.push(alt);
3831
3832 let mut alt = on(&[TIN_CA]);
3834 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3835 rule.lte("pk", 0)
3836 }));
3837 alt.n = counters(&[("expr", 0)]);
3838 alt.b = 1;
3839 alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
3840 implicit_list(matched, rule, context)
3841 }));
3842 alt.g = "expr,list,val,imp,comma".into();
3843 close.push(alt);
3844
3845 let mut alt = always();
3856 let condition = grammar.clone();
3857 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
3858 let next = context.t0().map(|token| token.tin);
3859 rule.lte("pk", 0)
3860 && rule.lte("expr_suffix", 0)
3861 && !next.is_some_and(|tin| condition.tin_suffix.contains(&tin))
3862 && !(condition.no_juxtapose && next.is_some_and(|tin| condition.starts_value(tin)))
3863 }));
3864 alt.n = counters(&[("expr", 0)]);
3865 alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
3866 implicit_list(matched, rule, context)
3867 }));
3868 alt.g = "expr,list,val,imp,space".into();
3869 close.push(alt);
3870
3871 let mut alt = always();
3873 alt.n = counters(&[("expr", 0)]);
3874 alt.g = "expr,expr-end".into();
3875 close.push(alt);
3876
3877 prepend_close_all(spec, close);
3878
3879 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3886 if is_op(&node_of(rule)) {
3887 let root = expression_root(rule);
3888 set_node(rule, root);
3889 }
3890 });
3891
3892 if let Some(evaluate) = grammar.evaluate.clone() {
3894 spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
3895 if 0 != counter(rule, "expr") {
3896 return;
3897 }
3898 if matches!(rule.u.get(INNER), Some(Value::Bool(true))) {
3906 return;
3907 }
3908 let Some(parent) = rule.parent_rule.clone() else {
3909 return;
3910 };
3911 let parent_node = parent.node.borrow().clone();
3912
3913 if let Value::Array(members) = &parent_node {
3926 let mut site = EvalSite::new(Some(parent.clone()), context);
3927 let reduced: Vec<Value> = members
3928 .iter()
3929 .map(|member| evaluation(&mut site.reborrow(), member, &evaluate))
3930 .collect();
3931 let reduced = Value::array(reduced);
3932 *parent.node.borrow_mut() = reduced.clone();
3933 publish(rule, reduced);
3938 return;
3939 }
3940
3941 let out = {
3943 let mut site = EvalSite::new(Some(parent.clone()), context);
3944 evaluation(&mut site, &parent_node, &evaluate)
3945 };
3946 *parent.node.borrow_mut() = out.clone();
3947
3948 if rule
3951 .prev_rule
3952 .as_ref()
3953 .is_some_and(|prev| flag(&prev.u, CAST_NEXT))
3954 {
3955 write_linked_node(rule.prev_rule.as_ref(), out.clone());
3956 }
3957
3958 publish(rule, out);
3965 });
3966 }
3967 });
3968}
3969
3970fn paren_depth(name: &str) -> String {
3975 format!("expr_paren_depth_{name}")
3976}
3977
3978fn install_paren(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3979 let grammar = grammar.clone();
3980 parser.define_rule("paren", move |spec| {
3981 spec.add_bo(|rule: &mut Rule, _context: &mut Context| {
3983 let counters = rule.n_mut();
3984 counters.insert("dmap".into(), 0);
3985 counters.insert("dlist".into(), 0);
3986 counters.insert("pk".into(), 0);
3987 });
3988
3989 let mut open: Vec<AltSpec> = Vec::new();
3990
3991 if grammar.has_required {
3994 let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
3995 let condition = grammar.clone();
3996 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3997 let close = rule.o1().map(|token| token.tin);
3998 paren_op_for(&condition, rule)
3999 .is_some_and(|op| Some(op.ctin) == close && op.content.required)
4000 }));
4001 alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4002 rule.o1().cloned()
4003 }));
4004 alt.g = "expr,expr-paren,empty,required".into();
4005 open.push(alt);
4006 }
4007
4008 let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
4010 alt.b = 1;
4011 alt.g = "expr,expr-paren,empty".into();
4012 let condition = grammar.clone();
4013 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4014 let close = rule.o1().map(|token| token.tin);
4015 paren_op_for(&condition, rule).is_some_and(|op| Some(op.ctin) == close)
4016 }));
4017 let ops = grammar.clone();
4018 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4019 open_paren(&ops, rule);
4020 });
4021 open.push(alt);
4022
4023 let mut alt = on(&grammar.tin_open);
4025 alt.p = Some("val".into());
4026 alt.n = counters(&[
4027 ("expr_paren", 1),
4028 ("expr", 0),
4029 ("expr_prefix", 0),
4030 ("expr_suffix", 0),
4031 ]);
4032 alt.g = "expr,expr-paren,open".into();
4033 let ops = grammar.clone();
4034 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4035 open_paren(&ops, rule);
4036 });
4037 open.push(alt);
4038
4039 prepend_open_all(spec, open);
4040
4041 let mut close: Vec<AltSpec> = Vec::new();
4042
4043 if grammar.separating {
4048 let mut alt = on(&grammar.tin_sep);
4049 let condition = grammar.clone();
4050 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4051 separated_paren(&condition, rule) && paren_term(rule).is_undefined()
4052 }));
4053 alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4054 rule.c0().cloned()
4055 }));
4056 alt.g = "expr,expr-paren,expr-sep,empty".into();
4057 close.push(alt);
4058
4059 let mut alt = on(&grammar.tin_sep);
4060 let condition = grammar.clone();
4061 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4062 separated_paren(&condition, rule)
4063 }));
4064 alt.p = Some("val".into());
4065 alt.n = counters(&[("expr", 0), ("expr_prefix", 0), ("expr_suffix", 0)]);
4066 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4067 let term = paren_term(rule);
4068 collect_paren_item(rule, term);
4069 rule.u_mut()
4070 .insert(PAREN_MORE.to_string(), Value::Bool(true));
4071 set_node(rule, Value::Undefined);
4073 });
4074 alt.g = "expr,expr-paren,expr-sep".into();
4075 close.push(alt);
4076 }
4077
4078 let mut alt = on(&grammar.tin_close);
4079 let condition = grammar.clone();
4080 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4082 let close = rule.c0().map(|token| token.tin);
4083 opened_paren(&condition, rule).is_some_and(|op| Some(op.ctin) == close)
4084 }));
4085 let ops = grammar.clone();
4086 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4087 close_paren(&ops, rule);
4088 });
4089 alt.g = "expr,expr-paren,close".into();
4090 close.push(alt);
4091
4092 prepend_close_all(spec, close);
4093
4094 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
4095 if flag(&rule.u, PAREN_MORE) {
4098 rule.u_mut()
4099 .insert(PAREN_MORE.to_string(), Value::Bool(false));
4100 return;
4101 }
4102 if rule
4107 .parent_rule
4108 .as_ref()
4109 .is_some_and(|parent| parent.u.contains_key(POSTFIX))
4110 {
4111 return;
4112 }
4113 let node = node_of(rule);
4114 let parent = rule.parent_rule.clone();
4115 write_linked_node(parent.as_ref(), node.clone());
4116 let grandparent = parent.and_then(|parent| parent.parent_rule.clone());
4117 write_linked_node(grandparent.as_ref(), node);
4118 });
4119 });
4120}
4121
4122fn paren_op_for(grammar: &Grammar, rule: &Rule) -> Option<Arc<Op>> {
4126 let tin = rule.o0()?.tin;
4127 if paren_has_preval(rule) {
4128 grammar.paren_preval.get(&tin).cloned()
4129 } else {
4130 grammar.paren_plain.get(&tin).cloned()
4131 }
4132}
4133
4134fn paren_has_preval(rule: &Rule) -> bool {
4138 let Some(parent) = rule.parent_rule.as_ref() else {
4139 return false;
4140 };
4141 parent.u.contains_key(POSTFIX)
4142 || parent
4143 .parent_rule
4144 .as_ref()
4145 .is_some_and(|grandparent| flag(&grandparent.u, "paren_preval"))
4146}
4147
4148const PAREN_OP: &str = "expr_paren_op";
4152
4153fn opened_paren(grammar: &Grammar, rule: &Rule) -> Option<Arc<Op>> {
4155 let Some(Value::String(name)) = rule.u.get(PAREN_OP) else {
4156 return None;
4157 };
4158 grammar.parens.iter().find(|op| &op.name == name).cloned()
4159}
4160
4161fn open_paren(grammar: &Grammar, rule: &mut Rule) {
4162 let Some(op) = paren_op_for(grammar, rule) else {
4163 return;
4164 };
4165 rule.u_mut()
4166 .insert(PAREN_OP.to_string(), Value::String(op.name.clone()));
4167 let group = !paren_has_preval(rule);
4170 rule.u_mut()
4171 .insert(PAREN_GROUP.to_string(), Value::Bool(group));
4172 if grammar.separating {
4175 rule.n_mut()
4176 .insert("expr_sep".into(), i32::from(op.content.separated));
4177 }
4178 let depth = paren_depth(&op.name);
4179 rule.u_mut().insert(depth.clone(), Value::Number(1.0));
4180 rule.n_mut().insert(depth, 1);
4181 set_node(rule, Value::Undefined);
4182}
4183
4184fn close_paren(grammar: &Grammar, rule: &mut Rule) {
4185 let child = rule.child_node.clone();
4186 let mut node = node_of(rule);
4187 if node.is_undefined() {
4200 node = child;
4201 }
4202
4203 let Some(op) = opened_paren(grammar, rule) else {
4204 set_node(rule, node);
4205 return;
4206 };
4207 let op = OpRef::at(&op, rule.c0().cloned());
4208 let depth = paren_depth(&op.op.name);
4209
4210 if local_number(rule, &depth) == i64::from(counter(rule, &depth)) {
4212 let mut terms: Vec<Value> = Vec::new();
4213
4214 let grandparent = rule
4215 .parent_rule
4216 .as_ref()
4217 .filter(|parent| !parent.u.contains_key(POSTFIX))
4218 .and_then(|parent| parent.parent_rule.clone());
4219 if let Some(grandparent) = &grandparent {
4220 let preval = grandparent.node.borrow().clone();
4221 if matches!(grandparent.u.get("paren_preval"), Some(Value::Bool(true)))
4222 && !preval.is_undefined()
4223 {
4224 terms.push(preval);
4225 }
4226 }
4227
4228 let mut content: Vec<Value> = paren_items(rule);
4231 if !node.is_undefined() {
4232 content.push(node);
4233 }
4234
4235 let postfix = rule
4238 .parent_rule
4239 .as_ref()
4240 .and_then(|parent| parent.u.get(POSTFIX).cloned());
4241 if let Some(postfix) = postfix {
4242 with_node_mut(&postfix, |entry| {
4243 entry.op = Some(op.op.clone());
4244 entry.token = op.token.clone();
4245 });
4246 for term in content {
4247 push_term(&postfix, term);
4248 }
4249 set_node(rule, postfix);
4250 return;
4251 }
4252
4253 terms.extend(content);
4254 set_node(rule, op.node(terms));
4255 } else {
4256 set_node(rule, node);
4257 }
4258}
4259
4260fn install_ternary(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
4265 let grammar = grammar.clone();
4266 parser.define_rule("ternary", move |spec| {
4267 let mut open: Vec<AltSpec> = Vec::new();
4268
4269 let mut alt = on(&grammar.tin_tern0);
4270 alt.p = Some("val".into());
4271 alt.n = counters(&[
4272 ("expr_ternary", 1),
4273 ("expr", 0),
4274 ("expr_prefix", 0),
4275 ("expr_suffix", 0),
4276 ]);
4277 alt.u = locals(&[("expr_ternary_step", Value::Number(1.0))]);
4278 alt.g = "expr,expr-ternary,open".into();
4279 let ops = grammar.clone();
4280 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4281 let Some(op) = Grammar::op_use(&ops.ternary, rule.o0()) else {
4282 return;
4283 };
4284 rule.u_mut().insert(
4285 "expr_ternary_name".into(),
4286 Value::String(op.op.name.clone()),
4287 );
4288
4289 let previous = linked_node(rule.prev_rule.as_ref());
4290 let node = if is_op(&previous) {
4291 let duplicate = dup_node(&previous);
4292 update_expr_node(
4293 &previous,
4294 Some(op.op.clone()),
4295 op.token.clone(),
4296 vec![duplicate],
4297 );
4298 previous
4299 } else {
4300 let node = op.node(vec![previous]);
4301 write_linked_node(rule.prev_rule.as_ref(), node.clone());
4302 node
4303 };
4304 set_node(rule, node);
4305
4306 let paren = if 0 != counter(rule, "expr_paren") {
4307 i64::from(counter(rule, "expr_paren"))
4308 } else {
4309 rule.prev_rule
4310 .as_ref()
4311 .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"))
4312 };
4313 rule.u_mut()
4314 .insert("expr_ternary_paren".into(), Value::Number(paren as f64));
4315 rule.n_mut().insert("expr_paren".into(), 0);
4316 });
4317 open.push(alt);
4318
4319 let mut alt = always();
4320 alt.p = Some("val".into());
4321 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4322 rule.prev_rule
4323 .as_ref()
4324 .is_some_and(|prev| 2 == snapshot_number(prev, "expr_ternary_step"))
4325 }));
4326 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4327 let (step, paren) = rule.prev_rule.as_ref().map_or((0, 0), |prev| {
4328 (
4329 snapshot_number(prev, "expr_ternary_step"),
4330 snapshot_number(prev, "expr_ternary_paren"),
4331 )
4332 });
4333 set_local_number(rule, "expr_ternary_step", step);
4334 set_local_number(rule, "expr_ternary_paren", paren);
4335 rule.n_mut().insert("expr_paren".into(), paren as i32);
4336 });
4337 alt.g = "expr,expr-ternary,step".into();
4338 open.push(alt);
4339
4340 prepend_open_all(spec, open);
4341
4342 let mut close: Vec<AltSpec> = Vec::new();
4343
4344 let mut alt = on(&grammar.tin_tern1);
4345 let condition = grammar.clone();
4346 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4347 if 1 != local_number(rule, "expr_ternary_step") {
4348 return false;
4349 }
4350 let Some(op) = rule
4351 .c0()
4352 .and_then(|token| condition.ternary.get(&token.tin))
4353 .cloned()
4354 else {
4355 return false;
4356 };
4357 matches!(rule.u.get("expr_ternary_name"), Some(Value::String(name)) if name == &op.name)
4358 }));
4359 alt.r = Some("ternary".into());
4360 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4361 let step = local_number(rule, "expr_ternary_step");
4362 set_local_number(rule, "expr_ternary_step", step + 1);
4363 let node = node_of(rule);
4364 push_term(&node, rule.child_node.clone());
4365 });
4366 alt.g = "expr,expr-ternary,step".into();
4367 close.push(alt);
4368
4369 let mut tins = vec![TIN_CA];
4373 tins.extend(grammar.tin_close.iter().copied());
4374 let mut alt = on(&tins);
4375 let condition = grammar.clone();
4378 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4379 let at_sep = rule
4380 .c0()
4381 .is_some_and(|token| condition.tin_sep.contains(&token.tin));
4382 implicit_ternary_cond(rule, context) && !(separated_here(rule) && at_sep)
4383 }));
4384 let closers = grammar.tin_close.clone();
4385 alt.b_fn = Some(Arc::new(move |_rule: &mut Rule, context: &mut Context| {
4386 usize::from(next_is_close(context, &closers))
4387 }));
4388 let closers = grammar.tin_close.clone();
4389 alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4390 let to_elem = !next_is_close(context, &closers)
4391 && (0 == rule.d
4392 || (rule
4393 .prev_rule
4394 .as_ref()
4395 .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren"))
4396 && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))));
4397 to_elem.then(|| "elem".to_string())
4398 }));
4399 alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
4400 implicit_ternary_action(rule, matched);
4401 None
4402 });
4403 alt.g = "expr,expr-ternary,list,val,imp,comma".into();
4404 close.push(alt);
4405
4406 let mut alt = always();
4409 let condition = grammar.clone();
4412 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4413 let next = context.t0().map(|token| token.tin);
4414 implicit_ternary_cond(rule, context)
4415 && !(separated_here(rule)
4416 && next.is_some_and(|tin| condition.tin_sep.contains(&tin)))
4417 && !(condition.no_juxtapose && next.is_some_and(|tin| condition.starts_value(tin)))
4418 }));
4419 let closers = grammar.tin_close.clone();
4420 alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4421 let ended = context.t0().is_some_and(|token| TIN_ZZ == token.tin);
4422 let to_elem = (0 == rule.d
4423 || !next_is_close(context, &closers)
4424 || rule
4425 .prev_rule
4426 .as_ref()
4427 .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren")))
4428 && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))
4429 && !ended;
4430 to_elem.then(|| "elem".to_string())
4431 }));
4432 alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
4433 implicit_ternary_action(rule, matched);
4434 None
4435 });
4436 alt.g = "expr,expr-ternary,list,val,imp,space".into();
4437 close.push(alt);
4438
4439 let mut alt = always();
4441 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4442 0 < rule.d && 2 == local_number(rule, "expr_ternary_step")
4443 }));
4444 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4445 let node = node_of(rule);
4446 push_term(&node, rule.child_node.clone());
4447 });
4448 alt.g = "expr,expr-ternary,close".into();
4449 close.push(alt);
4450
4451 prepend_close_all(spec, close);
4452
4453 if let Some(evaluate) = grammar.evaluate.clone() {
4462 spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
4463 if rule
4464 .next_rule_name
4465 .as_ref()
4466 .is_some_and(|name| "ternary" == name.as_ref())
4467 {
4468 return;
4469 }
4470 let node = node_of(rule);
4471 if !is_op(&node) {
4472 return;
4473 }
4474 if node_length(&node) < 4 {
4477 return;
4478 }
4479 let out = {
4480 let site_rule = rule.snapshot();
4484 let mut site = EvalSite::new(Some(site_rule), context);
4485 evaluation(&mut site, &node, &evaluate)
4486 };
4487 publish(rule, out.clone());
4488 let mut cursor = rule.prev_rule.clone();
4489 while let Some(current) = cursor {
4490 *current.node.borrow_mut() = out.clone();
4491 cursor = current.prev_rule.clone();
4492 }
4493 write_linked_node(rule.parent_rule.as_ref(), out);
4494 });
4495 }
4496 });
4497}
4498
4499fn snapshot_number(snapshot: &RuleSnapshot, name: &str) -> i64 {
4500 match snapshot.u.get(name) {
4501 Some(Value::Number(number)) => *number as i64,
4502 _ => 0,
4503 }
4504}
4505
4506fn next_is_close(context: &mut Context, closers: &[Tin]) -> bool {
4507 context
4508 .t0()
4509 .is_some_and(|token| closers.contains(&token.tin))
4510}
4511
4512fn implicit_ternary_cond(rule: &mut Rule, _context: &mut Context) -> bool {
4513 (0 == rule.d || 1 <= counter(rule, "expr_paren"))
4514 && 0 == counter(rule, "pk")
4515 && 2 == local_number(rule, "expr_ternary_step")
4516}
4517
4518fn implicit_ternary_action(rule: &mut Rule, matched: &AltMatch) {
4519 let paren = rule
4520 .prev_rule
4521 .as_ref()
4522 .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"));
4523 rule.n_mut().insert("expr_paren".into(), paren as i32);
4524
4525 let node = node_of(rule);
4526 push_term(&node, rule.child_node.clone());
4527
4528 if matched.r.as_deref() != Some("elem") {
4529 return;
4530 }
4531
4532 let list = Value::array(vec![node]);
4539 publish(rule, list.clone());
4540 if 1 <= counter(rule, "expr_paren") {
4541 let mut cursor = rule.parent_rule.clone();
4542 while let Some(current) = cursor {
4543 if "paren" == current.name.as_ref() {
4544 *current.node.borrow_mut() = list;
4545 break;
4546 }
4547 cursor = current.parent_rule.clone();
4548 }
4549 }
4550}
4551
4552pub fn plugin() -> Plugin {
4576 Plugin::new(PLUGIN_NAME, |parser: &mut Tabnas, options: &Value| {
4577 expr(parser, &ExprOptions::from_value(options))
4578 })
4579 .with_defaults(defaults())
4580}
4581
4582pub fn plugin_with(options: ExprOptions) -> Plugin {
4589 Plugin::new(PLUGIN_NAME, move |parser: &mut Tabnas, _options: &Value| {
4590 expr(parser, &options)
4591 })
4592}
4593
4594pub fn apply(parser: &mut Tabnas, options: ExprOptions) -> Result<(), PluginError> {
4597 parser.use_plugin(plugin_with(options), None).map(|_| ())
4598}
4599
4600pub fn make() -> Tabnas {
4613 make_with(ExprOptions::new())
4614}
4615
4616pub fn make_with(options: ExprOptions) -> Tabnas {
4618 make_on(tabnas_jsonic::make(), options)
4619}
4620
4621fn make_on(mut parser: Tabnas, options: ExprOptions) -> Tabnas {
4628 parser
4629 .use_plugin(plugin_with(options), None)
4630 .expect("the expression grammar installs on the jsonic base");
4631 parser
4632 .set_options(|options| options.lex.window = false)
4633 .expect("lex.window sets");
4634 parser
4635}
4636
4637#[cfg(test)]
4638mod window_tests {
4639 #[test]
4643 fn a_windowed_base_comes_out_without_the_window() {
4644 let mut base = tabnas_jsonic::make();
4645 base.set_options(|options| options.lex.window = true)
4646 .expect("lex.window sets");
4647 assert!(base.options.lex.window);
4648 let parser = super::make_on(base, super::ExprOptions::new());
4649 assert!(!parser.options.lex.window);
4650 assert!(super::parse_with(&parser, "1+2*3").is_ok());
4651 }
4652}
4653
4654static DEFAULT_PARSER: OnceLock<Tabnas> = OnceLock::new();
4661
4662pub fn parse(src: &str) -> Result<Value, TabnasError> {
4673 parse_with(DEFAULT_PARSER.get_or_init(make), src)
4674}
4675
4676pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
4683 let _guard = ArenaGuard::enter();
4684 let value = parser.parse(src)?;
4685 Ok(realize(&value))
4686}
4687
4688pub fn parse_scope<R>(
4725 parser: &Tabnas,
4726 src: &str,
4727 use_value: impl FnOnce(Value) -> R,
4728) -> Result<R, TabnasError> {
4729 let _guard = ArenaGuard::enter();
4730 let value = parser.parse(src)?;
4731 Ok(use_value(value))
4732}
4733
4734pub fn parse_simplified(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
4737 let _guard = ArenaGuard::enter();
4738 let value = parser.parse(src)?;
4739 Ok(simplify(&value))
4740}
4741
4742#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4746pub struct TranslationPart {
4747 pub entry: &'static str,
4749 pub source: Option<&'static str>,
4751}
4752
4753#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4755pub struct TranslationParts {
4756 pub manifest: &'static str,
4758 pub lift: Option<TranslationPart>,
4760 pub embed: Option<TranslationPart>,
4762 pub render: Option<TranslationPart>,
4764}
4765
4766const TRANSLATION: TranslationParts = TranslationParts {
4767 manifest: include_str!("../translate/manifest.json"),
4768 lift: None,
4769 embed: Some(TranslationPart {
4770 entry: "expr-embed",
4771 source: Some(include_str!("../translate/embed.alc")),
4772 }),
4773 render: Some(TranslationPart {
4774 entry: "expr-render",
4775 source: Some(include_str!("../translate/render.alc")),
4776 }),
4777};
4778
4779#[must_use]
4781pub const fn translate() -> Option<TranslationParts> {
4782 Some(TRANSLATION)
4783}
4784
4785pub fn manifest_text() -> &'static str {
4799 TRANSLATION.manifest
4800}
4801
4802pub fn render_text() -> &'static str {
4813 match TRANSLATION.render {
4814 Some(part) => part.source.unwrap_or_default(),
4815 None => "",
4816 }
4817}