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_ST, TIN_TX, TIN_VL,
66 TIN_ZZ,
67};
68
69pub const VERSION: &str = "0.5.20";
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, PartialEq)]
128pub struct OpDef {
129 pub src: Vec<String>,
130 pub osrc: String,
131 pub csrc: String,
132 pub left: Option<i64>,
133 pub right: Option<i64>,
134 pub prefix: bool,
135 pub suffix: bool,
136 pub infix: bool,
137 pub ternary: bool,
138 pub paren: bool,
139 pub preval: Option<PrevalDef>,
140 pub use_data: Value,
142 pub key: bool,
149 pub dynamic: bool,
153}
154
155impl Default for OpDef {
156 fn default() -> Self {
157 OpDef {
158 src: Vec::new(),
159 osrc: String::new(),
160 csrc: String::new(),
161 left: None,
162 right: None,
163 prefix: false,
164 suffix: false,
165 infix: false,
166 ternary: false,
167 paren: false,
168 preval: None,
169 use_data: Value::Undefined,
170 key: false,
171 dynamic: false,
172 }
173 }
174}
175
176impl OpDef {
177 pub fn infix(src: impl Into<String>, left: i64, right: i64) -> Self {
179 OpDef {
180 src: vec![src.into()],
181 infix: true,
182 left: Some(left),
183 right: Some(right),
184 ..Default::default()
185 }
186 }
187
188 pub fn prefix(src: impl Into<String>, right: i64) -> Self {
190 OpDef {
191 src: vec![src.into()],
192 prefix: true,
193 right: Some(right),
194 ..Default::default()
195 }
196 }
197
198 pub fn suffix(src: impl Into<String>, left: i64) -> Self {
200 OpDef {
201 src: vec![src.into()],
202 suffix: true,
203 left: Some(left),
204 ..Default::default()
205 }
206 }
207
208 pub fn ternary(first: impl Into<String>, second: impl Into<String>) -> Self {
210 OpDef {
211 src: vec![first.into(), second.into()],
212 ternary: true,
213 ..Default::default()
214 }
215 }
216
217 pub fn paren(osrc: impl Into<String>, csrc: impl Into<String>) -> Self {
219 OpDef {
220 osrc: osrc.into(),
221 csrc: csrc.into(),
222 paren: true,
223 ..Default::default()
224 }
225 }
226
227 pub fn key(src: impl Into<String>) -> Self {
230 OpDef {
231 src: vec![src.into()],
232 key: true,
233 ..Default::default()
234 }
235 }
236
237 pub fn dynamic_key(src: impl Into<String>) -> Self {
240 OpDef {
241 dynamic: true,
242 ..OpDef::key(src)
243 }
244 }
245
246 pub fn with_preval(mut self, preval: PrevalDef) -> Self {
248 self.preval = Some(preval);
249 self
250 }
251
252 pub fn with_use(mut self, use_data: Value) -> Self {
254 self.use_data = use_data;
255 self
256 }
257}
258
259#[derive(Debug, Clone, PartialEq)]
262pub struct Op {
263 pub name: String,
264 pub src: String,
265 pub left: i64,
266 pub right: i64,
267 pub use_data: Value,
268 pub prefix: bool,
269 pub suffix: bool,
270 pub infix: bool,
271 pub ternary: bool,
272 pub paren: bool,
273 pub terms: usize,
274 pub tkn: String,
275 pub tin: Tin,
276 pub osrc: String,
277 pub csrc: String,
278 pub otkn: String,
279 pub otin: Tin,
280 pub ctkn: String,
281 pub ctin: Tin,
282 pub preval: PrevalDef,
283 pub ternary_index: Option<usize>,
286 pub key: bool,
289 pub dynamic: bool,
292}
293
294impl Default for Op {
295 fn default() -> Self {
296 Op {
297 name: String::new(),
298 src: String::new(),
299 left: MIN_SAFE_INTEGER,
300 right: MAX_SAFE_INTEGER,
301 use_data: Value::Undefined,
302 prefix: false,
303 suffix: false,
304 infix: false,
305 ternary: false,
306 paren: false,
307 terms: 0,
308 tkn: String::new(),
309 tin: -1,
310 osrc: String::new(),
311 csrc: String::new(),
312 otkn: String::new(),
313 otin: -1,
314 ctkn: String::new(),
315 ctin: -1,
316 preval: PrevalDef::default(),
317 ternary_index: None,
318 key: false,
319 dynamic: false,
320 }
321 }
322}
323
324impl Op {
325 fn to_value(&self, token: Option<&Token>) -> Value {
329 let mut map: IndexMap<String, Value> = IndexMap::new();
330 map.insert("src".into(), Value::String(self.src.clone()));
331 map.insert("left".into(), number(self.left));
332 map.insert("right".into(), number(self.right));
333 map.insert("name".into(), Value::String(self.name.clone()));
334 map.insert("infix".into(), Value::Bool(self.infix));
335 map.insert("prefix".into(), Value::Bool(self.prefix));
336 map.insert("suffix".into(), Value::Bool(self.suffix));
337 map.insert("ternary".into(), Value::Bool(self.ternary));
338 map.insert("tkn".into(), Value::String(self.tkn.clone()));
339 map.insert("tin".into(), Value::Number(f64::from(self.tin)));
340 map.insert("terms".into(), Value::Number(self.terms as f64));
341 map.insert("use".into(), self.use_value());
342 map.insert("paren".into(), Value::Bool(self.paren));
343 map.insert("osrc".into(), Value::String(self.osrc.clone()));
344 map.insert("csrc".into(), Value::String(self.csrc.clone()));
345 map.insert("otkn".into(), Value::String(self.otkn.clone()));
346 map.insert("ctkn".into(), Value::String(self.ctkn.clone()));
347 map.insert("otin".into(), Value::Number(f64::from(self.otin)));
348 map.insert("ctin".into(), Value::Number(f64::from(self.ctin)));
349 map.insert("preval".into(), self.preval_value());
350 map.insert("key".into(), Value::Bool(self.key));
353 map.insert("dynamic".into(), Value::Bool(self.dynamic));
354 map.insert("token".into(), token_value(token));
355 Value::object(map)
356 }
357
358 fn use_value(&self) -> Value {
359 let mut used: IndexMap<String, Value> = match &self.use_data {
360 Value::Object(entries) => (**entries).clone(),
361 _ => IndexMap::new(),
362 };
363 if let Some(index) = self.ternary_index {
364 let mut ternary: IndexMap<String, Value> = IndexMap::new();
365 ternary.insert("opI".into(), Value::Number(index as f64));
366 used.insert("ternary".into(), Value::object(ternary));
367 }
368 Value::object(used)
369 }
370
371 fn preval_value(&self) -> Value {
372 let mut preval: IndexMap<String, Value> = IndexMap::new();
373 preval.insert("active".into(), Value::Bool(self.preval.active));
374 preval.insert("required".into(), Value::Bool(self.preval.required));
375 if let Some(allow) = &self.preval.allow {
376 preval.insert(
377 "allow".into(),
378 Value::array(allow.iter().cloned().map(Value::String).collect()),
379 );
380 }
381 Value::object(preval)
382 }
383}
384
385fn number(value: i64) -> Value {
389 Value::Number(value as f64)
390}
391
392fn token_value(token: Option<&Token>) -> Value {
395 let Some(token) = token else {
396 return Value::object(IndexMap::new());
397 };
398 let mut map: IndexMap<String, Value> = IndexMap::new();
399 map.insert("isToken".into(), Value::Bool(true));
400 map.insert("name".into(), Value::String(token.name.as_str().into()));
401 map.insert("tin".into(), Value::Number(f64::from(token.tin)));
402 map.insert("src".into(), Value::String(token.src.as_str().into()));
403 map.insert("len".into(), Value::Number(token.len as f64));
404 map.insert("sI".into(), Value::Number(token.site.pos as f64));
405 map.insert("rI".into(), Value::Number(token.site.ri as f64));
406 map.insert("cI".into(), Value::Number(token.site.ci as f64));
407 Value::object(map)
408}
409
410pub struct EvalSite<'a> {
423 rule: Option<Rc<RuleSnapshot>>,
424 context: Option<&'a mut Context>,
425 token: Option<Token>,
426}
427
428impl<'a> EvalSite<'a> {
429 pub fn detached() -> Self {
431 EvalSite {
432 rule: None,
433 context: None,
434 token: None,
435 }
436 }
437
438 pub fn new(rule: Option<Rc<RuleSnapshot>>, context: &'a mut Context) -> Self {
440 EvalSite {
441 rule,
442 context: Some(context),
443 token: None,
444 }
445 }
446
447 pub fn rule(&self) -> Option<&RuleSnapshot> {
449 self.rule.as_deref()
450 }
451
452 pub fn token(&self) -> Option<&Token> {
465 self.token.as_ref()
466 }
467
468 pub fn context(&mut self) -> Option<&mut Context> {
470 self.context.as_deref_mut()
471 }
472
473 pub fn flag(&self, name: &str) -> bool {
477 self.rule
478 .as_ref()
479 .is_some_and(|rule| matches!(rule.u.get(name), Some(Value::Bool(true))))
480 }
481
482 fn reborrow(&mut self) -> EvalSite<'_> {
486 EvalSite {
487 rule: self.rule.clone(),
488 context: self.context.as_deref_mut(),
489 token: None,
490 }
491 }
492}
493
494pub type Evaluate = Arc<dyn Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync>;
498
499#[derive(Clone, Default)]
506pub struct ExprOptions {
507 pub op: IndexMap<String, Option<OpDef>>,
508 pub evaluate: Option<Evaluate>,
509}
510
511impl fmt::Debug for ExprOptions {
512 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
513 formatter
514 .debug_struct("ExprOptions")
515 .field("op", &self.op)
516 .field("evaluate", &self.evaluate.as_ref().map(|_| "<function>"))
517 .finish()
518 }
519}
520
521impl ExprOptions {
522 pub fn new() -> Self {
525 Self::default()
526 }
527
528 pub fn with_op(mut self, name: impl Into<String>, def: OpDef) -> Self {
530 self.op.insert(name.into(), Some(def));
531 self
532 }
533
534 pub fn without_op(mut self, name: impl Into<String>) -> Self {
536 self.op.insert(name.into(), None);
537 self
538 }
539
540 pub fn with_evaluate(
542 mut self,
543 evaluate: impl Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync + 'static,
544 ) -> Self {
545 self.evaluate = Some(Arc::new(evaluate));
546 self
547 }
548
549 pub fn from_value(options: &Value) -> Self {
553 let mut resolved = ExprOptions::new();
554 let Some(op) = object_get(options, "op") else {
555 return resolved;
556 };
557 let Value::Object(entries) = op else {
558 return resolved;
559 };
560 for (name, def) in entries.iter() {
561 match def {
562 Value::Object(_) => {
563 resolved
564 .op
565 .insert(name.clone(), Some(op_def_from_value(def)));
566 }
567 _ => {
569 resolved.op.insert(name.clone(), None);
570 }
571 }
572 }
573 resolved
574 }
575}
576
577fn object_get<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
578 match value {
579 Value::Object(map) => map.get(key),
580 Value::MapRef(map) => map.value.get(key),
581 _ => None,
582 }
583}
584
585fn value_bool(value: Option<&Value>) -> bool {
586 matches!(value, Some(Value::Bool(true)))
587}
588
589fn value_i64(value: Option<&Value>) -> Option<i64> {
590 match value {
591 Some(Value::Number(number)) => Some(*number as i64),
592 _ => None,
593 }
594}
595
596fn value_string(value: Option<&Value>) -> String {
597 match value {
598 Some(Value::String(text)) => text.clone(),
599 Some(Value::Text(text)) => text.string.clone(),
600 _ => String::new(),
601 }
602}
603
604fn op_def_from_value(def: &Value) -> OpDef {
605 let mut out = OpDef {
606 osrc: value_string(object_get(def, "osrc")),
607 csrc: value_string(object_get(def, "csrc")),
608 left: value_i64(object_get(def, "left")),
609 right: value_i64(object_get(def, "right")),
610 prefix: value_bool(object_get(def, "prefix")),
611 suffix: value_bool(object_get(def, "suffix")),
612 infix: value_bool(object_get(def, "infix")),
613 ternary: value_bool(object_get(def, "ternary")),
614 paren: value_bool(object_get(def, "paren")),
615 use_data: object_get(def, "use").cloned().unwrap_or(Value::Undefined),
616 key: value_bool(object_get(def, "key")),
617 dynamic: value_bool(object_get(def, "dynamic")),
618 ..Default::default()
619 };
620 match object_get(def, "src") {
621 Some(Value::String(src)) => out.src = vec![src.clone()],
622 Some(Value::Array(srcs)) => {
623 out.src = srcs
624 .iter()
625 .map(|src| value_string(Some(src)))
626 .collect::<Vec<_>>()
627 }
628 _ => {}
629 }
630 out.preval = match object_get(def, "preval") {
631 None | Some(Value::Undefined) | Some(Value::Null) => None,
632 Some(Value::Bool(active)) => Some(PrevalDef {
633 active: *active,
634 required: false,
635 allow: None,
636 }),
637 Some(preval) => Some(PrevalDef {
638 active: match object_get(preval, "active") {
640 None | Some(Value::Undefined) | Some(Value::Null) => true,
641 Some(Value::Bool(active)) => *active,
642 Some(_) => true,
643 },
644 required: value_bool(object_get(preval, "required")),
645 allow: match object_get(preval, "allow") {
646 Some(Value::Array(allow)) => Some(
647 allow
648 .iter()
649 .map(|entry| value_string(Some(entry)))
650 .collect::<Vec<_>>(),
651 ),
652 _ => None,
653 },
654 }),
655 };
656 out
657}
658
659pub fn defaults() -> Value {
683 let mut ops: IndexMap<String, Value> = IndexMap::new();
684 ops.insert("positive".into(), prefix_value("+", 4_000_000));
685 ops.insert("negative".into(), prefix_value("-", 4_000_000));
686 ops.insert("addition".into(), infix_value("+", 2_000_000, 2_100_000));
689 ops.insert("subtraction".into(), infix_value("-", 2_000_000, 2_100_000));
690 ops.insert(
691 "multiplication".into(),
692 infix_value("*", 3_000_000, 3_100_000),
693 );
694 ops.insert("division".into(), infix_value("/", 3_000_000, 3_100_000));
695 ops.insert("remainder".into(), infix_value("%", 3_000_000, 3_100_000));
696 ops.insert("plain".into(), paren_value("(", ")"));
697
698 let mut map: IndexMap<String, Value> = IndexMap::new();
699 map.insert("op".into(), Value::object(ops));
700 Value::object(map)
701}
702
703fn prefix_value(src: &str, right: i64) -> Value {
704 let mut def: IndexMap<String, Value> = IndexMap::new();
705 def.insert("prefix".into(), Value::Bool(true));
706 def.insert("right".into(), number(right));
707 def.insert("src".into(), Value::String(src.into()));
708 Value::object(def)
709}
710
711fn infix_value(src: &str, left: i64, right: i64) -> Value {
712 let mut def: IndexMap<String, Value> = IndexMap::new();
713 def.insert("infix".into(), Value::Bool(true));
714 def.insert("left".into(), number(left));
715 def.insert("right".into(), number(right));
716 def.insert("src".into(), Value::String(src.into()));
717 Value::object(def)
718}
719
720fn paren_value(osrc: &str, csrc: &str) -> Value {
721 let mut def: IndexMap<String, Value> = IndexMap::new();
722 def.insert("paren".into(), Value::Bool(true));
723 def.insert("osrc".into(), Value::String(osrc.into()));
724 def.insert("csrc".into(), Value::String(csrc.into()));
725 Value::object(def)
726}
727
728fn default_ops() -> IndexMap<String, Option<OpDef>> {
730 ExprOptions::from_value(&defaults()).op
731}
732
733fn resolve_options(options: &ExprOptions) -> IndexMap<String, Option<OpDef>> {
737 let mut resolved = default_ops();
738 for (name, def) in &options.op {
739 resolved.shift_remove(name);
740 match def {
741 Some(def) => {
742 resolved.insert(name.clone(), Some(def.clone()));
743 }
744 None => {
745 resolved.insert(name.clone(), None);
746 }
747 }
748 }
749 resolved
750}
751
752#[derive(Debug, Clone)]
781struct ExprNode {
782 op: Option<Arc<Op>>,
783 token: Option<Token>,
784 terms: Vec<Value>,
785 root: u64,
795 size: usize,
799}
800
801#[derive(Default)]
802struct Arena {
803 nodes: HashMap<u64, ExprNode>,
804 next_id: u64,
805 active: usize,
808}
809
810thread_local! {
811 static ARENA: RefCell<Arena> = RefCell::new(Arena::default());
812 static OVER_LIMIT: Cell<bool> = const { Cell::new(false) };
815}
816
817const EXPR_META: &str = "expr";
819
820pub const NODE_LIMIT: usize = 127;
833
834pub const RULE_LIMIT: usize = 1024;
845
846fn node_id(value: &Value) -> Option<u64> {
848 let Value::ListRef(list) = value else {
849 return None;
850 };
851 match list.meta.get(EXPR_META) {
852 Some(Value::Number(id)) => Some(*id as u64),
853 _ => None,
854 }
855}
856
857pub fn is_op(value: &Value) -> bool {
860 op_of(value).is_some()
861}
862
863fn node_length(value: &Value) -> usize {
867 if let Some(length) = with_node(value, |entry| {
868 entry.terms.len() + usize::from(entry.op.is_some())
869 }) {
870 return length;
871 }
872 match value {
873 Value::Array(entries) => entries.len(),
874 Value::ListRef(list) => list.value.len(),
875 _ => 0,
876 }
877}
878
879fn is_op_kind(value: &Value, kind: fn(&Op) -> bool) -> bool {
880 op_of(value).is_some_and(|op| kind(&op))
881}
882
883fn is_paren_op(value: &Value) -> bool {
884 is_op_kind(value, |op| op.paren)
885}
886
887fn is_ternary_op(value: &Value) -> bool {
888 is_op_kind(value, |op| op.ternary)
889}
890
891pub fn op_of(value: &Value) -> Option<Arc<Op>> {
893 let id = node_id(value)?;
894 ARENA.with(|arena| {
895 arena
896 .borrow()
897 .nodes
898 .get(&id)
899 .and_then(|node| node.op.clone())
900 })
901}
902
903pub fn terms_of(value: &Value) -> Option<Vec<Value>> {
905 let id = node_id(value)?;
906 ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.terms.clone()))
907}
908
909fn new_node_under(
912 op: Option<Arc<Op>>,
913 token: Option<Token>,
914 terms: Vec<Value>,
915 under: Option<&Value>,
916) -> Value {
917 let inherited = under.and_then(root_id);
918 let terms_taken = terms.clone();
919 let id = ARENA.with(|arena| {
920 let mut arena = arena.borrow_mut();
921 arena.next_id += 1;
922 let id = arena.next_id;
923 arena.nodes.insert(
924 id,
925 ExprNode {
926 op,
927 token,
928 terms,
929 root: inherited.unwrap_or(id),
930 size: 1,
931 },
932 );
933 id
934 });
935 let handle = handle_for(id);
936 if under.is_some() {
937 grow(&handle, 1);
938 }
939 adopt_all(&handle, &terms_taken);
940 handle
941}
942
943fn new_node(op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) -> Value {
944 new_node_under(op, token, terms, None)
945}
946
947fn grow(node: &Value, count: usize) {
950 let Some(root) = root_id(node) else {
951 return;
952 };
953 let over = ARENA.with(|arena| {
954 let mut arena = arena.borrow_mut();
955 match arena.nodes.get_mut(&root) {
956 Some(entry) => {
957 entry.size += count;
958 entry.size > NODE_LIMIT
959 }
960 None => false,
961 }
962 });
963 if over {
964 OVER_LIMIT.with(|flag| flag.set(true));
965 }
966}
967
968fn expression_size(node: &Value) -> usize {
970 let Some(root) = root_id(node) else {
971 return 0;
972 };
973 ARENA.with(|arena| {
974 arena
975 .borrow()
976 .nodes
977 .get(&root)
978 .map_or(0, |entry| entry.size)
979 })
980}
981
982fn adopt(container: &Value, term: &Value) {
986 let (Some(into), Some(from)) = (root_id(container), root_id(term)) else {
987 return;
988 };
989 if into == from {
990 return;
991 }
992 grow(container, expression_size(term));
993}
994
995fn adopt_all(container: &Value, terms: &[Value]) {
996 for term in terms {
997 adopt(container, term);
998 }
999}
1000
1001fn handle_for(id: u64) -> Value {
1004 let mut meta: IndexMap<String, Value> = IndexMap::new();
1005 meta.insert(EXPR_META.into(), Value::Number(id as f64));
1006 Value::ListRef(Arc::new(ListRef {
1007 value: Vec::new(),
1008 implicit: false,
1009 child: None,
1010 meta,
1011 }))
1012}
1013
1014fn root_id(value: &Value) -> Option<u64> {
1016 let id = node_id(value)?;
1017 ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.root))
1018}
1019
1020fn root_node(value: &Value) -> Value {
1022 match root_id(value) {
1023 Some(id) => handle_for(id),
1024 None => value.clone(),
1025 }
1026}
1027
1028fn with_node<R>(value: &Value, read: impl FnOnce(&ExprNode) -> R) -> Option<R> {
1029 let id = node_id(value)?;
1030 ARENA.with(|arena| arena.borrow().nodes.get(&id).map(read))
1031}
1032
1033fn with_node_mut<R>(value: &Value, write: impl FnOnce(&mut ExprNode) -> R) -> Option<R> {
1034 let id = node_id(value)?;
1035 ARENA.with(|arena| arena.borrow_mut().nodes.get_mut(&id).map(write))
1036}
1037
1038fn update_expr_node(node: &Value, op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) {
1041 adopt_all(node, &terms);
1042 with_node_mut(node, |entry| {
1043 entry.op = op;
1044 entry.token = token;
1045 entry.terms = terms;
1046 });
1047}
1048
1049fn dup_node(node: &Value) -> Value {
1052 let Some((op, token, terms)) = with_node(node, |entry| {
1053 (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1054 }) else {
1055 return node.clone();
1056 };
1057 new_node_under(op, token, terms, Some(node))
1058}
1059
1060fn term_at(node: &Value, index: usize) -> Value {
1063 with_node(node, |entry| {
1064 entry
1065 .terms
1066 .get(index.saturating_sub(1))
1067 .cloned()
1068 .unwrap_or(Value::Undefined)
1069 })
1070 .unwrap_or(Value::Undefined)
1071}
1072
1073fn set_term(node: &Value, index: usize, value: Value) {
1076 adopt(node, &value);
1077 with_node_mut(node, |entry| {
1078 let slot = index.saturating_sub(1);
1079 while entry.terms.len() <= slot {
1080 entry.terms.push(Value::Undefined);
1081 }
1082 entry.terms[slot] = value;
1083 });
1084}
1085
1086fn push_term(node: &Value, value: Value) {
1088 adopt(node, &value);
1089 with_node_mut(node, |entry| entry.terms.push(value));
1090}
1091
1092fn term_count(node: &Value) -> usize {
1094 with_node(node, |entry| entry.terms.len()).unwrap_or(0)
1095}
1096
1097fn released_handle(id: u64) -> ! {
1111 panic!(
1112 "tabnas-expr: expression node {id} has been released. The value \
1113 holding this handle outlived its parse: realize it with \
1114 `tabnas_expr::realize` inside the `parse_scope` closure, or before \
1115 the next parse on this thread, and let the realized value escape \
1116 instead."
1117 )
1118}
1119
1120fn release_arena() {
1127 ARENA.with(|arena| {
1128 let mut arena = arena.borrow_mut();
1129 if 0 == arena.active {
1130 arena.nodes.clear();
1131 EVALUATED.with(|set| set.borrow_mut().clear());
1132 OVER_LIMIT.with(|flag| flag.set(false));
1133 }
1134 });
1135}
1136
1137struct ArenaGuard;
1140
1141impl ArenaGuard {
1142 fn enter() -> Self {
1143 ARENA.with(|arena| arena.borrow_mut().active += 1);
1144 OVER_LIMIT.with(|flag| flag.set(false));
1145 ArenaGuard
1146 }
1147}
1148
1149impl Drop for ArenaGuard {
1150 fn drop(&mut self) {
1151 ARENA.with(|arena| {
1152 let mut arena = arena.borrow_mut();
1153 arena.active = arena.active.saturating_sub(1);
1154 if 0 == arena.active {
1155 arena.nodes.clear();
1156 EVALUATED.with(|set| set.borrow_mut().clear());
1157 OVER_LIMIT.with(|flag| flag.set(false));
1158 }
1159 });
1160 }
1161}
1162
1163pub fn realize(value: &Value) -> Value {
1175 let mut open: Vec<u64> = Vec::new();
1176 realize_seen(value, &mut open)
1177}
1178
1179fn realize_seen(value: &Value, open: &mut Vec<u64>) -> Value {
1180 match value {
1181 Value::ListRef(list) => {
1182 let Some(id) = node_id(value) else {
1183 let mut out = (**list).clone();
1184 out.value = out
1185 .value
1186 .iter()
1187 .map(|entry| realize_seen(entry, open))
1188 .collect();
1189 return Value::ListRef(Arc::new(out));
1190 };
1191 if open.contains(&id) {
1195 return Value::String("[CIRCLE]".into());
1196 }
1197 let Some((op, token, terms)) = with_node(value, |entry| {
1198 (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1199 }) else {
1200 released_handle(id)
1201 };
1202 open.push(id);
1203 let mut out = Vec::with_capacity(terms.len() + 1);
1204 if let Some(op) = &op {
1205 out.push(op.to_value(token.as_ref()));
1206 }
1207 for term in &terms {
1208 out.push(realize_seen(term, open));
1209 }
1210 open.pop();
1211 Value::array(out)
1212 }
1213 Value::Array(entries) => Value::array(
1214 entries
1215 .iter()
1216 .map(|entry| realize_seen(entry, open))
1217 .collect(),
1218 ),
1219 Value::Object(entries) => Value::object(
1220 entries
1221 .iter()
1222 .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
1223 .collect(),
1224 ),
1225 Value::MapRef(map) => {
1226 let mut out = (**map).clone();
1227 out.value = out
1228 .value
1229 .iter()
1230 .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
1231 .collect();
1232 Value::MapRef(Arc::new(out))
1233 }
1234 other => other.clone(),
1235 }
1236}
1237
1238pub fn simplify(value: &Value) -> Value {
1245 let mut open: Vec<u64> = Vec::new();
1246 simplify_seen(value, &mut open)
1247}
1248
1249fn simplify_seen(value: &Value, open: &mut Vec<u64>) -> Value {
1250 match value {
1251 Value::ListRef(list) => {
1252 let Some(id) = node_id(value) else {
1253 return Value::array(
1254 list.value
1255 .iter()
1256 .map(|entry| simplify_seen(entry, open))
1257 .collect(),
1258 );
1259 };
1260 if open.contains(&id) {
1261 return Value::String("[CIRCLE]".into());
1262 }
1263 let Some((op, terms)) =
1264 with_node(value, |entry| (entry.op.clone(), entry.terms.clone()))
1265 else {
1266 released_handle(id)
1267 };
1268 open.push(id);
1269 let mut out = Vec::with_capacity(terms.len() + 1);
1270 if let Some(op) = &op {
1271 out.push(Value::String(op.src.clone()));
1274 }
1275 for term in &terms {
1276 if term.is_undefined() {
1279 continue;
1280 }
1281 out.push(simplify_seen(term, open));
1282 }
1283 open.pop();
1284 Value::array(out)
1285 }
1286 Value::Array(entries) if realized_source(entries.first()).is_some() => {
1290 let mut out = Vec::with_capacity(entries.len());
1291 out.push(Value::String(
1292 realized_source(entries.first()).unwrap_or_default(),
1293 ));
1294 for entry in entries.iter().skip(1) {
1295 if entry.is_undefined() {
1296 continue;
1297 }
1298 out.push(simplify_seen(entry, open));
1299 }
1300 Value::array(out)
1301 }
1302 Value::Array(entries) => Value::array(
1303 entries
1304 .iter()
1305 .map(|entry| simplify_seen(entry, open))
1306 .collect(),
1307 ),
1308 Value::Object(entries) => Value::object(
1309 entries
1310 .iter()
1311 .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
1312 .collect(),
1313 ),
1314 Value::MapRef(map) => Value::object(
1315 map.value
1316 .iter()
1317 .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
1318 .collect(),
1319 ),
1320 Value::Text(text) => Value::String(text.string.clone()),
1321 other => other.clone(),
1322 }
1323}
1324
1325fn realized_source(value: Option<&Value>) -> Option<String> {
1328 match object_get(value?, "src") {
1329 Some(Value::String(src)) if !src.is_empty() => Some(src.clone()),
1330 _ => None,
1331 }
1332}
1333
1334#[derive(Debug, Clone)]
1342pub struct OpRef {
1343 pub op: Arc<Op>,
1344 pub token: Option<Token>,
1345}
1346
1347impl OpRef {
1348 pub fn new(op: Op) -> Self {
1351 OpRef {
1352 op: Arc::new(opify(op)),
1353 token: None,
1354 }
1355 }
1356
1357 fn at(op: &Arc<Op>, token: Option<Token>) -> Self {
1358 OpRef {
1359 op: op.clone(),
1360 token,
1361 }
1362 }
1363
1364 pub fn node(&self, terms: Vec<Value>) -> Value {
1366 new_node(Some(self.op.clone()), self.token.clone(), terms)
1367 }
1368
1369 fn node_under(&self, terms: Vec<Value>, under: &Value) -> Value {
1371 new_node_under(
1372 Some(self.op.clone()),
1373 self.token.clone(),
1374 terms,
1375 Some(under),
1376 )
1377 }
1378}
1379
1380pub fn opify(mut op: Op) -> Op {
1384 if 0 == op.terms {
1385 op.terms = if op.ternary {
1386 3
1387 } else if op.infix {
1388 2
1389 } else {
1390 1
1391 };
1392 }
1393 op
1394}
1395
1396pub fn prattify(expr: &Value, op: &OpRef) -> Value {
1405 let mut out = expr.clone();
1406 let Some(expr_op) = op_of(expr) else {
1407 return out;
1408 };
1409 let new = &op.op;
1410
1411 if new.infix {
1412 if expr_op.suffix || new.left <= expr_op.right {
1413 let prior = dup_node(expr);
1416 update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
1417 } else {
1418 let end = expr_op.terms;
1420 let last = term_at(expr, end);
1421 let drill = op_of(&last).is_some_and(|last_op| last_op.right < new.left);
1422 if drill {
1423 out = prattify(&last, op);
1424 } else {
1425 out = op.node_under(vec![last], expr);
1426 set_term(expr, end, out.clone());
1427 }
1428 }
1429 } else if new.prefix {
1430 out = op.node_under(Vec::new(), expr);
1431 set_term(expr, expr_op.terms, out.clone());
1432 } else if new.suffix {
1433 if !expr_op.suffix && expr_op.right <= new.left {
1434 let end = expr_op.terms;
1435 let last = term_at(expr, end);
1436 let drill =
1440 op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left);
1441 if drill {
1442 prattify(&last, op);
1443 } else {
1444 set_term(expr, end, op.node_under(vec![last], expr));
1445 }
1446 } else {
1447 let prior = dup_node(expr);
1448 update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
1449 }
1450 }
1451
1452 out
1453}
1454
1455fn prior_expr(rule: &mut Rule, prior: Option<&Rc<RuleSnapshot>>, op: &OpRef) -> Value {
1458 let prior_value = prior.map_or(Value::Undefined, |prior| prior.node.borrow().clone());
1459
1460 let node = if is_op(&prior_value) && !op.op.prefix {
1461 let duplicate = dup_node(&prior_value);
1465 update_expr_node(
1466 &prior_value,
1467 Some(op.op.clone()),
1468 op.token.clone(),
1469 vec![duplicate],
1470 );
1471 prior_value
1472 } else {
1473 let terms = if op.op.prefix {
1478 Vec::new()
1479 } else {
1480 vec![prior_value]
1481 };
1482 let fresh = op.node(terms);
1483 if let Some(prior) = prior {
1484 *prior.node.borrow_mut() = fresh.clone();
1489 }
1490 fresh
1491 };
1492
1493 if let Some(prior) = prior {
1495 rule.parent_rule = Some(prior.clone());
1496 rule.parent_node = Some(prior.node.clone());
1497 }
1498
1499 node
1500}
1501
1502#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1508enum EvalKey {
1509 Node(u64),
1510 Shared(usize, usize),
1511}
1512
1513thread_local! {
1514 static EVALUATED: RefCell<Vec<EvalKey>> = const { RefCell::new(Vec::new()) };
1515}
1516
1517fn eval_key(value: &Value) -> Option<EvalKey> {
1518 if let Some(id) = node_id(value) {
1519 return Some(EvalKey::Node(id));
1520 }
1521 match value {
1522 Value::Array(entries) if !entries.is_empty() => Some(EvalKey::Shared(
1523 Arc::as_ptr(entries) as usize,
1524 entries.len(),
1525 )),
1526 Value::Object(entries) if !entries.is_empty() => Some(EvalKey::Shared(
1527 Arc::as_ptr(entries) as usize,
1528 entries.len(),
1529 )),
1530 Value::ListRef(list) => Some(EvalKey::Shared(
1531 Arc::as_ptr(list) as usize,
1532 list.value.len(),
1533 )),
1534 Value::MapRef(map) => Some(EvalKey::Shared(Arc::as_ptr(map) as usize, map.value.len())),
1535 _ => None,
1536 }
1537}
1538
1539fn evaluated_seen(value: &Value) -> bool {
1540 eval_key(value).is_some_and(|key| EVALUATED.with(|set| set.borrow().contains(&key)))
1541}
1542
1543fn evaluated_mark(value: &Value) {
1544 if let Some(key) = eval_key(value) {
1545 EVALUATED.with(|set| {
1546 let mut set = set.borrow_mut();
1547 if !set.contains(&key) {
1548 set.push(key);
1549 }
1550 });
1551 }
1552}
1553
1554#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1556pub struct EvaluationOptions {
1557 pub objects: bool,
1562}
1563
1564pub fn evaluation(site: &mut EvalSite<'_>, value: &Value, evaluate: &Evaluate) -> Value {
1574 evaluation_with(site, value, evaluate, EvaluationOptions::default())
1575}
1576
1577pub fn evaluation_with(
1580 site: &mut EvalSite<'_>,
1581 value: &Value,
1582 evaluate: &Evaluate,
1583 options: EvaluationOptions,
1584) -> Value {
1585 if value.is_undefined() || matches!(value, Value::Null) {
1586 return Value::Null;
1587 }
1588 if evaluated_seen(value) {
1589 return value.clone();
1590 }
1591
1592 let out = if is_op(value) {
1593 let Some((Some(op), token, terms)) = with_node(value, |entry| {
1594 (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1595 }) else {
1596 return value.clone();
1597 };
1598 let reduced: Vec<Value> = terms
1599 .iter()
1600 .map(|term| evaluation_with(&mut site.reborrow(), term, evaluate, options))
1601 .collect();
1602 let previous = std::mem::replace(&mut site.token, token);
1607 let reduction = evaluate(site, &op, &reduced);
1608 site.token = previous;
1609 reduction
1610 } else if let Value::Array(entries) = value {
1611 Value::array(
1617 entries
1618 .iter()
1619 .map(|entry| evaluation_with(&mut site.reborrow(), entry, evaluate, options))
1620 .collect(),
1621 )
1622 } else if options.objects && matches!(value, Value::Object(_) | Value::MapRef(_)) {
1623 let mut reduce = |entries: &IndexMap<String, Value>| -> IndexMap<String, Value> {
1625 entries
1626 .iter()
1627 .map(|(name, member)| {
1628 let member = evaluation_with(&mut site.reborrow(), member, evaluate, options);
1629 (name.clone(), member)
1630 })
1631 .collect()
1632 };
1633 match value {
1634 Value::MapRef(map) => {
1635 let mut out = (**map).clone();
1636 out.value = reduce(&map.value);
1637 Value::MapRef(Arc::new(out))
1638 }
1639 Value::Object(entries) => Value::object(reduce(entries)),
1640 _ => value.clone(),
1641 }
1642 } else {
1643 value.clone()
1644 };
1645
1646 if eval_key(&out) != eval_key(value) {
1650 evaluated_mark(&out);
1651 }
1652 out
1653}
1654
1655#[derive(Clone, Copy, PartialEq, Eq)]
1661enum Anyfix {
1662 Prefix,
1663 Suffix,
1664 Infix,
1665 Ternary,
1666}
1667
1668impl Anyfix {
1669 fn name(self) -> &'static str {
1670 match self {
1671 Anyfix::Prefix => "prefix",
1672 Anyfix::Suffix => "suffix",
1673 Anyfix::Infix => "infix",
1674 Anyfix::Ternary => "ternary",
1675 }
1676 }
1677
1678 fn selects(self, def: &OpDef) -> bool {
1679 match self {
1680 Anyfix::Prefix => def.prefix,
1681 Anyfix::Suffix => def.suffix,
1682 Anyfix::Infix => def.infix,
1683 Anyfix::Ternary => def.ternary,
1684 }
1685 }
1686
1687 fn terms(self) -> usize {
1688 match self {
1689 Anyfix::Ternary => 3,
1690 Anyfix::Infix => 2,
1691 _ => 1,
1692 }
1693 }
1694}
1695
1696fn operator_tin(parser: &mut Tabnas, src: &str) -> (Tin, String) {
1705 if let Some(tin) = parser.fixed(src) {
1706 let name = parser.token_name(tin);
1707 return (tin, name);
1708 }
1709 let name = format!("#E{src}");
1710 let tin = parser.token_with_source(name.clone(), src);
1711 (tin, name)
1712}
1713
1714fn binding_power(power: Option<i64>, unset: i64) -> i64 {
1724 match power {
1725 Some(0) | None => unset,
1726 Some(power) => power,
1727 }
1728}
1729
1730fn make_op_map(
1733 parser: &mut Tabnas,
1734 ops: &IndexMap<String, Option<OpDef>>,
1735 anyfix: Anyfix,
1736) -> IndexMap<Tin, Arc<Op>> {
1737 let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
1738 for (name, def) in ops {
1739 let Some(def) = def else { continue };
1740 if !anyfix.selects(def) {
1741 continue;
1742 }
1743 let src = def.src.first().cloned().unwrap_or_default();
1744 let (tin, tkn) = operator_tin(parser, &src);
1745
1746 let suffix = format!("-{}", anyfix.name());
1747 let op = Op {
1748 src: src.clone(),
1749 left: binding_power(def.left, MIN_SAFE_INTEGER),
1750 right: binding_power(def.right, MAX_SAFE_INTEGER),
1751 name: if name.ends_with(&suffix) {
1752 name.clone()
1753 } else {
1754 format!("{name}{suffix}")
1755 },
1756 infix: Anyfix::Infix == anyfix,
1757 prefix: Anyfix::Prefix == anyfix,
1758 suffix: Anyfix::Suffix == anyfix,
1759 ternary: Anyfix::Ternary == anyfix,
1760 tkn,
1761 tin,
1762 terms: anyfix.terms(),
1763 use_data: def.use_data.clone(),
1764 ..Default::default()
1765 };
1766
1767 if Anyfix::Ternary == anyfix {
1768 let second = def.src.get(1).cloned().unwrap_or_default();
1771 let (second_tin, second_tkn) = operator_tin(parser, &second);
1772
1773 let mut first = op.clone();
1774 first.ternary_index = Some(0);
1775 map.insert(tin, Arc::new(first));
1776
1777 let mut last = op;
1778 last.src = second;
1779 last.ternary_index = Some(1);
1780 last.tkn = second_tkn;
1781 last.tin = second_tin;
1782 map.insert(second_tin, Arc::new(last));
1783 } else {
1784 map.insert(tin, Arc::new(op));
1785 }
1786 }
1787 map
1788}
1789
1790fn make_paren_map(
1793 parser: &mut Tabnas,
1794 ops: &IndexMap<String, Option<OpDef>>,
1795) -> IndexMap<Tin, Arc<Op>> {
1796 let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
1797 for (name, def) in ops {
1798 let Some(def) = def else { continue };
1799 if !def.paren {
1800 continue;
1801 }
1802 let (otin, otkn) = operator_tin(parser, &def.osrc);
1803 let (ctin, ctkn) = operator_tin(parser, &def.csrc);
1804 let op = Op {
1805 name: format!("{name}-paren"),
1806 osrc: def.osrc.clone(),
1807 csrc: def.csrc.clone(),
1808 otkn,
1809 otin,
1810 ctkn,
1811 ctin,
1812 preval: def.preval.clone().unwrap_or_default(),
1813 paren: true,
1814 src: def.osrc.clone(),
1815 terms: 1,
1816 use_data: def.use_data.clone(),
1817 ..Default::default()
1818 };
1819 map.insert(otin, Arc::new(op));
1820 }
1821 map
1822}
1823
1824struct Grammar {
1827 prefix: IndexMap<Tin, Arc<Op>>,
1828 suffix: IndexMap<Tin, Arc<Op>>,
1829 infix: IndexMap<Tin, Arc<Op>>,
1830 ternary: IndexMap<Tin, Arc<Op>>,
1831 paren_open: IndexMap<Tin, Arc<Op>>,
1832 paren_close: IndexMap<Tin, Arc<Op>>,
1833 tin_prefix: Vec<Tin>,
1834 tin_suffix: Vec<Tin>,
1835 tin_infix: Vec<Tin>,
1836 tin_tern0: Vec<Tin>,
1837 tin_tern1: Vec<Tin>,
1838 tin_open: Vec<Tin>,
1839 tin_close: Vec<Tin>,
1840 evaluate: Option<Evaluate>,
1841}
1842
1843const VAL_TINS: [Tin; 4] = [TIN_TX, TIN_NR, TIN_ST, TIN_VL];
1846
1847impl Grammar {
1848 fn has_prefix(&self) -> bool {
1849 !self.tin_prefix.is_empty()
1850 }
1851
1852 fn has_infix(&self) -> bool {
1853 !self.tin_infix.is_empty()
1854 }
1855
1856 fn has_suffix(&self) -> bool {
1857 !self.tin_suffix.is_empty()
1858 }
1859
1860 fn has_ternary(&self) -> bool {
1861 !self.tin_tern0.is_empty() && !self.tin_tern1.is_empty()
1862 }
1863
1864 fn has_paren(&self) -> bool {
1865 !self.tin_open.is_empty() && !self.tin_close.is_empty()
1866 }
1867
1868 fn op_use(map: &IndexMap<Tin, Arc<Op>>, token: Option<&Token>) -> Option<OpRef> {
1871 let token = token?;
1872 map.get(&token.tin)
1873 .map(|op| OpRef::at(op, Some(token.clone())))
1874 }
1875}
1876
1877fn counter(rule: &Rule, name: &str) -> i32 {
1883 rule.n.get(name).copied().unwrap_or(0)
1884}
1885
1886fn local_number(rule: &Rule, name: &str) -> i64 {
1888 match rule.u.get(name) {
1889 Some(Value::Number(number)) => *number as i64,
1890 _ => 0,
1891 }
1892}
1893
1894fn set_local_number(rule: &mut Rule, name: &str, value: i64) {
1895 rule.u_mut()
1896 .insert(name.to_string(), Value::Number(value as f64));
1897}
1898
1899fn set_node(rule: &mut Rule, value: Value) {
1905 rule.node = Rc::new(RefCell::new(value));
1906}
1907
1908fn node_of(rule: &Rule) -> Value {
1909 rule.node.borrow().clone()
1910}
1911
1912const ATTACH: &str = "expr_attach";
1916
1917fn publish_expr(rule: &mut Rule, attach: Value) {
1931 set_node(rule, attach.clone());
1932 rule.u_mut().insert(ATTACH.to_string(), attach);
1933}
1934
1935fn publish(rule: &mut Rule, value: Value) {
1937 *rule.node.borrow_mut() = value;
1938}
1939
1940fn expression_root(rule: &Rule) -> Value {
1947 root_node(&node_of(rule))
1948}
1949
1950fn linked_node(link: Option<&Rc<RuleSnapshot>>) -> Value {
1958 let Some(link) = link else {
1959 return Value::Undefined;
1960 };
1961 if let Some(attach) = link.u.get(ATTACH) {
1962 if is_op(attach) {
1963 return attach.clone();
1964 }
1965 }
1966 link.node.borrow().clone()
1967}
1968
1969fn write_linked_node(link: Option<&Rc<RuleSnapshot>>, value: Value) {
1970 if let Some(link) = link {
1971 *link.node.borrow_mut() = value;
1972 }
1973}
1974
1975fn counters(pairs: &[(&str, i32)]) -> HashMap<String, i32> {
1976 pairs
1977 .iter()
1978 .map(|(name, value)| ((*name).to_string(), *value))
1979 .collect()
1980}
1981
1982fn locals(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
1983 pairs
1984 .iter()
1985 .map(|(name, value)| ((*name).to_string(), value.clone()))
1986 .collect()
1987}
1988
1989fn on(tins: &[Tin]) -> AltSpec {
1991 AltSpec {
1992 s: vec![tins.to_vec()],
1993 ..Default::default()
1994 }
1995}
1996
1997fn on2(first: &[Tin], second: &[Tin]) -> AltSpec {
1999 AltSpec {
2000 s: vec![first.to_vec(), second.to_vec()],
2001 ..Default::default()
2002 }
2003}
2004
2005fn always() -> AltSpec {
2007 AltSpec::default()
2008}
2009
2010fn group_has(tags: &str, tag: &str) -> bool {
2011 tags.split(',').any(|entry| entry.trim() == tag)
2012}
2013
2014fn prepend_open_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
2018 for alt in alts.into_iter().rev() {
2019 spec.prepend_open(alt);
2020 }
2021}
2022
2023fn prepend_close_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
2024 for alt in alts.into_iter().rev() {
2025 spec.prepend_close(alt);
2026 }
2027}
2028
2029pub fn expr(parser: &mut Tabnas, options: &ExprOptions) -> Result<(), PluginError> {
2039 let rules = parser.rule_names();
2040
2041 if rules.iter().any(|name| "expr" == name) {
2045 return Ok(());
2046 }
2047
2048 if !rules.iter().any(|name| "val" == name) {
2052 return Err(PluginError(
2053 "tabnas-expr: the instance carries no `val` rule. This plugin layers on the \
2054 jsonic base grammar; install that first (tabnas_jsonic::jsonic, or \
2055 tabnas_expr::make)."
2056 .into(),
2057 ));
2058 }
2059
2060 let ops = resolve_options(options);
2061
2062 if let Err(error) = make_key_map(&ops) {
2067 return Err(PluginError(format!(
2068 "tabnas-expr: {error} [{}]",
2069 error.code()
2070 )));
2071 }
2072
2073 let prefix = make_op_map(parser, &ops, Anyfix::Prefix);
2074 let suffix = make_op_map(parser, &ops, Anyfix::Suffix);
2075 let infix = make_op_map(parser, &ops, Anyfix::Infix);
2076 let ternary = make_op_map(parser, &ops, Anyfix::Ternary);
2077 let paren_open = make_paren_map(parser, &ops);
2078 let paren_close: IndexMap<Tin, Arc<Op>> = paren_open
2079 .values()
2080 .map(|op| (op.ctin, op.clone()))
2081 .collect();
2082
2083 let grammar = Arc::new(Grammar {
2084 tin_prefix: prefix.keys().copied().collect(),
2085 tin_suffix: suffix.keys().copied().collect(),
2086 tin_infix: infix.keys().copied().collect(),
2087 tin_tern0: ternary
2088 .values()
2089 .filter(|op| Some(0) == op.ternary_index)
2090 .map(|op| op.tin)
2091 .collect(),
2092 tin_tern1: ternary
2093 .values()
2094 .filter(|op| Some(1) == op.ternary_index)
2095 .map(|op| op.tin)
2096 .collect(),
2097 tin_open: paren_open.values().map(|op| op.otin).collect(),
2098 tin_close: paren_close.values().map(|op| op.ctin).collect(),
2099 prefix,
2100 suffix,
2101 infix,
2102 ternary,
2103 paren_open,
2104 paren_close,
2105 evaluate: options.evaluate.clone(),
2106 });
2107
2108 comment_before_fixed(parser, &grammar);
2109
2110 parser.parse_prepare(|_context: &mut Context| release_arena());
2115
2116 bound_expression_size(parser);
2117
2118 install_val(parser, &grammar);
2119 install_list(parser, &grammar);
2120 install_map(parser, &grammar);
2121 install_elem(parser, &grammar);
2122 install_pair(parser, &grammar);
2123 install_expr(parser, &grammar);
2124 if grammar.has_paren() {
2125 install_paren(parser, &grammar);
2126 }
2127 if grammar.has_ternary() {
2128 install_ternary(parser, &grammar);
2129 }
2130
2131 Ok(())
2132}
2133
2134fn comment_before_fixed(parser: &mut Tabnas, grammar: &Grammar) {
2160 let options = parser.config();
2161 let markers: Vec<String> = options
2162 .comment
2163 .definitions
2164 .values()
2165 .filter(|def| def.lex)
2166 .map(|def| def.start.clone())
2167 .filter(|start| !start.is_empty())
2168 .collect();
2169 if markers.is_empty() {
2170 return;
2171 }
2172
2173 let sources: Vec<String> = grammar
2174 .prefix
2175 .values()
2176 .chain(grammar.suffix.values())
2177 .chain(grammar.infix.values())
2178 .chain(grammar.ternary.values())
2179 .map(|op| op.src.clone())
2180 .chain(
2181 grammar
2182 .paren_open
2183 .values()
2184 .flat_map(|op| [op.osrc.clone(), op.csrc.clone()]),
2185 )
2186 .filter(|src| !src.is_empty())
2187 .collect();
2188
2189 let contested: Vec<String> = markers
2190 .into_iter()
2191 .filter(|marker| {
2192 sources
2193 .iter()
2194 .any(|src| src.len() < marker.len() && marker.starts_with(src.as_str()))
2195 })
2196 .collect();
2197 if contested.is_empty() {
2198 return;
2199 }
2200
2201 parser.lex_check_ref(COMMENT_FIRST, move |remaining: &str| {
2202 if contested
2203 .iter()
2204 .any(|marker| remaining.starts_with(marker.as_str()))
2205 {
2206 tabnas::LexCheckResult::Skip
2207 } else {
2208 tabnas::LexCheckResult::Continue
2209 }
2210 });
2211 let _ = parser.grammar_json(COMMENT_FIRST_DOCUMENT);
2212}
2213
2214fn bound_expression_size(parser: &mut Tabnas) {
2221 let budget = parser.config().parse.budget.clone();
2222 let existing = budget.on_check.clone();
2223 let every = match budget.check_every_n {
2224 0 => 32,
2225 set => set.min(32),
2226 };
2227 parser.parse_budget(every, move |context: &Context| {
2228 if OVER_LIMIT.with(Cell::get) {
2229 return false;
2230 }
2231 if context.rule_stack.len() > RULE_LIMIT {
2232 return false;
2233 }
2234 existing.as_ref().is_none_or(|check| check(context))
2235 });
2236}
2237
2238const COMMENT_FIRST: &str = "@expr-comment-before-fixed";
2239const COMMENT_FIRST_DOCUMENT: &str =
2240 r#"{"options":{"fixed":{"check":"@expr-comment-before-fixed"}}}"#;
2241
2242fn install_val(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2247 let grammar = grammar.clone();
2248 parser.define_rule("val", move |spec| {
2249 if grammar.has_ternary() && grammar.tin_tern1.contains(&TIN_CL) {
2252 for alt in spec.open.iter_mut().filter(|alt| group_has(&alt.g, "pair")) {
2253 let previous = alt.c_fn.clone();
2254 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2255 previous
2256 .as_ref()
2257 .is_none_or(|condition| condition(rule, context))
2258 && 0 == counter(rule, "expr_ternary")
2259 }));
2260 }
2261 }
2262
2263 let mut open: Vec<AltSpec> = Vec::new();
2264
2265 if grammar.has_prefix() {
2267 let mut alt = on(&grammar.tin_prefix);
2268 alt.b = 1;
2269 alt.n = counters(&[("expr_prefix", 1), ("expr_suffix", 0)]);
2270 alt.p = Some("expr".into());
2271 alt.g = "expr,expr-prefix".into();
2272 alt.add_action(detach_node);
2273 open.push(alt);
2274 }
2275
2276 if grammar.has_paren() {
2278 let mut alt = on2(&VAL_TINS, &grammar.tin_open);
2279 alt.b = 1;
2280 alt.p = Some("expr".into());
2281 let condition = grammar.clone();
2282 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2283 let Some(pdef) = rule
2284 .o1()
2285 .and_then(|token| condition.paren_open.get(&token.tin))
2286 .cloned()
2287 else {
2288 return false;
2289 };
2290 if !pdef.preval.active {
2291 return false;
2292 }
2293 let Some(allow) = &pdef.preval.allow else {
2294 return true;
2295 };
2296 let preval = rule.resolve_open_value(0, context);
2297 allow.contains(&value_string(Some(&preval)))
2298 }));
2299 alt.u = locals(&[("paren_preval", Value::Bool(true))]);
2300 alt.g = "expr,expr-paren,expr-paren-preval".into();
2301 alt.add_action(|rule: &mut Rule, context: &mut Context| {
2302 let preval = rule.resolve_open_value(0, context);
2303 set_node(rule, preval);
2304 });
2305 open.push(alt);
2306 }
2307
2308 if grammar.has_paren() {
2311 let mut alt = on(&grammar.tin_open);
2312 alt.b = 1;
2313 alt.p = Some("expr".into());
2314 let condition = grammar.clone();
2315 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2316 rule.o0()
2317 .and_then(|token| condition.paren_open.get(&token.tin))
2318 .is_some_and(|pdef| !pdef.preval.required)
2319 }));
2320 alt.g = "expr,expr-paren".into();
2321 alt.add_action(detach_node);
2322 open.push(alt);
2323 }
2324
2325 prepend_open_all(spec, open);
2326
2327 let mut close: Vec<AltSpec> = Vec::new();
2328
2329 if grammar.has_infix() {
2336 let mut alt = on(&grammar.tin_infix);
2337 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2338 0 < counter(rule, "no_comma_op")
2339 && rule.c0().is_some_and(|token| "," == token.src.as_str())
2340 }));
2341 alt.b = 1;
2342 alt.g = "expr,no-comma-op-bail".into();
2343 close.push(alt);
2344 }
2345
2346 if grammar.has_ternary() {
2347 let mut alt = on(&grammar.tin_tern0);
2348 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2349 0 == counter(rule, "expr")
2350 }));
2351 alt.b = 1;
2352 alt.r = Some("ternary".into());
2353 alt.g = "expr,expr-ternary".into();
2354 close.push(alt);
2355 }
2356
2357 if grammar.has_infix() {
2359 let mut alt = on(&grammar.tin_infix);
2360 alt.b = 1;
2361 alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 0)]);
2362 alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2363 (0 == counter(rule, "expr")).then(|| "expr".to_string())
2364 }));
2365 alt.g = "expr,expr-infix".into();
2366 close.push(alt);
2367 }
2368
2369 if grammar.has_suffix() {
2371 let mut alt = on(&grammar.tin_suffix);
2372 alt.b = 1;
2373 alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 1)]);
2374 alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2375 (0 == counter(rule, "expr")).then(|| "expr".to_string())
2376 }));
2377 alt.g = "expr,expr-suffix".into();
2378 close.push(alt);
2379 }
2380
2381 if grammar.has_paren() {
2383 let mut alt = on(&grammar.tin_close);
2384 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2385 0 != counter(rule, "expr_paren")
2386 }));
2387 alt.b = 1;
2388 alt.g = "expr,expr-paren".into();
2389 close.push(alt);
2390 }
2391
2392 if grammar.has_paren() {
2406 let mut alt = on(&grammar.tin_open);
2407 alt.b = 1;
2408 let condition = grammar.clone();
2409 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2410 let Some(pdef) = rule
2411 .c0()
2412 .and_then(|token| condition.paren_open.get(&token.tin))
2413 .cloned()
2414 else {
2415 return false;
2416 };
2417 let node = node_of(rule);
2418 if !pdef.preval.active || node.is_undefined() {
2419 return false;
2420 }
2421 let Some(allow) = &pdef.preval.allow else {
2422 return true;
2423 };
2424 allow.contains(&value_string(Some(&node)))
2425 }));
2426 alt.p = Some("expr".into());
2427 alt.u = locals(&[("paren_preval", Value::Bool(true))]);
2428 alt.g = "expr,expr-paren,expr-paren-preval-chain".into();
2429 close.push(alt);
2430 }
2431
2432 if grammar.has_ternary() {
2433 let mut alt = on(&grammar.tin_tern1);
2434 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2435 0 != counter(rule, "expr_ternary")
2436 }));
2437 alt.b = 1;
2438 alt.g = "expr,expr-ternary".into();
2439 close.push(alt);
2440 }
2441
2442 let mut comma = on(&[TIN_CA]);
2445 comma.c_fn = Some(Arc::new(no_implicit_in_expr));
2446 comma.b = 1;
2447 comma.g = "expr,list,val,imp,comma,top".into();
2448 close.push(comma);
2449
2450 let mut space = on(&VAL_TINS);
2453 space.c_fn = Some(Arc::new(no_implicit_in_expr));
2454 space.b = 1;
2455 space.g = "expr,list,val,imp,space,top".into();
2456 close.push(space);
2457
2458 prepend_close_all(spec, close);
2459 });
2460}
2461
2462fn detach_node(rule: &mut Rule, _context: &mut Context) {
2472 let node = node_of(rule);
2473 set_node(rule, node);
2474}
2475
2476fn no_implicit_in_expr(rule: &mut Rule, _context: &mut Context) -> bool {
2477 (1 == rule.d && (1 <= counter(rule, "expr") || 1 <= counter(rule, "expr_ternary")))
2478 || (1 <= counter(rule, "expr_ternary") && 1 <= counter(rule, "expr_paren"))
2479}
2480
2481fn clear_expr_counters(rule: &mut Rule) {
2486 let counters = rule.n_mut();
2487 counters.insert("expr".into(), 0);
2488 counters.insert("expr_prefix".into(), 0);
2489 counters.insert("expr_suffix".into(), 0);
2490 counters.insert("expr_paren".into(), 0);
2491 counters.insert("expr_ternary".into(), 0);
2492}
2493
2494fn install_list(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2495 let grammar = grammar.clone();
2496 parser.define_rule("list", move |spec| {
2497 spec.prepend_bo(|rule: &mut Rule, _context: &mut Context| {
2498 let implicit = rule
2501 .prev_rule
2502 .as_ref()
2503 .is_some_and(|prev| matches!(prev.u.get("implist"), Some(Value::Bool(true))));
2504 if !implicit {
2505 clear_expr_counters(rule);
2506 }
2507 });
2508
2509 if grammar.has_paren() {
2510 let mut alt = on(&grammar.tin_close);
2511 alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2514 let square = rule.c0().is_some_and(|token| TIN_CS == token.tin);
2515 if square && 0 == counter(rule, "expr_paren") {
2516 0
2517 } else {
2518 1
2519 }
2520 }));
2521 alt.g = "expr".into();
2522 prepend_close_all(spec, vec![alt]);
2523
2524 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
2525 propagate_to_paren(rule);
2526 });
2527 }
2528 });
2529}
2530
2531fn install_map(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2532 let grammar = grammar.clone();
2533 parser.define_rule("map", move |spec| {
2534 spec.prepend_bo(|rule: &mut Rule, _context: &mut Context| clear_expr_counters(rule));
2536
2537 if grammar.has_paren() {
2538 let mut alt = on(&grammar.tin_close);
2539 alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2542 let brace = rule.c0().is_some_and(|token| TIN_CB == token.tin);
2543 if brace && 0 == counter(rule, "expr_paren") {
2544 0
2545 } else {
2546 1
2547 }
2548 }));
2549 alt.g = "expr".into();
2550 prepend_close_all(spec, vec![alt]);
2551 }
2552 });
2553}
2554
2555fn install_elem(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2556 let grammar = grammar.clone();
2557 parser.define_rule("elem", move |spec| {
2558 if !grammar.has_paren() {
2559 return;
2560 }
2561 let mut close: Vec<AltSpec> = Vec::new();
2562
2563 let mut alt = on(&grammar.tin_close);
2565 alt.b = 1;
2566 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2567 0 != counter(rule, "expr_paren")
2568 }));
2569 alt.g = "expr,expr-paren,imp,close,list".into();
2570 close.push(alt);
2571
2572 let mut alt = on(&grammar.tin_open);
2574 alt.b = 1;
2575 alt.r = Some("elem".into());
2576 alt.g = "expr,expr-paren,imp,open,list".into();
2577 close.push(alt);
2578
2579 prepend_close_all(spec, close);
2580
2581 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
2587 propagate_to_paren(rule);
2588 });
2589 });
2590}
2591
2592fn propagate_to_paren(rule: &mut Rule) {
2594 if 0 == counter(rule, "expr_paren") {
2595 return;
2596 }
2597 let node = node_of(rule);
2598 let mut cursor = rule.parent_rule.clone();
2599 while let Some(current) = cursor {
2600 if "paren" == current.name.as_ref() {
2601 *current.node.borrow_mut() = node;
2602 return;
2603 }
2604 cursor = current.parent_rule.clone();
2605 }
2606}
2607
2608fn install_pair(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2609 let grammar = grammar.clone();
2610 parser.define_rule("pair", move |spec| {
2611 if !grammar.has_paren() {
2612 return;
2613 }
2614 let mut alt = on(&grammar.tin_close);
2616 alt.b = 1;
2617 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2618 0 != counter(rule, "expr_paren") || 0 < counter(rule, "pk")
2619 }));
2620 alt.g = "expr,expr-paren,imp,map".into();
2621 prepend_close_all(spec, vec![alt]);
2622 });
2623}
2624
2625fn expr_root(rule: &Rule) -> Value {
2638 let parent = linked_node(rule.parent_rule.as_ref());
2639 if rule.parent_rule.is_some() && is_op(&parent) {
2640 return parent;
2641 }
2642
2643 let mut root: Option<Value> = None;
2646 if "expr" == rule.name.as_ref() {
2647 let node = node_of(rule);
2648 if is_op(&node) {
2649 root = Some(node);
2650 }
2651 }
2652 let mut cursor = rule.prev_rule.clone();
2653 while let Some(current) = cursor {
2654 if "expr" == current.name.as_ref() {
2655 let node = current.node.borrow().clone();
2656 if is_op(&node) {
2657 root = Some(node);
2658 }
2659 }
2660 cursor = current.prev_rule.clone();
2661 }
2662
2663 root.unwrap_or_else(|| node_of(rule))
2664}
2665
2666fn top_list(rule: &mut Rule) -> Value {
2674 let list = Value::array(vec![expr_root(rule)]);
2675
2676 if rule.parent_rule.is_some() {
2677 write_linked_node(rule.parent_rule.as_ref(), list.clone());
2678 return list;
2679 }
2680
2681 set_node(rule, list.clone());
2687 let mut cursor = rule.prev_rule.clone();
2688 while let Some(current) = cursor {
2689 *current.node.borrow_mut() = list.clone();
2690 cursor = current.prev_rule.clone();
2691 }
2692
2693 list
2694}
2695
2696fn implicit_list(mut matched: AltMatch, rule: &mut Rule, context: &mut Context) -> AltMatch {
2699 let mut paren: Option<Rc<RuleSnapshot>> = None;
2704 let mut paren_index = 0usize;
2705 for index in (0..context.rule_stack.len()).rev() {
2706 let frame = &context.rule_stack[index];
2707 let name = frame.name.as_ref();
2708 if "paren" == name {
2709 paren = Some(frame.clone());
2710 paren_index = index;
2711 break;
2712 }
2713 if "map" == name || "list" == name {
2714 return matched;
2715 }
2716 }
2717
2718 let Some(paren) = paren else {
2719 return matched;
2720 };
2721
2722 let expr_node = node_of(rule);
2728 let expr_node = if is_op(&expr_node) {
2729 expression_root(rule)
2730 } else {
2731 expr_node
2732 };
2733
2734 let paren_node = paren.node.borrow().clone();
2744 if matches!(&paren_node, Value::Array(members) if !members.is_empty()) {
2745 return matched;
2749 }
2750
2751 *paren.node.borrow_mut() = Value::array(vec![expr_node.clone()]);
2752 matched.r = Some("elem".into());
2753 matched.b = 0;
2754
2755 let list = paren.node.borrow().clone();
2756 set_node(rule, list.clone());
2757
2758 write_linked_node(rule.parent_rule.as_ref(), list.clone());
2764
2765 for index in (paren_index + 1)..context.rule_stack.len() {
2781 let frame = context.rule_stack[index].clone();
2782 let name = frame.name.as_ref().to_string();
2783 let node = frame.node.borrow().clone();
2784 let carries = "expr" == name
2785 || ("val" == name
2786 && (node.is_undefined()
2787 || matches!(node, Value::Null)
2788 || same_node(&node, &expr_node)
2789 || is_op(&node)));
2790 if carries {
2791 *frame.node.borrow_mut() = list.clone();
2792 }
2793 }
2794
2795 matched
2796}
2797
2798fn same_node(left: &Value, right: &Value) -> bool {
2800 match (node_id(left), node_id(right)) {
2801 (Some(left), Some(right)) => left == right,
2802 _ => false,
2803 }
2804}
2805
2806fn install_expr(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2807 let grammar = grammar.clone();
2808 parser.define_rule("expr", move |spec| {
2809 let mut open: Vec<AltSpec> = Vec::new();
2810
2811 if grammar.has_paren() {
2813 let mut alt = on(&grammar.tin_open);
2814 alt.p = Some("paren".into());
2815 alt.b = 1;
2816 alt.g = "expr,expr-paren,expr-start".into();
2817 open.push(alt);
2818 }
2819
2820 if grammar.has_prefix() {
2821 let mut alt = on(&grammar.tin_prefix);
2822 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2823 0 != counter(rule, "expr_prefix")
2824 }));
2825 alt.n = counters(&[("expr", 1), ("dlist", 1), ("dmap", 1)]);
2826 alt.p = Some("val".into());
2827 alt.g = "expr,expr-prefix".into();
2828 let ops = grammar.clone();
2829 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
2830 let Some(op) = Grammar::op_use(&ops.prefix, rule.o0()) else {
2831 return;
2832 };
2833 let parent = linked_node(rule.parent_rule.as_ref());
2834 if is_op(&parent) && !is_ternary_op(&parent) && !is_paren_op(&parent) {
2842 let attach = prattify(&parent, &op);
2843 publish_expr(rule, attach);
2844 } else {
2845 let prior = rule.parent_rule.clone();
2846 let node = prior_expr(rule, prior.as_ref(), &op);
2847 publish_expr(rule, node);
2848 }
2849 });
2850 open.push(alt);
2851 }
2852
2853 if grammar.has_infix() {
2854 let mut alt = on(&grammar.tin_infix);
2855 alt.p = Some("val".into());
2856 alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
2857 alt.g = "expr,expr-infix".into();
2858 let ops = grammar.clone();
2859 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
2860 let Some(op) = Grammar::op_use(&ops.infix, rule.o0()) else {
2861 return;
2862 };
2863 let parent = linked_node(rule.parent_rule.as_ref());
2864 let previous = linked_node(rule.prev_rule.as_ref());
2865
2866 if is_op(&parent) && !is_ternary_op(&parent) {
2868 let attach = prattify(&parent, &op);
2869 publish_expr(rule, attach);
2870 }
2871 else if is_op(&previous) {
2873 let attach = prattify(&previous, &op);
2874 if let Some(prev) = rule.prev_rule.clone() {
2875 rule.parent_node = Some(prev.node.clone());
2876 rule.parent_rule = Some(prev);
2877 }
2878 publish_expr(rule, attach);
2879 }
2880 else {
2882 let prior = rule.prev_rule.clone();
2883 let node = prior_expr(rule, prior.as_ref(), &op);
2884 publish_expr(rule, node);
2885 }
2886 });
2887 open.push(alt);
2888 }
2889
2890 if grammar.has_suffix() {
2891 let mut alt = on(&grammar.tin_suffix);
2892 alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
2893 alt.g = "expr,expr-suffix".into();
2894 let ops = grammar.clone();
2895 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
2896 let Some(op) = Grammar::op_use(&ops.suffix, rule.o0()) else {
2897 return;
2898 };
2899 let previous = linked_node(rule.prev_rule.as_ref());
2900 if is_op(&previous) {
2901 let attach = prattify(&previous, &op);
2902 publish_expr(rule, attach);
2903 } else {
2904 let prior = rule.prev_rule.clone();
2905 let node = prior_expr(rule, prior.as_ref(), &op);
2906 publish_expr(rule, node);
2907 }
2908 });
2909 open.push(alt);
2910 }
2911
2912 prepend_open_all(spec, open);
2913
2914 spec.add_bc(|rule: &mut Rule, _context: &mut Context| {
2916 let node = node_of(rule);
2917 let Some(op) = op_of(&node) else {
2918 return;
2919 };
2920 let child = rule.child_node.clone();
2921 if term_count(&node) < op.terms && !same_node(&node, &child) {
2922 push_term(&node, child);
2923 }
2924 });
2925
2926 let mut close: Vec<AltSpec> = Vec::new();
2927
2928 let mut alt = always();
2929 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2930 rule.child_rule
2931 .as_ref()
2932 .is_some_and(|child| "paren" == child.name.as_ref())
2933 }));
2934 alt.n = counters(&[("expr", 0)]);
2935 alt.g = "expr,expr-end,expr-paren-end".into();
2936 close.push(alt);
2937
2938 if grammar.has_infix() {
2944 let mut alt = on(&grammar.tin_infix);
2945 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2946 0 < counter(rule, "no_comma_op")
2947 && rule.c0().is_some_and(|token| "," == token.src.as_str())
2948 }));
2949 alt.b = 1;
2950 alt.n = counters(&[("expr", 0)]);
2951 alt.g = "expr,no-comma-op-bail".into();
2952 close.push(alt);
2953 }
2954
2955 if grammar.has_infix() {
2956 let mut alt = on(&grammar.tin_infix);
2958 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2959 0 == counter(rule, "expr_prefix")
2960 }));
2961 alt.b = 1;
2962 alt.r = Some("expr".into());
2963 alt.g = "expr,expr-infix,expr-prefix".into();
2964 close.push(alt);
2965
2966 let mut alt = on(&grammar.tin_infix);
2967 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2968 0 != counter(rule, "expr_prefix")
2969 }));
2970 alt.b = 1;
2971 alt.g = "expr,expr-infix".into();
2972 close.push(alt);
2973 }
2974
2975 if grammar.has_suffix() {
2976 let mut alt = on(&grammar.tin_suffix);
2977 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2978 0 == counter(rule, "expr_prefix")
2979 }));
2980 alt.b = 1;
2981 alt.r = Some("expr".into());
2982 alt.g = "expr,expr-suffix,expr-prefix".into();
2983 close.push(alt);
2984 }
2985
2986 if grammar.has_paren() {
2987 let mut alt = on(&grammar.tin_close);
2988 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2989 0 != counter(rule, "expr_paren")
2990 }));
2991 alt.b = 1;
2992 alt.g = "expr".into();
2993 close.push(alt);
2994 }
2995
2996 if grammar.has_ternary() {
2997 let mut alt = on(&grammar.tin_tern0);
2998 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2999 0 == counter(rule, "expr_prefix")
3000 }));
3001 alt.b = 1;
3002 alt.r = Some("ternary".into());
3003 alt.g = "expr,expr-ternary".into();
3004 close.push(alt);
3005 }
3006
3007 let mut alt = on(&[TIN_CA]);
3009 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3010 0 == rule.d
3011 }));
3012 alt.n = counters(&[("expr", 0)]);
3013 alt.r = Some("elem".into());
3014 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3015 let list = top_list(rule);
3016 set_node(rule, list);
3017 });
3018 alt.g = "expr,comma,list,top".into();
3019 close.push(alt);
3020
3021 let mut alt = on(&VAL_TINS);
3023 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3024 0 == rule.d
3025 }));
3026 alt.n = counters(&[("expr", 0)]);
3027 alt.b = 1;
3028 alt.r = Some("elem".into());
3029 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3030 let list = top_list(rule);
3031 set_node(rule, list);
3032 });
3033 alt.g = "expr,space,list,top".into();
3034 close.push(alt);
3035
3036 let mut alt = on(&[TIN_CA]);
3038 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3039 rule.lte("pk", 0)
3040 }));
3041 alt.n = counters(&[("expr", 0)]);
3042 alt.b = 1;
3043 alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
3044 implicit_list(matched, rule, context)
3045 }));
3046 alt.g = "expr,list,val,imp,comma".into();
3047 close.push(alt);
3048
3049 let mut alt = always();
3060 let suffix_tins = grammar.tin_suffix.clone();
3061 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
3062 rule.lte("pk", 0)
3063 && rule.lte("expr_suffix", 0)
3064 && !context
3065 .t0()
3066 .is_some_and(|token| suffix_tins.contains(&token.tin))
3067 }));
3068 alt.n = counters(&[("expr", 0)]);
3069 alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
3070 implicit_list(matched, rule, context)
3071 }));
3072 alt.g = "expr,list,val,imp,space".into();
3073 close.push(alt);
3074
3075 let mut alt = always();
3077 alt.n = counters(&[("expr", 0)]);
3078 alt.g = "expr,expr-end".into();
3079 close.push(alt);
3080
3081 prepend_close_all(spec, close);
3082
3083 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3090 if is_op(&node_of(rule)) {
3091 let root = expression_root(rule);
3092 set_node(rule, root);
3093 }
3094 });
3095
3096 if let Some(evaluate) = grammar.evaluate.clone() {
3098 spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
3099 if 0 != counter(rule, "expr") {
3100 return;
3101 }
3102 let Some(parent) = rule.parent_rule.clone() else {
3103 return;
3104 };
3105 let parent_node = parent.node.borrow().clone();
3106
3107 if let Value::Array(members) = &parent_node {
3120 let mut site = EvalSite::new(Some(parent.clone()), context);
3121 let reduced: Vec<Value> = members
3122 .iter()
3123 .map(|member| evaluation(&mut site.reborrow(), member, &evaluate))
3124 .collect();
3125 let reduced = Value::array(reduced);
3126 *parent.node.borrow_mut() = reduced.clone();
3127 publish(rule, reduced);
3132 return;
3133 }
3134
3135 let out = {
3137 let mut site = EvalSite::new(Some(parent.clone()), context);
3138 evaluation(&mut site, &parent_node, &evaluate)
3139 };
3140 *parent.node.borrow_mut() = out.clone();
3141
3142 publish(rule, out);
3149 });
3150 }
3151 });
3152}
3153
3154fn paren_depth(name: &str) -> String {
3159 format!("expr_paren_depth_{name}")
3160}
3161
3162fn install_paren(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3163 let grammar = grammar.clone();
3164 parser.define_rule("paren", move |spec| {
3165 spec.add_bo(|rule: &mut Rule, _context: &mut Context| {
3167 let counters = rule.n_mut();
3168 counters.insert("dmap".into(), 0);
3169 counters.insert("dlist".into(), 0);
3170 counters.insert("pk".into(), 0);
3171 });
3172
3173 let mut open: Vec<AltSpec> = Vec::new();
3174
3175 let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
3177 alt.b = 1;
3178 alt.g = "expr,expr-paren,empty".into();
3179 let condition = grammar.clone();
3180 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3181 let open = rule
3182 .o0()
3183 .and_then(|token| condition.paren_open.get(&token.tin));
3184 let close = rule
3185 .o1()
3186 .and_then(|token| condition.paren_close.get(&token.tin));
3187 match (open, close) {
3188 (Some(open), Some(close)) => open.name == close.name,
3189 _ => false,
3190 }
3191 }));
3192 let ops = grammar.clone();
3193 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3194 open_paren(&ops, rule);
3195 });
3196 open.push(alt);
3197
3198 let mut alt = on(&grammar.tin_open);
3200 alt.p = Some("val".into());
3201 alt.n = counters(&[
3202 ("expr_paren", 1),
3203 ("expr", 0),
3204 ("expr_prefix", 0),
3205 ("expr_suffix", 0),
3206 ]);
3207 alt.g = "expr,expr-paren,open".into();
3208 let ops = grammar.clone();
3209 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3210 open_paren(&ops, rule);
3211 });
3212 open.push(alt);
3213
3214 prepend_open_all(spec, open);
3215
3216 let mut alt = on(&grammar.tin_close);
3217 let condition = grammar.clone();
3218 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3219 let Some(pdef) = rule
3220 .c0()
3221 .and_then(|token| condition.paren_close.get(&token.tin))
3222 .cloned()
3223 else {
3224 return false;
3225 };
3226 0 != counter(rule, &paren_depth(&pdef.name))
3227 }));
3228 let ops = grammar.clone();
3229 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3230 close_paren(&ops, rule);
3231 });
3232 alt.g = "expr,expr-paren,close".into();
3233 prepend_close_all(spec, vec![alt]);
3234
3235 spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3236 let node = node_of(rule);
3237 let parent = rule.parent_rule.clone();
3238 write_linked_node(parent.as_ref(), node.clone());
3239 let grandparent = parent.and_then(|parent| parent.parent_rule.clone());
3240 write_linked_node(grandparent.as_ref(), node);
3241 });
3242 });
3243}
3244
3245fn open_paren(grammar: &Grammar, rule: &mut Rule) {
3246 let Some(op) = Grammar::op_use(&grammar.paren_open, rule.o0()) else {
3247 return;
3248 };
3249 let depth = paren_depth(&op.op.name);
3250 rule.u_mut().insert(depth.clone(), Value::Number(1.0));
3251 rule.n_mut().insert(depth, 1);
3252 set_node(rule, Value::Undefined);
3253}
3254
3255fn close_paren(grammar: &Grammar, rule: &mut Rule) {
3256 let child = rule.child_node.clone();
3257 let mut node = node_of(rule);
3258 if node.is_undefined() {
3271 node = child;
3272 }
3273
3274 let Some(op) = Grammar::op_use(&grammar.paren_close, rule.c0()) else {
3275 set_node(rule, node);
3276 return;
3277 };
3278 let depth = paren_depth(&op.op.name);
3279
3280 if local_number(rule, &depth) == i64::from(counter(rule, &depth)) {
3282 let mut terms: Vec<Value> = Vec::new();
3283
3284 let grandparent = rule
3285 .parent_rule
3286 .as_ref()
3287 .and_then(|parent| parent.parent_rule.clone());
3288 if let Some(grandparent) = &grandparent {
3289 let preval = grandparent.node.borrow().clone();
3290 if matches!(grandparent.u.get("paren_preval"), Some(Value::Bool(true)))
3291 && !preval.is_undefined()
3292 {
3293 terms.push(preval);
3294 }
3295 }
3296
3297 if !node.is_undefined() {
3298 terms.push(node);
3299 }
3300
3301 set_node(rule, op.node(terms));
3302 } else {
3303 set_node(rule, node);
3304 }
3305}
3306
3307fn install_ternary(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3312 let grammar = grammar.clone();
3313 parser.define_rule("ternary", move |spec| {
3314 let mut open: Vec<AltSpec> = Vec::new();
3315
3316 let mut alt = on(&grammar.tin_tern0);
3317 alt.p = Some("val".into());
3318 alt.n = counters(&[
3319 ("expr_ternary", 1),
3320 ("expr", 0),
3321 ("expr_prefix", 0),
3322 ("expr_suffix", 0),
3323 ]);
3324 alt.u = locals(&[("expr_ternary_step", Value::Number(1.0))]);
3325 alt.g = "expr,expr-ternary,open".into();
3326 let ops = grammar.clone();
3327 alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3328 let Some(op) = Grammar::op_use(&ops.ternary, rule.o0()) else {
3329 return;
3330 };
3331 rule.u_mut().insert(
3332 "expr_ternary_name".into(),
3333 Value::String(op.op.name.clone()),
3334 );
3335
3336 let previous = linked_node(rule.prev_rule.as_ref());
3337 let node = if is_op(&previous) {
3338 let duplicate = dup_node(&previous);
3339 update_expr_node(
3340 &previous,
3341 Some(op.op.clone()),
3342 op.token.clone(),
3343 vec![duplicate],
3344 );
3345 previous
3346 } else {
3347 let node = op.node(vec![previous]);
3348 write_linked_node(rule.prev_rule.as_ref(), node.clone());
3349 node
3350 };
3351 set_node(rule, node);
3352
3353 let paren = if 0 != counter(rule, "expr_paren") {
3354 i64::from(counter(rule, "expr_paren"))
3355 } else {
3356 rule.prev_rule
3357 .as_ref()
3358 .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"))
3359 };
3360 rule.u_mut()
3361 .insert("expr_ternary_paren".into(), Value::Number(paren as f64));
3362 rule.n_mut().insert("expr_paren".into(), 0);
3363 });
3364 open.push(alt);
3365
3366 let mut alt = always();
3367 alt.p = Some("val".into());
3368 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3369 rule.prev_rule
3370 .as_ref()
3371 .is_some_and(|prev| 2 == snapshot_number(prev, "expr_ternary_step"))
3372 }));
3373 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3374 let (step, paren) = rule.prev_rule.as_ref().map_or((0, 0), |prev| {
3375 (
3376 snapshot_number(prev, "expr_ternary_step"),
3377 snapshot_number(prev, "expr_ternary_paren"),
3378 )
3379 });
3380 set_local_number(rule, "expr_ternary_step", step);
3381 set_local_number(rule, "expr_ternary_paren", paren);
3382 rule.n_mut().insert("expr_paren".into(), paren as i32);
3383 });
3384 alt.g = "expr,expr-ternary,step".into();
3385 open.push(alt);
3386
3387 prepend_open_all(spec, open);
3388
3389 let mut close: Vec<AltSpec> = Vec::new();
3390
3391 let mut alt = on(&grammar.tin_tern1);
3392 let condition = grammar.clone();
3393 alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3394 if 1 != local_number(rule, "expr_ternary_step") {
3395 return false;
3396 }
3397 let Some(op) = rule
3398 .c0()
3399 .and_then(|token| condition.ternary.get(&token.tin))
3400 .cloned()
3401 else {
3402 return false;
3403 };
3404 matches!(rule.u.get("expr_ternary_name"), Some(Value::String(name)) if name == &op.name)
3405 }));
3406 alt.r = Some("ternary".into());
3407 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3408 let step = local_number(rule, "expr_ternary_step");
3409 set_local_number(rule, "expr_ternary_step", step + 1);
3410 let node = node_of(rule);
3411 push_term(&node, rule.child_node.clone());
3412 });
3413 alt.g = "expr,expr-ternary,step".into();
3414 close.push(alt);
3415
3416 let mut tins = vec![TIN_CA];
3420 tins.extend(grammar.tin_close.iter().copied());
3421 let mut alt = on(&tins);
3422 alt.c_fn = Some(Arc::new(implicit_ternary_cond));
3423 let closers = grammar.tin_close.clone();
3424 alt.b_fn = Some(Arc::new(move |_rule: &mut Rule, context: &mut Context| {
3425 usize::from(next_is_close(context, &closers))
3426 }));
3427 let closers = grammar.tin_close.clone();
3428 alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
3429 let to_elem = !next_is_close(context, &closers)
3430 && (0 == rule.d
3431 || (rule
3432 .prev_rule
3433 .as_ref()
3434 .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren"))
3435 && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))));
3436 to_elem.then(|| "elem".to_string())
3437 }));
3438 alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
3439 implicit_ternary_action(rule, matched);
3440 None
3441 });
3442 alt.g = "expr,expr-ternary,list,val,imp,comma".into();
3443 close.push(alt);
3444
3445 let mut alt = always();
3448 alt.c_fn = Some(Arc::new(implicit_ternary_cond));
3449 let closers = grammar.tin_close.clone();
3450 alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
3451 let ended = context.t0().is_some_and(|token| TIN_ZZ == token.tin);
3452 let to_elem = (0 == rule.d
3453 || !next_is_close(context, &closers)
3454 || rule
3455 .prev_rule
3456 .as_ref()
3457 .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren")))
3458 && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))
3459 && !ended;
3460 to_elem.then(|| "elem".to_string())
3461 }));
3462 alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
3463 implicit_ternary_action(rule, matched);
3464 None
3465 });
3466 alt.g = "expr,expr-ternary,list,val,imp,space".into();
3467 close.push(alt);
3468
3469 let mut alt = always();
3471 alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3472 0 < rule.d && 2 == local_number(rule, "expr_ternary_step")
3473 }));
3474 alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3475 let node = node_of(rule);
3476 push_term(&node, rule.child_node.clone());
3477 });
3478 alt.g = "expr,expr-ternary,close".into();
3479 close.push(alt);
3480
3481 prepend_close_all(spec, close);
3482
3483 if let Some(evaluate) = grammar.evaluate.clone() {
3492 spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
3493 if rule
3494 .next_rule_name
3495 .as_ref()
3496 .is_some_and(|name| "ternary" == name.as_ref())
3497 {
3498 return;
3499 }
3500 let node = node_of(rule);
3501 if !is_op(&node) {
3502 return;
3503 }
3504 if node_length(&node) < 4 {
3507 return;
3508 }
3509 let out = {
3510 let site_rule = rule.snapshot();
3514 let mut site = EvalSite::new(Some(site_rule), context);
3515 evaluation(&mut site, &node, &evaluate)
3516 };
3517 publish(rule, out.clone());
3518 let mut cursor = rule.prev_rule.clone();
3519 while let Some(current) = cursor {
3520 *current.node.borrow_mut() = out.clone();
3521 cursor = current.prev_rule.clone();
3522 }
3523 write_linked_node(rule.parent_rule.as_ref(), out);
3524 });
3525 }
3526 });
3527}
3528
3529fn snapshot_number(snapshot: &RuleSnapshot, name: &str) -> i64 {
3530 match snapshot.u.get(name) {
3531 Some(Value::Number(number)) => *number as i64,
3532 _ => 0,
3533 }
3534}
3535
3536fn next_is_close(context: &mut Context, closers: &[Tin]) -> bool {
3537 context
3538 .t0()
3539 .is_some_and(|token| closers.contains(&token.tin))
3540}
3541
3542fn implicit_ternary_cond(rule: &mut Rule, _context: &mut Context) -> bool {
3543 (0 == rule.d || 1 <= counter(rule, "expr_paren"))
3544 && 0 == counter(rule, "pk")
3545 && 2 == local_number(rule, "expr_ternary_step")
3546}
3547
3548fn implicit_ternary_action(rule: &mut Rule, matched: &AltMatch) {
3549 let paren = rule
3550 .prev_rule
3551 .as_ref()
3552 .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"));
3553 rule.n_mut().insert("expr_paren".into(), paren as i32);
3554
3555 let node = node_of(rule);
3556 push_term(&node, rule.child_node.clone());
3557
3558 if matched.r.as_deref() != Some("elem") {
3559 return;
3560 }
3561
3562 let list = Value::array(vec![node]);
3569 publish(rule, list.clone());
3570 if 1 <= counter(rule, "expr_paren") {
3571 let mut cursor = rule.parent_rule.clone();
3572 while let Some(current) = cursor {
3573 if "paren" == current.name.as_ref() {
3574 *current.node.borrow_mut() = list;
3575 break;
3576 }
3577 cursor = current.parent_rule.clone();
3578 }
3579 }
3580}
3581
3582pub fn plugin() -> Plugin {
3606 Plugin::new(PLUGIN_NAME, |parser: &mut Tabnas, options: &Value| {
3607 expr(parser, &ExprOptions::from_value(options))
3608 })
3609 .with_defaults(defaults())
3610}
3611
3612pub fn plugin_with(options: ExprOptions) -> Plugin {
3619 Plugin::new(PLUGIN_NAME, move |parser: &mut Tabnas, _options: &Value| {
3620 expr(parser, &options)
3621 })
3622}
3623
3624pub fn apply(parser: &mut Tabnas, options: ExprOptions) -> Result<(), PluginError> {
3627 parser.use_plugin(plugin_with(options), None).map(|_| ())
3628}
3629
3630pub fn make() -> Tabnas {
3643 make_with(ExprOptions::new())
3644}
3645
3646pub fn make_with(options: ExprOptions) -> Tabnas {
3648 let mut parser = tabnas_jsonic::make();
3649 parser
3650 .use_plugin(plugin_with(options), None)
3651 .expect("the expression grammar installs on the jsonic base");
3652 parser
3653}
3654
3655static DEFAULT_PARSER: OnceLock<Tabnas> = OnceLock::new();
3662
3663pub fn parse(src: &str) -> Result<Value, TabnasError> {
3674 parse_with(DEFAULT_PARSER.get_or_init(make), src)
3675}
3676
3677pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
3684 let _guard = ArenaGuard::enter();
3685 let value = parser.parse(src)?;
3686 Ok(realize(&value))
3687}
3688
3689pub fn parse_scope<R>(
3726 parser: &Tabnas,
3727 src: &str,
3728 use_value: impl FnOnce(Value) -> R,
3729) -> Result<R, TabnasError> {
3730 let _guard = ArenaGuard::enter();
3731 let value = parser.parse(src)?;
3732 Ok(use_value(value))
3733}
3734
3735pub fn parse_simplified(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
3738 let _guard = ArenaGuard::enter();
3739 let value = parser.parse(src)?;
3740 Ok(simplify(&value))
3741}
3742
3743#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3747pub struct TranslationPart {
3748 pub entry: &'static str,
3750 pub source: Option<&'static str>,
3752}
3753
3754#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3756pub struct TranslationParts {
3757 pub manifest: &'static str,
3759 pub lift: Option<TranslationPart>,
3761 pub embed: Option<TranslationPart>,
3763 pub render: Option<TranslationPart>,
3765}
3766
3767const TRANSLATION: TranslationParts = TranslationParts {
3768 manifest: include_str!("../translate/manifest.json"),
3769 lift: None,
3770 embed: Some(TranslationPart {
3771 entry: "expr-embed",
3772 source: Some(include_str!("../translate/embed.alc")),
3773 }),
3774 render: Some(TranslationPart {
3775 entry: "expr-render",
3776 source: Some(include_str!("../translate/render.alc")),
3777 }),
3778};
3779
3780#[must_use]
3782pub const fn translate() -> Option<TranslationParts> {
3783 Some(TRANSLATION)
3784}
3785
3786pub fn manifest_text() -> &'static str {
3800 TRANSLATION.manifest
3801}
3802
3803pub fn render_text() -> &'static str {
3814 match TRANSLATION.render {
3815 Some(part) => part.source.unwrap_or_default(),
3816 None => "",
3817 }
3818}