1
//! The forms of a BLOCK, TAGBODY or HANDLER-CASE body a non-local exit may
2
//! skip (plan 0014 PERSIST): a definition there may not commit at compile
3
//! time, so it is refused, or a DEFVAR of a cell only maybe binds it.
4

            
5
use std::borrow::Cow;
6

            
7
use crate::ast::Expr;
8
use crate::compiler::expr::fold::walk::{Node, Scope, Step, Visit, is_literal, walk_body};
9
use crate::error::Result;
10
use crate::runtime::{ExitRegion, FormId, SymbolTable, form_id};
11

            
12
use super::super::DEFINITION_FORMS;
13

            
14
/// How often a form a region holds runs.
15
#[derive(Clone, Debug, PartialEq)]
16
pub(super) enum Region {
17
    /// At most once: a caught exit before it, of the named form, may skip it.
18
    AfterExit(ExitRegion),
19
    /// Zero or more times: a GO may skip it or come back to it.
20
    Repeated,
21
}
22

            
23
/// Runs `f` in `region`, or as an ordinary form for `None`.
24
233727
pub(super) fn in_region<T>(
25
233727
    symbols: &mut SymbolTable,
26
233727
    region: Option<&Region>,
27
233727
    f: impl FnOnce(&mut SymbolTable) -> Result<T>,
28
233727
) -> Result<T> {
29
233727
    let Some(region) = region else {
30
137909
        return f(symbols);
31
    };
32
95818
    match region {
33
94525
        Region::AfterExit(exit) => symbols.enter_exit_region(exit.clone()),
34
1293
        Region::Repeated => symbols.enter_skippable()?,
35
    }
36
95818
    let result = f(symbols);
37
95818
    let left = match region {
38
94525
        Region::AfterExit(_) => symbols.leave_exit_region(),
39
1293
        Region::Repeated => symbols.exit_skippable(),
40
    };
41
95818
    result.and_then(|value| left.map(|()| value))
42
233727
}
43

            
44
/// The region of form `idx` of the `form` body whose first skipped form is
45
/// `first`; the definitions `kept` run before the exit inside that form.
46
108081
pub(super) fn after_exit(
47
108081
    idx: usize,
48
108081
    first: usize,
49
108081
    form: &'static str,
50
108081
    kept: &[FormId],
51
108081
) -> Option<Region> {
52
108081
    let kept = if idx == first {
53
58044
        kept.to_vec()
54
    } else {
55
50037
        Vec::new()
56
    };
57
108081
    (idx >= first).then_some(Region::AfterExit(ExitRegion { form, kept }))
58
108081
}
59

            
60
/// The definitions inside `forms[first]` that run before the exit it holds:
61
/// those textually before it in its sequential forms (PROGN, LET, LET*), up
62
/// to a DEFUN or DEFMACRO whose body holds the exit, a call of which may leave.
63
159628
pub(super) fn kept_definitions(
64
159628
    forms: &[Expr],
65
159628
    start: Start,
66
159628
    exits: impl Fn(&Expr) -> bool,
67
159628
) -> Vec<FormId> {
68
159628
    let mut kept = Vec::new();
69
159628
    if start.exited {
70
217
        return kept;
71
159411
    }
72
159411
    if let Some(form) = forms.get(start.at).filter(|form| exits(form)) {
73
131036
        leading_definitions(form, &exits, &mut kept);
74
28375
    }
75
159411
    kept
76
159628
}
77

            
78
/// Collects the definitions of `form` before its first exit into `kept`;
79
/// whether `form` holds that exit.
80
141937
fn leading_definitions(
81
141937
    form: &Expr,
82
141937
    exits: &impl Fn(&Expr) -> bool,
83
141937
    kept: &mut Vec<FormId>,
84
141937
) -> bool {
85
141937
    let Expr::List(elems) = form else {
86
838
        return exits(form);
87
    };
88
141099
    if defers(form) {
89
3962
        kept.push(form_id(&elems[1..]));
90
3962
        return exits(form);
91
137137
    }
92
137137
    if runs_whole(form) {
93
418
        kept.push(form_id(&elems[1..]));
94
418
        return false;
95
136719
    }
96
136719
    let (inits, body) = match elems.first() {
97
136713
        Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case("PROGN") => (Vec::new(), &elems[1..]),
98
        Some(Expr::Symbol(head))
99
131921
            if (head.eq_ignore_ascii_case("LET") || head.eq_ignore_ascii_case("LET*"))
100
4907
                && elems.len() > 2 =>
101
        {
102
4907
            (binding_inits(&elems[1]), &elems[2..])
103
        }
104
127020
        _ => return exits(form),
105
    };
106
9699
    inits.into_iter().any(exits)
107
7983
        || body
108
7983
            .iter()
109
10901
            .any(|form| leading_definitions(form, exits, kept))
110
141937
}
111

            
112
4907
fn binding_inits(bindings: &Expr) -> Vec<&Expr> {
113
4907
    let Expr::List(bindings) = bindings else {
114
        return Vec::new();
115
    };
116
4907
    bindings
117
4907
        .iter()
118
4919
        .filter_map(|binding| match binding {
119
4919
            Expr::List(parts) => parts.get(1),
120
            _ => None,
121
4919
        })
122
        .collect()
123
4907
}
124

            
125
/// Where the forms an exit may skip start in a body, and whether a DEFUN or
126
/// DEFMACRO holding the exit precedes them, so that no definition before the
127
/// exit is known to run.
128
#[derive(Clone, Copy, Debug, PartialEq)]
129
pub(super) struct Start {
130
    pub(super) at: usize,
131
    pub(super) exited: bool,
132
}
133

            
134
/// The first of `forms` an exit may skip: the first form that `exits`, or the
135
/// one after it when that form is a DEFUN or DEFMACRO, whose body does not
136
/// run where it is defined.
137
154352
pub(super) fn first_skipped(forms: &[Expr], exits: impl Fn(&Expr) -> bool) -> Start {
138
154352
    match forms.iter().position(exits) {
139
131040
        Some(at) if defers(&forms[at]) => Start {
140
218
            at: at + 1,
141
218
            exited: true,
142
218
        },
143
130822
        Some(at) => Start { at, exited: false },
144
23312
        None => Start {
145
23312
            at: forms.len(),
146
23312
            exited: false,
147
23312
        },
148
    }
149
154352
}
150

            
151
/// A HANDLER-CASE body split where a signal may start to skip it: the forms
152
/// before the first that may signal, and the rest, a region when it holds a
153
/// definition.
154
pub(super) struct SignalSplit<'a> {
155
    pub(super) leading: &'a [Expr],
