1
//! The syntactic question `eval_block` asks of a BLOCK body before folding
2
//! it: whether a `return-from` may leave the block. A client of the scoped
3
//! walk in `expr::fold::walk`, narrowed to one block name.
4
//!
5
//! The answer errs towards "cannot fold". A macro call counts as an exit
6
//! unless the macro is a pure template: any other expansion may depend on the
7
//! environment at the call site (lexical bindings, earlier stores in the
8
//! body), which the scan cannot reconstruct.
9

            
10
use crate::ast::Expr;
11
use crate::compiler::expr::fold::walk::{Node, Scope, Step, Visit, walk_body};
12
#[cfg(test)]
13
use crate::runtime::SymbolKind;
14
use crate::runtime::SymbolTable;
15

            
16
use super::block_parse::{NIL_LABEL, label};
17
use super::nil_block::is_loop;
18

            
19
pub(super) const DEFMACRO: &str = "DEFMACRO";
20

            
21
/// Whether a `(return-from name …)` in `body` may leave the block `name`.
22
/// Quoted data, inner blocks rebinding `name`, the dead branch of a
23
/// conditional whose test is a literal, and a lambda discarded by a body are
24
/// skipped; everything else, lambda bodies included, counts. A template macro
25
/// is expanded (its expansion is the same in every environment); any other
26
/// macro call, or one that fails to expand, counts as an exit, as does any
27
/// body that defines a macro.
28
190120
pub(super) fn has_exit_to(symbols: &SymbolTable, name: &str, body: &[Expr]) -> bool {
29
190120
    scan(
30
190120
        symbols,
31
190120
        ExitTo {
32
190120
            name,
33
190120
            own_loop: false,
34
190120
            defining_exits: true,
35
190120
        },
36
190120
        body,
37
190120
    )
38
190120
}
39

            
40
/// Whether a `(return …)` in `looped`, a DO / DO* / DOLIST form, may leave
41
/// the NIL block the loop itself opens; the loops nested in it open their own.
42
465008
pub(super) fn loop_exits(symbols: &SymbolTable, looped: &Expr) -> bool {
43
465008
    scan(
44
465008
        symbols,
45
465008
        ExitTo {
46
465008
            name: NIL_LABEL,
47
465008
            own_loop: true,
48
465008
            defining_exits: false,
49
465008
        },
50
465008
        std::slice::from_ref(looped),
51
465008
    )
52
465008
}
53

            
54
655128
fn scan(symbols: &SymbolTable, mut visitor: ExitTo, body: &[Expr]) -> bool {
55
655128
    (visitor.defining_exits && body.iter().any(defines_macro))
56
654077
        || !matches!(walk_body(symbols, &[], body, &mut visitor), Ok(false))
57
655128
}
58

            
59
/// Whether `form` defines a macro anywhere outside quoted data: its
60
/// expansion is not analysed, so the enclosing block may be left through it.
61
3967520
pub(super) fn defines_macro(form: &Expr) -> bool {
62
3967520
    match form {
63
        Expr::List(elems) => {
64
1368780
            matches!(elems.first(), Some(Expr::Symbol(h)) if h.eq_ignore_ascii_case(DEFMACRO))
65
1366447
                || elems.iter().any(defines_macro)
66
        }
67
        Expr::Cons(car, cdr) => defines_macro(car) || defines_macro(cdr),
68
        Expr::Quasiquote(inner)
69
        | Expr::Unquote(inner)
70
        | Expr::UnquoteSplicing(inner)
71
20
        | Expr::Lambda(_, inner) => defines_macro(inner),
72
2598720
        _ => false,
73
    }
74
3967520
}
75

            
76
struct ExitTo<'a> {
77
    name: &'a str,
78
    /// The first loop met is the one whose own block is asked about.
79
    own_loop: bool,
80
    /// A macro definition may be used to leave the block, unseen: true unless
81
    /// a loop's own block is asked about, where a use is an opaque macro.
82
    defining_exits: bool,
83
}
84

            
85
impl ExitTo<'_> {
86
317877
    fn names(&self, elems: &[Expr]) -> bool {
87
317877
        elems
88
317877
            .get(1)
89
317877
            .and_then(label)
90
317877
            .is_some_and(|n| n.eq_ignore_ascii_case(self.name))
91
317877
    }
92

            
93
1538318
    fn shadows(&mut self, head: &str) -> bool {
94
1538318
        if !is_loop(head) || !self.name.eq_ignore_ascii_case(NIL_LABEL) {
95
1027872
            return false;
96
510446
        }
97
510446
        !std::mem::take(&mut self.own_loop)
98
1538318
    }
99
}
100

            
101
impl Visit for ExitTo<'_> {
102
11855248
    fn visit(&mut self, _env: &SymbolTable, _scope: &Scope, node: Node<'_>) -> Step {
103
11855248
        match node {
104
1830373
            Node::Special(head, elems) if head.eq_ignore_ascii_case("RETURN-FROM") => {
105
291633
                if self.names(elems) {
106
154960
                    Step::Found
107
                } else {
108
136673
                    Step::Descend
109
                }
110
            }
111
            Node::Special(head, elems)
112
1538740
                if head.eq_ignore_ascii_case("BLOCK") && self.names(elems) =>
113
            {
114
422
                if elems.iter().any(defines_macro) {
115
2
                    Step::Found
116
                } else {
117
420
                    Step::Skip
118
                }
119
            }
120
1538318
            Node::Special(head, _) if self.shadows(head) => Step::Skip,
121
1492880
            Node::Special(head, _) if head.eq_ignore_ascii_case(DEFMACRO) => {
122
4
                match self.defining_exits {
123
1
                    true => Step::Found,
124
3
                    false => Step::Skip,
125
                }
126
            }
127
6604
            Node::OpaqueMacro => Step::Found,
128
7895029
            Node::DiscardedLambda | Node::Datum | Node::Free(_) => Step::Skip,
129
3616118
            Node::Special(..) | Node::Native(_) | Node::Call | Node::Other => Step::Descend,
130
        }
131
11855248
    }
132

            
133
343187
    fn prunes_dead_branches(&self) -> bool {
134
343187
        true
135
343187
    }
136
}
137

            
138
#[cfg(test)]
139
#[path = "exit_scan_tests.rs"]
140
mod tests;