1use crate::ast::logic::LogicExpr;
28use crate::ast::stmt::{ClosureBody, Expr, ReadSource, SelectBranch, Stmt, StringPart, TypeExpr};
29use crate::error::{ParseError, ParseErrorKind};
30use crate::token::Span;
31
32pub const DEFAULT_MAX_AST_DEPTH: usize = 128;
46
47pub const MIN_AST_DEPTH: usize = 16;
50
51pub fn max_ast_depth() -> usize {
59 static LIMIT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
60 *LIMIT.get_or_init(|| limit_from(std::env::var("LOGOS_MAX_AST_DEPTH").ok().as_deref()))
61}
62
63pub fn limit_from(env_value: Option<&str>) -> usize {
67 match env_value.and_then(|v| v.trim().parse::<usize>().ok()) {
68 Some(n) => n.max(MIN_AST_DEPTH),
69 None => DEFAULT_MAX_AST_DEPTH,
70 }
71}
72
73pub fn max_parse_recursion() -> usize {
96 (max_ast_depth() / 8).max(MIN_AST_DEPTH)
97}
98
99enum Node<'w, 'a> {
101 S(&'w Stmt<'a>),
102 E(&'w Expr<'a>),
103 T(&'w TypeExpr<'a>),
104 L(&'w LogicExpr<'a>),
105}
106
107pub fn program_depth(stmts: &[Stmt<'_>]) -> usize {
109 let mut work: Vec<(Node<'_, '_>, usize)> = stmts.iter().map(|s| (Node::S(s), 1)).collect();
110 let mut max_depth = 0usize;
111
112 while let Some((node, depth)) = work.pop() {
113 max_depth = max_depth.max(depth);
114 let d = depth + 1;
115 match node {
116 Node::S(stmt) => push_stmt_children(stmt, d, &mut work),
117 Node::E(expr) => push_expr_children(expr, d, &mut work),
118 Node::T(ty) => push_type_children(ty, d, &mut work),
119 Node::L(logic) => push_logic_children(logic, d, &mut work),
120 }
121 }
122 max_depth
123}
124
125pub enum Visited<'w, 'a> {
127 Stmt(&'w Stmt<'a>),
128 Expr(&'w Expr<'a>),
129}
130
131pub fn for_each_node<'w, 'a>(stmts: &'w [Stmt<'a>], mut visit: impl FnMut(Visited<'w, 'a>)) {
135 walk_nodes(stmts, |node| {
136 visit(node);
137 Walk::Into
138 });
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum Walk {
144 Into,
146 Past,
149}
150
151pub fn walk_nodes<'w, 'a>(stmts: &'w [Stmt<'a>], mut visit: impl FnMut(Visited<'w, 'a>) -> Walk) {
155 let mut work: Vec<(Node<'w, 'a>, usize)> = stmts.iter().map(|s| (Node::S(s), 1)).collect();
156 while let Some((node, depth)) = work.pop() {
157 let d = depth + 1;
158 match node {
159 Node::S(stmt) => {
160 if visit(Visited::Stmt(stmt)) == Walk::Into {
161 push_stmt_children(stmt, d, &mut work);
162 }
163 }
164 Node::E(expr) => {
165 if visit(Visited::Expr(expr)) == Walk::Into {
166 push_expr_children(expr, d, &mut work);
167 }
168 }
169 Node::T(ty) => push_type_children(ty, d, &mut work),
170 Node::L(logic) => push_logic_children(logic, d, &mut work),
171 }
172 }
173}
174
175pub fn expr_children<'w, 'a>(expr: &'w Expr<'a>) -> Vec<&'w Expr<'a>> {
179 if matches!(expr, Expr::Closure { .. }) {
180 return Vec::new();
181 }
182 let mut work = Vec::new();
183 push_expr_children(expr, 0, &mut work);
184 work.into_iter()
185 .filter_map(|(node, _)| match node {
186 Node::E(e) => Some(e),
187 _ => None,
188 })
189 .collect()
190}
191
192pub fn stmt_expr_children<'w, 'a>(stmt: &'w Stmt<'a>) -> Vec<&'w Expr<'a>> {
195 let mut work = Vec::new();
196 push_stmt_children(stmt, 0, &mut work);
197 work.into_iter()
198 .filter_map(|(node, _)| match node {
199 Node::E(e) => Some(e),
200 _ => None,
201 })
202 .collect()
203}
204
205pub fn validate_program_depth(stmts: &[Stmt<'_>], span: Span) -> Result<(), ParseError> {
208 let limit = max_ast_depth();
209 let depth = program_depth(stmts);
210 if depth > limit {
211 return Err(ParseError {
212 kind: ParseErrorKind::AstTooDeep {
213 depth,
214 max_depth: limit,
215 },
216 span,
217 });
218 }
219 Ok(())
220}
221
222#[cfg(test)]
223#[path = "../../logicaffeine_tests/unit/logicaffeine_language/ast_depth/tests.rs"]
224mod tests;
225
226fn push_stmt_children<'w, 'a>(stmt: &'w Stmt<'a>, d: usize, work: &mut Vec<(Node<'w, 'a>, usize)>) {
227 macro_rules! e {
228 ($x:expr) => {
229 work.push((Node::E($x), d))
230 };
231 }
232 macro_rules! block {
233 ($b:expr) => {
234 for s in $b.iter() {
235 work.push((Node::S(s), d));
236 }
237 };
238 }
239 match stmt {
240 Stmt::Let {
241 ty,
242 value,
243 var: _,
244 mutable: _,
245 } => {
246 if let Some(t) = ty {
247 work.push((Node::T(t), d));
248 }
249 e!(value);
250 }
251 Stmt::Set { value, target: _ } => e!(value),
252 Stmt::Swap { a: _, b: _ } => {}
254 Stmt::Call { args, function: _ } => {
255 for a in args {
256 e!(a);
257 }
258 }
259 Stmt::If {
260 cond,
261 then_block,
262 else_block,
263 } => {
264 e!(cond);
265 block!(then_block);
266 if let Some(b) = else_block {
267 block!(b);
268 }
269 }
270 Stmt::While {
271 cond,
272 body,
273 decreasing,
274 } => {
275 e!(cond);
276 if let Some(x) = decreasing {
277 e!(x);
278 }
279 block!(body);
280 }
281 Stmt::Repeat {
282 iterable,
283 body,
284 pattern: _,
285 } => {
286 e!(iterable);
287 block!(body);
288 }
289 Stmt::Return { value } => {
290 if let Some(x) = value {
291 e!(x);
292 }
293 }
294 Stmt::Break => {}
295 Stmt::Assert { proposition } => work.push((Node::L(proposition), d)),
296 Stmt::Trust {
297 proposition,
298 justification: _,
299 } => work.push((Node::L(proposition), d)),
300 Stmt::RuntimeAssert {
301 condition,
302 hard: _,
303 dim: _,
304 reason,
305 } => {
306 e!(condition);
307 if let Some(r) = reason {
308 e!(r);
309 }
310 }
311 Stmt::Fail { reason } => e!(reason),
312 Stmt::Give { object, recipient } => {
313 e!(object);
314 e!(recipient);
315 }
316 Stmt::Show { object, recipient } => {
317 e!(object);
318 e!(recipient);
319 }
320 Stmt::SetField {
321 object,
322 value,
323 field: _,
324 } => {
325 e!(object);
326 e!(value);
327 }
328 Stmt::StructDef { .. } => {}
329 Stmt::TestDef { cases, body, .. } => {
330 if let Some(table) = cases {
331 for row in &table.rows {
332 for cell in row {
333 e!(cell);
334 }
335 }
336 }
337 block!(body);
338 }
339 Stmt::Expect { condition } => e!(condition),
340 Stmt::ExpectFail { body, message: _ } => block!(body),
341 Stmt::ExpectOutput { .. } => {}
342 Stmt::AdvanceTime { millis } => e!(millis),
343 Stmt::GivenFile { .. } => {}
344 Stmt::Observe { payloads, .. } => {
345 for (_, expr) in payloads {
346 e!(expr);
347 }
348 }
349 Stmt::During { body, .. } => block!(body),
350 Stmt::ForAll {
351 constraint, body, ..
352 } => {
353 if let Some(c) = constraint {
354 e!(c);
355 }
356 block!(body);
357 }
358 Stmt::FunctionDef {
359 params,
360 body,
361 return_type,
362 ..
363 } => {
364 for (_, t) in params {
365 work.push((Node::T(t), d));
366 }
367 if let Some(t) = return_type {
368 work.push((Node::T(t), d));
369 }
370 block!(body);
371 }
372 Stmt::Inspect {
373 target,
374 arms,
375 has_otherwise: _,
376 } => {
377 e!(target);
378 for arm in arms {
379 block!(arm.body);
380 }
381 }
382 Stmt::Push { value, collection } => {
383 e!(value);
384 e!(collection);
385 }
386 Stmt::Pop {
387 collection,
388 into: _,
389 } => e!(collection),
390 Stmt::Add { value, collection } => {
391 e!(value);
392 e!(collection);
393 }
394 Stmt::Remove { value, collection } => {
395 e!(value);
396 e!(collection);
397 }
398 Stmt::SetIndex {
399 collection,
400 index,
401 value,
402 } => {
403 e!(collection);
404 e!(index);
405 e!(value);
406 }
407 Stmt::Splice { body } => block!(body),
408 Stmt::ComponentDef(def) => {
409 for (_, t) in &def.props {
410 work.push((Node::T(t), d));
411 }
412 if let crate::ast::component::ComponentKind::Page { params, .. } = &def.kind {
413 for (_, t) in params {
414 work.push((Node::T(t), d));
415 }
416 }
417 for f in &def.state {
418 if let Some(t) = f.ty {
419 work.push((Node::T(t), d));
420 }
421 e!(f.init);
422 }
423 for ev in &def.events {
424 block!(ev.body);
425 }
426 for a in &def.actions {
427 for (_, t) in &a.params {
428 work.push((Node::T(t), d));
429 }
430 block!(a.body);
431 }
432 if let Some(v) = &def.view {
433 let (es, bs) = v.exprs_and_blocks();
434 for x in es {
435 e!(x);
436 }
437 for b in bs {
438 block!(b);
439 }
440 }
441 }
442 Stmt::DirectiveDef {
443 params,
444 body,
445 removed,
446 ..
447 } => {
448 for (_, t) in params {
449 work.push((Node::T(t), d));
450 }
451 block!(body);
452 if let Some(r) = removed {
453 block!(r);
454 }
455 }
456 Stmt::RouteDef {
457 params,
458 return_type,
459 body,
460 ..
461 } => {
462 for (_, t) in params {
463 work.push((Node::T(t), d));
464 }
465 if let Some(t) = return_type {
466 work.push((Node::T(t), d));
467 }
468 match &**body {
469 crate::ast::component::RouteBody::Statements(b) => block!(b),
470 crate::ast::component::RouteBody::View(v) => {
471 let (es, bs) = v.exprs_and_blocks();
472 for x in es {
473 e!(x);
474 }
475 for b in bs {
476 block!(b);
477 }
478 }
479 }
480 }
481 Stmt::MiddlewareDef { param, body } => {
482 work.push((Node::T(param.1), d));
483 block!(body);
484 }
485 Stmt::RedirectDef { .. } => {}
486 Stmt::Ui(u) => {
487 for x in u.exprs() {
488 e!(x);
489 }
490 }
491 Stmt::ServeFetches | Stmt::Replay { .. } => {}
492 Stmt::GivenFetch {
493 url, status, body, ..
494 } => {
495 e!(url);
496 e!(status);
497 e!(body);
498 }
499 Stmt::Fetch {
500 url, body, as_type, ..
501 } => {
502 e!(url);
503 if let Some(b) = body {
504 e!(b);
505 }
506 work.push((Node::T(as_type), d));
507 }
508 Stmt::Reversibly { body } => block!(body),
509 Stmt::Zone {
510 body,
511 name: _,
512 capacity: _,
513 source_file: _,
514 } => block!(body),
515 Stmt::Concurrent { tasks } => block!(tasks),
516 Stmt::Parallel { tasks } => block!(tasks),
517 Stmt::ReadFrom { source, var: _ } => match source {
518 ReadSource::Console => {}
519 ReadSource::File(path) => e!(path),
520 },
521 Stmt::WriteFile { content, path } => {
522 e!(content);
523 e!(path);
524 }
525 Stmt::Spawn { .. } => {}
526 Stmt::SendMessage {
527 message,
528 destination,
529 ..
530 } => {
531 e!(message);
532 e!(destination);
533 }
534 Stmt::AwaitMessage { source, .. } => e!(source),
535 Stmt::StreamMessage {
536 values,
537 destination,
538 } => {
539 e!(values);
540 e!(destination);
541 }
542 Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
543 e!(source);
544 e!(target);
545 }
546 Stmt::IncreaseCrdt {
547 object,
548 amount,
549 field: _,
550 } => {
551 e!(object);
552 e!(amount);
553 }
554 Stmt::DecreaseCrdt {
555 object,
556 amount,
557 field: _,
558 } => {
559 e!(object);
560 e!(amount);
561 }
562 Stmt::AppendToSequence { sequence, value } => {
563 e!(sequence);
564 e!(value);
565 }
566 Stmt::ResolveConflict {
567 object,
568 value,
569 field: _,
570 } => {
571 e!(object);
572 e!(value);
573 }
574 Stmt::Check { .. } => {}
575 Stmt::Listen { address, secure } => {
576 e!(address);
577 if let Some(pad) = secure {
578 e!(pad.pad);
579 }
580 }
581 Stmt::Serve { port, handler } => {
582 e!(port);
583 e!(handler);
584 }
585 Stmt::ConnectTo { address, secure } => {
586 e!(address);
587 if let Some(pad) = secure {
588 e!(pad.pad);
589 }
590 }
591 Stmt::LetPeerAgent { address, var: _ } => e!(address),
592 Stmt::Sleep { milliseconds } => e!(milliseconds),
593 Stmt::Sync { topic, var: _ } => e!(topic),
594 Stmt::Mount { path, var: _ } => e!(path),
595 Stmt::LaunchTask { args, function: _ } => {
596 for a in args {
597 e!(a);
598 }
599 }
600 Stmt::LaunchTaskWithHandle {
601 args,
602 handle: _,
603 function: _,
604 } => {
605 for a in args {
606 e!(a);
607 }
608 }
609 Stmt::CreatePipe { .. } => {}
610 Stmt::SendPipe { value, pipe } => {
611 e!(value);
612 e!(pipe);
613 }
614 Stmt::ReceivePipe { pipe, var: _ } => e!(pipe),
615 Stmt::TrySendPipe {
616 value,
617 pipe,
618 result: _,
619 } => {
620 e!(value);
621 e!(pipe);
622 }
623 Stmt::TryReceivePipe { pipe, var: _ } => e!(pipe),
624 Stmt::StopTask { handle } => e!(handle),
625 Stmt::CloseChannel { channel } => e!(channel),
626 Stmt::AwaitTask { handle, result: _ } => e!(handle),
627 Stmt::Select { branches } => {
628 for branch in branches {
629 match branch {
630 SelectBranch::Receive { pipe, body, var: _ } => {
631 e!(pipe);
632 block!(body);
633 }
634 SelectBranch::Timeout { milliseconds, body } => {
635 e!(milliseconds);
636 block!(body);
637 }
638 }
639 }
640 }
641 Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {}
644 Stmt::Escape { .. } => {}
645 Stmt::Require { .. } => {}
646 Stmt::Site(_) => {}
648 }
649}
650
651fn push_expr_children<'w, 'a>(expr: &'w Expr<'a>, d: usize, work: &mut Vec<(Node<'w, 'a>, usize)>) {
652 macro_rules! e {
653 ($x:expr) => {
654 work.push((Node::E($x), d))
655 };
656 }
657 match expr {
658 Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone | Expr::Escape { .. } => {}
659 Expr::Dom(q) => {
660 if let Some(sel) = q.selector() {
661 e!(sel);
662 }
663 }
664 Expr::View(v) => {
665 let (es, bs) = v.exprs_and_blocks();
666 for x in es {
667 e!(x);
668 }
669 for b in bs {
670 for st in b.iter() {
671 work.push((Node::S(st), d));
672 }
673 }
674 }
675 Expr::BinaryOp { left, right, op: _ } => {
676 e!(left);
677 e!(right);
678 }
679 Expr::Not { operand } => e!(operand),
680 Expr::Call { args, function: _ } => {
681 for a in args {
682 e!(a);
683 }
684 }
685 Expr::Index { collection, index } => {
686 e!(collection);
687 e!(index);
688 }
689 Expr::Slice {
690 collection,
691 start,
692 end,
693 } => {
694 e!(collection);
695 e!(start);
696 e!(end);
697 }
698 Expr::Copy { expr } => e!(expr),
699 Expr::Give { value } => e!(value),
700 Expr::Length { collection } => e!(collection),
701 Expr::Contains { collection, value } => {
702 e!(collection);
703 e!(value);
704 }
705 Expr::Union { left, right } => {
706 e!(left);
707 e!(right);
708 }
709 Expr::Intersection { left, right } => {
710 e!(left);
711 e!(right);
712 }
713 Expr::ManifestOf { zone } => e!(zone),
714 Expr::ChunkAt { index, zone } => {
715 e!(index);
716 e!(zone);
717 }
718 Expr::List(items) => {
719 for x in items {
720 e!(x);
721 }
722 }
723 Expr::Tuple(items) => {
724 for x in items {
725 e!(x);
726 }
727 }
728 Expr::Range { start, end } => {
729 e!(start);
730 e!(end);
731 }
732 Expr::FieldAccess { object, field: _ } => e!(object),
733 Expr::New {
734 type_args,
735 init_fields,
736 type_name: _,
737 } => {
738 for t in type_args {
739 work.push((Node::T(t), d));
740 }
741 for (_, x) in init_fields {
742 e!(x);
743 }
744 }
745 Expr::NewVariant {
746 fields,
747 enum_name: _,
748 variant: _,
749 } => {
750 for (_, x) in fields {
751 e!(x);
752 }
753 }
754 Expr::OptionSome { value } => e!(value),
755 Expr::WithCapacity { value, capacity } => {
756 e!(value);
757 e!(capacity);
758 }
759 Expr::Closure {
760 params,
761 body,
762 return_type,
763 } => {
764 for (_, t) in params {
765 work.push((Node::T(t), d));
766 }
767 if let Some(t) = return_type {
768 work.push((Node::T(t), d));
769 }
770 match body {
771 ClosureBody::Expression(x) => e!(x),
772 ClosureBody::Block(b) => {
773 for s in *b {
774 work.push((Node::S(s), d));
775 }
776 }
777 }
778 }
779 Expr::CallExpr { callee, args } => {
780 e!(callee);
781 for a in args {
782 e!(a);
783 }
784 }
785 Expr::InterpolatedString(parts) => {
786 for part in parts {
787 match part {
788 StringPart::Literal(_) => {}
789 StringPart::Expr {
790 value,
791 format_spec: _,
792 debug: _,
793 } => e!(value),
794 }
795 }
796 }
797 }
798}
799
800fn push_type_children<'w, 'a>(
801 ty: &'w TypeExpr<'a>,
802 d: usize,
803 work: &mut Vec<(Node<'w, 'a>, usize)>,
804) {
805 match ty {
806 TypeExpr::Primitive(_) | TypeExpr::Named(_) => {}
807 TypeExpr::Generic { params, base: _ } => {
808 for t in *params {
809 work.push((Node::T(t), d));
810 }
811 }
812 TypeExpr::Tuple(params) => {
813 for t in *params {
814 work.push((Node::T(t), d));
815 }
816 }
817 TypeExpr::Record { field_types, .. } => {
818 for t in *field_types {
819 work.push((Node::T(t), d));
820 }
821 }
822 TypeExpr::Function { inputs, output } => {
823 for t in *inputs {
824 work.push((Node::T(t), d));
825 }
826 work.push((Node::T(output), d));
827 }
828 TypeExpr::Refinement {
829 base,
830 predicate,
831 var: _,
832 } => {
833 work.push((Node::T(base), d));
834 work.push((Node::L(predicate), d));
835 }
836 TypeExpr::Persistent { inner } | TypeExpr::Mutable { inner } => {
837 work.push((Node::T(inner), d));
838 }
839 }
840}
841
842fn push_logic_children<'w, 'a>(
843 logic: &'w LogicExpr<'a>,
844 d: usize,
845 work: &mut Vec<(Node<'w, 'a>, usize)>,
846) {
847 macro_rules! l {
848 ($x:expr) => {
849 work.push((Node::L($x), d))
850 };
851 }
852 match logic {
853 LogicExpr::Predicate { .. }
856 | LogicExpr::Identity { .. }
857 | LogicExpr::Metaphor { .. }
858 | LogicExpr::Atom(_)
859 | LogicExpr::Categorical(_)
860 | LogicExpr::Relation(_)
861 | LogicExpr::NeoEvent(_)
862 | LogicExpr::Comparative { .. }
863 | LogicExpr::Superlative { .. } => {}
864 LogicExpr::Quantifier { body, .. } => l!(body),
865 LogicExpr::Modal { operand, .. } => l!(operand),
866 LogicExpr::Temporal { body, .. } => l!(body),
867 LogicExpr::TemporalBinary { left, right, .. } => {
868 l!(left);
869 l!(right);
870 }
871 LogicExpr::Aspectual { body, .. } => l!(body),
872 LogicExpr::Voice { body, .. } => l!(body),
873 LogicExpr::BinaryOp { left, right, .. } => {
874 l!(left);
875 l!(right);
876 }
877 LogicExpr::UnaryOp { operand, .. } => l!(operand),
878 LogicExpr::Question { body, .. } => l!(body),
879 LogicExpr::YesNoQuestion { body } => l!(body),
880 LogicExpr::Lambda { body, .. } => l!(body),
881 LogicExpr::App { function, argument } => {
882 l!(function);
883 l!(argument);
884 }
885 LogicExpr::Intensional { content, .. } => l!(content),
886 LogicExpr::Event { predicate, .. } => l!(predicate),
887 LogicExpr::Imperative { action } => l!(action),
888 LogicExpr::Exclamative { body, .. } => l!(body),
889 LogicExpr::Optative { wish } => l!(wish),
890 LogicExpr::Implicature {
891 assertion,
892 implicature,
893 } => {
894 l!(assertion);
895 l!(implicature);
896 }
897 LogicExpr::SpeechAct { content, .. } => l!(content),
898 LogicExpr::Counterfactual {
899 antecedent,
900 consequent,
901 } => {
902 l!(antecedent);
903 l!(consequent);
904 }
905 LogicExpr::Causal { effect, cause } => {
906 l!(effect);
907 l!(cause);
908 }
909 LogicExpr::Concessive { main, concession } => {
910 l!(main);
911 l!(concession);
912 }
913 LogicExpr::Scopal { body, .. } => l!(body),
914 LogicExpr::Control { infinitive, .. } => l!(infinitive),
915 LogicExpr::Presupposition {
916 assertion,
917 presupposition,
918 } => {
919 l!(assertion);
920 l!(presupposition);
921 }
922 LogicExpr::Focus { scope, .. } => l!(scope),
923 LogicExpr::TemporalAnchor { body, .. } => l!(body),
924 LogicExpr::Distributive { predicate } => l!(predicate),
925 LogicExpr::GroupQuantifier {
926 restriction, body, ..
927 } => {
928 l!(restriction);
929 l!(body);
930 }
931 }
932}