156
    pub(super) rest: Cow<'a, Expr>,
157
    pub(super) region: Option<Region>,
158
}
159

            
160
/// Splits a HANDLER-CASE `body` at its first form that [`may_signal`].
161
75078
pub(super) fn split_at_signal<'a>(symbols: &SymbolTable, body: &'a Expr) -> SignalSplit<'a> {
162
75078
    let forms = body_forms(body);
163
75078
    let start = first_skipped(forms, may_signal);
164
75078
    let from = start.at;
165
75078
    let skips = forms[from..]
166
75078
        .iter()
167
91155
        .any(|form| holds_definition(symbols, form));
168
75078
    let (leading, rest, first) = match (skips, from) {
169
        (true, 1..) => {
170
626
            let progn = std::iter::once(Expr::symbol("PROGN")).chain(forms[from..].iter().cloned());
171
626
            (&forms[..from], Cow::Owned(Expr::List(progn.collect())), 0)
172
        }
173
74452
        _ => (&[][..], Cow::Borrowed(body), from),
174
    };
175
75078
    let first = Start { at: first, ..start };
176
75078
    let kept = kept_definitions(body_forms(&rest), first, may_signal);
177
75078
    SignalSplit {
178
75078
        leading,
179
75078
        rest,
180
75078
        region: skips.then_some(Region::AfterExit(ExitRegion {
181
75078
            form: "HANDLER-CASE",
182
75078
            kept,
183
75078
        })),
184
75078
    }
185
75078
}
186

            
187
150156
fn body_forms(body: &Expr) -> &[Expr] {
188
150156
    match body {
189
145150
        Expr::List(elems) if head_is(body, "PROGN") => &elems[1..],
190
107584
        _ => std::slice::from_ref(body),
191
    }
192
150156
}
193

            
194
/// Whether running `form` may exit or signal: anything but a literal, quoted
195
/// data, a DEFUN, a DEFMACRO, a DEFSTRUCT or a definition whose init is a
196
/// literal may.
197
229604
fn may_signal(form: &Expr) -> bool {
198
229604
    match form {
199
        Expr::Quote(_) | Expr::Datum(_) => false,
200
223974
        Expr::List(elems) if is_cell_definition(form) => {
201
12910
            elems.get(2).is_some_and(|init| !is_literal(init))
202
        }
203
216694
        _ => !is_literal(form) && !defers(form) && !head_is(form, "DEFSTRUCT"),
204
    }
205
229604
}
206

            
207
/// Whether `form` defines something and cannot exit while it does.
208
137137
fn runs_whole(form: &Expr) -> bool {
209
137137
    head_is(form, "DEFSTRUCT") || is_cell_definition(form) && !may_signal(form)
210
137137
}
211

            
212
361111
fn is_cell_definition(form: &Expr) -> bool {
213
361111
    head_is(form, "DEFVAR") || head_is(form, "DEFPARAMETER")
214
361111
}
215

            
216
485699
fn defers(form: &Expr) -> bool {
217
485699
    head_is(form, "DEFUN") || head_is(form, "DEFMACRO")
218
485699
}
219

            
220
2168843
fn head_is(form: &Expr, name: &str) -> bool {
221
2168843
    matches!(form, Expr::List(elems) if matches!(elems.first(), Some(Expr::Symbol(head)) if head.eq_ignore_ascii_case(name)))
222
2168843
}
223

            
224
/// Whether `form` may define something; a macro use the walk cannot read may.
225
91155
fn holds_definition(symbols: &SymbolTable, form: &Expr) -> bool {
226
91155
    !matches!(
227
91155
        walk_body(symbols, &[], std::slice::from_ref(form), &mut Definitions),
228
91155
        Ok(false)
229
91155
    )
230
91155
}
231

            
232
struct Definitions;
233

            
234
impl Visit for Definitions {
235
374506
    fn visit(&mut self, _env: &SymbolTable, _scope: &Scope, node: Node<'_>) -> Step {
236
374506
        match node {
237
            Node::Special(head, _)
238
81286
                if DEFINITION_FORMS
239
81286
                    .iter()
240
387875
                    .any(|d| head.eq_ignore_ascii_case(d)) =>
241
            {
242
6677
                Step::Found
243
            }
244
630
            Node::OpaqueMacro => Step::Found,
245
199743
            Node::DiscardedLambda | Node::Datum | Node::Free(_) => Step::Skip,
246
167456
            Node::Special(..) | Node::Native(_) | Node::Call | Node::Other => Step::Descend,
247
        }
248
374506
    }
249
}
250

            
251
#[cfg(test)]
252
#[path = "skip_region_tests.rs"]
253
mod tests;