1#![forbid(unsafe_code)]
15
16use crate::dialect::PerformativeDef;
17use crate::r2::ResourceState;
18use crate::sexpr::{Atom, SExpr};
19use alloc::collections::BTreeMap;
20use alloc::string::String;
21use alloc::vec::Vec;
22
23pub type Bindings = BTreeMap<String, SExpr>;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ExpandedTemplate {
29 Single(SExpr),
30 Sequence(Vec<SExpr>),
31}
32
33pub fn expand_template(
37 def: &PerformativeDef,
38 args: &[SExpr],
39 rs: &mut ResourceState,
40) -> Option<SExpr> {
41 let _start_depth = rs.current_depth;
42 let bindings = build_bindings(&def.params, args);
43 let result = match eval_template(&def.template, &bindings, rs)? {
44 ExpandedTemplate::Single(expr) => Some(expr),
45 ExpandedTemplate::Sequence(exprs) => Some(SExpr::List(exprs)),
46 };
47 #[cfg(feature = "tracing")]
48 tracing::event!(
49 tracing::Level::INFO,
50 performative = %def.name,
51 start_depth = _start_depth,
52 final_depth = rs.current_depth,
53 expansion_size = rs.expansion_size,
54 "template_expand_depth"
55 );
56 result
57}
58
59pub fn expand_template_with_bindings(
64 template: &SExpr,
65 bindings: &Bindings,
66 rs: &mut ResourceState,
67) -> Option<ExpandedTemplate> {
68 let _start_depth = rs.current_depth;
69 let result = eval_template(template, bindings, rs);
70 #[cfg(feature = "tracing")]
71 tracing::event!(
72 tracing::Level::INFO,
73 start_depth = _start_depth,
74 final_depth = rs.current_depth,
75 expansion_size = rs.expansion_size,
76 success = result.is_some(),
77 "template_expand_depth"
78 );
79 result
80}
81
82pub fn eval_type_predicate(value: &SExpr, type_name: &str) -> bool {
88 if let Some(ty) = crate::shape::TypeConstraint::from_str(type_name) {
89 return ty.matches_builtin(value);
90 }
91 type_name == "agent" && matches!(value, SExpr::Atom(Atom::Symbol(s)) if s.starts_with('@'))
92}
93
94fn build_bindings(params: &[SExpr], args: &[SExpr]) -> Bindings {
100 let mut bindings = Bindings::new();
101 for (param, arg) in params.iter().zip(args.iter()) {
102 if let SExpr::Atom(Atom::Symbol(name)) = param {
103 bindings.insert(name.clone(), arg.clone());
104 }
105 }
106 bindings
107}
108
109fn eval_template(
111 template: &SExpr,
112 bindings: &Bindings,
113 rs: &mut ResourceState,
114) -> Option<ExpandedTemplate> {
115 let rs_inner = rs.enter_depth()?;
116 *rs = rs_inner;
117
118 let result = eval_form(template, bindings, rs)?;
119
120 let size = match &result {
121 ExpandedTemplate::Single(expr) => expr.byte_size() as u32,
122 ExpandedTemplate::Sequence(exprs) => {
123 exprs.iter().map(|e| e.byte_size() as u32).sum::<u32>()
124 }
125 };
126 *rs = rs.add_expansion(size)?;
127 Some(result)
128}
129
130fn eval_form(
132 template: &SExpr,
133 bindings: &Bindings,
134 rs: &mut ResourceState,
135) -> Option<ExpandedTemplate> {
136 match template {
137 SExpr::Atom(_) => {
138 let subst = substitute_atom(template, bindings);
139 Some(ExpandedTemplate::Single(subst))
140 }
141 SExpr::List(items) if items.is_empty() => {
142 Some(ExpandedTemplate::Single(SExpr::List(Vec::new())))
143 }
144 SExpr::List(items) => {
145 if let Some(head) = items.first() {
147 if head.is_symbol("literal") {
149 return eval_literal(items, bindings);
150 }
151 if head.is_symbol("cond") {
153 return eval_cond(&items[1..], bindings, rs);
154 }
155 }
156
157 if is_sequence_template(items) {
161 return eval_sequence(items, bindings, rs);
162 }
163
164 let result = substitute_expr(template, bindings);
166 Some(ExpandedTemplate::Single(result))
167 }
168 }
169}
170
171fn eval_literal(items: &[SExpr], bindings: &Bindings) -> Option<ExpandedTemplate> {
173 if items.len() != 2 {
174 return None;
175 }
176 let body = substitute_expr(&items[1], bindings);
177 Some(ExpandedTemplate::Single(body))
178}
179
180fn eval_cond(
182 clauses: &[SExpr],
183 bindings: &Bindings,
184 rs: &mut ResourceState,
185) -> Option<ExpandedTemplate> {
186 for clause in clauses {
187 match clause {
188 SExpr::List(parts) if parts.len() == 2 => {
189 if parts[0].is_symbol("else") {
191 return eval_form(&parts[1], bindings, rs);
192 }
193 let test = &parts[0];
195 let body = &parts[1];
196 if eval_condition(test, bindings) {
197 return eval_form(body, bindings, rs);
198 }
199 }
200 _ if clause.is_symbol("else") => {
202 return None;
204 }
205 _ => return None,
206 }
207 }
208 None
210}
211
212fn eval_condition(condition: &SExpr, bindings: &Bindings) -> bool {
214 match condition {
215 SExpr::List(items) if items.len() == 3 => {
216 if items[0].is_symbol("=") {
218 let lhs = resolve_value(&items[1], bindings);
219 let rhs = resolve_value(&items[2], bindings);
220 return values_equal(&lhs, &rhs);
221 }
222 if items[0].is_symbol("member") {
224 let value = resolve_value(&items[1], bindings);
225 if let SExpr::List(members) = &items[2] {
226 return members
227 .iter()
228 .any(|m| values_equal(&value, &resolve_value(m, bindings)));
229 }
230 return false;
231 }
232 if items[0].is_symbol("type?") {
234 let value = resolve_value(&items[1], bindings);
235 if let SExpr::Atom(Atom::Symbol(type_name)) = &items[2] {
236 return eval_type_predicate(&value, type_name);
237 }
238 return false;
239 }
240 false
241 }
242 _ => false,
243 }
244}
245
246fn is_sequence_template(items: &[SExpr]) -> bool {
251 !items.is_empty()
252 && items.iter().all(|item| match item {
253 SExpr::List(inner) => {
254 !inner.is_empty() && (inner[0].is_symbol("literal") || inner[0].is_symbol("cond"))
255 }
256 _ => false,
257 })
258}
259
260fn eval_sequence(
262 items: &[SExpr],
263 bindings: &Bindings,
264 rs: &mut ResourceState,
265) -> Option<ExpandedTemplate> {
266 let mut results = Vec::with_capacity(items.len());
267 for item in items {
268 match eval_form(item, bindings, rs)? {
269 ExpandedTemplate::Single(expr) => results.push(expr),
270 ExpandedTemplate::Sequence(exprs) => results.extend(exprs),
271 }
272 }
273 Some(ExpandedTemplate::Sequence(results))
274}
275
276fn resolve_value(expr: &SExpr, bindings: &Bindings) -> SExpr {
279 if let SExpr::Atom(Atom::Symbol(name)) = expr {
280 if let Some(val) = bindings.get(name.as_str()) {
281 return val.clone();
282 }
283 }
284 expr.clone()
285}
286
287fn values_equal(a: &SExpr, b: &SExpr) -> bool {
293 if a == b {
294 return true;
295 }
296 match (a, b) {
298 (SExpr::Atom(Atom::Symbol(sa)), SExpr::Atom(Atom::Symbol(sb))) => sa == sb,
299 _ => false,
300 }
301}
302
303fn substitute_atom(expr: &SExpr, bindings: &Bindings) -> SExpr {
305 if let SExpr::Atom(Atom::Symbol(name)) = expr {
306 if let Some(val) = bindings.get(name.as_str()) {
307 return val.clone();
308 }
309 }
310 expr.clone()
311}
312
313fn substitute_expr(template: &SExpr, bindings: &Bindings) -> SExpr {
315 match template {
316 SExpr::Atom(Atom::Symbol(name)) => {
317 if let Some(val) = bindings.get(name.as_str()) {
318 val.clone()
319 } else {
320 template.clone()
321 }
322 }
323 SExpr::Atom(_) => template.clone(),
324 SExpr::List(items) => {
325 SExpr::List(items.iter().map(|e| substitute_expr(e, bindings)).collect())
326 }
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use super::*;
333 use alloc::vec;
334
335 fn parse(s: &str) -> SExpr {
339 s.parse().unwrap()
340 }
341
342 fn bindings_from(pairs: &[(&str, SExpr)]) -> Bindings {
343 pairs
344 .iter()
345 .map(|(k, v)| (String::from(*k), v.clone()))
346 .collect()
347 }
348
349 #[test]
354 fn simple_substitution() {
355 let def = PerformativeDef {
356 role: None,
357 name: String::from("greet"),
358 params: vec![SExpr::Atom(Atom::Symbol(String::from("x")))],
359 template: SExpr::List(vec![
360 SExpr::Atom(Atom::Symbol(String::from("hello"))),
361 SExpr::Atom(Atom::Symbol(String::from("x"))),
362 ]),
363 };
364 let args = vec![SExpr::Atom(Atom::Str(String::from("world")))];
365 let mut rs = ResourceState::new(8, 512);
366 let result = expand_template(&def, &args, &mut rs).unwrap();
367 assert_eq!(
368 result,
369 SExpr::List(vec![
370 SExpr::Atom(Atom::Symbol(String::from("hello"))),
371 SExpr::Atom(Atom::Str(String::from("world"))),
372 ])
373 );
374 }
375
376 #[test]
381 fn tv_pipe_tpl_001_literal_substitution() {
382 let template = parse("(literal (tell @alice message))");
383 let bindings = bindings_from(&[("message", SExpr::Atom(Atom::Str("hello".into())))]);
384 let mut rs = ResourceState::new(8, 512);
385 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
386 assert_eq!(
387 result,
388 ExpandedTemplate::Single(parse("(tell @alice \"hello\")"))
389 );
390 }
391
392 #[test]
397 fn tv_pipe_tpl_002_cond_equality() {
398 let template = parse(
399 "(cond ((= priority urgent) (literal (tell @emergency message))) (else (literal (tell @normal message))))",
400 );
401 let bindings = bindings_from(&[
402 ("priority", SExpr::Atom(Atom::Symbol("urgent".into()))),
403 ("message", SExpr::Atom(Atom::Str("fire!".into()))),
404 ]);
405 let mut rs = ResourceState::new(8, 512);
406 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
407 assert_eq!(
408 result,
409 ExpandedTemplate::Single(parse("(tell @emergency \"fire!\")"))
410 );
411 }
412
413 #[test]
414 fn tv_pipe_tpl_002_cond_equality_else_branch() {
415 let template = parse(
416 "(cond ((= priority urgent) (literal (tell @emergency message))) (else (literal (tell @normal message))))",
417 );
418 let bindings = bindings_from(&[
419 ("priority", SExpr::Atom(Atom::Symbol("low".into()))),
420 ("message", SExpr::Atom(Atom::Str("info".into()))),
421 ]);
422 let mut rs = ResourceState::new(8, 512);
423 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
424 assert_eq!(
425 result,
426 ExpandedTemplate::Single(parse("(tell @normal \"info\")"))
427 );
428 }
429
430 #[test]
435 fn tv_pipe_tpl_003_cond_membership() {
436 let template = parse(
437 "(cond ((member category (urgent critical)) (literal (tell @emergency message))) (else (literal (tell @normal message))))",
438 );
439 let bindings = bindings_from(&[
440 ("category", SExpr::Atom(Atom::Symbol("urgent".into()))),
441 ("message", SExpr::Atom(Atom::Str("alert".into()))),
442 ]);
443 let mut rs = ResourceState::new(8, 512);
444 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
445 assert_eq!(
446 result,
447 ExpandedTemplate::Single(parse("(tell @emergency \"alert\")"))
448 );
449 }
450
451 #[test]
452 fn tv_pipe_tpl_003_cond_membership_no_match() {
453 let template = parse(
454 "(cond ((member category (urgent critical)) (literal (tell @emergency message))) (else (literal (tell @normal message))))",
455 );
456 let bindings = bindings_from(&[
457 ("category", SExpr::Atom(Atom::Symbol("info".into()))),
458 ("message", SExpr::Atom(Atom::Str("note".into()))),
459 ]);
460 let mut rs = ResourceState::new(8, 512);
461 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
462 assert_eq!(
463 result,
464 ExpandedTemplate::Single(parse("(tell @normal \"note\")"))
465 );
466 }
467
468 #[test]
473 fn tv_pipe_tpl_004_type_number() {
474 assert!(eval_type_predicate(&SExpr::Atom(Atom::Num(42)), "number"));
475 assert!(!eval_type_predicate(
476 &SExpr::Atom(Atom::Str("42".into())),
477 "number"
478 ));
479 }
480
481 #[test]
482 fn tv_pipe_tpl_005_type_string() {
483 assert!(eval_type_predicate(
484 &SExpr::Atom(Atom::Str("hello".into())),
485 "string"
486 ));
487 assert!(!eval_type_predicate(&SExpr::Atom(Atom::Num(42)), "string"));
488 }
489
490 #[test]
491 fn tv_pipe_tpl_006_type_agent() {
492 assert!(eval_type_predicate(
493 &SExpr::Atom(Atom::Symbol("@alice".into())),
494 "agent"
495 ));
496 assert!(!eval_type_predicate(
497 &SExpr::Atom(Atom::Symbol("alice".into())),
498 "agent"
499 ));
500 }
501
502 #[test]
503 fn type_predicate_bool() {
504 assert!(eval_type_predicate(&SExpr::Atom(Atom::Bool(true)), "bool"));
505 }
506
507 #[test]
508 fn type_predicate_symbol() {
509 assert!(eval_type_predicate(
510 &SExpr::Atom(Atom::Symbol("foo".into())),
511 "symbol"
512 ));
513 }
514
515 #[test]
516 fn type_predicate_unknown() {
517 assert!(!eval_type_predicate(
518 &SExpr::Atom(Atom::Num(1)),
519 "unknown-type"
520 ));
521 }
522
523 #[test]
528 fn type_condition_number() {
529 let condition = parse("(type? value number)");
530 let bindings = bindings_from(&[("value", SExpr::Atom(Atom::Num(42)))]);
531 assert!(eval_condition(&condition, &bindings));
532 }
533
534 #[test]
535 fn type_condition_string() {
536 let condition = parse("(type? value string)");
537 let bindings = bindings_from(&[("value", SExpr::Atom(Atom::Str("hello".into())))]);
538 assert!(eval_condition(&condition, &bindings));
539 }
540
541 #[test]
542 fn type_condition_agent() {
543 let condition = parse("(type? value agent)");
544 let bindings = bindings_from(&[("value", SExpr::Atom(Atom::Symbol("@alice".into())))]);
545 assert!(eval_condition(&condition, &bindings));
546 }
547
548 #[test]
553 fn tv_pipe_tpl_007_sequence() {
554 let template = parse(
555 "((literal (tell @coordinator \"start\")) (literal (tell @worker \"task\")) (literal (tell @coordinator \"done\")))",
556 );
557 let bindings = Bindings::new();
558 let mut rs = ResourceState::new(8, 4096);
559 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
560 assert_eq!(
561 result,
562 ExpandedTemplate::Sequence(vec![
563 parse("(tell @coordinator \"start\")"),
564 parse("(tell @worker \"task\")"),
565 parse("(tell @coordinator \"done\")"),
566 ])
567 );
568 }
569
570 #[test]
575 fn tv_pipe_tpl_008_plain_substitution() {
576 let template = parse("(tell x (greeting y))");
577 let bindings = bindings_from(&[
578 ("x", SExpr::Atom(Atom::Symbol("alice".into()))),
579 ("y", SExpr::Atom(Atom::Symbol("hello".into()))),
580 ]);
581 let mut rs = ResourceState::new(8, 512);
582 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
583 assert_eq!(
584 result,
585 ExpandedTemplate::Single(parse("(tell alice (greeting hello))"))
586 );
587 }
588
589 #[test]
594 fn expansion_respects_depth_limit() {
595 let template = parse("(literal (tell @alice \"hi\"))");
596 let bindings = Bindings::new();
597 let mut rs = ResourceState::new(1, 512);
599 assert!(expand_template_with_bindings(&template, &bindings, &mut rs).is_none());
600 }
601
602 #[test]
603 fn expansion_respects_size_limit() {
604 let template = parse("(literal (tell @alice \"a very long message that exceeds bounds\"))");
605 let bindings = Bindings::new();
606 let mut rs = ResourceState::new(8, 5);
608 assert!(expand_template_with_bindings(&template, &bindings, &mut rs).is_none());
609 }
610
611 #[test]
616 fn empty_bindings_no_substitution() {
617 let template = parse("(tell @alice x)");
618 let bindings = Bindings::new();
619 let mut rs = ResourceState::new(8, 512);
620 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
621 assert_eq!(result, ExpandedTemplate::Single(parse("(tell @alice x)")));
623 }
624
625 #[test]
626 fn atom_template() {
627 let template = parse("x");
628 let bindings = bindings_from(&[("x", SExpr::Atom(Atom::Num(42)))]);
629 let mut rs = ResourceState::new(8, 512);
630 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
631 assert_eq!(result, ExpandedTemplate::Single(SExpr::Atom(Atom::Num(42))));
632 }
633
634 #[test]
635 fn cond_no_else_no_match() {
636 let template = parse("(cond ((= x y) (literal (tell @a \"yes\"))))");
637 let bindings = bindings_from(&[
638 ("x", SExpr::Atom(Atom::Symbol("a".into()))),
639 ("y", SExpr::Atom(Atom::Symbol("b".into()))),
640 ]);
641 let mut rs = ResourceState::new(8, 512);
642 assert!(expand_template_with_bindings(&template, &bindings, &mut rs).is_none());
644 }
645
646 #[test]
647 fn equality_same_symbols() {
648 let condition = parse("(= x y)");
649 let bindings = bindings_from(&[
650 ("x", SExpr::Atom(Atom::Symbol("same".into()))),
651 ("y", SExpr::Atom(Atom::Symbol("same".into()))),
652 ]);
653 assert!(eval_condition(&condition, &bindings));
654 }
655
656 #[test]
657 fn equality_different_symbols() {
658 let condition = parse("(= x y)");
659 let bindings = bindings_from(&[
660 ("x", SExpr::Atom(Atom::Symbol("a".into()))),
661 ("y", SExpr::Atom(Atom::Symbol("b".into()))),
662 ]);
663 assert!(!eval_condition(&condition, &bindings));
664 }
665
666 #[test]
667 fn member_in_list() {
668 let condition = parse("(member x (a b c))");
669 let bindings = bindings_from(&[("x", SExpr::Atom(Atom::Symbol("b".into())))]);
670 assert!(eval_condition(&condition, &bindings));
671 }
672
673 #[test]
674 fn member_not_in_list() {
675 let condition = parse("(member x (a b c))");
676 let bindings = bindings_from(&[("x", SExpr::Atom(Atom::Symbol("d".into())))]);
677 assert!(!eval_condition(&condition, &bindings));
678 }
679
680 #[test]
681 fn nested_substitution_in_literal() {
682 let template = parse("(literal (tell @alice (mood greeting)))");
683 let bindings = bindings_from(&[
684 ("mood", SExpr::Atom(Atom::Symbol("happy".into()))),
685 ("greeting", SExpr::Atom(Atom::Str("hello!".into()))),
686 ]);
687 let mut rs = ResourceState::new(8, 512);
688 let result = expand_template_with_bindings(&template, &bindings, &mut rs).unwrap();
689 assert_eq!(
690 result,
691 ExpandedTemplate::Single(parse("(tell @alice (happy \"hello!\"))"))
692 );
693 }
694
695 #[test]
696 fn expand_template_backwards_compat() {
697 let def = PerformativeDef {
699 role: None,
700 name: String::from("notify"),
701 params: vec![
702 SExpr::Atom(Atom::Symbol(String::from("recipient"))),
703 SExpr::Atom(Atom::Symbol(String::from("msg"))),
704 ],
705 template: parse("(tell recipient msg)"),
706 };
707 let args = vec![
708 SExpr::Atom(Atom::Symbol("@bob".into())),
709 SExpr::Atom(Atom::Str("hey".into())),
710 ];
711 let mut rs = ResourceState::new(8, 512);
712 let result = expand_template(&def, &args, &mut rs).unwrap();
713 assert_eq!(result, parse("(tell @bob \"hey\")"));
714 }
715}